Skip to content

Self-hosted, Self-Improving, Federated Everything App — dev management, agent orchestration, persistent mind, digital twin, second brain, and creative pipeline from a single dashboard over Tailscale to port the user into the OS

84.2 KB
Raw Blame
/**
 * LoRA Manager — install / browse / delete Civitai and HuggingFace LoRAs.
 *
 * Paste a Civitai or HuggingFace URL to download and install. Each LoRA card
 * shows the preview, base model (Flux.1 / Flux.2 / Z-Image / LTX / Other),
 * trigger words, recommended scale, and a "Test in Image Gen" / Video Gen
 * deep-link that preselects the LoRA on the generation page.
 */

import { useState, useEffect, useCallback, useRef } from 'react';
import { Link, useSearchParams } from 'react-router';
import { Trash2, Download, ExternalLink, Sparkles, AlertTriangle, KeyRound, Check, X, RefreshCw, Wand2, Search, Activity, PlayCircle, Package, Compass } from 'lucide-react';
import BrailleSpinner from '../components/BrailleSpinner';
import EmptyState from '../components/EmptyState';
import TabPills from '../components/ui/TabPills';
import PageSkeleton from '../components/ui/PageSkeleton';
import toast from '../components/ui/Toast';
import Modal from '../components/ui/Modal';
import DownloadPreflightConfirm from '../components/models/DownloadPreflightConfirm.jsx';
import Banner from '../components/ui/Banner';
import ConfirmButtonPair from '../components/ui/ConfirmButtonPair';
import ProgressBar from '../components/ui/ProgressBar';
import { FormField } from '../components/ui/FormField';
import { useConfirmDelete } from '../hooks/useConfirmDelete';
import useDownloadPreflightConfirm from '../hooks/useDownloadPreflightConfirm';
import { formatBytes, formatCount } from '../utils/formatters';
import { RUNNER_FAMILIES, VIDEO_LORA_FAMILIES, isVideoLoraFamily } from '../lib/runnerFamilies';
import { LORA_EFFECT_STATUSES, loraEffectDetail, loraEffectBadge } from '../lib/loraEffect';
import {
  listLorasFull,
  installLoraFromCivitai,
  previewLoraInstall,
  installLoraFromHuggingfaceStream,
  deleteLoraFull,
  getCivitaiAuth,
  setCivitaiAuth,
  clearCivitaiAuth,
  getCivitaiSuggestions,
  searchCivitaiLoras,
  searchVideoLoras,
  probeLoraEffect,
} from '../services/api';

const RUNNER_LABEL = {
  [RUNNER_FAMILIES.MFLUX]: 'Flux 1',
  [RUNNER_FAMILIES.FLUX2]: 'Flux 2',
  [RUNNER_FAMILIES.Z_IMAGE]: 'Z-Image',
  [RUNNER_FAMILIES.ERNIE]: 'ERNIE',
  [RUNNER_FAMILIES.HIDREAM]: 'HiDream',
  [RUNNER_FAMILIES.QWEN]: 'Qwen',
  [VIDEO_LORA_FAMILIES.LTX_VIDEO]: 'LTX-Video',
  [VIDEO_LORA_FAMILIES.MINIMAX_H3]: 'MiniMax H3',
};
const RUNNER_BADGE_CLASS = {
  [RUNNER_FAMILIES.MFLUX]: 'bg-port-accent/20 text-port-accent border-port-accent/30',
  [RUNNER_FAMILIES.FLUX2]: 'bg-purple-600/20 text-purple-300 border-purple-500/30',
  [RUNNER_FAMILIES.Z_IMAGE]: 'bg-emerald-600/20 text-emerald-300 border-emerald-500/30',
  [RUNNER_FAMILIES.ERNIE]: 'bg-amber-600/20 text-amber-300 border-amber-500/30',
  [RUNNER_FAMILIES.HIDREAM]: 'bg-rose-600/20 text-rose-300 border-rose-500/30',
  [RUNNER_FAMILIES.QWEN]: 'bg-sky-600/20 text-sky-300 border-sky-500/30',
  [VIDEO_LORA_FAMILIES.LTX_VIDEO]: 'bg-fuchsia-600/20 text-fuchsia-300 border-fuchsia-500/30',
  [VIDEO_LORA_FAMILIES.MINIMAX_H3]: 'bg-teal-600/20 text-teal-300 border-teal-500/30',
};

// Top-level view split (#7231). Discovery — curated picks, six per-family
// Civitai lists, the video catalog, and two live searches — used to render
// ABOVE the installed grid, so managing an already-installed adapter meant
// scrolling past thousands of pixels of recommendations that grow as results
// arrive. Installed is now its own view and the default one; discovery is one
// labeled click away. The chosen view lives in `?loraView` (not local state) so
// it survives reload and Back/Forward, per the URL-is-the-source-of-truth
// convention in `client/src/AGENTS.md`.
const VIEW_PARAM = 'loraView';
const VIEW_INSTALLED = 'installed';
const VIEW_DISCOVER = 'discover';
const DEFAULT_VIEW = VIEW_INSTALLED;
const VIEW_IDS = [VIEW_INSTALLED, VIEW_DISCOVER];
// `id="tab-<view>"` / `aria-controls="lorapanel-<view>"` pairing for TabPills.
const VIEW_PANEL_PREFIX = 'lorapanel';

// Image/Video filter applied to BOTH the suggestion panel and the installed
// list (see the user request: filter suggestions + installed by media type).
const MEDIA_FILTERS = [
  { id: 'all', label: 'All' },
  { id: 'image', label: 'Image' },
  { id: 'video', label: 'Video' },
];

// Stable identity for a suggestion's specific model+version — used for React
// keys, install-in-flight tracking, and "Load more" dedup. Curated cards pass
// a family-specific versionId that differs from the card's primary, so the key
// takes the two ids explicitly rather than a whole card.
const suggestionKey = (modelId, versionId) => `${modelId}-${versionId}`;
const cardKey = (card) => suggestionKey(card.modelId, card.versionId);
const hfCardKey = (card) => `${card.repo}:${card.file || ''}`;
const installedHfKey = (lora) => `${lora.huggingface?.repo || ''}:${lora.huggingface?.file || ''}`;

// Manual family choices when HF autodetection returns HF_UNKNOWN_FAMILY.
// Image families first — the previous LTX-only confirm silently mis-tagged
// Flux.2 Klein adapters (Alissonerdx/CharacterSheet) as video LoRAs.
const HF_FAMILY_OVERRIDES = [
  { family: RUNNER_FAMILIES.FLUX2, label: 'Flux 2' },
  { family: RUNNER_FAMILIES.MFLUX, label: 'Flux 1' },
  { family: RUNNER_FAMILIES.Z_IMAGE, label: 'Z-Image' },
  { family: RUNNER_FAMILIES.QWEN, label: 'Qwen' },
  { family: RUNNER_FAMILIES.ERNIE, label: 'ERNIE' },
  { family: RUNNER_FAMILIES.HIDREAM, label: 'HiDream' },
  { family: VIDEO_LORA_FAMILIES.LTX_VIDEO, label: 'LTX-Video' },
  { family: VIDEO_LORA_FAMILIES.MINIMAX_H3, label: 'MiniMax H3' },
];

// Integer download percent (0..100) from an SSE progress frame, or null when
// the frame carries no numeric ratio (server sent no Content-Length → the UI
// shows an indeterminate bar). Shared by the HF install form button, the
// progress bar, and the curated video quick-install button.
const pctOf = (progress) => (progress && typeof progress.progress === 'number' ? Math.round(progress.progress * 100) : null);

