Skip to content

Open source CapCut alternative.

TypeScript
95.8 KB
Raw Blame
"use client";

import { dismissLibraryImport, importLibraryFiles, useLibraryImports } from "@/cut/lib/libraryIntake";
import { LibraryImportCard } from "@/cut/components/LibraryImportCard";

import { libraryFolderRef, projectFolderRef } from "@/cut/lib/folderReference";
import { Fragment, useCallback, useEffect, useRef, useState } from "react";
import { useQueryClient } from "@tanstack/react-query";
import { useFormatter, useLocale, useTranslations } from "next-intl";
import { Captions, Check, Clapperboard, ClipboardList, Copy, Download, Ellipsis, Film, FolderOpen, FolderPlus, Image as ImageIcon, Loader2, Music, Shapes, Sparkles, Trash2, Upload, X, Blend } from "lucide-react";
import { Button } from "@/components/ui/button";
import { ScrollArea } from "@/components/ui/scroll-area";
import { Tooltip, TooltipContent, TooltipProvider, TooltipTrigger } from "@/components/ui/tooltip";
import { LiveElapsed } from "@/cut/components/Elapsed";
import {
  AlertDialog,
  AlertDialogAction,
  AlertDialogCancel,
  AlertDialogContent,
  AlertDialogDescription,
  AlertDialogFooter,
  AlertDialogHeader,
  AlertDialogTitle,
} from "@/components/ui/alert-dialog";
import { SectionTitle } from "@/cut/components/SectionTitle";
import { DropdownMenuItem, DropdownMenuSeparator } from "@/components/ui/dropdown-menu";
import { MEDIA_CORS } from "@/cut/lib/mediaCors";
import { apiFetch } from "@/cut/lib/backend";
import { useCutCaps, useLocalCompute } from "@/cut/lib/backend/hooks";
import {
  clearAssetDrag,
  draggingLibrary,
  draggingTemplate,
  hasLibraryDrag,
  hasTemplateDrag,
  setAssetDragData,
  setObjectDragImage,
} from "@/cut/lib/assetDrag";
import {
  draggingRef,
  refFromAsset,
  useAssetDrop,
  type AssetRef,
} from "@/cut/lib/assetRef";
import { RefDropZone } from "./RefDropZone";
import { deleteExport, downloadProjectExport, exportFileUrl, revealExport } from "@/cut/lib/exportClient";
import {
  exportCancelable,
  exportInFlight,
  useExportRows,
  useExports,
  useWatchExportLands,
  type ExportRow,
} from "@/cut/lib/exportStore";
import { useElapsed } from "@/cut/hooks/useElapsed";
import { useInView } from "@/cut/hooks/useInView";
import { useMediaFileSize } from "@/cut/hooks/useMediaFileSize";
import { formatBytes } from "@/lib/bytes";
import {
  addAssetToLibraryTemplate,
  addLibraryAssetToProject,
  addProjectTemplateToTimeline,
  addTemplateToProject,
  deleteFromLibrary,
  deleteLibraryFolder,
  deleteTemplate,
  folderDeleteTakes,
  importLibraryAsset,
  importTemplateToProject,
  libraryMediaUrl,
  moveLibraryItem,
  updateLibraryFolder,
  renameTemplate,
  saveAssetToLibrary,
  saveTemplate,
  type LibraryAsset,
  type LibraryData,
  type LibraryFolder,
} from "@/cut/lib/library";
import { useClipTitles } from "@/cut/lib/clipTitle";
import { patchLibrary, refetchLibrary, renameInLibrary, useLibrary } from "@/cut/lib/queries";
import {
  activeResidency,
  availableResidencies,
  type Residency,
} from "@/cut/lib/residency";
import { isSoundPresetTemplate } from "@/cut/lib/soundPresets";
import { isGradePresetTemplate } from "@/cut/lib/gradePresets";
import { isStylePresetTemplate } from "@/cut/lib/stylePresets";
import { retryUpload } from "@/cut/lib/importQueue";
import {
  forgetLinkedCopies,
  linkedAccept,
  LUT_FILE_ICON,
} from "@/cut/lib/linkedLibrary";
import { downloadMedia, MEDIA_ACCEPT, revealMedia } from "@/cut/lib/media";
import { useProxyJobs } from "@/cut/lib/mediaProxy";
import { isLinkedAssetType, mediaUrl } from "@/cut/lib/types";
import {
  genPulseOverlay,
  isGenTab,
  useActiveWork,
  useGenNotify,
  useGenPulse,
  useWatchGenTab,
} from "@/cut/lib/genNotify";
import { useGenerate, type GenerateJob } from "@/cut/lib/generate";
import { CAPTION_LIMIT, normalizeTags } from "@/cut/lib/publish";
import { assetClipUses, useEditor } from "@/cut/lib/store";
import { useEnvironment } from "@/cut/lib/environment";
import { formatTime } from "@/cut/lib/time";
import { useLocalPref } from "@/cut/lib/uiState";
import type { MediaAsset, SidePanelTab } from "@/cut/lib/types";
import { cn } from "@/lib/utils";
import { containerOfName, isStemsName } from "@/cut/lib/exportDelivery";
import { useRevealEffect } from "@/cut/lib/refReveal";
import { reportSideTab } from "@/cut/lib/onboarding";
import { usePanelRequestEffect } from "@/cut/lib/panelRequest";
import { CopyNameLabel } from "./AssetRefs";
import { AudioCardFace, AudioPanel } from "./AudioPanel";
import { childrenOf, folderTrail, folderWithin, parentOf } from "@/cut/lib/folderTree";
import {
  FolderCrumb,
  FolderMenuItems,
  FolderShelf,
  Marquee,
  folderSelId,
  splitPick,
  useTilePicks,
} from "./desktopFolders";
import {
  DeleteConfirm,
  SelectionMenu,
  usePickWords,
  useSelectionMenu,
} from "./selectionMenu";
import { TemplateCard } from "./TemplateCard";
import { GenerateVideoPanel } from "./GeneratePanel";
import { ImageGenPanel } from "./ImageGenPanel";
import { EffectsPanel } from "./EffectsPanel";
import { TransitionsPanel } from "./TransitionsPanel";
import { ElementsPanel } from "./ElementsPanel";
import { StockImagesPanel } from "./StockImagesPanel";
import { SampleLibrary } from "./StockMusicPanel";
import { StockVideosPanel } from "./StockVideosPanel";
import { STOCK_MUSIC } from "@/cut/lib/stockMusicManifest";
import { STOCK_SFX } from "@/cut/lib/stockSfxManifest";
import { STOCK_VIDEOS } from "@/cut/lib/stockVideoManifest";
import { LibraryCard } from "@/cut/components/LibraryCard";
import { CardActionsMenu } from "@/cut/components/CardActionsMenu";
import { RenameInput } from "@/cut/components/RenameInput";
import { ShelfBadge } from "@/cut/components/ShelfBadge";
import { MediaCardShell } from "./MediaCardShell";
import { lightboxItemFromAsset } from "@/cut/lib/lightbox";
import { PICKED_RING } from "@/cut/lib/assetPick";
import { SubTabs } from "./SubTabs";

// Drag a library clip onto a folder tile to file it (side panel, single card).
const LIBRARY_MOVE_MIME = "application/x-cut-library-move";
// A dragged folder row, filed into another folder or back out to a crumb.
const LIBRARY_FOLDER_MOVE_MIME = "application/x-cut-library-folder";
// A Project Files selection dragged onto a folder tile or the crumb: the
// payload is the picked asset ids, so one drop files the whole selection.
const MEDIA_MOVE_MIME = "application/x-cut-media-move";
import { PlatformPreviewDialog, type ExportItem } from "./PlatformPreview";
import { SubtitlesPanel } from "./SubtitlesPanel";

type Tab = SidePanelTab;

/** The rail's three runs: file tabs, AI-generate tabs, finishing tabs. */
const railGroup = (id: Tab): "files" | "gen" | "finish" =>
  id === "video" || id === "image" || id === "audio" ? "gen"
  : id === "subtitles" || id === "publish" ? "finish"
  : "files";

const TABS: { id: Tab; icon: typeof Film }[] = [
  { id: "media", icon: Clapperboard },
  { id: "elements", icon: Shapes },
  { id: "effects", icon: Sparkles },
  { id: "transitions", icon: Blend },
  { id: "video", icon: Film },
  { id: "image", icon: ImageIcon },
  { id: "audio", icon: Music },
  { id: "subtitles", icon: Captions },
  { id: "publish", icon: ClipboardList },
];