export default function Loras() {
  // Active view. An unknown/hand-edited `?loraView=` degrades to Installed
  // rather than rendering a blank panel.
  const [searchParams, setSearchParams] = useSearchParams();
  const rawView = searchParams.get(VIEW_PARAM);
  const view = VIEW_IDS.includes(rawView) ? rawView : DEFAULT_VIEW;
  // A PUSH, not `replace` — switching views is a navigation the user expects
  // Back to undo (the acceptance criterion), unlike the in-view media filter.
  // Writing the default drops the param so a pristine URL stays clean.
  const setView = useCallback((next) => {
    setSearchParams((prev) => {
      const params = new URLSearchParams(prev);
      if (!next || next === DEFAULT_VIEW) params.delete(VIEW_PARAM);
      else params.set(VIEW_PARAM, next);
      return params;
    });
  }, [setSearchParams]);
  const [loras, setLoras] = useState([]);
  const [loading, setLoading] = useState(true);
  const [error, setError] = useState(null);
  const [installUrl, setInstallUrl] = useState('');
  const [installing, setInstalling] = useState(false);
  // HuggingFace LoRA import (Flux.2 Klein image adapters, fal / Lightricks
  // LTX video LoRAs) — separate from the Civitai installer above.
  const [hfUrl, setHfUrl] = useState('');
  const [hfInstalling, setHfInstalling] = useState(false);
  // Byte-level download progress for the in-flight HF install (form OR curated
  // quick-install — only one runs at a time). `{ received, total, progress }`
  // where progress is 0..1, or null when the server had no Content-Length.
  const [hfProgress, setHfProgress] = useState(null);
  // When autodetection can't classify the repo (HF_UNKNOWN_FAMILY), hold the
  // URL here to render an inline family picker — the API supports an explicit
  // family override, so a valid LoRA with an unrecognizable id shouldn't
  // dead-end at an error toast (or get force-tagged as LTX-Video).
  const [hfFamilyPrompt, setHfFamilyPrompt] = useState(null);
  const [deleting, setDeleting] = useState(null);
  // Arms one installed card's delete at a time — a LoRA is a multi-gigabyte
  // file with no undo, so the trash icon only reveals an inline confirm pair
  // instead of deleting on the first click/tap (#3519).
  const deleteConfirm = useConfirmDelete();
  // Civitai auth — `auth` is `{ hasKey, source }`; `authPrompt` is set to a
  // pending install URL when a 401/403 redirects the user to the inline key
  // form. The form saves the key and retries the same install in one click
  // so users don't have to remember what they were installing.
  const [auth, setAuth] = useState({ hasKey: false, source: 'none' });
  const [authPrompt, setAuthPrompt] = useState(null);
  // suggestions: { runners: { mflux: [...], flux2: [...], 'z-image': [...] }, video: [...], fetchedAt }
  const [suggestions, setSuggestions] = useState(null);
  // Stays true until the first fetch settles — nothing is requested before the
  // Discover view is opened, so this reads as "no catalog result yet" and the
  // panel's first frame shows the loader instead of flashing empty sections.
  const [loadingSuggestions, setLoadingSuggestions] = useState(true);
  const [installingSuggestion, setInstallingSuggestion] = useState(null);
  // Name of the most recent successful install, cleared once the user acts on
  // it. Drives the Discover view's "View installed" hand-off so a finished
  // download doesn't leave the user hunting the catalog for its result.
  const [lastInstalled, setLastInstalled] = useState(null);
  const { confirm: downloadConfirm, request: requestDownloadConfirm, cancel: cancelDownloadConfirm, confirmRun: runDownloadConfirm } = useDownloadPreflightConfirm();
  // Repo+file key of the video suggestion currently installing. A single HF
  // repo can publish multiple versions that must remain independently selectable.
  const [installingVideoKey, setInstallingVideoKey] = useState(null);
  // Image/Video media-type filter for both panels. 'all' | 'image' | 'video'.
  const [mediaFilter, setMediaFilter] = useState('all');

  const refresh = useCallback(() => {
    setError(null);
    setLoading(true);
    // silent:true — the failure renders as a persistent inline error Banner;
    // the default toast would say the same thing a second time.
    listLorasFull({ silent: true })
      .then(setLoras)
      .catch((err) => setError(err?.message || 'Failed to load LoRAs'))
      .finally(() => setLoading(false));
  }, []);

  const refreshSuggestions = useCallback(({ force = false } = {}) => {
    setLoadingSuggestions(true);
    getCivitaiSuggestions({ force }, { silent: true })
      .then(setSuggestions)
      .catch((err) => toast.error(err?.message || 'Failed to load suggestions'))
      .finally(() => setLoadingSuggestions(false));
  }, []);

  useEffect(() => {
    let active = true;
    refresh();
    getCivitaiAuth().then((a) => { if (active) setAuth(a); }).catch(() => {});
    return () => { active = false; };
  }, [refresh]);

  // Discovery is fetched the first time its view is opened, not on mount —
  // the default Installed view never needs it, and a ref (not `suggestions`)
  // gates the fetch so a legitimately empty catalog response isn't re-requested
  // on every switch back.
  const suggestionsRequested = useRef(false);
  useEffect(() => {
    // Reaching Installed retires the install hand-off — however the user got
    // there (the tab, the banner's own button, or Back), the banner has done
    // its job and must not reappear on the next visit to Discover.
    if (view === VIEW_INSTALLED) setLastInstalled(null);
    if (view !== VIEW_DISCOVER || suggestionsRequested.current) return;
    suggestionsRequested.current = true;
    refreshSuggestions();
  }, [view, refreshSuggestions]);

  // silent:true so the auth-error path goes through the modal instead of a
  // one-shot toast the user can't act on. Shared by the initial install
  // submit and the post-key-save retry so both behave identically.
  //
  // A gated Civitai model can already fail with CIVITAI_AUTH at the PREVIEW
  // step (previewCivitaiInstall fetches the model metadata, which needs the
  // same key the download does) — before startCivitaiInstall ever runs. Catch
  // it here and route it into the existing key-entry prompt instead of
  // letting the hook's generic error land inside the preflight modal, which
  // has no path back to that prompt.
  const requestLoraDownload = useCallback((title, url, source, run, extra = {}) => requestDownloadConfirm({
    title,
    preview: () => previewLoraInstall({ url, source, ...extra, silent: true }).catch((err) => {
      if (source === 'civitai' && err?.code === 'CIVITAI_AUTH') {
        setAuthPrompt({ url, message: err.message || 'This LoRA needs an API key.' });
        // No confirm modal opens for a `handled` rejection, so nothing else
        // will clear a suggestion card's spinner for this attempt.
        setInstallingSuggestion(null);
        const handled = new Error(err.message);
        handled.handled = true;
        throw handled;
      }
      throw err;
    }),
    run,
  }), [requestDownloadConfirm]);

  // Dismissing the confirm modal without confirming ends a suggestion card's
  // install attempt before startCivitaiInstall/startVideoSuggestionInstall
  // ever run — clear its spinner here too, or it sticks until another card
  // is clicked. A no-op for every other caller of the shared modal.
  const handleCancelDownloadConfirm = useCallback(() => {
    cancelDownloadConfirm();
    setInstallingSuggestion(null);
  }, [cancelDownloadConfirm]);

  const startCivitaiInstall = useCallback(async (url) => {
    if (!url || installing) return;
    setInstalling(true);
    await installLoraFromCivitai({ url, silent: true })
      .then((sidecar) => {
        toast.success(`Installed ${sidecar.name}`);
        setLastInstalled(sidecar.name);
        setInstallUrl('');
        refresh();
      })
      .catch((err) => {
        // Early-access content is gated by Civitai membership, not by API
        // key — routing into the key-prompt modal would be misleading
        // because the user's key (saved or env) can't unlock it. Surface
        // the message (which already includes hours-remaining) as a toast.
        if (err?.code === 'CIVITAI_EARLY_ACCESS') {
          toast.error(err.message || 'LoRA is in Civitai early-access');
        } else if (err?.code === 'CIVITAI_AUTH') {
          setAuthPrompt({ url, message: err.message || 'This LoRA needs an API key.' });
        } else {
          toast.error(err?.message || 'Install failed');
        }
      })
      // Clears whichever suggestion card (if any) triggered this install —
      // a no-op for the manual-form submit, which never sets it.
      .finally(() => { setInstalling(false); setInstallingSuggestion(null); });
  }, [installing, refresh]);

  const performInstall = useCallback((url) => {
    if (!url || installing) return undefined;
    return requestLoraDownload('Install LoRA', url, 'civitai', () => startCivitaiInstall(url));
  }, [installing, requestLoraDownload, startCivitaiInstall]);

  const handleInstall = (e) => {
    e?.preventDefault?.();
    return performInstall(installUrl.trim());
  };

  // Install a LoRA from a HuggingFace repo. The family is auto-detected
  // server-side from the repo id/tags/filenames (Flux.2 Klein → flux2,
  // LTX-Video → ltx-video); HF_UNKNOWN_FAMILY surfaces as an inline picker
  // of image and video families rather than a dead-end toast.
  // Shared install runner: `family` is undefined for the first attempt
  // (server autodetects) and set to the override on the inline-confirm retry.
  const runHfInstall = useCallback(async (url, family) => {
    // Cross-guard against the curated video quick-install: both write the shared
    // hfProgress, so allowing them to overlap makes both progress readouts show
    // interleaved byte counts. Only one HF install runs at a time.
    if (!url || hfInstalling || installingVideoKey) return;
    setHfInstalling(true);
    setHfProgress(null);
    await installLoraFromHuggingfaceStream({ url, family, onProgress: setHfProgress })
      .then((sidecar) => {
        toast.success(`Installed ${sidecar.name}`);
        setLastInstalled(sidecar.name);
        setHfUrl('');
        setHfFamilyPrompt(null);
        refresh();
      })
      .catch((err) => {
        // Autodetection failed but the install is otherwise valid — offer an
        // inline family picker rather than toast a dead-end or force LTX.
        // (Skip when we already tried with an explicit override.)
        if (err?.code === 'HF_UNKNOWN_FAMILY' && !family) {
          // The picker is the ENTIRE feedback for this branch — it deliberately
          // raises no toast. It renders inside the Discover panel, and the
          // install keeps running after the user leaves that tab, so surface
          // the tab too or the failure is completely silent.
          setView(VIEW_DISCOVER);
          setHfFamilyPrompt(url);
        } else {
          toast.error(err?.message || 'HuggingFace install failed');
        }
      })
      .finally(() => { setHfInstalling(false); setHfProgress(null); });
  }, [hfInstalling, installingVideoKey, refresh]);

  const handleHfInstall = useCallback((e) => {
    e?.preventDefault?.();
    setHfFamilyPrompt(null);
    const url = hfUrl.trim();
    if (!url) return undefined;
    return requestLoraDownload('Install HuggingFace LoRA', url, 'huggingface', () => runHfInstall(url, undefined));
  }, [hfUrl, runHfInstall, requestLoraDownload]);

  // Quick-install a curated video LoRA suggestion. Routes through the HF
  // installer (not the Civitai one) with the card's known family. Tracks the
  // in-flight repo in its own state because the Civitai `installingSuggestion`
  // key is modelId/versionId-based — video installs have neither.
  const startVideoSuggestionInstall = useCallback(async (card) => {
    // Cross-guard against the form install (see runHfInstall) — one HF install
    // at a time so they don't clobber the shared hfProgress.
    if (!card?.installUrl || installingVideoKey || hfInstalling) return;
    setInstallingVideoKey(hfCardKey(card));
    setHfProgress(null);
    await installLoraFromHuggingfaceStream({
      url: card.installUrl,
      family: card.runnerFamily,
      file: card.file,
      onProgress: setHfProgress,
    })
      .then((sidecar) => {
        toast.success(`Installed ${sidecar.name}`);
        setLastInstalled(sidecar.name);
        refresh();
      })
      .catch((err) => toast.error(err?.message || 'HuggingFace install failed'))
      .finally(() => { setInstallingVideoKey(null); setHfProgress(null); });
  }, [installingVideoKey, hfInstalling, refresh]);

  // Card carries its own family/file, so the preview forwards them and shows
  // the exact file "Quick install" is about to fetch — not a re-guess.
  const installVideoSuggestion = useCallback((card) => {
    if (!card?.installUrl || installingVideoKey || hfInstalling) return undefined;
    return requestLoraDownload(
      'Install video LoRA',
      card.installUrl,
      'huggingface',
      () => startVideoSuggestionInstall(card),
      { family: card.runnerFamily, file: card.file },
    );
  }, [installingVideoKey, hfInstalling, requestLoraDownload, startVideoSuggestionInstall]);

  // The measurement lives in the LIST, not in the card. The Installed section
  // swaps between LoraGrid and InstalledGroups when the media filter changes,
  // which unmounts every card — a badge held only in card state would vanish
  // right after the user ran the check. The server has cached the same report in
  // the sidecar, so this just keeps the page consistent without a refetch.
  const handleMeasured = useCallback((filename, effectReport) => {
    setLoras((prev) => prev.map((l) => (l.filename === filename ? { ...l, effectReport } : l)));
  }, []);

  const handleDelete = async (filename) => {
    setDeleting(filename);
    await deleteLoraFull(filename, { silent: true })
      .then(() => {
        toast.success('LoRA deleted');
        setLoras((prev) => prev.filter((l) => l.filename !== filename));
      })
      .catch((err) => toast.error(err?.message || 'Delete failed'))
      .finally(() => setDeleting(null));
  };

  // Installed list narrowed to the active media filter. Video families
  // (ltx-video) are video; everything else (image families + legacy null) is
  // image.
  const visibleLoras = loras.filter((l) => {
    if (mediaFilter === 'image') return !isVideoLoraFamily(l.runnerFamily);
    if (mediaFilter === 'video') return isVideoLoraFamily(l.runnerFamily);
    return true;
  });

  // Download percent for the in-flight HF install (drives the form button label
  // and progress bar), or null when the total is unknown.
  const hfPct = pctOf(hfProgress);

  return (
    <div className="space-y-6">
      {/* An h2, not an h1: this page is the LoRAs tab under the Models section
          (#4728), whose PageHeader already owns the page's h1. */}
      <div>
        <h2 className="text-2xl font-bold text-white mb-1">LoRA Manager</h2>
        <p className="text-sm text-gray-400">
          Install LoRA fine-tunes from Civitai or HuggingFace and apply them to your Image Gen and Video Gen renders.
        </p>
      </div>

      {/* View switch + primary action, directly under the heading so both are
          above the fold on a phone. Discovery lives behind the second tab, so
          no amount of catalog growth can push the installed list down. */}
      <div className="flex flex-wrap items-center justify-between gap-3">
        <TabPills
          tabs={[
            { id: VIEW_INSTALLED, label: 'Installed', icon: Package, count: loras.length },
            { id: VIEW_DISCOVER, label: 'Discover / install', icon: Compass },
          ]}
          activeTab={view}
          onChange={setView}
          variant="pills"
          size="sm"
          ariaLabel="LoRA view"
          controlsIdPrefix={VIEW_PANEL_PREFIX}
        />
        <div className="flex max-w-full flex-wrap items-center gap-2 sm:gap-3">
          <MediaFilter value={mediaFilter} onChange={setMediaFilter} />
          {view === VIEW_INSTALLED && (
            <button
              type="button"
              onClick={() => setView(VIEW_DISCOVER)}
              className="min-h-11 shrink-0 bg-port-accent text-white px-3 rounded text-sm font-medium hover:bg-port-accent/90 flex items-center justify-center gap-2"
            >
              <Download size={14} aria-hidden="true" />
              Install LoRA
            </button>
          )}
        </div>
      </div>

      {/* A HuggingFace download keeps running when the user leaves Discover,
          but every readout of it (the form's bar, the card's percent) lives in
          that panel — so a multi-gigabyte transfer would silently have no
          indicator anywhere. Mirror it here, and only while Discover is closed,
          so the two are never on screen at once. */}
      {view !== VIEW_DISCOVER && (hfInstalling || installingVideoKey) && (
        <div className="bg-port-card border border-port-border rounded-lg p-3">
          <HfDownloadProgress progress={hfProgress} />
        </div>
      )}

      {view === VIEW_DISCOVER && (
        <div id={`${VIEW_PANEL_PREFIX}-${VIEW_DISCOVER}`} role="tabpanel" aria-labelledby={`tab-${VIEW_DISCOVER}`} className="space-y-6">
          {lastInstalled && (
            <Banner
              tone="success"
              size="md"
              icon={Check}
              align="center"
              actions={(
                <button
                  type="button"
                  onClick={() => setView(VIEW_INSTALLED)}
                  className="text-xs font-medium px-3 py-1 rounded bg-port-success/20 hover:bg-port-success/30 whitespace-nowrap"
                >
                  View installed
                </button>
              )}
            >
              Installed {lastInstalled}.
            </Banner>
          )}

          <form
            onSubmit={handleInstall}
            className="bg-port-card border border-port-border rounded-lg p-4 space-y-3"
          >
            <div className="flex items-center justify-between">
              <div className="flex items-center gap-2 text-sm font-medium text-gray-300">
                <Download size={16} />
                <span>Install from Civitai</span>
              </div>
              <CivitaiKeyBadge auth={auth} onManage={() => setAuthPrompt({ url: null, message: '' })} />
            </div>
            {/* No `autoFocus`: this form used to mount once with the page, so
                focusing it was a landing convenience. It now remounts on every
                switch into Discover, where it would steal focus from the tab
                the user just activated and swallow their next arrow key. */}
            <div className="flex flex-wrap gap-2 sm:flex-nowrap">
              <input
                type="text"
                value={installUrl}
                onChange={(e) => setInstallUrl(e.target.value)}
                aria-label="Civitai model URL"
                placeholder="https://civitai.com/models/2600698/realstagram"
                className="min-h-11 min-w-0 flex-1 bg-port-bg border border-port-border rounded px-3 py-2 text-sm text-gray-200 placeholder:text-gray-600"
                disabled={installing}
              />
              <button
                type="submit"
                disabled={installing || !installUrl.trim()}
                className="min-h-11 bg-port-accent text-white px-4 rounded text-sm font-medium hover:bg-port-accent/90 disabled:opacity-50 disabled:cursor-not-allowed flex items-center justify-center gap-2"
              >
                {installing ? 'Downloading…' : 'Install'}
              </button>
            </div>
            <p className="text-xs text-gray-500">
              Paste any <code className="bg-port-bg px-1 rounded">civitai.com</code> /{' '}
              <code className="bg-port-bg px-1 rounded">civitai.red</code> model URL — or just the
              numeric model id. Restricted LoRAs need an API key — PortOS will prompt you for one if a download is rejected.
            </p>
          </form>

          <form
            onSubmit={handleHfInstall}
            className="bg-port-card border border-port-border rounded-lg p-4 space-y-3"
          >
            <div className="flex items-center gap-2 text-sm font-medium text-gray-300">
              <Download size={16} />
              <span>Install LoRA from HuggingFace</span>
            </div>
            <div className="flex flex-wrap gap-2 sm:flex-nowrap">
              <input
                type="text"
                value={hfUrl}
                onChange={(e) => setHfUrl(e.target.value)}
                aria-label="HuggingFace LoRA URL"
                placeholder="https://huggingface.co/Alissonerdx/CharacterSheet"
                className="min-h-11 min-w-0 flex-1 bg-port-bg border border-port-border rounded px-3 py-2 text-sm text-gray-200 placeholder:text-gray-600"
                disabled={hfInstalling}
              />
              <button
                type="submit"
                disabled={hfInstalling || !!installingVideoKey || !hfUrl.trim()}
                className="min-h-11 bg-port-accent text-white px-4 rounded text-sm font-medium hover:bg-port-accent/90 disabled:opacity-50 disabled:cursor-not-allowed flex items-center justify-center gap-2"
              >
                {hfInstalling ? (hfPct != null ? `Downloading ${hfPct}%` : 'Downloading…') : 'Install'}
              </button>
            </div>
            {hfInstalling && <HfDownloadProgress progress={hfProgress} />}
            <p className="text-xs text-gray-500">
              Paste a <code className="bg-port-bg px-1 rounded">huggingface.co</code> repo URL — or an{' '}
              <code className="bg-port-bg px-1 rounded">org/name</code> id — for an image or video LoRA
              (e.g. <code className="bg-port-bg px-1 rounded">Alissonerdx/CharacterSheet</code> or{' '}
              <code className="bg-port-bg px-1 rounded">fal/ltx2.3-audio-reactive-lora</code>).
              Flux.2 Klein adapters apply in <Link to="/media/image" className="text-port-accent hover:underline">Image Gen</Link>;
              LTX-Video LoRAs apply in <Link to="/media/video" className="text-port-accent hover:underline">Video Gen</Link>.
              Gated repos use your HuggingFace token from Image Gen settings.
            </p>
            {hfFamilyPrompt && (
              <div className="rounded border border-port-warning/40 bg-port-warning/10 px-3 py-2 space-y-2">
                <span className="text-xs text-gray-300">
                  Couldn&apos;t detect the model family for <code className="bg-port-bg px-1 rounded">{hfFamilyPrompt}</code>. Choose the runner this LoRA targets:
                </span>
                <div className="flex flex-wrap items-center gap-2">
                  {HF_FAMILY_OVERRIDES.map(({ family, label }) => (
                    <button
                      key={family}
                      type="button"
                      onClick={() => requestLoraDownload(
                        'Install HuggingFace LoRA',
                        hfFamilyPrompt,
                        'huggingface',
                        () => runHfInstall(hfFamilyPrompt, family),
                        { family },
                      )}
                      disabled={hfInstalling}
                      className="min-h-11 bg-port-accent text-white px-3 rounded text-xs font-medium hover:bg-port-accent/90 disabled:opacity-50"
                    >
                      {hfInstalling ? (hfPct != null ? `Installing ${hfPct}%` : 'Installing…') : `Install as ${label}`}
                    </button>
                  ))}
                  <button
                    type="button"
                    onClick={() => setHfFamilyPrompt(null)}
                    disabled={hfInstalling}
                    className="text-gray-400 hover:text-gray-200 px-2 py-1 rounded text-xs disabled:opacity-50"
                  >
                    Cancel
                  </button>
                </div>
              </div>
            )}
          </form>

          <SuggestionsPanel
            suggestions={suggestions}
            loading={loadingSuggestions}
            mediaFilter={mediaFilter}
            installedFilenames={new Set(loras.map((l) => l.filename))}
            installedHfKeys={new Set(loras.filter((l) => l.huggingface?.repo).map(installedHfKey))}
            installingSuggestionKey={installingSuggestion}
            installingVideoKey={installingVideoKey}
            installingVideoProgress={hfProgress}
            videoInstallBusy={hfInstalling}
            onRefresh={() => refreshSuggestions({ force: true })}
            onInstallVideo={installVideoSuggestion}
            onInstall={(card, url, versionId) => {
              // Curated cards pass a family-specific (url, versionId); non-curated
              // cards omit versionId and we fall back to the card's primary.
              const vid = versionId ?? card.versionId;
              const key = suggestionKey(card.modelId, vid);
              setInstallingSuggestion(key);
              // performInstall() resolves once the PREVIEW is ready (the confirm
              // modal is now showing) — the actual install can run far later, so
              // clearing this card's spinner belongs to that install's own
              // lifecycle (startCivitaiInstall's finally) and the cancel/auth-
              // redirect paths that can end this attempt before it ever starts,
              // not to this promise settling.
              performInstall(url || card.installUrl);
            }}
          />
        </div>
      )}

      {view === VIEW_INSTALLED && (
        <div id={`${VIEW_PANEL_PREFIX}-${VIEW_INSTALLED}`} role="tabpanel" aria-labelledby={`tab-${VIEW_INSTALLED}`}>
          <h2 className="text-lg font-semibold text-white mb-3">Installed</h2>
          {loading && <PageSkeleton header="none" label="Loading installed LoRAs" layout="grid" cards={6} />}
          {error && (
            <Banner tone="error" size="md" icon={AlertTriangle} align="center">{error}</Banner>
          )}
          {/* The empty state names the next action rather than pointing at
              "the suggestions above" — discovery is now a view away, not a
              scroll away. */}
          {!loading && !error && visibleLoras.length === 0 && (
            <EmptyState
              icon={Package}
              title={loras.length === 0 ? 'No LoRAs installed yet' : `No ${mediaFilter} LoRAs installed`}
              message={loras.length === 0
                ? 'Browse curated picks and Civitai / HuggingFace search, or paste a model URL, to install your first adapter.'
                : `You have other LoRAs installed — switch the Show filter, or install a ${mediaFilter} LoRA.`}
              actionLabel="Discover LoRAs to install"
              onAction={() => setView(VIEW_DISCOVER)}
            />
          )}
          {/* On "All", split installed LoRAs into Video/Image subsections (with the
              same header style as the suggestion panel) so it's self-evident which
              renders each applies to. A specific filter already scopes the list, so
              render it flat. */}
          {visibleLoras.length > 0 && (
            mediaFilter === 'all'
              ? <InstalledGroups loras={visibleLoras} deleting={deleting} onDelete={handleDelete} onMeasured={handleMeasured} deleteConfirm={deleteConfirm} />
              : <LoraGrid loras={visibleLoras} deleting={deleting} onDelete={handleDelete} onMeasured={handleMeasured} deleteConfirm={deleteConfirm} />
          )}
        </div>
      )}

      {/* Both overlays stay OUTSIDE the view gate: an install started in
          Discover can still hit a 401 (or finish its preflight) after the user
          has switched to Installed, and unmounting the dialog would strand
          that attempt with no way to recover the key. */}
      {authPrompt && (
        <CivitaiAuthModal
          pendingUrl={authPrompt.url}
          message={authPrompt.message}
          auth={auth}
          onClose={() => setAuthPrompt(null)}
          onSaved={(updatedAuth) => setAuth(updatedAuth)}
          onRetry={() => {
            // After save, retry with the original URL — the server now reads
            // the freshly-saved key from settings. performInstall handles the
            // bad-key reopen by re-setting authPrompt.
            const url = authPrompt.url;
            setAuthPrompt(null);
            if (url) performInstall(url);
          }}
        />
      )}
      <DownloadPreflightConfirm
        open={Boolean(downloadConfirm)}
        title={downloadConfirm?.title}
        loading={Boolean(downloadConfirm?.loading)}
        error={downloadConfirm?.error}
        assessment={downloadConfirm?.assessment}
        confirmLabel="Start download"
        onCancel={handleCancelDownloadConfirm}
        onConfirm={runDownloadConfirm}
      />
    </div>
  );
}

// Byte-level download progress bar for an in-flight HuggingFace LoRA install.
// `progress` is `{ received, total, progress }` (progress 0..1) or null. When
// the server had no Content-Length (total 0 / progress null) the bar renders an
// indeterminate pulse instead of a fill.
function HfDownloadProgress({ progress }) {
  const pct = pctOf(progress);
  const total = progress?.total || 0;
  return (
    <div className="space-y-1">
      <div className="flex items-center justify-between text-[11px] text-gray-400">
        <span>{pct != null ? `Downloading… ${pct}%` : 'Downloading…'}</span>
        {total > 0 && (
          <span className="font-mono text-gray-500">{formatBytes(progress.received)} / {formatBytes(total)}</span>
        )}
      </div>
      <ProgressBar percent={pct} label="Download progress" duration={200} />
    </div>
  );
}

// Segmented All / Image / Video control. Pure presentational — the parent owns
// the `mediaFilter` state and applies it to both the suggestion panel and the
// installed list.
function MediaFilter({ value, onChange }) {
  return (
    <div className="flex flex-wrap items-center gap-2">
      <span className="text-xs text-gray-500">Show</span>
      <div className="inline-flex max-w-full rounded-lg border border-port-border overflow-hidden">
        {MEDIA_FILTERS.map((f) => (
          <button
            key={f.id}
            type="button"
            onClick={() => onChange(f.id)}
            aria-pressed={value === f.id}
            className={`min-h-11 px-3 text-xs font-medium transition-colors ${
              value === f.id
                ? 'bg-port-accent text-white'
                : 'bg-port-card text-gray-400 hover:text-gray-200'
            }`}
          >
            {f.label}
          </button>
        ))}
      </div>
    </div>
  );
}