export function SidePanel({
  projectId,
  onImport,
  importing,
}: {
  projectId: string;
  onImport: (files: FileList | File[], opts?: { mediaOnly?: boolean; folderId?: string }) => void;
  importing: boolean;
}) {
  const t = useTranslations("media.sidePanel");
  // A shared view opens only the surfaces the share opted in. The rail still
  // shows every tab so the viewer sees what the editor has; a tab the share
  // withholds sits locked, and hovering it says why. The Library is the
  // viewer's own cross-project shelf and never appears there.
  const sharedFeatures = useEditor((s) => s.sharedFeatures);
  const { chatgpt } = useEnvironment();
  // Inside ChatGPT the card shows no credits, so the tabs that spend them
  // leave the rail altogether.
  const spends = (id: Tab) => id === "video" || id === "image" || id === "audio" || id === "subtitles";
  const railTabs = chatgpt ? TABS.filter(({ id }) => !spends(id)) : TABS;
  const offered = (id: Tab): boolean =>
    !sharedFeatures ||
    (id === "media"
      ? sharedFeatures.media
      : id === "video" || id === "image" || id === "audio"
        ? sharedFeatures.genai
        : id === "subtitles"
          ? sharedFeatures.subtitles
          : id === "publish"
            ? sharedFeatures.details
            : false);
  const visibleTabs = railTabs.filter(({ id }) => offered(id));
  // `null` collapses the panel: clicking the active tab unselects it, leaving
  // just the icon rail so the video canvas takes the freed width.
  const [tabPref, setTab] = useLocalPref<Tab | null>("cut-side-tab", "media", (v) =>
    v === null || TABS.some((x) => x.id === v)
  );
  // The remembered tab may be hidden in this share — the viewer's own last tab
  // in their own editor, which this share never offered. A share opens on what
  // it does offer, so a link shared for its subtitles lands on the transcript
  // with the rail open.
  const tab =
    tabPref !== null && !visibleTabs.some((t) => t.id === tabPref)
      ? (visibleTabs[0]?.id ?? null)
      : tabPref;
  // The Audio tab's Voice/Music sub-tab lives here so the Music sub-tab can lay
  // out as two columns — the generator plus the sample library — like Image/Video.
  const [audioSub, setAudioSub] = useLocalPref<"voice" | "music">(
    "cut-audio-subtab",
    "voice",
    (v) => v === "voice" || v === "music"
  );
  // Each library column folds away behind its edge knob; every choice sticks.
  const videoFold = useLibraryFold("cut-video-library");
  const imageFold = useLibraryFold("cut-image-library");
  const musicFold = useLibraryFold("cut-music-library");
  const genFold = tab === "image" ? imageFold : videoFold;
  // The Media rail tile as a drop target: a Library card (asset or template)
  // dropped on it joins the project. Project media (cards and timeline clips)
  // arrives through the ref zone below; these HTML5 handlers cover the
  // library-asset and template drags.
  const [dropTab, setDropTab] = useState<Tab | null>(null);
  const acceptsDrop = (id: Tab, e: React.DragEvent) => {
    const tpl = hasTemplateDrag(e) ? draggingTemplate() : null;
    return id === "media" && (hasLibraryDrag(e) || tpl?.scope === "library");
  };
  // A project asset dropped on the Media tile — from a card or dragged
  // straight off the timeline — reveals it in the panel (clears its origin tag).
  const dropRefOnTab = (ref: AssetRef) => {
    if (ref.scope !== "project") return;
    useEditor.getState().updateAsset(ref.id, { origin: undefined, chatId: undefined });
  };
  // Generations that finished while their tab was closed: a blue count rides
  // the rail icon, and opening the tab lets the new tiles pulse for a beat.
  const unseen = useGenNotify((s) => s.unseen);
  useWatchGenTab(tab, projectId);
  // Media badges too: its arrivals are exports finishing in the background.
  useWatchExportLands(projectId);
  // While a tab owns work in flight its rail tile spins — the work's own panel
  // is usually closed while it runs. Each tab's running state comes from the
  // store that owns that work: exports for Media, panel renders for
  // Video/Image, registered syntheses for Audio, the transcription pass for
  // Subtitles.
  // Read through the same assembly the Media tab's own Exports list uses, so
  // the rail tile spins for exactly the work that list shows — a queued engine
  // job, and a render this tab is doing itself.
  const exporting = useExportRows(projectId).some(exportInFlight);
  const panelRendering = (s: { jobs: GenerateJob[] }, kind: GenerateJob["kind"]) =>
    s.jobs.some(
      (j) => j.projectId === projectId && j.kind === kind && j.status === "running" && !j.chatId
    );
  const videoBusy = useGenerate((s) => panelRendering(s, "video"));
  const imageBusy = useGenerate((s) => panelRendering(s, "image"));
  const audioBusy = useActiveWork("audio") > 0;
  const subtitlesBusy = useEditor((s) => s.subtitleStatus === "running");
  const busy: Partial<Record<Tab, boolean>> = {
    media: exporting,
    video: videoBusy,
    image: imageBusy,
    audio: audioBusy,
    subtitles: subtitlesBusy,
  };

  // Clicking a reference token anywhere jumps here: switch to the tab that
  // owns the asset; the matching card scrolls into view and flashes.
  useRevealEffect((ref) => {
    if (ref.scope === "project" || ref.scope === "library" || ref.scope === "folder") {
      setTab("media");
      return;
    }
    if (STOCK_SFX.some((s) => s.id === ref.id)) {
      setTab("effects");
      return;
    }
    if (STOCK_MUSIC.some((m) => m.id === ref.id)) {
      setTab("audio");
      setAudioSub("music");
      musicFold.setOpen(true);
      return;
    }
    // The revealed tile lives in a library column; unfold it if hidden.
    if (STOCK_VIDEOS.some((v) => v.id === ref.id)) {
      setTab("video");
      videoFold.setOpen(true);
    } else {
      setTab("image");
      imageFold.setOpen(true);
    }
  });

  // The assistant's set_side_panel tool: open the tab it wants on screen, or
  // collapse the panel so the canvas gets the room.
  usePanelRequestEffect(setTab);

  // The starter tour waits on the Media tab opening.
  useEffect(() => {
    reportSideTab(tab);
  }, [tab]);

  // The Audio tab's second column; when it's absent the audio generator is the
  // outermost column and takes the floating close button on its own corner.
  const musicLibrary = !sharedFeatures && audioSub === "music" && STOCK_MUSIC.length > 0;

  return (
    <div className="flex min-h-0 border-r border-border bg-card">
      {/* Icon rail — its divider drops when collapsed so the panel's outer
          border becomes the single line between the rail and the canvas. It
          scrolls down its own length when a short window cannot show every tab;
          the floating scrollbar keeps all 68px for the tiles, so the widest
          label still fits. */}
      <ScrollArea
        data-tour="side-rail"
        className={cn(
          "min-h-0 w-[68px] shrink-0",
          tab !== null && "border-r border-border"
        )}
        contentClassName="flex flex-col items-center gap-1 py-3"
      >
        {railTabs.map(({ id, icon: Icon }, tabIndex) => {
          const locked = !offered(id);
          // The open tab never badges — its completions are already on screen.
          const unseenCount = isGenTab(id) && id !== tab ? unseen[id].length : 0;
          // Full width of the rail, whatever a scrollbar has left of it, so a
          // label that no longer fits ellipsises inside the tile rather than
          // running out past both edges of a centred one. The open tab reads
          // from its icon chip's deeper fill; no ring, so nothing to keep off
          // the rail edges. The outline stays off — click focus otherwise
          // draws one around the tile.
          const tileClass = cn(
            "flex w-full min-w-0 shrink-0 flex-col items-center gap-1 rounded-lg px-1 py-1.5 text-muted-foreground outline-none transition-colors",
            locked ? "cursor-default opacity-50" : "hover:text-foreground"
          );
          const inner = (
            <>
              <span
                className={cn(
                  "relative grid size-9 place-items-center rounded-lg transition-colors",
                  tab === id ? "bg-foreground/10 text-foreground" : !locked && "hover:bg-muted/60",
                  dropTab === id && "bg-primary/15 text-primary"
                )}
              >
                <Icon className="size-4.5" />
                <TileStatus count={unseenCount} busy={!!busy[id]} />
              </span>
              <span
                className={cn(
                  "w-full truncate text-center text-[10px] font-medium tracking-tight",
                  tab === id && "text-foreground"
                )}
              >
                {t(`tabs.${id}`)}
              </span>
            </>
          );

          // A locked tile stays a live element so hover reaches it: a disabled
          // button swallows pointer events and the tooltip would never open.
          const tile = locked ? (
            <TooltipProvider>
              <Tooltip>
                <TooltipTrigger
                  render={<button className={tileClass} aria-disabled type="button" />}
                >
                  {inner}
                </TooltipTrigger>
                <TooltipContent side="right" sideOffset={8}>
                  {t("viewOnly")}
                </TooltipContent>
              </Tooltip>
            </TooltipProvider>
          ) : (
            <button
              className={tileClass}
              aria-pressed={tab === id}
              data-tour={`side-${id}`}
              onClick={() => {
                // In the card the panel and the inspector share the room next
                // to the preview, so opening one closes the other. The clip
                // stays where it is; clicking it again brings its panel back.
                if (chatgpt && tab !== id) useEditor.getState().select(null);
                setTab(tab === id ? null : id);
              }}
              onDragOver={(e) => {
                if (!acceptsDrop(id, e)) return;
                e.preventDefault();
                e.dataTransfer.dropEffect = "copy";
                setDropTab(id);
              }}
              onDragLeave={() => setDropTab((d) => (d === id ? null : d))}
              onDrop={(e) => {
                if (!acceptsDrop(id, e)) return;
                e.preventDefault();
                setDropTab(null);
                const tpl = draggingTemplate();
                if (tpl?.scope === "library") void importTemplateToProject(projectId, tpl.template);
                else {
                  const lib = draggingLibrary();
                  if (lib) void importLibraryAsset(projectId, lib);
                }
                clearAssetDrag();
              }}
            >
              {inner}
            </button>
          );

          return (
            <Fragment key={id}>
              {/* Soft breaks between the file tabs, the AI-generate tabs, and the finishing tabs. */}
              {tabIndex > 0 && railGroup(id) !== railGroup(railTabs[tabIndex - 1].id) && (
                <div aria-hidden className="my-1 h-px w-8 shrink-0 bg-border" />
              )}
              {id === "media" && !locked ? (
                <RefDropZone
                  onRef={dropRefOnTab}
                  className="w-full shrink-0 rounded-lg"
                  activeClassName="bg-primary/10"
                >
                  {tile}
                </RefDropZone>
              ) : (
                tile
              )}
            </Fragment>
          );
        })}
      </ScrollArea>

      {tab === null ? null : (
        <div className="flex min-h-0">
          {tab === "image" || tab === "video" ? (
        // The generate tabs are two columns: the generate input on the left,
        // the stock reference browser on the right. Clicking a stock tile loads
        // its prompt into the generate panel beside it.
        <>
          <div
            className={cn(
              "relative flex w-[252px] min-h-0 shrink-0 flex-col",
              !sharedFeatures && genFold.open && "border-r border-border"
            )}
          >
            <ClosePanelButton onClose={() => setTab(null)} />
            {tab === "image" ? (
              <ImageGenPanel projectId={projectId} />
            ) : (
              <GenerateVideoPanel projectId={projectId} />
            )}
            {!sharedFeatures && !genFold.open && genFold.knob}
          </div>
          {/* Video browses wider: 16:9 clip tiles need the room. A shared view
              shows only the project's own generations — no stock browsing. */}
          {!sharedFeatures && genFold.open && (
            <div
              className={cn(
                "relative flex min-h-0 shrink-0 flex-col",
                tab === "image" ? "w-[264px]" : "w-[340px]"
              )}
            >
              {tab === "image" ? <StockImagesPanel /> : <StockVideosPanel />}
              {genFold.knob}
            </div>
          )}
        </>
      ) : tab === "audio" ? (
        // Music is two columns like the generate tabs — the generator on the
        // left, the sample library on the right; Voice is a single column.
        <>
          <div
            className={cn(
              "relative flex w-[264px] min-h-0 shrink-0 flex-col",
              musicLibrary && musicFold.open && "border-r border-border"
            )}
          >
            <ClosePanelButton onClose={() => setTab(null)} />
            <AudioPanel
              projectId={projectId}
              importing={importing}
              sub={audioSub}
              onSub={setAudioSub}
            />
            {musicLibrary && !musicFold.open && musicFold.knob}
          </div>
          {musicLibrary && musicFold.open && (
            <div className="relative flex w-[340px] min-h-0 shrink-0 flex-col">
              <SampleLibrary projectId={projectId} />
              {musicFold.knob}
            </div>
          )}
        </>
      ) : (
        <div
          data-field-panel=""
          className="relative flex w-[264px] min-h-0 shrink-0 flex-col"
        >
          <ClosePanelButton onClose={() => setTab(null)} />
          {tab === "media" && (
            <MediaPanel projectId={projectId} onImport={onImport} importing={importing} />
          )}
          {tab === "elements" && <ElementsPanel projectId={projectId} />}
          {tab === "effects" && <EffectsPanel />}
          {tab === "transitions" && <TransitionsPanel />}
          {tab === "subtitles" && <SubtitlesPanel />}
          {tab === "publish" && <PublishPanel />}
        </div>
      )}
        </div>
      )}
    </div>
  );
}

type DragProps = Pick<
  React.HTMLAttributes<HTMLElement>,
  "onDragEnter" | "onDragOver" | "onDragLeave" | "onDrop"
>;

/** Narrow a whole-panel drop zone to the drags it can take: OS files, plus the
 * refs `takesRef` accepts. Without this a card dragged out of the panel — on
 * its way to the timeline — would light the panel it came from. */
function forDrags(props: DragProps, takesRef: (ref: AssetRef) => boolean): DragProps {
  const ok = (e: React.DragEvent) => {
    if (Array.from(e.dataTransfer.types).includes("Files")) return true;
    const ref = draggingRef();
    return !!ref && takesRef(ref);
  };
  return {
    onDragEnter: (e) => {
      if (ok(e)) props.onDragEnter?.(e);
    },
    onDragOver: (e) => {
      if (ok(e)) props.onDragOver?.(e);
    },
    onDragLeave: (e) => {
      if (ok(e)) props.onDragLeave?.(e);
    },
    onDrop: (e) => {
      if (ok(e)) props.onDrop?.(e);
    },
  };
}

/** Floats over the first column's header row, whatever panel owns it; a solid
 * face keeps it legible where the column scrolls beneath it. Same action as
 * clicking the active rail tile. */
function ClosePanelButton({ onClose }: { onClose: () => void }) {
  const t = useTranslations("media.sidePanel");
  return (
    <button
      type="button"
      aria-label={t("closePanel")}
      title={t("closePanel")}
      className="absolute top-2.5 right-2.5 z-10 grid size-7 place-items-center rounded-md bg-card text-muted-foreground transition-colors hover:bg-muted hover:text-foreground"
      onClick={onClose}
    >
      <X className="size-4" />
    </button>
  );
}

/** One library column's fold: the remembered open flag plus its edge knob.
 * Render the knob inside the library column while open (it folds the column
 * away), and inside the column left of it while folded (it brings the library
 * back). The host column must be `relative`. */
function useLibraryFold(key: string) {
  const [open, setOpen] = useLocalPref<boolean>(key, true, (v) => typeof v === "boolean");
  return {
    open,
    setOpen,
    knob: <LibraryKnob open={open} onToggle={() => setOpen(!open)} />,
  };
}

/** The fold's handle: a thin pill floating over the canvas at the vertical
 * middle, a small gap right of the panel border. The hit target is wider than
 * the pill so it stays easy to grab. */
function LibraryKnob({ open, onToggle }: { open: boolean; onToggle: () => void }) {
  const t = useTranslations("media.sidePanel");
  return (
    <button
      type="button"
      aria-label={open ? t("hideLibrary") : t("showLibrary")}
      title={open ? t("hideLibrary") : t("showLibrary")}
      className="group absolute top-1/2 -right-[16px] z-20 flex h-16 w-4 -translate-y-1/2 items-center justify-center outline-none"
      onClick={onToggle}
    >
      <span className="h-9 w-[5px] rounded-full bg-muted-foreground/35 transition-colors group-hover:bg-muted-foreground/70" />
    </button>
  );
}

/** The rail tile's corner status, one look for every tab: a blue count of
 * arrivals that finished while the tab was closed, else a spinner while the
 * tab owns work still in flight. */
function TileStatus({ count, busy }: { count: number; busy: boolean }) {
  if (count > 0)
    return (
      <span className="absolute -top-1 -right-1 grid h-[15px] min-w-[15px] place-items-center rounded-full bg-[#0a84ff] px-1 text-[9px] leading-none font-semibold text-white tabular-nums ring-2 ring-card">
        {count}
      </span>
    );
  if (busy)
    return (
      <span className="absolute -top-1 -right-1 grid size-[15px] place-items-center rounded-full bg-card ring-2 ring-card">
        <Loader2 className="size-3 animate-spin text-primary" />
      </span>
    );
  return null;
}

/** A file size in megabytes with one decimal, in the page's number style:
 * 12582912 bytes → "12.0" (the message adds the unit). */
function megabytes(format: ReturnType<typeof useFormatter>, bytes: number): string {
  return format.number(bytes / (1024 * 1024), { minimumFractionDigits: 1, maximumFractionDigits: 1 });
}

function PanelHead({ title }: { title: string }) {
  return (
    <div className="flex h-12 shrink-0 items-center pr-2.5 pl-4">
      <span className="text-sm font-semibold tracking-tight">{title}</span>
    </div>
  );
}

/** Fresh-arrival ring for an export row that landed while the tab was closed. */
function ExportPulse({ file }: { file: string }) {
  const pulse = useGenPulse("media", file);
  return pulse ? <div aria-hidden className={genPulseOverlay} /> : null;
}

/** An export's first frame. A master the browser cannot decode — ProRes in a
 * MOV — shows as a film badge in its place. */
function ExportThumb({
  src,
  onPlayable,
  onUnplayable,
}: {
  src: string;
  onPlayable: () => void;
  onUnplayable: () => void;
}) {
  const [playable, setPlayable] = useState(true);
  if (!playable) {
    return (
      <span className="flex h-11 w-[25px] shrink-0 items-center justify-center rounded-[4px] bg-muted text-muted-foreground">
        <Film className="size-3" />
      </span>
    );
  }
  return (
    <video crossOrigin={MEDIA_CORS}
      muted
      playsInline
      preload="metadata"
      src={src}
      onLoadedMetadata={onPlayable}
      onError={() => {
        setPlayable(false);
        onUnplayable();
      }}
      className="h-11 w-[25px] shrink-0 rounded-[4px] bg-black object-cover"
    />
  );
}

/** An export still being worked on, in the Exports list: spinner, live
 * progress, and a cancel that stops it. This is the project's record of the
 * work, so an export hidden from the dock still has its row and its cancel
 * here. One row for both kinds of work — a job the engine or the render worker
 * owns, and a render this tab is doing itself, which is how a cloud or browser
 * project exports and which carries its progress on its own local row. */
function ExportingRow({ row, settling = false }: { row: ExportRow; settling?: boolean }) {
  const t = useTranslations("media.exports");
  const { status } = row.data;
  const running = !settling && (status === "running" || status === "rendering");
  const cancelable = !settling && exportCancelable(row);
  const startedAt = row.kind === "job" ? row.data.startedAt ?? null : row.data.createdAt;
  const elapsed = useElapsed(running ? startedAt : null);
  const progress = row.kind === "job" ? row.data.progress : (row.data.progress ?? 0);
  const pct = Math.round(progress * 100);
  return (
    <div className="relative flex w-full items-center gap-2.5 overflow-hidden rounded-lg border border-border p-1.5">
      <div className="grid h-11 w-[25px] shrink-0 place-items-center rounded-[4px] bg-muted">
        <Loader2 className="size-3.5 animate-spin text-primary" />
      </div>
      <span className="min-w-0 flex-1">
        <span className="block truncate text-[11.5px] font-medium">{t("exporting")}</span>
        <span className="block text-[10.5px] text-muted-foreground tabular-nums">
          {settling
            ? t("finishing")
            : running
              ? elapsed
                ? t("progressElapsed", { pct, elapsed })
                : t("progress", { pct })
              : status === "preparing"
                ? t("preparing")
                : t("queued")}
        </span>
      </span>
      {cancelable && (
        <Button
          variant="ghost"
          size="xs"
          className="shrink-0 text-muted-foreground hover:text-destructive"
          onClick={() => useExports.getState().cancel(row.data.id)}
        >
          {t("cancel")}
        </Button>
      )}
      {running && (
        <div className="absolute inset-x-0 bottom-0 h-0.5 bg-secondary">
          <div
            className="h-full bg-primary transition-[width] duration-300"
            style={{ width: `${pct}%` }}
          />
        </div>
      )}
    </div>
  );
}

/** The Media tab: Project Files is this project's own imports and exports;
 * Library is the shared cross-project shelf. */
function MediaPanel({
  projectId,
  onImport,
  importing,
}: {
  projectId: string;
  onImport: (files: FileList | File[], opts?: { mediaOnly?: boolean; folderId?: string }) => void;
  importing: boolean;
}) {
  const t = useTranslations("media.mediaPanel");
  // A shared view shows only the project's own files — the Library is the
  // viewer's cross-project shelf, so the toggle drops and a plain head stays.
  const sharedFeatures = useEditor((s) => s.sharedFeatures);
  const [sub, setSub] = useLocalPref<"project" | "library">(
    "cut-media-subtab",
    "project",
    (v) => v === "project" || v === "library"
  );
  const view = sharedFeatures ? "project" : sub;
  // A revealed card may sit on the other sub-tab; bring its side on screen.
  useRevealEffect((ref) => {
    if (ref.folder?.scope === "project") setSub("project");
    else if (ref.folder?.scope === "library") setSub("library");
    else if (ref.scope === "project") setSub("project");
    else if (ref.scope === "library") setSub("library");
  });
  return (
    <>
      {sharedFeatures ? (
        <PanelHead title={t("media")} />
      ) : (
        /* PanelHead's height, so the side panel's floating close button lands
           on the toggle's centerline; the right padding keeps clear of it. */
        <div className="flex h-12 shrink-0 items-center pr-12 pl-3.5">
          <SubTabs
            tabs={[
              { id: "project", label: t("projectFiles") },
              { id: "library", label: t("library") },
            ]}
            value={view}
            onChange={setSub}
          />
        </div>
      )}
      {view === "project" ? (
        <ProjectFilesPanel
          // Which folder is open is remembered per project and read once, at
          // mount, so the panel starts fresh when another project opens.
          key={projectId}
          projectId={projectId}
          onImport={onImport}
          importing={importing}
        />
      ) : (
        <LibraryPanel projectId={projectId} onImport={onImport} />
      )}
    </>
  );
}