function SuggestionsPanel({ suggestions, loading, mediaFilter = 'all', installedFilenames, installedHfKeys, installingSuggestionKey, installingVideoKey, installingVideoProgress, videoInstallBusy, onRefresh, onInstall, onInstallVideo }) {
  const curated = suggestions?.curated || [];
  const runners = suggestions?.runners || {};
  const video = suggestions?.video || [];
  const showImage = mediaFilter !== 'video';
  const showVideo = mediaFilter !== 'image';
  const sections = [
    { key: 'curated', label: 'Curated picks', cards: curated, hint: 'Hand-picked LoRAs that work across multiple base models.' },
    // The runner-family sections always render, even when Civitai search
    // returns zero — `alwaysShow` lets the user see every base-model header at
    // a glance instead of silently collapsing the empty ones. `runner` (the
    // family key) marks the section as searchable + paginated; it's tracked
    // separately from `alwaysShow` so the two concerns can't accidentally couple.
    { key: RUNNER_FAMILIES.MFLUX,   runner: RUNNER_FAMILIES.MFLUX,   label: 'Top for Flux 1',  cards: runners[RUNNER_FAMILIES.MFLUX] || [],   hint: 'Most-downloaded LoRAs trained against Flux.1 D / Flux.1 S.', alwaysShow: true },
    { key: RUNNER_FAMILIES.FLUX2,   runner: RUNNER_FAMILIES.FLUX2,   label: 'Top for Flux 2',  cards: runners[RUNNER_FAMILIES.FLUX2] || [],   hint: 'Most-downloaded LoRAs trained against Flux.2 Klein 4B / 9B.', alwaysShow: true },
    { key: RUNNER_FAMILIES.Z_IMAGE, runner: RUNNER_FAMILIES.Z_IMAGE, label: 'Top for Z-Image', cards: runners[RUNNER_FAMILIES.Z_IMAGE] || [], hint: 'Most-downloaded LoRAs trained against Z-Image / Z-Image-Turbo.', alwaysShow: true },
    { key: RUNNER_FAMILIES.ERNIE,   runner: RUNNER_FAMILIES.ERNIE,   label: 'Top for ERNIE',   cards: runners[RUNNER_FAMILIES.ERNIE] || [],   hint: 'Most-downloaded LoRAs trained against ERNIE-Image.', alwaysShow: true },
    { key: RUNNER_FAMILIES.HIDREAM, runner: RUNNER_FAMILIES.HIDREAM, label: 'Top for HiDream', cards: runners[RUNNER_FAMILIES.HIDREAM] || [], hint: 'Most-downloaded LoRAs trained against HiDream.', alwaysShow: true },
    { key: RUNNER_FAMILIES.QWEN,    runner: RUNNER_FAMILIES.QWEN,    label: 'Top for Qwen',    cards: runners[RUNNER_FAMILIES.QWEN] || [],    hint: 'Most-downloaded LoRAs trained against Qwen-Image.', alwaysShow: true },
  ];
  return (
    <div className="space-y-4">
      <div className="flex items-center justify-between">
        <h2 className="text-lg font-semibold text-white flex items-center gap-2">
          <Wand2 size={18} className="text-port-accent" />
          Suggested LoRAs
        </h2>
        <button
          type="button"
          onClick={onRefresh}
          disabled={loading}
          className="text-xs text-gray-400 hover:text-gray-200 flex items-center gap-1 disabled:opacity-50"
          title="Re-fetch from Civitai (busts the 1-hour cache)"
        >
          <RefreshCw size={12} className={loading ? 'animate-spin' : ''} />
          Refresh
        </button>
      </div>
      {loading && !suggestions && (
        <div className="text-sm text-gray-500">Loading suggestions…</div>
      )}
      {showImage && sections.map((section) => (
        <SuggestionsSection
          key={section.key}
          label={section.label}
          hint={section.hint}
          cards={section.cards}
          alwaysShow={section.alwaysShow}
          // Runner-family sections carry a `runner` key → keyword search box +
          // "Load more" pagination; the curated section has none and stays static.
          runner={section.runner || null}
          resetSignal={suggestions?.fetchedAt}
          installedFilenames={installedFilenames}
          installingSuggestionKey={installingSuggestionKey}
          onInstall={onInstall}
        />
      ))}
      {showVideo && (
        <VideoSuggestionsSection
          cards={video}
          installedHfKeys={installedHfKeys}
          installingVideoKey={installingVideoKey}
          installingVideoProgress={installingVideoProgress}
          videoInstallBusy={videoInstallBusy}
          onInstall={onInstallVideo}
        />
      )}
    </div>
  );
}

// Family filter for the live HuggingFace search below the curated list.
const VIDEO_FAMILY_FILTERS = [
  { id: 'all', label: 'All video' },
  { id: VIDEO_LORA_FAMILIES.LTX_VIDEO, label: 'LTX-Video' },
  { id: VIDEO_LORA_FAMILIES.MINIMAX_H3, label: 'MiniMax H3' },
];

// Curated HuggingFace video LoRAs (small hand-picked list, installed via the
// HF path) PLUS a live keyword/author/repository search across all of
// HuggingFace (#6500). Installed-state matches the exact repo+file pair
// because a repo may publish multiple independently installable LoRA
// versions, and a search result may offer more than one installable file.
function VideoSuggestionsSection({ cards, installedHfKeys, installingVideoKey, installingVideoProgress, videoInstallBusy, onInstall }) {
  const list = cards || [];
  return (
    <div>
      <div className="flex items-baseline gap-3 mb-2">
        <h3 className="text-sm font-medium text-gray-300">Video LoRAs</h3>
        <span className="text-xs text-gray-600">{list.length}</span>
      </div>
      <p className="text-xs text-gray-500 mb-2">
        Curated LTX-Video LoRAs from HuggingFace — apply on an LTX-2 (ltx2) model in{' '}
        <Link to="/media/video" className="text-port-accent hover:underline">Video Gen</Link>.
      </p>
      {list.length === 0 ? (
        <p className="text-xs text-gray-600 italic">No video LoRA suggestions yet.</p>
      ) : (
        <div className="grid grid-cols-1 sm:grid-cols-2 lg:grid-cols-3 xl:grid-cols-4 gap-3">
          {list.map((card) => (
            <VideoSuggestionCard
              key={hfCardKey(card)}
              card={card}
              installedHfKeys={installedHfKeys}
              installingVideoKey={installingVideoKey}
              installingVideoProgress={installingVideoProgress}
              // Disable every quick-install button while ANY HF install is in
              // flight (this card's, another card's, or the form's) — one at a time.
              busy={!!installingVideoKey || videoInstallBusy}
              onInstall={onInstall}
            />
          ))}
        </div>
      )}
      <VideoSearchSection
        installedHfKeys={installedHfKeys}
        installingVideoKey={installingVideoKey}
        installingVideoProgress={installingVideoProgress}
        videoInstallBusy={videoInstallBusy}
        onInstall={onInstall}
      />
    </div>
  );
}

// Live search across all of HuggingFace for LTX-Video / MiniMax H3 LoRAs —
// the video counterpart to SuggestionsSection's per-runner Civitai search
// below. Kept as its own always-mounted subsection (not gated by the curated
// list) so a curated fetch failure never hides the search box.
function VideoSearchSection({ installedHfKeys, installingVideoKey, installingVideoProgress, videoInstallBusy, onInstall }) {
  const [family, setFamily] = useState('all');
  const [query, setQuery] = useState('');
  const [author, setAuthor] = useState('');
  const [activeQuery, setActiveQuery] = useState('');
  const [activeAuthor, setActiveAuthor] = useState('');
  // null = no search run yet (box not shown as "searched"); [] = a real empty result.
  const [items, setItems] = useState(null);
  const [cursor, setCursor] = useState(null);
  const [loading, setLoading] = useState(false);
  const [error, setError] = useState(null);
  // Bumped on every fetch; a response is applied only if it's still the LATEST
  // request — so switching family/query mid-flight can't have a slower older
  // response clobber a faster newer one.
  const requestIdRef = useRef(0);

  const fetchPage = useCallback((q, a, fam, { append, useCursor }) => {
    const requestId = requestIdRef.current + 1;
    requestIdRef.current = requestId;
    setLoading(true);
    setError(null);
    searchVideoLoras({ family: fam, query: q, author: a, cursor: useCursor, limit: 12 })
      .then((res) => {
        if (requestIdRef.current !== requestId) return; // superseded by a later request
        const results = res?.items || [];
        setCursor(res?.nextCursor || null);
        setActiveQuery(q);
        setActiveAuthor(a);
        setItems((prev) => {
          if (!append || prev === null) return results;
          const seen = new Set(prev.map(hfCardKey));
          return [...prev, ...results.filter((c) => !seen.has(hfCardKey(c)))];
        });
      })
      .catch((err) => {
        if (requestIdRef.current !== requestId) return;
        setError(err?.message || 'HuggingFace search failed');
      })
      .finally(() => {
        if (requestIdRef.current === requestId) setLoading(false);
      });
  }, []);

  const handleSearch = (e) => {
    e?.preventDefault?.();
    if (loading) return;
    fetchPage(query.trim(), author.trim(), family, { append: false, useCursor: null });
  };

  // Switching family re-runs whatever search is active (or the box's current
  // values pre-submit) under the new filter — otherwise the header/family
  // pills would show results from the family the user just left.
  const handleFamilyChange = (nextFamily) => {
    setFamily(nextFamily);
    if (items !== null) fetchPage(activeQuery, activeAuthor, nextFamily, { append: false, useCursor: null });
  };

  const clearSearch = () => {
    requestIdRef.current += 1; // invalidate any in-flight request
    setQuery(''); setAuthor(''); setActiveQuery(''); setActiveAuthor('');
    setItems(null); setCursor(null); setError(null); setLoading(false);
  };

  const loadMore = () => {
    if (loading) return;
    fetchPage(activeQuery, activeAuthor, family, { append: true, useCursor: cursor });
  };

  const retry = () => fetchPage(activeQuery, activeAuthor, family, { append: false, useCursor: null });

  const list = items || [];
  const hasSearched = items !== null;
  const canLoadMore = hasSearched && !error && cursor !== null;

  return (
    <div className="mt-4 pt-4 border-t border-port-border/60">
      <div className="flex items-baseline gap-3 mb-2">
        <h3 className="text-sm font-medium text-gray-300">Search HuggingFace</h3>
        {hasSearched && <span className="text-xs text-gray-600">{list.length}</span>}
      </div>
      <p className="text-xs text-gray-500 mb-2">
        Search all of HuggingFace for LTX-Video / MiniMax H3 LoRAs by name, author, or repository.
      </p>
      <form onSubmit={handleSearch} className="flex flex-wrap items-start gap-2 mb-3">
        <div className="inline-flex max-w-full rounded-lg border border-port-border overflow-hidden">
          {VIDEO_FAMILY_FILTERS.map((f) => (
            <button
              key={f.id}
              type="button"
              onClick={() => handleFamilyChange(f.id)}
              aria-pressed={family === f.id}
              className={`min-h-11 px-3 text-xs font-medium transition-colors ${
                family === f.id ? 'bg-port-accent text-white' : 'bg-port-card text-gray-400 hover:text-gray-200'
              }`}
            >
              {f.label}
            </button>
          ))}
        </div>
        <div className="relative min-w-0 flex-1 basis-40 max-w-md">
          <Search size={13} className="absolute left-2.5 top-1/2 -translate-y-1/2 text-gray-600 pointer-events-none" />
          <input
            type="text"
            value={query}
            onChange={(e) => setQuery(e.target.value)}
            placeholder="Search name or repository…"
            aria-label="Search HuggingFace video LoRAs by name or repository"
            className="min-h-11 w-full bg-port-bg border border-port-border rounded pl-8 pr-3 py-1.5 text-xs text-gray-200 placeholder:text-gray-600"
          />
        </div>
        <input
          type="text"
          value={author}
          onChange={(e) => setAuthor(e.target.value)}
          placeholder="Author (optional)"
          aria-label="Filter HuggingFace video LoRAs by author"
          className="min-h-11 w-32 max-w-full bg-port-bg border border-port-border rounded px-3 py-1.5 text-xs text-gray-200 placeholder:text-gray-600"
        />
        <button
          type="submit"
          disabled={loading}
          className="min-h-11 bg-port-accent/90 text-white px-3 rounded text-xs font-medium hover:bg-port-accent disabled:opacity-50"
        >
          {loading ? 'Searching…' : 'Search'}
        </button>
        {hasSearched && (
          <button
            type="button"
            onClick={clearSearch}
            className="min-h-11 px-3 rounded text-xs text-gray-400 hover:text-gray-200 border border-port-border"
          >
            Clear
          </button>
        )}
      </form>
      {error && (
        <Banner
          tone="error"
          size="sm"
          align="center"
          className="mb-3"
          actions={(
            <button type="button" onClick={retry} disabled={loading} className="underline hover:no-underline disabled:opacity-50">
              {loading ? 'Retrying…' : 'Retry'}
            </button>
          )}
        >
          {error}
        </Banner>
      )}
      {hasSearched && !error && list.length === 0 && !loading && (
        <p className="text-xs text-gray-600 italic">No matching video LoRAs found on HuggingFace.</p>
      )}
      {list.length > 0 && (
        <div className="grid grid-cols-1 sm:grid-cols-2 lg:grid-cols-3 xl:grid-cols-4 gap-3">
          {list.map((card) => (
            <VideoSuggestionCard
              key={hfCardKey(card)}
              card={card}
              installedHfKeys={installedHfKeys}
              installingVideoKey={installingVideoKey}
              installingVideoProgress={installingVideoProgress}
              busy={!!installingVideoKey || videoInstallBusy}
              onInstall={onInstall}
            />
          ))}
        </div>
      )}
      {canLoadMore && (
        <div className="mt-3 flex justify-center">
          <button
            type="button"
            onClick={loadMore}
            disabled={loading}
            className="text-xs text-gray-300 hover:text-white px-4 py-1.5 rounded border border-port-border hover:border-port-accent/40 disabled:opacity-50 flex items-center gap-1.5"
          >
            {loading ? <BrailleSpinner text="Loading…" /> : <><Download size={12} /> Load more</>}
          </button>
        </div>
      )}
    </div>
  );
}