function ProjectFilesPanel({
  projectId,
  onImport,
  importing,
}: {
  projectId: string;
  onImport: (files: FileList | File[], opts?: { mediaOnly?: boolean; folderId?: string }) => void;
  importing: boolean;
}) {
  const t = useTranslations("media.projectFiles");
  const te = useTranslations("media.exports");
  const { pickLabel, foldersGoNote } = usePickWords();
  const format = useFormatter();
  const caps = useCutCaps();
  // Only user-imported media lives here; anything Cut created (recordings, AI
  // generations, voiceovers, freeze frames, stock adds) is tagged with an
  // `origin` and stays where it was made.
  // Fonts are project assets (their bytes live in media/) but they belong to
  // the text inspector's font menu, never the Media grid.
  const assets = useEditor((s) => s.assets).filter((a) => a.origin == null && !isLinkedAssetType(a.type));
  // The panel's folders, plus which one is open; the grid shows the open
  // folder's files, or the unfiled ones at the root.
  const folders = useEditor((s) => s.mediaFolders);
  // Folders are the project's own, so which one is open is remembered under
  // the project's own key: opening a second project leaves the first one's
  // place standing.
  const [storedFolder, setOpenFolder] = useLocalPref<string | null>(
    `cut-media-folder:${projectId}`,
    null,
    (v) => v === null || typeof v === "string"
  );
  // A remembered folder may have been deleted since — here or on another
  // machine. Once the doc is in, an id no folder answers for reads as the
  // root, without writing that back over what is remembered.
  const projectLoaded = useEditor((s) => s.loaded);
  const openFolder =
    storedFolder !== null && projectLoaded && !folders.some((f) => f.id === storedFolder)
      ? null
      : storedFolder;
  useRevealEffect((ref) => {
    if (ref.folder?.scope === "project" && ref.folder.projectId === projectId) setOpenFolder(ref.folder.folderId);
  });
  const shown = assets.filter((a) => (a.folderId ?? null) === openFolder);
  const readOnly = useEditor((s) => s.readOnly);
  // The shelf's folders join the pick at the root, while the project takes
  // changes; a shared view's folders only open.
  const shelfFolders = openFolder === null ? folders : [];
  const order = [
    ...(readOnly ? [] : shelfFolders).map((f) => folderSelId(f.id)),
    ...shown.map((a) => a.id),
  ];
  // Which tiles are picked, so a sweep or a ⇧-click can hand the timeline a
  // run of media in one drag. Anything that leaves the grid leaves the pick.
  const { picked, setPicked, pick } = useTilePicks(order);
  // Built once for the whole grid; each card hands the same array on. The
  // folders in the pick stay on the shelf: nothing drags them.
  const pickedIds = splitPick(picked).items;
  // The name field of a folder being made: [] from the empty-space menu, the
  // picked ids when the selection menu starts one — those file into the
  // folder the moment its name is committed.
  const [creatingIds, setCreatingIds] = useState<string[] | null>(null);
  // The folder whose name field is open, when the right-click menu opened it.
  const [renamingFolder, setRenamingFolder] = useState<string | null>(null);
  // The right-click menu at the cursor: `ids` carries the selection it acts
  // on, empty over empty space (just "New folder").
  const ctx = useSelectionMenu({ picked, setPicked, shown: order });
  // A delete that would also take timeline clips, or a folder with files in
  // it, waits on this confirm; unused media and an empty folder go without
  // one. The ids are the pick's, folders and files alike.
  const [deletingIds, setDeletingIds] = useState<string[] | null>(null);
  const deletingSet = splitPick(deletingIds ?? []);
  const deletingFolders = folders.filter((f) => deletingSet.folders.includes(f.id));
  const deletingFiles = assets.filter((a) => deletingSet.items.includes(a.id));
  const deletingHeld = assets.filter(
    (a) => !!a.folderId && deletingSet.folders.includes(a.folderId)
  ).length;
  const templates = useEditor((s) => s.templates);
  const exportOpen = useEditor((s) => s.exportOpen);
  // A render that finishes in the background (dialog closed) drops a new file in
  // the exports folder; re-read the list when it lands so it shows without a
  // manual refresh.
  // Refetch the finished-file list whenever a settled export job for this
  // project enters or leaves the feed. The trigger is the joined id list, so a
  // render landing on the same poll that drops a dismissed card still reads as
  // a change — a settled-job count stays equal through that swap and left the
  // new file off the shelf.
  const exportsSettled = useExports(
    (s) =>
      s.jobs
        .filter((j) => j.projectId === projectId && (j.status === "done" || j.status === "error"))
        .map((j) => j.id)
        .sort()
        .join()
  );
  // This project's exports still being worked on, assembled the way the dock
  // assembles every project's. A cloud or browser project renders in the tab,
  // and that render carries its progress on a local row; the engine's feed
  // alone showed nothing at all while it ran.
  const exporting = useExportRows(projectId).filter(exportInFlight);
  // The whole panel takes drops: OS files import into this project and stay off
  // the timeline, and a project asset made elsewhere (a generation, a
  // recording) dropped here moves into Media. It lights up for both.
  const { active: dropActive, attachTarget, targetProps } = useAssetDrop(
    (ref) => {
      // Filed straight into the open folder, so the drop lands where the eye is.
      if (ref.scope === "project")
        useEditor.getState().updateAsset(ref.id, {
          origin: undefined,
          chatId: undefined,
          folderId: openFolder ?? undefined,
        });
    },
    readOnly
      ? undefined
      : (files) => onImport(files, { mediaOnly: true, folderId: openFolder ?? undefined })
  );
  const inputRef = useRef<HTMLInputElement>(null);
  const [exports, setExports] = useState<ExportItem[]>([]);
  // Rows that just left the in-flight set. The file they produced is on disk
  // before the list below has re-read the folder, so they stay on screen as
  // "Finishing…" until that read lands; otherwise the section empties for a
  // beat and pops back with the new file.
  const [settling, setSettling] = useState<ExportRow[]>([]);
  const lastExporting = useRef<ExportRow[]>([]);
  const [preview, setPreview] = useState<ExportItem | null>(null);
  // Exports this browser cannot decode — a ProRes master — have no post
  // preview to open; their row shows a badge and says what they are.
  const [unplayable, setUnplayable] = useState<Set<string>>(() => new Set());
  const [deletingExport, setDeletingExport] = useState<ExportItem | null>(null);

  // Whatever is being worked on right now. When the last of it drops out — a
  // job settling, a tab-side render finishing — the folder has a new file in
  // it, so this is the second trigger for the re-read below. It covers the
  // paths the job feed alone misses: a render this tab did itself never passes
  // through a queued engine job.
  const exportingKey = exporting
    .map((r) => r.data.id)
    .sort()
    .join();

  // Refresh the list on open, when the export dialog closes, and when a
  // background render settles (done/error) or finishes in this tab.
  useEffect(() => {
    const gone = lastExporting.current.filter(
      (r) => r.data.projectId === projectId && !exporting.some((x) => x.data.id === r.data.id)
    );
    lastExporting.current = exporting;
    if (gone.length > 0) setSettling((s) => [...s, ...gone]);
    if (exportOpen) return;
    let alive = true;
    void apiFetch(`/api/cut/projects/${projectId}/exports`)
      .then((r) => (r.ok ? (r.json() as Promise<ExportItem[]>) : []))
      .catch(() => [] as ExportItem[])
      .then((list) => {
        if (!alive) return;
        setExports(list);
        setSettling([]);
      });
    return () => {
      alive = false;
    };
    // The trigger keys stand in for `exporting`, whose array identity changes
    // on every poll tick.
    // eslint-disable-next-line react-hooks/exhaustive-deps
  }, [projectId, exportOpen, exportsSettled, exportingKey]);

  const removeExport = async () => {
    const it = deletingExport;
    if (!it) return;
    setDeletingExport(null);
    try {
      await deleteExport(projectId, it.file);
    } catch {
      // Fall through and re-read the folder so the list mirrors disk truth
      // (a failed delete stays visible rather than reappearing later).
    }
    const list = await apiFetch(`/api/cut/projects/${projectId}/exports`)
      .then((r) => (r.ok ? (r.json() as Promise<ExportItem[]>) : []))
      .catch(() => [] as ExportItem[]);
    setExports(list);
    if (preview && !list.some((e) => e.file === preview.file)) setPreview(null);
  };

  // Delete a pick, folders and files. A folder takes every file in it with
  // it: unused media and an empty folder go straight away; media on the
  // timeline, or a folder with files in it, waits on the confirm below,
  // which names what goes.
  const removeMany = (ids: string[]) => {
    const s = useEditor.getState();
    const { folders: goneFolders, items } = splitPick(ids);
    const held = s.assets.filter((a) => !!a.folderId && goneFolders.includes(a.folderId));
    const gone = new Set([...items, ...held.map((a) => a.id)]);
    const uses = assetClipUses(s, gone);
    if (uses > 0 || held.length > 0) setDeletingIds(ids);
    else deleteNow(ids);
  };
  const deleteNow = (ids: string[]) => {
    const s = useEditor.getState();
    const { folders: goneFolders, items } = splitPick(ids);
    for (const id of goneFolders) s.removeMediaFolder(id);
    for (const id of items) s.removeAsset(id);
  };

  // Right-click: over a card, the selection menu (the card joins the pick if
  // it wasn't in it); over empty panel space at the root, the New-folder menu.
  const onPanelContextMenu = (e: React.MouseEvent) => {
    if (readOnly || ctx.onContextMenu(e) || openFolder !== null) return;
    e.preventDefault();
    ctx.openAt(e, []);
  };

  return (
    <div
      ref={attachTarget}
      {...forDrags(
        targetProps,
        // Only media made elsewhere — a generation, a recording — moves in here;
        // the panel's own cards are already Media.
        (ref) =>
          ref.scope === "project" &&
          useEditor.getState().assets.find((a) => a.id === ref.id)?.origin != null
      )}
      className={cn(
        "flex min-h-0 flex-1 flex-col",
        dropActive &&
          "rounded-xl bg-[#0a84ff]/5 outline-2 outline-dashed outline-offset-[-4px] outline-[#0a84ff]/60"
      )}
      onContextMenu={onPanelContextMenu}
    >
      {/* An export in flight spins on the Media rail tile, not here. */}
      {!readOnly && (
        <div className="px-3.5 pb-3">
          <Button variant="outline" className="w-full" onClick={() => inputRef.current?.click()}>
            <Upload data-icon="inline-start" /> {t("upload")}
          </Button>
          <input
            ref={inputRef}
            type="file"
            accept={`${MEDIA_ACCEPT},${linkedAccept()}`}
            multiple
            hidden
            onChange={(e) => {
              // Upload stocks Project Files only; dropping on the canvas places.
              if (e.target.files?.length)
                onImport(e.target.files, { mediaOnly: true, folderId: openFolder ?? undefined });
              e.target.value = "";
            }}
          />
        </div>
      )}

      {openFolder !== null && (
        <div className="flex h-9 shrink-0 items-center px-2 pb-1.5">
          <FolderCrumb
            className="text-sm"
            root={t("root")}
            onRename={!readOnly ? (id, name) => useEditor.getState().renameMediaFolder(id, name) : undefined}
            trail={[
              { id: openFolder, name: folders.find((f) => f.id === openFolder)?.name ?? t("folder") },
            ]}
            mime={MEDIA_MOVE_MIME}
            onGo={() => setOpenFolder(null)}
            onDrop={(ids) => useEditor.getState().moveAssetsToMediaFolder(ids, null)}
          />
        </div>
      )}
      {/* The shelf scrolls with the grid, so one sweep reaches both. */}
      <ScrollArea className="min-h-0 flex-1" contentClassName="pt-1 pb-3.5">
        {openFolder === null && (
          <div className="shrink-0 px-3.5">
            <FolderShelf
              rows
              folders={readOnly ? folders.map((f) => ({ ...f, locked: true })) : folders}
              mime={MEDIA_MOVE_MIME}
              referenceOf={projectId ? (f) => projectFolderRef(f, projectId) : undefined}
              picked={picked}
              onPick={(e, id) => pick(e, folderSelId(id), order)}
              renaming={renamingFolder}
              onRenamingChange={setRenamingFolder}
              statOf={(id) => ({ count: assets.filter((a) => a.folderId === id).length })}
              onOpen={(id) => setOpenFolder(id)}
              onCreate={(name) => {
                useEditor.getState().addMediaFolder(name, creatingIds ?? undefined);
              }}
              onRename={(id, name) => useEditor.getState().renameMediaFolder(id, name)}
              // A folder in a pick with others takes the pick; alone, itself.
              onDelete={(id) =>
                removeMany(
                  picked.has(folderSelId(id)) && picked.size > 1 ? [...picked] : [folderSelId(id)]
                )
              }
              onDropIds={(ids, fid) => useEditor.getState().moveAssetsToMediaFolder(ids, fid)}
              onDropFiles={
                readOnly
                  ? undefined
                  : (files, fid) => onImport(files, { mediaOnly: true, folderId: fid })
              }
              onRefDrop={(ref, fid) => {
                // Media made elsewhere — a generation, a recording, a timeline
                // clip's asset — dropped on a folder tile joins Media filed there.
                if (ref.scope !== "project") return;
                useEditor.getState().updateAsset(ref.id, {
                  origin: undefined,
                  chatId: undefined,
                  folderId: fid,
                });
              }}
              creating={creatingIds !== null}
              onCreatingChange={(c) => {
                if (!c) setCreatingIds(null);
              }}
            />
          </div>
        )}

        {openFolder === null && templates.length > 0 && (
          <div className="grid grid-cols-2 gap-2.5 px-3.5 pb-3">
            {templates.map((tpl) => (
              <TemplateCard
                key={tpl.id}
                tile="fill"
                template={tpl}
                mediaSrc={(f) => mediaUrl(projectId, f)}
                drag={{ scope: "project", template: tpl }}
                addTitle={t("addToTimeline")}
                onAdd={() => void addProjectTemplateToTimeline(projectId, tpl)}
                onRename={(name) => useEditor.getState().renameTemplate(tpl.id, name)}
                onDelete={() => useEditor.getState().removeTemplate(tpl.id)}
                onRefDrop={(r) => {
                  if (r.scope === "project") useEditor.getState().addAssetToTemplate(tpl.id, r.id);
                }}
                extraMenu={
                  <DropdownMenuItem onClick={() => void saveTemplate(projectId, tpl)}>
                    <FolderPlus /> {t("addToLibrary")}
                  </DropdownMenuItem>
                }
              />
            ))}
          </div>
        )}
        {order.length === 0 && !importing ? (
          openFolder !== null ? (
            <div className="px-3.5 py-6 text-center text-xs text-muted-foreground">
              {t("emptyFolder")}
            </div>
          ) : assets.length === 0 && folders.length === 0 ? (
            <div className="px-2 py-7 text-center text-xs leading-relaxed text-balance text-muted-foreground">
              <div className="mb-3 flex justify-center gap-3.5">
                <Film className="size-5" />
                <Music className="size-5" />
              </div>
              {t("empty")}
            </div>
          ) : null
        ) : (
          <Marquee
            scope="self"
            rootClassName="relative px-3.5"
            className="grid grid-cols-2 content-start gap-2.5"
            selected={picked}
            setSelected={setPicked}
          >
            {shown.map((a) => (
              <AssetCard
                key={a.id}
                asset={a}
                projectId={projectId}
                selected={picked.has(a.id)}
                onSelect={(e) => pick(e, a.id, order)}
                dragGroup={pickedIds}
                onDragLanded={() => setPicked(new Set())}
              />
            ))}
            {importing && (
              <div className="flex aspect-square flex-col items-center justify-center gap-2 rounded-lg border border-dashed border-input text-[11px] text-muted-foreground">
                <Loader2 className="size-4 animate-spin" />
                <span>
                  {t("importing")} <LiveElapsed />
                </span>
              </div>
            )}
          </Marquee>
        )}

        {openFolder === null && exports.length + exporting.length + settling.length > 0 && (
          <div className="mt-5 px-3.5">
            <div className="mb-2 text-[13px] font-semibold tracking-tight">{te("title")}</div>
            <div className="flex flex-col gap-1.5">
              {exporting.map((row) => (
                <ExportingRow key={row.data.id} row={row} />
              ))}
              {settling
                .filter((row) => !exporting.some((x) => x.data.id === row.data.id))
                .map((row) => (
                  <ExportingRow key={row.data.id} row={row} settling />
                ))}
              {exports.map((it) => (
                <div
                  key={it.file}
                  className="export-row group relative flex w-full items-center gap-2.5 overflow-hidden rounded-lg border border-border p-1.5 transition-colors hover:border-input hover:bg-muted/50"
                >
                  <ExportPulse file={it.file} />
                  {isStemsName(it.file) ? (
                  // A stems zip has no picture to preview; it downloads.
                  <div className="flex min-w-0 flex-1 items-center gap-2.5">
                    <span className="flex h-11 w-[25px] shrink-0 items-center justify-center rounded-[4px] bg-muted text-muted-foreground">
                      <Music className="size-3" />
                    </span>
                    <span className="min-w-0 flex-1">
                      <span className="block truncate text-[11.5px] font-medium">{it.file}</span>
                      <span className="block text-[10.5px] text-muted-foreground">
                        {te("stemsMeta", { size: megabytes(format, it.size) })}
                      </span>
                    </span>
                  </div>
                  ) : (
                  <button
                    type="button"
                    className="flex min-w-0 flex-1 items-center gap-2.5 text-left"
                    title={unplayable.has(it.file) ? te("masterFile") : te("previewAsPost")}
                    onClick={() => !unplayable.has(it.file) && setPreview(it)}
                  >
                    <ExportThumb
                      // A re-export under the same name is a new file; the key
                      // lets it try to play again.
                      key={`${it.file}:${it.mtime}`}
                      src={`${exportFileUrl(projectId, it)}#t=0.1`}
                      onPlayable={() =>
                        setUnplayable((u) => {
                          if (!u.has(it.file)) return u;
                          const next = new Set(u);
                          next.delete(it.file);
                          return next;
                        })
                      }
                      onUnplayable={() => setUnplayable((u) => new Set(u).add(it.file))}
                    />
                    <span className="min-w-0 flex-1">
                      <span className="block truncate text-[11.5px] font-medium">
                        {format.dateTime(new Date(it.mtime), {
                          month: "short",
                          day: "numeric",
                          hour: "numeric",
                          minute: "2-digit",
                        })}
                      </span>
                      <span className="block text-[10.5px] text-muted-foreground">
                        {te("fileMeta", { size: megabytes(format, it.size), container: containerOfName(it.file).label })}
                      </span>
                    </span>
                  </button>
                  )}
                  <div className="flex shrink-0 items-center gap-0.5 pr-0.5 opacity-0 transition-opacity group-hover:opacity-100">
                    {caps.revealInFinder ? (
                      <Button
                        variant="ghost"
                        size="icon-xs"
                        aria-label={te("showInFinder")}
                        title={te("showInFinder")}
                        onClick={() => void revealExport(projectId, it.file).catch(() => {})}
                      >
                        <FolderOpen />
                      </Button>
                    ) : (
                      <Button
                        variant="ghost"
                        size="icon-xs"
                        aria-label={te("downloadExport")}
                        title={te("download")}
                        onClick={() => downloadProjectExport(projectId, it)}
                      >
                        <Download />
                      </Button>
                    )}
                    <Button
                      variant="ghost"
                      size="icon-xs"
                      aria-label={te("deleteExport")}
                      title={te("deleteExport")}
                      className="text-muted-foreground hover:text-destructive"
                      onClick={() => setDeletingExport(it)}
                    >
                      <Trash2 />
                    </Button>
                  </div>
                </div>
              ))}
            </div>
          </div>
        )}
      </ScrollArea>
      {preview && (
        <PlatformPreviewDialog
          projectId={projectId}
          item={preview}
          onClose={() => setPreview(null)}
        />
      )}

      <AlertDialog open={!!deletingExport} onOpenChange={(o) => !o && setDeletingExport(null)}>
        <AlertDialogContent>
          <AlertDialogHeader>
            <AlertDialogTitle>{te("deleteTitle")}</AlertDialogTitle>
            <AlertDialogDescription>{te("deleteDescription")}</AlertDialogDescription>
          </AlertDialogHeader>
          <AlertDialogFooter>
            <AlertDialogCancel>{te("cancel")}</AlertDialogCancel>
            <AlertDialogAction
              className="bg-destructive/10 text-destructive hover:bg-destructive/20"
              onClick={(e) => {
                e.preventDefault();
                void removeExport();
              }}
            >
              {te("delete")}
            </AlertDialogAction>
          </AlertDialogFooter>
        </AlertDialogContent>
      </AlertDialog>

      <SelectionMenu menu={ctx.menu} onClose={ctx.close}>
        {ctx.menu?.ids.length === 0 ? (
          <DropdownMenuItem onClick={() => setCreatingIds([])}>
            <FolderPlus /> {t("newFolder")}
          </DropdownMenuItem>
        ) : ctx.menu && splitPick(ctx.menu.ids).folders.length === 1 && ctx.menu.ids.length === 1 ? (
          // A menu over one folder offers the folder's own actions.
          <FolderMenuItems
            onRename={() => setRenamingFolder(splitPick(ctx.menu!.ids).folders[0])}
            onDelete={() => removeMany(ctx.menu!.ids)}
          />
        ) : (
          <>
            {/* Folders file into nothing here, so a pick holding one makes
                no new folder. */}
            {ctx.menu && splitPick(ctx.menu.ids).folders.length === 0 && (
              <>
                <DropdownMenuItem
                  onClick={() => {
                    // The name field opens on the root shelf; the picked ids
                    // file into the folder when the name is committed.
                    setCreatingIds(ctx.menu!.ids);
                    setOpenFolder(null);
                  }}
                >
                  <FolderPlus /> {t("newFolder")}
                </DropdownMenuItem>
                <DropdownMenuSeparator />
              </>
            )}
            <DropdownMenuItem variant="destructive" onClick={() => removeMany(ctx.menu!.ids)}>
              <Trash2 /> {t("delete")}
            </DropdownMenuItem>
          </>
        )}
      </SelectionMenu>

      <DeleteConfirm
        open={deletingIds !== null}
        title={
          deletingFolders.length === 0 && deletingFiles.length === 1
            ? t("removeOneTitle")
            : t("removeManyTitle", { label: pickLabel(deletingFolders, deletingFiles, "file", deletingHeld) })
        }
        description={`${foldersGoNote(deletingFolders.length, deletingHeld)}${t("clipsRemovedToo")}`}
        action={t("remove")}
        onClose={() => setDeletingIds(null)}
        onConfirm={() => {
          deleteNow(deletingIds ?? []);
          setDeletingIds(null);
        }}
      />
    </div>
  );
}

/** The tile's upload state. The clip is already usable, so this stays out of
 * the way: a line across the bottom of the tile while the bytes go out, and a
 * message only if they don't arrive. */
function UploadState({ asset }: { asset: MediaAsset }) {
  const t = useTranslations("media.uploadState");
  const upload = asset.upload;
  if (!upload) return null;
  if (upload.error) {
    return (
      <div className="absolute inset-x-0 bottom-0 flex items-center gap-1.5 bg-black/70 px-1.5 py-1 text-[10px] text-white">
        <span className="min-w-0 flex-1 truncate">{t("failed")}</span>
        <button
          type="button"
          className="shrink-0 font-medium underline underline-offset-2"
          onClick={(e) => {
            e.stopPropagation();
            retryUpload(asset.id);
          }}
        >
          {t("retry")}
        </button>
      </div>
    );
  }
  return (
    <span className="absolute inset-x-0 bottom-0 h-[3px] bg-black/25">
      <span
        className="block h-full bg-primary transition-[width] duration-150"
        style={{ width: `${Math.round(upload.progress * 100)}%` }}
      />
    </span>
  );
}

/** The line across the bottom of a ProRes tile while its preview proxy is
 * being made. The clip already plays, off the master, so this stays as quiet
 * as an upload's. */
function ProxyState({ asset }: { asset: MediaAsset }) {
  const job = useProxyJobs((s) => s.jobs[asset.id]);
  if (!job || job.kind !== "making") return null;
  return (
    <span className="absolute inset-x-0 bottom-0 h-[3px] bg-black/25">
      <span
        className="block h-full bg-primary transition-[width] duration-150"
        style={{ width: `${Math.round(job.progress * 100)}%` }}
      />
    </span>
  );
}