// Shared by the curated list and the live search. Owns its own install-key
// (repo+file) so a search card offering several `.safetensors` files can let
// the user pick one — `installingVideoKey`/`installedHfKeys` are matched
// against the CURRENTLY SELECTED file, not just the card's recommended
// default. Curated cards never carry more than one file, so this collapses
// to the original behavior for them.
function VideoSuggestionCard({ card, installedHfKeys, installingVideoKey, installingVideoProgress, busy, onInstall }) {
  const fileOptions = Array.isArray(card.files) && card.files.length > 1 ? card.files : null;
  const [selectedFile, setSelectedFile] = useState(card.file);
  const [showPreview, setShowPreview] = useState(false);
  const effectiveCard = fileOptions && selectedFile !== card.file ? { ...card, file: selectedFile } : card;
  const key = hfCardKey(effectiveCard);
  const installed = installedHfKeys?.has(key);
  const installing = installingVideoKey === key;
  const pct = pctOf(installing ? installingVideoProgress : null);
  const inputId = `hf-video-file-${key}`;
  return (
    <div className="bg-port-card border border-port-border rounded-lg overflow-hidden flex flex-col">
      {showPreview && card.previewVideoUrl ? (
        // Mounted only after a click — the browser makes no network request
        // for the clip until the user asks for it, and `controls` (no
        // `autoPlay`) keeps playback itself opt-in too.
        <video
          src={card.previewVideoUrl}
          controls
          preload="none"
          referrerPolicy="no-referrer"
          className="w-full h-64 object-cover bg-black"
        />
      ) : card.previewImageUrl ? (
        <div className="relative">
          <img src={card.previewImageUrl} alt="" className="w-full h-64 object-cover bg-port-bg" loading="lazy" referrerPolicy="no-referrer" />
          {card.previewVideoUrl && (
            <button
              type="button"
              onClick={() => setShowPreview(true)}
              className="absolute inset-0 flex items-center justify-center bg-black/20 hover:bg-black/40 text-white/90 hover:text-white transition-colors"
              aria-label="Play example clip"
              title="Play example clip"
            >
              <PlayCircle size={40} />
            </button>
          )}
        </div>
      ) : card.previewVideoUrl ? (
        <button
          type="button"
          onClick={() => setShowPreview(true)}
          className="w-full h-64 bg-port-bg flex items-center justify-center text-gray-600 hover:text-gray-400"
          aria-label="Play example clip"
          title="Play example clip"
        >
          <PlayCircle size={32} />
        </button>
      ) : (
        <div className="w-full h-64 bg-port-bg flex items-center justify-center text-gray-700">
          <Sparkles size={32} />
        </div>
      )}
      <div className="p-3 flex-1 flex flex-col gap-2">
        <div className="flex items-start justify-between gap-2">
          <h4 className="font-semibold text-white text-sm flex-1 break-words">{card.name}</h4>
          <span className={`text-[10px] px-1.5 py-0.5 rounded border whitespace-nowrap ${RUNNER_BADGE_CLASS[card.runnerFamily] || 'bg-gray-600/20 text-gray-300 border-gray-500/30'}`}>
            {RUNNER_LABEL[card.runnerFamily] || 'Video'}
          </span>
        </div>
        {card.note && <p className="text-[11px] text-gray-400 italic break-words">{card.note}</p>}
        {typeof card.downloads === 'number' && (
          <div className="text-[10px] text-gray-600">↓ {formatCount(card.downloads)}</div>
        )}
        {card.description && (
          <details className="text-[11px] text-gray-500">
            <summary className="cursor-pointer hover:text-gray-300">Details</summary>
            <p className="mt-1 text-[10px] leading-snug bg-port-bg p-1.5 rounded border border-port-border line-clamp-4">{card.description}</p>
          </details>
        )}
        {fileOptions && (
          <div>
            <label htmlFor={inputId} className="block text-[10px] uppercase tracking-wide text-gray-500 mb-0.5">File</label>
            <select
              id={inputId}
              value={selectedFile}
              onChange={(e) => setSelectedFile(e.target.value)}
              disabled={installed || installing}
              className="w-full bg-port-bg border border-port-border rounded px-2 py-1 text-[11px] text-gray-200"
            >
              {fileOptions.map((f) => (
                <option key={f.file} value={f.file}>{f.file}{f.recommended ? ' (recommended)' : ''}</option>
              ))}
            </select>
          </div>
        )}
        <div className="flex items-center gap-2 mt-auto">
          {installed ? (
            <button disabled className="flex-1 bg-port-success/20 text-port-success border border-port-success/30 px-3 py-1.5 rounded text-xs font-medium flex items-center justify-center gap-1">
              <Check size={12} /> Installed
            </button>
          ) : (
            <button
              type="button"
              onClick={() => onInstall(effectiveCard)}
              disabled={installing || busy}
              className="flex-1 bg-port-accent text-white px-3 py-1.5 rounded text-xs font-medium hover:bg-port-accent/90 disabled:opacity-50 disabled:cursor-not-allowed"
            >
              {installing ? (pct != null ? `Installing ${pct}%` : 'Installing…') : 'Quick install'}
            </button>
          )}
        </div>
        {card.hfUrl && (
          <a href={card.hfUrl} target="_blank" rel="noopener noreferrer" className="text-[10px] text-gray-500 hover:text-gray-300 inline-flex items-center gap-1 self-start" title="Open on HuggingFace">
            <ExternalLink size={11} /> View on HuggingFace
          </a>
        )}
      </div>
    </div>
  );
}

function SuggestionsSection({ label, hint, cards, alwaysShow = false, runner = null, resetSignal, installedFilenames, installingSuggestionKey, onInstall }) {
  const baseCards = cards || [];
  const searchable = !!runner;

  // Live state for keyword search + "Load more" pagination. `liveCards === null`
  // means we're showing the cached top-N from props; once the user searches or
  // pages, we switch to the live list. `activeQuery` is the last submitted
  // keyword ('' = top ranking); `cursor` is Civitai's next-page token.
  const [query, setQuery] = useState('');
  const [activeQuery, setActiveQuery] = useState('');
  const [liveCards, setLiveCards] = useState(null);
  const [cursor, setCursor] = useState(null);
  const [loading, setLoading] = useState(false);
  const requestIdRef = useRef(0);

  // Drop any live search/pagination so the section falls back to the cached
  // top-N. Shared by Clear, the empty-box submit, and the Refresh effect.
  // Stable identity (setters never change) so the effect can depend on it.
  const resetToCached = useCallback(() => {
    requestIdRef.current += 1;
    setActiveQuery(''); setLiveCards(null); setCursor(null);
    setLoading(false);
  }, []);

  // A global Refresh (new fetchedAt) re-seeds the cached top-N — drop live
  // results so the section doesn't show stale ones under the new header. Also
  // fires once harmlessly on mount (all setters are no-ops at their defaults).
  useEffect(() => { setQuery(''); resetToCached(); }, [resetSignal, resetToCached]);

  const fetchPage = useCallback(async (q, { append, useCursor }) => {
    const requestId = requestIdRef.current + 1;
    requestIdRef.current = requestId;
    setLoading(true);
    await searchCivitaiLoras({ runner, query: q, cursor: useCursor, limit: 12 })
      .then((res) => {
        if (requestIdRef.current !== requestId) return;
        const items = res?.items || [];
        setCursor(res?.nextCursor || null);
        setActiveQuery(q);
        setLiveCards((prev) => {
          if (!append || prev === null) return items;
          // Dedup by modelId-versionId — re-fetched leaders can repeat.
          const seen = new Set(prev.map(cardKey));
          return [...prev, ...items.filter((c) => !seen.has(cardKey(c)))];
        });
      })
      .catch((err) => {
        if (requestIdRef.current === requestId) toast.error(err?.message || 'Civitai search failed');
      })
      .finally(() => {
        if (requestIdRef.current === requestId) setLoading(false);
      });
  }, [runner]);

  const handleSearch = (e) => {
    e?.preventDefault?.();
    if (loading) return; // Enter while a fetch is in flight → no overlapping requests
    const q = query.trim();
    if (!q) { resetToCached(); return; } // empty box → cached top-N
    fetchPage(q, { append: false, useCursor: null });
  };

  const clearSearch = () => { setQuery(''); resetToCached(); };

  const loadMore = () => {
    if (loading) return;
    // First click from the cached view fetches page 1 live (top ranking or the
    // active query); later clicks page forward with the cursor.
    if (liveCards === null) fetchPage(activeQuery, { append: false, useCursor: null });
    else fetchPage(activeQuery, { append: true, useCursor: cursor });
  };

  const list = liveCards !== null ? liveCards : baseCards;
  // "Load more" is available until we've gone live AND Civitai reports no
  // further cursor. In the cached view we assume more exists (only top-4 shown).
  const canLoadMore = searchable && (liveCards === null || cursor !== null);

  if (list.length === 0 && !alwaysShow && !searchable) return null;
  return (
    <div>
      <div className="flex items-baseline gap-3 mb-2">
        <h3 className="text-sm font-medium text-gray-300">{label}</h3>
        <span className="text-xs text-gray-600">{list.length}</span>
        {activeQuery && (
          <span className="text-xs text-port-accent">results for “{activeQuery}”</span>
        )}
      </div>
      {hint && <p className="text-xs text-gray-500 mb-2">{hint}</p>}
      {searchable && (
        <form onSubmit={handleSearch} className="flex flex-wrap items-start gap-2 mb-3">
          <div className="relative min-w-0 flex-1 basis-40 max-w-md">
            <Search size={13} className="absolute left-2.5 top-1/2 -translate-y-1/2 text-gray-600 pointer-events-none" />
            <input
              type="text"
              value={query}
              onChange={(e) => setQuery(e.target.value)}
              placeholder={`Search ${RUNNER_LABEL[runner] || runner} LoRAs on Civitai…`}
              aria-label={`Search ${RUNNER_LABEL[runner] || runner} LoRAs on Civitai`}
              className="min-h-11 w-full bg-port-bg border border-port-border rounded pl-8 pr-3 py-1.5 text-xs text-gray-200 placeholder:text-gray-600"
            />
          </div>
          <button
            type="submit"
            disabled={loading}
            className="min-h-11 bg-port-accent/90 text-white px-3 rounded text-xs font-medium hover:bg-port-accent disabled:opacity-50"
          >
            {loading ? 'Searching…' : 'Search'}
          </button>
          {activeQuery && (
            <button
              type="button"
              onClick={clearSearch}
              className="min-h-11 px-3 rounded text-xs text-gray-400 hover:text-gray-200 border border-port-border"
              title="Clear search — back to top ranking"
            >
              Clear
            </button>
          )}
        </form>
      )}
      {list.length === 0 ? (
        <p className="text-xs text-gray-600 italic">
          {activeQuery
            ? `No LoRAs match “${activeQuery}” for this base model${canLoadMore ? ' on this page — try Load more.' : '.'}`
            : 'No LoRAs found on Civitai for this base model yet.'}
        </p>
      ) : (
        <div className="grid grid-cols-1 sm:grid-cols-2 lg:grid-cols-3 xl:grid-cols-4 gap-3">
          {list.map((card) => (
            <SuggestionCard
              key={cardKey(card)}
              card={card}
              installedFilenames={installedFilenames}
              installingSuggestionKey={installingSuggestionKey}
              onInstall={onInstall}
            />
          ))}
        </div>
      )}
      {/* "Load more" sits OUTSIDE the empty/non-empty branch on purpose: a live
          Civitai page can come back empty yet carry a nextCursor (later pages
          hold matches for some keyword + base-model combos), so the control
          must stay reachable to advance past empty pages instead of trapping
          the user on a false "no matches" state. */}
      {canLoadMore && (
        <div className="mt-3 flex justify-center">
          <button
            type="button"
            onClick={loadMore}
            disabled={loading}
            className="text-xs text-gray-300 hover:text-white px-4 py-1.5 rounded border border-port-border hover:border-port-accent/40 disabled:opacity-50 flex items-center gap-1.5"
          >
            {loading ? <BrailleSpinner text="Loading…" /> : <><Download size={12} /> Load more</>}
          </button>
        </div>
      )}
    </div>
  );
}

function SuggestionCard({ card, installedFilenames, installingSuggestionKey, onInstall }) {
  const installs = card.curated && card.installs && Object.keys(card.installs).length > 0 ? card.installs : null;
  // Badges: prefer the installs map's keys (per-family with versions), else
  // the runnerFamilies array, else the single primary-version family.
  const badgeFamilies = installs
    ? Object.keys(installs)
    : (Array.isArray(card.runnerFamilies) && card.runnerFamilies.length
      ? card.runnerFamilies
      : (card.runnerFamily ? [card.runnerFamily] : []));
  const isInstalled = (versionId) => versionId != null
    && [...installedFilenames].some((f) => f.endsWith(`-v${versionId}.safetensors`));
  const isInstalling = (versionId) => installingSuggestionKey === suggestionKey(card.modelId, versionId);
  return (
    <div className="bg-port-card border border-port-border rounded-lg overflow-hidden flex flex-col">
      {card.previewImageUrl ? (
        <img src={card.previewImageUrl} alt="" className="w-full h-64 object-cover bg-port-bg" loading="lazy" referrerPolicy="no-referrer" />
      ) : (
        <div className="w-full h-64 bg-port-bg flex items-center justify-center text-gray-700">
          <Sparkles size={32} />
        </div>
      )}
      <div className="p-3 flex-1 flex flex-col gap-2">
        <div className="flex items-start justify-between gap-2">
          <h4 className="font-semibold text-white text-sm flex-1 break-words">{card.name}</h4>
          {card.curated && (
            <span className="text-[10px] px-1.5 py-0.5 rounded bg-port-warning/20 text-port-warning border border-port-warning/30 whitespace-nowrap">curated</span>
          )}
        </div>
        {badgeFamilies.length > 0 && !installs && (
          <div className="flex flex-wrap gap-1">
            {badgeFamilies.map((f) => (
              <span key={f} className={`text-[10px] px-1.5 py-0.5 rounded border whitespace-nowrap ${RUNNER_BADGE_CLASS[f] || 'bg-gray-600/20 text-gray-300 border-gray-500/30'}`}>
                {RUNNER_LABEL[f] || f}
              </span>
            ))}
          </div>
        )}
        {card.note && <p className="text-[11px] text-gray-400 italic break-words">{card.note}</p>}
        {card.samplePrompt && (
          <details className="text-[11px] text-gray-500">
            <summary className="cursor-pointer hover:text-gray-300">Sample prompt</summary>
            <p className="mt-1 font-mono text-[10px] leading-snug bg-port-bg p-1.5 rounded border border-port-border line-clamp-4">{card.samplePrompt}</p>
          </details>
        )}
        <div className="text-[10px] text-gray-600 flex items-center gap-3 mt-auto">
          {card.creator && <span className="truncate" title={card.creator}>by {card.creator}</span>}
          {typeof card.downloads === 'number' && <span>↓ {formatCount(card.downloads)}</span>}
        </div>
        {installs ? (
          <div className="flex flex-col gap-1">
            <p className="text-[10px] uppercase tracking-wide text-gray-500">Install for</p>
            <div className="flex flex-wrap gap-1.5">
              {Object.entries(installs).map(([family, info]) => {
                const installed = isInstalled(info.versionId);
                const installing = isInstalling(info.versionId);
                const baseClass = installed
                  ? 'bg-port-success/20 text-port-success border-port-success/30'
                  : (RUNNER_BADGE_CLASS[family] || 'bg-port-accent/20 text-port-accent border-port-accent/30');
                return (
                  <button
                    key={family}
                    type="button"
                    onClick={() => onInstall(card, info.installUrl, info.versionId)}
                    disabled={installed || installing}
                    title={installed ? 'Already installed' : `Install ${info.baseModel || family} version`}
                    className={`text-[11px] px-2 py-1 rounded border flex items-center gap-1 ${baseClass} hover:brightness-125 disabled:opacity-60 disabled:cursor-not-allowed`}
                  >
                    {installed ? <Check size={11} /> : null}
                    {installing ? 'Installing…' : (RUNNER_LABEL[family] || family)}
                  </button>
                );
              })}
            </div>
          </div>
        ) : (
          <div className="flex items-center gap-2">
            {isInstalled(card.versionId) ? (
              <button disabled className="flex-1 bg-port-success/20 text-port-success border border-port-success/30 px-3 py-1.5 rounded text-xs font-medium flex items-center justify-center gap-1">
                <Check size={12} /> Installed
              </button>
            ) : (
              <button
                type="button"
                onClick={() => onInstall(card, card.installUrl, card.versionId)}
                disabled={isInstalling(card.versionId)}
                className="flex-1 bg-port-accent text-white px-3 py-1.5 rounded text-xs font-medium hover:bg-port-accent/90 disabled:opacity-50"
              >
                {isInstalling(card.versionId) ? 'Installing…' : 'Quick install'}
              </button>
            )}
          </div>
        )}
        {card.civitaiUrl && (
          <a href={card.civitaiUrl} target="_blank" rel="noopener noreferrer" className="text-[10px] text-gray-500 hover:text-gray-300 inline-flex items-center gap-1 self-start" title="Open on Civitai">
            <ExternalLink size={11} /> View on Civitai
          </a>
        )}
      </div>
    </div>
  );
}

function CivitaiKeyBadge({ auth, onManage }) {
  if (auth?.hasKey) {
    const label = auth.source === 'env' ? 'Key (env)' : 'Key saved';
    return (
      <button
        type="button"
        onClick={onManage}
        className="text-[11px] flex items-center gap-1 px-2 py-1 rounded border bg-port-success/10 text-port-success border-port-success/30 hover:bg-port-success/20"
        title={auth.source === 'env' ? 'CIVITAI_API_KEY env var is active' : 'API key saved in PortOS settings'}
      >
        <Check size={11} />
        {label}
      </button>
    );
  }
  return (
    <button
      type="button"
      onClick={onManage}
      className="text-[11px] flex items-center gap-1 px-2 py-1 rounded border bg-port-bg text-gray-400 border-port-border hover:text-gray-200 hover:border-port-accent/30"
    >
      <KeyRound size={11} />
      Add API key
    </button>
  );
}

function CivitaiAuthModal({ pendingUrl, message, auth, onClose, onSaved, onRetry }) {
  const [apiKey, setApiKey] = useState('');
  const [saving, setSaving] = useState(false);
  const [clearing, setClearing] = useState(false);

  const handleSave = async (e) => {
    e?.preventDefault?.();
    if (!apiKey.trim() || saving) return;
    setSaving(true);
    await setCivitaiAuth(apiKey.trim(), { silent: true })
      .then((updated) => {
        toast.success('Civitai API key saved');
        onSaved?.(updated);
        if (pendingUrl) {
          // Hand control back to the page so it can re-attempt the install
          // — the modal closes itself in the retry path.
          onRetry?.();
        } else {
          onClose?.();
        }
      })
      .catch((err) => toast.error(err?.message || 'Failed to save API key'))
      .finally(() => setSaving(false));
  };

  const handleClear = async () => {
    setClearing(true);
    await clearCivitaiAuth({ silent: true })
      .then((updated) => {
        toast.success(updated.hasKey ? 'Saved key cleared (env CIVITAI_API_KEY still active)' : 'Civitai API key cleared');
        onSaved?.(updated);
      })
      .catch((err) => toast.error(err?.message || 'Failed to clear API key'))
      .finally(() => setClearing(false));
  };

  return (
    <Modal
      open
      onClose={onClose}
      size="sm"
      ariaLabelledBy="civitai-auth-title"
      panelClassName="bg-port-card border border-port-border rounded-lg p-5 space-y-4"
    >
      <div className="flex items-start justify-between gap-3">
        <div className="flex items-center gap-2">
          <KeyRound size={18} className="text-port-accent" />
          <h2 id="civitai-auth-title" className="text-base font-semibold text-white">Civitai API key</h2>
        </div>
        <button onClick={onClose} className="text-gray-400 hover:text-gray-200 min-h-[44px] min-w-[44px] flex items-center justify-center" aria-label="Close">
          <X size={16} />
        </button>
      </div>

      {message && (
        <Banner icon={AlertTriangle}>{message}</Banner>
      )}

      <p className="text-xs text-gray-400 leading-relaxed">
        Some Civitai LoRAs require a logged-in token to download (adult or restricted content). Generate one at{' '}
        <a href="https://civitai.com/user/account" target="_blank" rel="noopener noreferrer" className="text-port-accent hover:underline">
          civitai.com/user/account
        </a>{' '}
        → API Keys. PortOS stores it in <code className="bg-port-bg px-1 rounded">data/settings.json</code>.
      </p>

      <form onSubmit={handleSave} className="space-y-2">
        <FormField label="API key" labelClassName="block text-xs font-medium text-gray-400" className="space-y-2">
          <input
            type="password"
            value={apiKey}
            onChange={(e) => setApiKey(e.target.value)}
            placeholder={auth?.hasKey ? '•••• key already set — paste a new one to replace' : 'paste your Civitai API key'}
            className="w-full bg-port-bg border border-port-border rounded px-3 py-2 text-sm text-gray-200 placeholder:text-gray-600 font-mono"
            disabled={saving}
            autoFocus
          />
        </FormField>
        <div className="flex items-center gap-2 pt-1">
          <button
            type="submit"
            disabled={saving || !apiKey.trim()}
            className="flex-1 bg-port-accent text-white px-4 py-2 rounded text-sm font-medium hover:bg-port-accent/90 disabled:opacity-50 disabled:cursor-not-allowed"
          >
            {saving ? 'Saving…' : (pendingUrl ? 'Save key & retry install' : 'Save key')}
          </button>
          {auth?.hasKey && auth?.source === 'settings' && (
            <button
              type="button"
              onClick={handleClear}
              disabled={clearing}
              className="px-3 py-2 rounded text-xs text-port-error hover:bg-port-error/10 border border-port-error/30 disabled:opacity-50"
            >
              {clearing ? 'Clearing…' : 'Clear'}
            </button>
          )}
        </div>
      </form>
    </Modal>
  );
}