function AssetCard({
  asset,
  projectId,
  selected,
  onSelect,
  dragGroup,
  onDragLanded,
}: {
  asset: MediaAsset;
  projectId: string;
  selected?: boolean;
  /** Clicking the card picks it — plain replaces the selection, ⇧/⌘ adds to
   * it. A pick never places anything; the timeline gets media by drag or by
   * the card's "Add to timeline" menu item. */
  onSelect?: (e: React.MouseEvent) => void;
  /** Everything picked right now, so dragging one card drags them all. */
  dragGroup?: string[];
  /** A drop that landed leaves nothing to keep picked. */
  onDragLanded?: () => void;
}) {
  const t = useTranslations("media.assetCard");
  const locale = useLocale();
  const caps = useCutCaps();
  const [saved, setSaved] = useState(false);
  // Number of timeline items that would be cascade-deleted; null = no prompt.
  const [confirmUses, setConfirmUses] = useState<number | null>(null);
  // ⌘C over the card copies its mention token (`@v2`). A card inside the
  // current pick carries the whole set, the same rule its drag follows.
  const refs = () => {
    const all = useEditor.getState().assets;
    const ids = selected && dragGroup?.length ? dragGroup : [asset.id];
    return ids
      .map((id) => all.find((x) => x.id === id))
      .filter((x): x is MediaAsset => !!x)
      .map(refFromAsset);
  };
  // A media-heavy project would open every one of these connections at once;
  // the source waits until the tile has been scrolled near.
  const [tileRef, seen] = useInView<HTMLDivElement>();
  // The size pill only shows on hover, so the lookup waits for the first one.
  const [hovered, setHovered] = useState(false);
  const sizeBytes = useMediaFileSize(asset.url, hovered && !asset.upload);

  const add = () => useEditor.getState().addAssetAtPlayhead(asset.id);

  const saveToLibrary = async (e: React.MouseEvent) => {
    e.stopPropagation();
    try {
      await saveAssetToLibrary(projectId, asset);
      setSaved(true);
      setTimeout(() => setSaved(false), 1800);
    } catch {
      // Library write failed; nothing to roll back.
    }
  };

  const [renaming, setRenaming] = useState(false);
  const finishRename = (name?: string) => {
    setRenaming(false);
    if (name) useEditor.getState().renameAsset(asset.id, name);
  };

  const remove = () => {
    const s = useEditor.getState();
    const uses = assetClipUses(s, new Set([asset.id]));
    // Deleting an unused asset is harmless; only confirm when it would also
    // remove clips from the timeline.
    if (uses > 0) setConfirmUses(uses);
    else s.removeAsset(asset.id);
  };

  return (
    <>
    <MediaCardShell
      scope="project"
      id={asset.id}
      refs={refs}
      // A file still on its way up has nothing to show yet.
      view={asset.upload ? undefined : () => lightboxItemFromAsset(asset)}
      restTime={0.1}
      className="asset-card group flex flex-col gap-1.5 text-left"
      draggable={!renaming}
      onClick={onSelect}
      onDragStart={(e) => {
        setAssetDragData(e, asset.id, dragGroup);
        // The same selection as a folder-move payload, so a folder tile or
        // the crumb can take the drop; the ghost gathers the picked cards
        // into one stack under the cursor, counted.
        const ids =
          selected && dragGroup?.includes(asset.id)
            ? [asset.id, ...dragGroup.filter((x) => x !== asset.id)]
            : [asset.id];
        e.dataTransfer.setData(MEDIA_MOVE_MIME, JSON.stringify(ids));
        setObjectDragImage(e, ids.length, ids, onDragLanded);
      }}
      onHover={() => setHovered(true)}
    >
      {({ flash, videoRef }) => (
        <>
          <div
            ref={tileRef}
            data-drag-object
            className={cn(
              // A file looks the same in both themes, like the Library's.
              "light relative aspect-square overflow-hidden rounded-xl border border-page-border bg-muted bg-clip-padding shadow-sm transition-colors group-hover:border-page-input",
              (flash || selected) && PICKED_RING
            )}
          >
            {asset.type === "video" ? (
              // Native first frame as the poster — full-resolution, no blurry thumb.
              seen && (
                <video crossOrigin={MEDIA_CORS}
                  ref={videoRef}
                  src={`${asset.url}#t=0.1`}
                  poster={asset.thumbs?.[0]}
                  preload="metadata"
                  muted
                  loop
                  playsInline
                  className="size-full object-cover"
                />
              )
            ) : asset.type === "image" ? (
              // eslint-disable-next-line @next/next/no-img-element -- engine/static file, not Next-optimizable
              <img crossOrigin={MEDIA_CORS} src={asset.url} alt={asset.name} loading="lazy" className="size-full object-cover" />
            ) : asset.type === "lut" ? (
              // eslint-disable-next-line @next/next/no-img-element -- static icon
              <img src={LUT_FILE_ICON} alt={asset.name} className="size-full object-contain p-2" />
            ) : (
              <AudioCardFace
                url={asset.url}
                duration={asset.duration}
                peaks={asset.peaks}
              />
            )}
            {asset.type === "video" && (
              <span
                data-drag-omit
                className="absolute right-1 bottom-1 rounded-[5px] bg-black/65 px-1 py-px font-mono text-[9.5px] text-white tabular-nums"
              >
                {formatTime(asset.duration)}
              </span>
            )}
            {sizeBytes != null && (
              <span
                className={cn(
                  "absolute font-mono tabular-nums opacity-0 transition-opacity group-hover:opacity-100",
                  asset.type === "audio"
                    ? // Clear of the play circle, matching the face's duration pill.
                      "bottom-3 left-12 rounded-md bg-[#2b4e42] px-1.5 py-0.5 text-[10px] text-[#d6eddf]"
                    : "bottom-1 left-1 rounded-[5px] bg-black/65 px-1 py-px text-[9.5px] text-white"
                )}
              >
                {formatBytes(sizeBytes, locale)}
              </span>
            )}
            <CardActionsMenu
              icon={saved ? <Check className="size-3" /> : <Ellipsis className="size-3" />}
              className="absolute top-1 right-1 size-5 bg-black/45 hover:bg-black/65"
              onUse={add}
              onRename={() => setRenaming(true)}
              onDownload={() => downloadMedia(projectId, asset)}
              downloadDisabled={!!asset.upload}
              extra={
                <>
                  <DropdownMenuItem onClick={saveToLibrary} disabled={!!asset.upload}>
                    <FolderPlus /> {t("saveToLibrary")}
                  </DropdownMenuItem>
                  {caps.revealInFinder && (
                    <DropdownMenuItem
                      onClick={() => void revealMedia(projectId, asset.fileName).catch(() => {})}
                    >
                      <FolderOpen /> {t("showInFinder")}
                    </DropdownMenuItem>
                  )}
                </>
              }
              onDelete={() => remove()}
            />
            {asset.type === "audio" && renaming && (
              <RenameInput
                value={asset.name}
                className="absolute top-1.5 right-1.5 left-1.5 w-auto bg-background"
                onDone={finishRename}
              />
            )}
            {asset.type === "audio" && !renaming && (
              <CopyNameLabel
                name={asset.name}
                dark
                className="absolute top-1.5 left-1.5 max-w-[70%] px-2 py-1 text-[11px] font-medium text-white transition-[max-width] group-hover:max-w-[calc(100%-4.75rem)]"
              />
            )}
            {asset.upload && <UploadState asset={asset} />}
            {!asset.upload && <ProxyState asset={asset} />}
          </div>
          {asset.type !== "audio" &&
            (renaming ? (
              <RenameInput value={asset.name} className="text-[11px]" onDone={finishRename} />
            ) : (
              <CopyNameLabel name={asset.name} className="text-[11px] text-muted-foreground" />
            ))}
        </>
      )}
    </MediaCardShell>
    <AlertDialog open={confirmUses !== null} onOpenChange={(o) => !o && setConfirmUses(null)}>
      <AlertDialogContent aria-describedby={undefined}>
        <AlertDialogHeader>
          <AlertDialogTitle>{t("removeTitle", { name: asset.name })}</AlertDialogTitle>
        </AlertDialogHeader>
        <AlertDialogFooter>
          <AlertDialogCancel>{t("cancel")}</AlertDialogCancel>
          <AlertDialogAction
            className="bg-destructive/10 text-destructive hover:bg-destructive/20"
            onClick={(e) => {
              e.preventDefault();
              useEditor.getState().removeAsset(asset.id);
              setConfirmUses(null);
            }}
          >
            {t("remove")}
          </AlertDialogAction>
        </AlertDialogFooter>
      </AlertDialogContent>
    </AlertDialog>
    </>
  );
}

// The derived folder holding phone recordings in the editor's Library panel.
// Not a server folder: assets tagged origin "camera" file here by themselves,
// so phone footage is one click from any project.
const CAMERA_ROLL_FOLDER = "camera-roll";
/** A stable empty list, so the titling hook sees no work rather than a new
 * array on every render. */
const EMPTY_CLIPS: LibraryAsset[] = [];