// Responsive grid of installed LoRA cards. Extracted so the Installed section
// can render either one flat grid (filtered view) or several grouped grids
// (the "All" view) without duplicating the grid markup.
function LoraGrid({ loras, deleting, onDelete, onMeasured, deleteConfirm }) {
  return (
    <div className="grid grid-cols-1 sm:grid-cols-2 lg:grid-cols-3 xl:grid-cols-4 gap-4">
      {loras.map((lora) => (
        <LoraCard
          key={lora.filename}
          lora={lora}
          onDelete={() => onDelete(lora.filename)}
          onMeasured={onMeasured}
          deleting={deleting === lora.filename}
          deleteConfirm={deleteConfirm}
        />
      ))}
    </div>
  );
}

// Installed LoRAs split into Video / Image subsections for the "All" view, each
// with a labeled header mirroring the suggestion panel's grouping. Empty groups
// are omitted. Video is listed first (fewer, and the source of the layout
// confusion this grouping resolves).
function InstalledGroups({ loras, deleting, onDelete, onMeasured, deleteConfirm }) {
  const video = loras.filter((l) => isVideoLoraFamily(l.runnerFamily));
  const image = loras.filter((l) => !isVideoLoraFamily(l.runnerFamily));
  const groups = [
    { key: 'video', label: 'Video LoRAs', items: video },
    { key: 'image', label: 'Image LoRAs', items: image },
  ].filter((g) => g.items.length > 0);
  return (
    <div className="space-y-5">
      {groups.map((g) => (
        <div key={g.key}>
          <div className="flex items-baseline gap-3 mb-2">
            <h3 className="text-sm font-medium text-gray-300">{g.label}</h3>
            <span className="text-xs text-gray-600">{g.items.length}</span>
          </div>
          <LoraGrid loras={g.items} deleting={deleting} onDelete={onDelete} onMeasured={onMeasured} deleteConfirm={deleteConfirm} />
        </div>
      ))}
    </div>
  );
}

function LoraCard({ lora, onDelete, onMeasured, deleting, deleteConfirm }) {
  const family = lora.runnerFamily;
  const familyLabel = family ? (RUNNER_LABEL[family] || family) : 'Unsupported base';
  const badgeClass = family ? (RUNNER_BADGE_CLASS[family] || 'bg-gray-600/20 text-gray-300 border-gray-500/30') : 'bg-port-warning/20 text-port-warning border-port-warning/30';
  const triggerWords = lora.triggerWords || [];
  const civitai = lora.civitai;
  // The gen pages read ?lora=<filename> as a preselect hint via query string;
  // keeps the manager → gen handoff URL-driven (deep-linkable). Video-family
  // LoRAs (ltx-video, minimax-h3) deep-link to Video Gen — routing them to Image
  // Gen would preselect a video adapter into an incompatible image render.
  const isVideoLora = isVideoLoraFamily(family);
  const testHref = `${isVideoLora ? '/media/video' : '/media/image'}?lora=${encodeURIComponent(lora.filename)}`;
  // The confirm pair also stays mounted while the delete is in flight (the hook
  // disarms the moment it fires), so the spinner replaces the row rather than
  // flashing the trash icon back for the duration of the request.
  const confirming = deleteConfirm.isConfirming(lora.filename) || deleting;
  // A sidecar-less install can reach the client with no `name` (the server
  // falls back to the filename, but peers and hand-dropped files predate that),
  // and "Delete undefined" is a bad thing to announce over a destructive action.
  const displayName = lora.name || lora.filename;

  // Read straight off the server's CACHED report (listLorasFull never probes) — an
  // explicit re-check hands the new one to `onMeasured`, which updates the list
  // entry, so the badge survives this card being unmounted by a filter change.
  const effect = lora.effectReport || null;
  const [checkingEffect, setCheckingEffect] = useState(false);
  const effectSummary = loraEffectDetail(effect);
  const runEffectCheck = async () => {
    setCheckingEffect(true);
    await probeLoraEffect(lora.filename, { force: true, silent: true })
      .then((report) => {
        onMeasured?.(lora.filename, report);
        const summary = loraEffectDetail(report);
        if (report?.status === LORA_EFFECT_STATUSES.ZERO) {
          toast.error(`${displayName} has no measurable effect — a render would look as if it were off`);
        } else if (report?.status === LORA_EFFECT_STATUSES.OK) {
          toast.success(`${displayName} is active — ${summary}`);
        } else {
          toast(summary || `${displayName}: ${loraEffectBadge(report?.status).label}`);
        }
      })
      .catch((err) => toast.error(err?.message || 'Effect check failed'))
      .finally(() => setCheckingEffect(false));
  };

  return (
    <div className="bg-port-card border border-port-border rounded-lg overflow-hidden flex flex-col">
      {lora.previewImageUrl ? (
        <img
          src={lora.previewImageUrl}
          alt=""
          className="w-full h-64 object-cover bg-port-bg"
          loading="lazy"
          referrerPolicy="no-referrer"
        />
      ) : (
        <div className="w-full h-64 bg-port-bg flex items-center justify-center text-gray-700">
          <Sparkles size={32} />
        </div>
      )}
      <div className="p-3 flex-1 flex flex-col">
        <div className="flex items-start justify-between gap-2 mb-2">
          <h3 className="font-semibold text-white text-sm flex-1 break-words">{displayName}</h3>
          <span className={`text-[10px] px-2 py-0.5 rounded border whitespace-nowrap ${badgeClass}`} title={civitai?.baseModel || 'Unknown'}>
            {familyLabel}
          </span>
        </div>

        {/* Trained-in-PortOS lineage: character chip links back to the
            retained training artifacts in Data Maintenance. */}
        {lora.source === 'trained' && lora.character && (
          <div className="mb-2">
            <Link
              to="/settings/data-maintenance"
              className="inline-flex items-center gap-1 text-[11px] px-2 py-0.5 rounded-full bg-port-success/15 text-port-success border border-port-success/30 hover:bg-port-success/25"
              title="Trained in PortOS — open the training dataset"
            >
              <Sparkles size={11} /> Character: {lora.character.name}
            </Link>
          </div>
        )}

        {triggerWords.length > 0 && (
          <div className="mb-2">
            <div className="text-[10px] uppercase tracking-wide text-gray-500 mb-1">Trigger words</div>
            <div className="flex flex-wrap gap-1">
              {triggerWords.map((w) => (
                <code key={w} className="text-[11px] bg-port-bg px-1.5 py-0.5 rounded text-gray-300 border border-port-border">{w}</code>
              ))}
            </div>
          </div>
        )}

        <div className="text-[11px] text-gray-500 grid grid-cols-2 gap-x-2 gap-y-0.5 mb-3">
          <span>Recommended scale</span><span className="text-gray-300 font-mono text-right">{Number(lora.recommendedScale ?? 1).toFixed(2)}</span>
          <span>Size</span><span className="text-gray-300 font-mono text-right">{formatBytes(lora.sizeBytes)}</span>
          {civitai?.creator && (<><span>Creator</span><span className="text-gray-300 truncate text-right" title={civitai.creator}>{civitai.creator}</span></>)}
          {civitai?.baseModel && (<><span>Base model</span><span className="text-gray-300 truncate text-right" title={civitai.baseModel}>{civitai.baseModel}</span></>)}
        </div>

        {effect && (
          <div className="text-[11px] mb-3 -mt-1">
            <span className={`font-medium ${loraEffectBadge(effect.status).tone}`}>
              {loraEffectBadge(effect.status).label}
            </span>
            {/* loraEffectDetail returns null when the badge already says
                everything, so a reason-less verdict doesn't render as
                "Unreadable — Unreadable". */}
            {effectSummary && <span className="text-gray-500"> — {effectSummary}</span>}
          </div>
        )}

        {/* Armed state replaces the whole action row instead of squeezing the
            confirm pair in beside Test/Civitai — a narrow card (or a phone at
            one column) has no room for both, and the row would wrap. */}
        {confirming ? (
          <div className="mt-auto">
            <ConfirmButtonPair
              prompt="Delete file?"
              confirmText="Delete"
              confirmIcon={Trash2}
              busy={deleting}
              busyText="Deleting"
              ariaLabel={`Confirm delete ${displayName}`}
              onConfirm={() => deleteConfirm.confirmDelete(onDelete)}
              onCancel={deleteConfirm.cancelDelete}
            />
          </div>
        ) : (
          <div className="mt-auto flex items-center gap-2">
            <Link
              to={testHref}
              className="flex-1 bg-port-accent text-white px-3 py-1.5 rounded text-xs font-medium hover:bg-port-accent/90 text-center"
            >
              Test
            </Link>
            {civitai?.url && (
              <a
                href={civitai.url}
                target="_blank"
                rel="noopener noreferrer"
                className="text-gray-400 hover:text-gray-200 p-1.5 rounded hover:bg-port-bg"
                title="Open on Civitai"
                aria-label="Open on Civitai"
              >
                <ExternalLink size={14} />
              </a>
            )}
            {lora.huggingface?.url && (
              <a
                href={lora.huggingface.url}
                target="_blank"
                rel="noopener noreferrer"
                className="text-gray-400 hover:text-gray-200 p-1.5 rounded hover:bg-port-bg"
                title="Open on HuggingFace"
                aria-label="Open on HuggingFace"
              >
                <ExternalLink size={14} />
              </a>
            )}
            <button
              onClick={runEffectCheck}
              disabled={checkingEffect}
              className="min-h-[44px] min-w-[44px] inline-flex items-center justify-center text-gray-400 hover:text-gray-200 p-1.5 rounded hover:bg-port-bg disabled:opacity-50 disabled:cursor-not-allowed"
              title={`Check whether ${displayName} actually changes a render`}
              aria-label={`Check effect of ${displayName}`}
            >
              {checkingEffect ? <BrailleSpinner /> : <Activity size={14} />}
            </button>
            <button
              onClick={() => deleteConfirm.requestDelete(lora.filename)}
              className="min-h-[44px] min-w-[44px] inline-flex items-center justify-center text-port-error hover:text-port-error/80 p-1.5 rounded hover:bg-port-error/10"
              title={`Delete ${displayName}`} aria-label={`Delete ${displayName}`}
            >
              <Trash2 size={14} />
            </button>
          </div>
        )}
      </div>
    </div>
  );
}