function LibraryPanel({ projectId, onImport }: {
  projectId: string;
  onImport: (files: FileList | File[], opts?: { mediaOnly?: boolean; folderId?: string }) => void;
}) {
  const t = useTranslations("media.library");
  const { pickLabel, foldersGoNote, phoneGoNote } = usePickWords();
  const client = useQueryClient();
  // One cached listing serves every library surface (lib/queries.ts), and it
  // stays live while this panel is open: the shelf re-reads on a timer and
  // whenever the window comes back to the front, so a clip recorded on the
  // phone takes its place in the grid with nothing to reload.
  const library = useLibrary({ live: true });
  const engineUp = useLocalCompute();
  // A picker only offers what it can copy into the project, so a shelf that
  // isn't answering — the Mac's, with the app closed — is left out of it.
  const reachable = useCallback((r: Residency) => r !== "local" || engineUp, [engineUp]);
  // A shelf that answered — or failed outright, which the invitation covers.
  // The listing keeps retrying behind it, so a backend that comes back fills
  // the grid on its own.
  const loaded = library.data !== undefined || library.isError;
  const assets = (library.data?.assets ?? []).filter((a) => reachable(a.residency));
  const folders = (library.data?.folders ?? []).filter((f) => reachable(f.residency));
  // Saved text styles and sound presets ride the template rails but are not
  // templates: they belong to their inspectors, not this shelf.
  const templates = (library.data?.templates ?? []).filter(
    (t) => reachable(t.residency) && !isStylePresetTemplate(t) && !isSoundPresetTemplate(t) && !isGradePresetTemplate(t)
  );
  const listing: LibraryData = { assets, folders, templates };
  const patch = useCallback(
    (fn: (prev: LibraryData) => LibraryData) => patchLibrary(client, fn),
    [client]
  );
  const reload = useCallback(() => refetchLibrary(client), [client]);
  const [openFolder, setOpenFolder] = useLocalPref<string | null>(
    "cut-library-folder",
    null,
    (v) => v === null || typeof v === "string"
  );
  // What a delete is about to take: the pick when the card is in it, else
  // the one card. Null while nothing is being asked.
  const [deleting, setDeleting] = useState<LibraryDeleteSet | null>(null);
  // The folder whose name field is open, when the right-click menu opened it.
  const [renamingFolder, setRenamingFolder] = useState<string | null>(null);
  const arrivals = useLibraryImports((state) => state.items);
  const pending = arrivals.filter((item) => item.folderId === openFolder);

  // Where an asset shows: phone recordings gather in the derived Camera Roll
  // folder whatever their server folderId says.
  const folderOf = (a: LibraryAsset) =>
    a.origin === "camera" ? CAMERA_ROLL_FOLDER : (a.folderId ?? null);
  const cameraClips = assets.filter((a) => a.origin === "camera");
  const cameraCount = cameraClips.length;
  // Phone recordings name themselves off what is said in them. Only while the
  // Camera Roll folder is open — a panel showing anything else has no reason
  // to read those files.
  useClipTitles(openFolder === CAMERA_ROLL_FOLDER ? cameraClips : EMPTY_CLIPS, patch);

  // A remembered folder can vanish between sessions; drop back to the root.
  const knownFolder =
    folders.some((f) => f.id === openFolder) ||
    (openFolder === CAMERA_ROLL_FOLDER && cameraCount > 0);
  useEffect(() => {
    if (loaded && openFolder !== null && !knownFolder) setOpenFolder(null);
  }, [loaded, knownFolder, openFolder, setOpenFolder]);

  // A revealed library asset may sit inside a folder — open it so the card is
  // on screen to scroll to and flash.
  useRevealEffect((ref) => {
    if (ref.folder?.scope === "library") { setOpenFolder(ref.folder.folderId); return; }
    if (ref.scope !== "library") return;
    const a = assets.find((x) => x.id === ref.id);
    if (a) setOpenFolder(folderOf(a));
  });

  const removeTemplate = async (r: Residency, id: string) => {
    patch((d) => ({ ...d, templates: d.templates.filter((t) => t.id !== id) }));
    await deleteTemplate(r, id).catch(() => void reload());
  };

  const commitTemplateRename = async (r: Residency, id: string, name: string) => {
    patch((d) => ({
      ...d,
      templates: d.templates.map((t) => (t.id === id ? { ...t, name } : t)),
    }));
    await renameTemplate(r, id, name).catch(() => void reload());
  };

  // Delete a set. A folder takes everything under it — the folders filed
  // there, however deep, and every asset and template they hold — the way
  // the shelf deletes it; an asset filed in one of those needs no delete of
  // its own. A camera clip filed there stays in Camera Roll, unfiled.
  const remove = async (set: LibraryDeleteSet) => {
    setDeleting(null);
    const takes = folderDeleteTakes(listing, set.folders);
    const inTree = (x: { folderId?: string | null }) => !!x.folderId && takes.tree.has(x.folderId);
    const goneAssets = set.items.filter((a) => !inTree(a));
    const gone = new Set([...goneAssets, ...takes.assets, ...takes.templates].map((a) => a.id));
    forgetLinkedCopies([...goneAssets, ...takes.assets]);
    patch((d) => ({
      ...d,
      folders: d.folders.filter((f) => !takes.tree.has(f.id)),
      assets: d.assets
        .filter((a) => !gone.has(a.id))
        .map((a) => (inTree(a) ? { ...a, folderId: null } : a)),
      templates: d.templates.filter((t) => !gone.has(t.id)),
    }));
    setPicked(new Set());
    try {
      await Promise.all([
        ...goneAssets.map((a) => deleteFromLibrary(a.residency, a.id)),
        ...set.folders.map((f) => deleteLibraryFolder(f.residency, f.id)),
      ]);
    } catch {
      // Server delete failed; pull a fresh list so the UI stays truthful.
      void reload();
    }
  };
  // How many items the folders hold between them, however deep — what the
  // confirm counts beside them: what shows inside them, so a camera clip
  // filed there, which shows in Camera Roll, is left out.
  const heldBy = (fs: LibraryFolder[]) => {
    const takes = folderDeleteTakes(listing, fs);
    return takes.assets.length + takes.templates.length;
  };
  // How many of the items a delete takes were synced from the phone, which
  // takes them off the phone too.
  const phoneSynced = (set: LibraryDeleteSet) =>
    [...set.items, ...folderDeleteTakes(listing, set.folders).assets].filter((a) => !!a.origin)
      .length;

  // Every item carries its shelf; a folder belongs to one, so an item only
  // files into a folder on the same shelf.
  const shelfOf = (id: string): Residency | null =>
    assets.find((a) => a.id === id)?.residency ??
    templates.find((t) => t.id === id)?.residency ??
    null;

  const move = async (id: string, folderId: string | null) => {
    if (folderId === CAMERA_ROLL_FOLDER) return; // derived; only the phone files here
    const residency = shelfOf(id);
    if (!residency) return;
    if (folderId && folders.find((f) => f.id === folderId)?.residency !== residency) return;
    patch((d) => ({
      ...d,
      assets: d.assets.map((a) => (a.id === id ? { ...a, folderId } : a)),
      templates: d.templates.map((t) => (t.id === id ? { ...t, folderId } : t)),
    }));
    await moveLibraryItem(residency, id, folderId).catch(() => void reload());
  };

  // New items land on the open folder's shelf, or on the bound backend at the
  // root — the same rule the full-page library follows.
  const shelfForNew = (folderId: string | null) =>
    (folderId ? folders.find((f) => f.id === folderId)?.residency : null) ?? activeResidency();

  const upload = (files: FileList | File[], into: string | null = openFolder) => {
    const folderId = into === CAMERA_ROLL_FOLDER ? null : into;
    const residency = shelfForNew(folderId);
    if (!reachable(residency)) return Promise.resolve();
    return importLibraryFiles(files, { residency, folderId }, client);
  };

  // The whole panel takes drops: OS files upload to the shared library (into
  // the open folder), and project media dropped here is saved to it.
  const { active: dropActive, attachTarget, targetProps } = useAssetDrop(
    (ref) => {
      if (ref.scope !== "project") return;
      const asset = useEditor.getState().assets.find((a) => a.id === ref.id);
      if (!asset) return;
      void saveAssetToLibrary(projectId, asset)
        .then(() => void reload())
        .catch(() => {});
    },
    (files) => void upload(files)
  );

  const all = assets;
  const shown = all.filter((a) => folderOf(a) === openFolder);

  const renameFolder = async (id: string, name: string) => {
    const r = folders.find((f) => f.id === id)?.residency;
    if (!r || !reachable(r)) return;
    patch((d) => ({ ...d, folders: d.folders.map((f) => f.id === id ? { ...f, name } : f) }));
    await updateLibraryFolder(r, id, { name }).catch(() => void reload());
  };
  const bothShelves = availableResidencies().length > 1;
  const shownTemplates = templates.filter((t) => (t.folderId ?? null) === openFolder);
  // The shelf at this level: the folders filed here. At the top the Camera
  // Roll tile leads it while the phone has synced anything; the roll itself
  // holds no folders.
  const cameraRoll: LibraryFolder & { locked?: boolean } = {
    id: CAMERA_ROLL_FOLDER,
    name: t("cameraRoll"),
    createdAt: 0,
    residency: "cloud",
    locked: true,
  };
  const shelfFolders: (LibraryFolder & { locked?: boolean })[] =
    openFolder === null
      ? [...(cameraCount > 0 ? [cameraRoll] : []), ...childrenOf(folders, null)]
      : openFolder === CAMERA_ROLL_FOLDER
        ? []
        : childrenOf(folders, openFolder);
  const trail =
    openFolder === CAMERA_ROLL_FOLDER ? [cameraRoll] : folderTrail(folders, openFolder);

  // Which cards are picked, so a sweep or a ⇧-click hands the timeline (or a
  // folder tile) a run of clips in one drag. Only what the open folder shows
  // can be picked — the shelf's folders and the grid's cards — so walking into
  // another folder leaves its selection behind.
  const order = [
    ...shelfFolders.filter((f) => !f.locked).map((f) => folderSelId(f.id)),
    ...shown.map((a) => a.id),
  ];
  const { picked, setPicked, pick } = useTilePicks(order);
  // Built once for the whole grid; each card hands the same array on.
  const pickedRun = shown.filter((a) => picked.has(a.id));
  const pickSet: LibraryDeleteSet = {
    folders: shelfFolders.filter((f) => !f.locked && picked.has(folderSelId(f.id))),
    items: pickedRun,
  };
  // A card inside the pick carries the whole set, the rule its drag and ⌘C
  // follow.
  const setOf = (a: LibraryAsset): LibraryDeleteSet =>
    picked.has(a.id) ? pickSet : { folders: [], items: [a] };
  const ctx = useSelectionMenu({ picked, setPicked, shown: order });
  // What the open right-click menu acts on.
  const ctxSet: LibraryDeleteSet = ctx.menu
    ? {
        folders: shelfFolders.filter(
          (f) => !f.locked && ctx.menu!.ids.includes(folderSelId(f.id))
        ),
        items: shown.filter((a) => ctx.menu!.ids.includes(a.id)),
      }
    : { folders: [], items: [] };
  // A menu over one folder offers the folder's own actions.
  const ctxFolder =
    ctxSet.folders.length === 1 && ctxSet.items.length === 0 ? ctxSet.folders[0] : null;
  // What the open confirm counts: the items the folders hold, and everything
  // going in all.
  const deletingHeld = deleting ? heldBy(deleting.folders) : 0;
  const deletingTotal = (deleting?.items.length ?? 0) + deletingHeld;

  // Let a clip be dragged onto a folder tile to file it (alongside the timeline
  // drag payload the card already sets), the folders in the pick riding under
  // their own MIME. The ghost is the card's picture, and it hands over to the
  // timeline's segment preview.
  const onCardDragExtra = (e: React.DragEvent, a: LibraryAsset) => {
    const { folders: pickedFolders, items } = picked.has(a.id)
      ? splitPick(picked)
      : { folders: [], items: [a.id] };
    e.dataTransfer.setData(LIBRARY_MOVE_MIME, JSON.stringify(items));
    if (pickedFolders.length)
      e.dataTransfer.setData(LIBRARY_FOLDER_MOVE_MIME, JSON.stringify(pickedFolders));
    e.dataTransfer.effectAllowed = "copyMove";
    const ids = [a.id, ...items.filter((id) => id !== a.id), ...pickedFolders.map(folderSelId)];
    setObjectDragImage(e, ids.length, ids, () => setPicked(new Set()));
  };

  // File folders under a folder (or out to the root, parentId null). A folder
  // files only beside itself: under a folder on its own shelf, never under
  // itself or anything inside it.
  const moveFolders = async (ids: string[], parentId: string | null) => {
    if (parentId === CAMERA_ROLL_FOLDER) return;
    const target = parentId ? folders.find((f) => f.id === parentId)?.residency : null;
    if (parentId && !target) return;
    const moving = folders.filter(
      (f) =>
        ids.includes(f.id) &&
        (!target || f.residency === target) &&
        parentOf(f) !== parentId &&
        !folderWithin(folders, parentId, f.id)
    );
    if (moving.length === 0) return;
    const idset = new Set(moving.map((f) => f.id));
    patch((d) => ({
      ...d,
      folders: d.folders.map((f) => (idset.has(f.id) ? { ...f, parentId } : f)),
    }));
    setPicked(new Set());
    await Promise.all(
      moving.map((f) => updateLibraryFolder(f.residency, f.id, { parentId }))
    ).catch(() => void reload());
  };

  return (
    <div
      ref={attachTarget}
      {...forDrags(targetProps, (ref) => ref.scope === "project")}
      className={cn(
        "flex min-h-0 flex-1 flex-col",
        dropActive &&
          "rounded-xl bg-[#0a84ff]/5 outline-2 outline-dashed outline-offset-[-4px] outline-[#0a84ff]/60"
      )}
      onContextMenu={ctx.onContextMenu}
    >
      {!loaded ? (
        <div className="grid flex-1 place-items-center text-muted-foreground">
          <Loader2 className="size-4 animate-spin" />
        </div>
      ) : (
        /* Crumb, folder rows, templates and cards scroll as one list, so a
           long shelf and a full folder both reach their end. */
        <ScrollArea className="min-h-0 flex-1" contentClassName="pt-1 pb-3.5">
          {openFolder !== null && (
            <div className="flex h-9 shrink-0 items-center px-2 pb-1.5">
              <FolderCrumb
                className="text-sm"
                root={t("root")}
                trail={trail}
                onRename={openFolder !== CAMERA_ROLL_FOLDER ? renameFolder : undefined}
                mime={LIBRARY_MOVE_MIME}
                folderMime={LIBRARY_FOLDER_MOVE_MIME}
                onGo={setOpenFolder}
                onDrop={(ids, id) => ids.forEach((fid) => void move(fid, id))}
                onDropFolders={(ids, id) => void moveFolders(ids, id)}
              />
            </div>
          )}
          <div className="shrink-0 px-3.5">
            <FolderShelf
              rows
              folders={shelfFolders}
              referenceOf={(f) => libraryFolderRef(f, folders)}
              mime={LIBRARY_MOVE_MIME}
              folderMime={LIBRARY_FOLDER_MOVE_MIME}
              statOf={(id) => ({
                count:
                  all.filter((a) => folderOf(a) === id).length +
                  templates.filter((t) => (t.folderId ?? null) === id).length +
                  childrenOf(folders, id).length,
              })}
              badgeOf={(id) => {
                const r = folders.find((f) => f.id === id)?.residency;
                return bothShelves && r ? <ShelfBadge residency={r} /> : null;
              }}
              picked={picked}
              onPick={(e, id) => pick(e, folderSelId(id), order)}
              renaming={renamingFolder}
              onRenamingChange={setRenamingFolder}
              onOpen={(id) => setOpenFolder(id)}
              onRename={renameFolder}
              // A folder in a pick with others takes the pick to the
              // confirm; alone, itself.
              onDelete={(id) => {
                const f = folders.find((x) => x.id === id);
                if (!f) return;
                const size = pickSet.folders.length + pickSet.items.length;
                if (picked.has(folderSelId(id)) && size > 1) setDeleting(pickSet);
                else setDeleting({ folders: [f], items: [] });
              }}
              onDropIds={(ids, fid) => ids.forEach((id) => void move(id, fid))}
              onDropFolders={(ids, fid) => void moveFolders(ids, fid)}
              onRefDrop={(ref, fid) => {
                // Project media dropped on a folder tile (a Media card or a
                // timeline clip): save it to the library, filed in that folder.
                // The copy lands on the project's own shelf, so a folder on the
                // other one can't take it.
                if (ref.scope !== "project") return;
                if (folders.find((f) => f.id === fid)?.residency !== activeResidency()) return;
                const asset = useEditor.getState().assets.find((a) => a.id === ref.id);
                if (!asset) return;
                void saveAssetToLibrary(projectId, asset)
                  .then((saved) => moveLibraryItem(saved.residency, saved.id, fid))
                  .then(() => void reload())
                  .catch(() => {});
              }}
            />
          </div>
          {shownTemplates.length > 0 && (
            <div className="shrink-0 px-3.5 pb-3">
              <div className="grid grid-cols-2 gap-2.5">
                {shownTemplates.map((tpl) => (
                  <TemplateCard
                    key={tpl.id}
                    tile="fill"
                    template={tpl}
                    mediaSrc={(f) => libraryMediaUrl(f, tpl.residency)}
                    drag={{ scope: "library", template: tpl }}
                    onDragStartExtra={(e) => {
                      e.dataTransfer.setData(LIBRARY_MOVE_MIME, JSON.stringify([tpl.id]));
                      e.dataTransfer.effectAllowed = "copyMove";
                    }}
                    addTitle={t("addToProject")}
                    onAdd={() => void addTemplateToProject(projectId, tpl)}
                    onRename={(name) => void commitTemplateRename(tpl.residency, tpl.id, name)}
                    onDelete={() => void removeTemplate(tpl.residency, tpl.id)}
                    onRefDrop={(r) => {
                      if (r.scope !== "project") return;
                      const asset = useEditor.getState().assets.find((a) => a.id === r.id);
                      if (!asset) return;
                      void addAssetToLibraryTemplate(projectId, tpl, asset)
                        .then((updated) =>
                          patch((d) => ({
                            ...d,
                            templates: d.templates.map((x) =>
                              x.id === updated.id ? updated : x
                            ),
                          }))
                        )
                        .catch(() => void reload());
                    }}
                  />
                ))}
              </div>
            </div>
          )}
          {order.length === 0 && pending.length === 0 ? (
            // At the root, filed-away assets, folders, and templates all count as
            // content — the invitation is only for a truly empty library.
            openFolder !== null ? (
              shownTemplates.length === 0 ? (
                <div className="px-3.5 py-6 text-center text-xs text-muted-foreground">{t("emptyFolder")}</div>
              ) : null
            ) : all.length === 0 && folders.length === 0 && templates.length === 0 ? (
              <div className="text-balance px-3.5 py-6 text-center text-xs text-muted-foreground">
                {t("empty")}
              </div>
            ) : null
          ) : (
              <Marquee
                scope="self"
                rootClassName="relative px-3.5"
                className="grid grid-cols-2 content-start gap-2.5"
                selected={picked}
                setSelected={setPicked}
              >
                {shown.map((a) => (
                  <LibraryCard
                    key={a.id}
                    asset={a}
                    mention
                    selected={picked.has(a.id)}
                    onClick={(e) => pick(e, a.id, order)}
                    dragGroup={pickedRun}
                    // A linked item is used from its own menu; there is nothing to place.
                    onUse={
                      isLinkedAssetType(a.type) ? undefined : () => void addLibraryAssetToProject(projectId, a)
                    }
                    onDelete={() => setDeleting(setOf(a))}
                    onRename={(name) => renameInLibrary(client, a, name)}
                    onDragStartExtra={(e) => onCardDragExtra(e, a)}
                  />
                ))}
                {pending.map((item) => (
                  <LibraryImportCard key={item.id} item={item}
                    onRetry={() => void item.run()}
                    onDismiss={() => dismissLibraryImport(item.id)}
                    onUse={item.file ? () => onImport([item.file!], { mediaOnly: true }) : undefined}
                  />
                ))}
              </Marquee>
          )}
        </ScrollArea>
      )}

      <SelectionMenu menu={ctx.menu} onClose={ctx.close}>
        {ctxFolder ? (
          <FolderMenuItems
            onRename={() => setRenamingFolder(ctxFolder.id)}
            onDelete={() => setDeleting({ folders: [ctxFolder], items: [] })}
          />
        ) : (
          <DropdownMenuItem variant="destructive" onClick={() => setDeleting(ctxSet)}>
            <Trash2 /> {t("delete")}
          </DropdownMenuItem>
        )}
      </SelectionMenu>

      <DeleteConfirm
        open={!!deleting}
        title={
          deleting ? t("deleteTitle", { label: pickLabel(deleting.folders, deleting.items, "item", deletingHeld) }) : ""
        }
        description={`${foldersGoNote(deleting?.folders.length ?? 0, deletingHeld)}${phoneGoNote(deleting ? phoneSynced(deleting) : 0, deletingTotal)}${t("keepCopy", { count: deletingTotal })}`}
        action={t("remove")}
        onClose={() => setDeleting(null)}
        onConfirm={() => deleting && void remove(deleting)}
      />
    </div>
  );
}

/** What a library delete is about to take: folders and assets, picked
 * together. */
type LibraryDeleteSet = { folders: LibraryFolder[]; items: LibraryAsset[] };

function CopyChip({ text, label }: { text: string; label: string }) {
  const t = useTranslations("media.publish");
  const [copied, setCopied] = useState(false);
  return (
    <button
      className="copy-chip inline-flex items-center gap-1 rounded-md px-1.5 py-0.5 text-[10.5px] font-medium text-muted-foreground transition-colors hover:bg-muted hover:text-foreground disabled:opacity-40"
      disabled={!text}
      title={label}
      onClick={() => {
        void navigator.clipboard.writeText(text).then(() => {
          setCopied(true);
          setTimeout(() => setCopied(false), 1500);
        });
      }}
    >
      {copied ? <Check className="size-3 text-emerald-600" /> : <Copy className="size-3" />}
      {copied ? t("copied") : t("copy")}
    </button>
  );
}

function PublishPanel() {
  const t = useTranslations("media.publish");
  const format = useFormatter();
  const readOnly = useEditor((s) => s.readOnly);
  const publish = useEditor((s) => s.publish);
  const setPublish = useEditor((s) => s.setPublish);
  const notes = useEditor((s) => s.notes);
  const setNotes = useEditor((s) => s.setNotes);
  const tagsLine = normalizeTags(publish.tags);
  const combined = [publish.caption.trim(), tagsLine].filter(Boolean).join("\n\n");
  const count = combined.length;
  const [copiedAll, setCopiedAll] = useState(false);

  return (
    <>
      <PanelHead title={t("title")} />
      <ScrollArea className="min-h-0" contentClassName="flex flex-col gap-4 px-3.5 pb-4">
        <div className="flex flex-col gap-1.5">
          <div className="flex items-center justify-between">
            <SectionTitle>{t("caption")}</SectionTitle>
            <CopyChip text={publish.caption.trim()} label={t("copyCaption")} />
          </div>
          <textarea
            className="publish-caption min-h-[110px] w-full resize-y rounded-lg border border-input bg-transparent px-2.5 py-2 text-[12.5px] leading-relaxed outline-none focus:border-ring"
            placeholder={t("captionPlaceholder")}
            value={publish.caption}
            readOnly={readOnly}
            onChange={(e) => setPublish({ caption: e.target.value })}
          />
        </div>

        <div className="flex flex-col gap-1.5">
          <div className="flex items-center justify-between">
            <SectionTitle>{t("tags")}</SectionTitle>
            <CopyChip text={tagsLine} label={t("copyTags")} />
          </div>
          <input
            className="publish-tags w-full rounded-lg border border-input bg-transparent px-2.5 py-2 text-[12.5px] outline-none focus:border-ring"
            placeholder={t("tagsPlaceholder")}
            value={publish.tags}
            readOnly={readOnly}
            onChange={(e) => setPublish({ tags: e.target.value })}
          />
          {tagsLine && (
            <div className="publish-tag-preview flex flex-wrap gap-1">
              {tagsLine.split(" ").map((tag) => (
                <span key={tag} className="rounded-md bg-muted px-1.5 py-0.5 font-mono text-[10.5px]">
                  {tag}
                </span>
              ))}
            </div>
          )}
          <p className="text-[11px] leading-relaxed text-muted-foreground">
            {t("tagsHint")}
          </p>
        </div>

        <div className="flex flex-col gap-1.5">
          <div className="flex items-center justify-between">
            <SectionTitle>{t("soundTitle")}</SectionTitle>
            <CopyChip text={publish.soundTitle.trim()} label={t("copySoundTitle")} />
          </div>
          <input
            className="publish-sound w-full rounded-lg border border-input bg-transparent px-2.5 py-2 text-[12.5px] outline-none focus:border-ring"
            placeholder={t("soundTitlePlaceholder")}
            value={publish.soundTitle}
            readOnly={readOnly}
            onChange={(e) => setPublish({ soundTitle: e.target.value })}
          />
        </div>

        <div className="flex flex-col gap-1.5 border-t border-border pt-4">
          <SectionTitle>{t("notes")}</SectionTitle>
          <label className="flex items-center justify-between gap-2 text-[12px] text-muted-foreground">
            {t("published")}
            <input
              type="date"
              className="notes-date rounded-lg border border-input bg-transparent px-2 py-1 text-[12px] outline-none focus:border-ring"
              value={notes.publishedAt}
              disabled={readOnly}
              onChange={(e) => setNotes({ publishedAt: e.target.value })}
            />
          </label>
          <textarea
            className="notes-links min-h-[54px] w-full resize-y rounded-lg border border-input bg-transparent px-2.5 py-2 font-mono text-[11.5px] leading-relaxed outline-none focus:border-ring"
            placeholder={t("linksPlaceholder")}
            value={notes.links.join("\n")}
            readOnly={readOnly}
            onChange={(e) => setNotes({ links: e.target.value.split("\n") })}
          />
          <textarea
            className="notes-text min-h-[70px] w-full resize-y rounded-lg border border-input bg-transparent px-2.5 py-2 text-[12.5px] leading-relaxed outline-none focus:border-ring"
            placeholder={t("notesPlaceholder")}
            value={notes.text}
            readOnly={readOnly}
            onChange={(e) => setNotes({ text: e.target.value })}
          />
        </div>

        <div className="mt-1 flex flex-col gap-2">
          <Button
            className="w-full"
            disabled={!combined}
            onClick={() => {
              void navigator.clipboard.writeText(combined).then(() => {
                setCopiedAll(true);
                setTimeout(() => setCopiedAll(false), 1500);
              });
            }}
          >
            {copiedAll ? (
              <>
                <Check data-icon="inline-start" /> {t("copied")}
              </>
            ) : (
              <>
                <Copy data-icon="inline-start" /> {t("copyAll")}
              </>
            )}
          </Button>
          <p
            className={cn(
              "publish-count text-right font-mono text-[11px] tabular-nums",
              count > CAPTION_LIMIT ? "font-semibold text-red-600" : "text-muted-foreground"
            )}
          >
            {t("count", { count: format.number(count), limit: format.number(CAPTION_LIMIT) })}
          </p>
        </div>
      </ScrollArea>
    </>
  );
}