import React, {
  useCallback,
  useEffect,
  useMemo,
  useRef,
  useState,
  useContext,
  useReducer,
} from 'react';
import { createRoot } from 'react-dom/client';
import axios from 'axios';
import {
  HashRouter,
  Navigate,
  Route,
  Routes,
  Outlet,
  useLocation,
  useNavigate,
  matchPath,
} from 'react-router-dom';
import './styles.css';
import AssetManager, { getAssetFromVersion, resolveDocumentAssetUrl } from './asset_manager';
import useApiError from './hooks/useApiError';
import SkeuomorphicWorkspace from './skeuomorphic_ws';
import { DownloadIcon, EditIcon } from './ui/icons';
import { generateRandomTagColor, getTagColorStyle, HEX_COLOR_PATTERN } from './utils/colors';
import Sidebar from './sidebar/Sidebar';
import DocumentsTable, { FilterBar } from './documents/DocumentsTable';

const runtimeApiBase =
  typeof window !== 'undefined' && window.__PAPERCRATE_API_BASE_URL
    ? window.__PAPERCRATE_API_BASE_URL
    : '';

const DEFAULT_DEV_API = 'http://127.0.0.1:3000';
const ASSET_PRESIGN_TTL_MS = 240 * 1000; // backend issues 5 min tokens; refresh slightly early

const API_ROOT = (runtimeApiBase || process.env.API_BASE_URL || DEFAULT_DEV_API).replace(/\/$/, '');

const api = axios.create({
  baseURL: API_ROOT ? `${API_ROOT}/api` : '/api',
  withCredentials: true,
});

const STORED_TOKEN = window.localStorage.getItem('papercrate_token') || '';
if (STORED_TOKEN) {
  api.defaults.headers.common.Authorization = `Bearer ${STORED_TOKEN}`;
}

const initialAppState = {
  status: STORED_TOKEN ? 'authenticated' : 'logged-out',
  token: STORED_TOKEN,
  error: null,
  isRefreshing: false,
};

const AppStateContext = React.createContext(null);
const AppDispatchContext = React.createContext(null);

const appStateReducer = (state, action) => {
  switch (action.type) {
    case 'LOGIN_REQUEST':
      return { ...state, status: 'authenticating', error: null };
    case 'LOGIN_SUCCESS':
      return { ...state, status: 'authenticated', token: action.token, error: null };
    case 'LOGIN_FAILURE':
      return { status: 'logged-out', token: '', error: action.error || null, isRefreshing: false };
    case 'BOOTSTRAP_START':
      return { ...state, status: 'bootstrapping', error: null };
    case 'BOOTSTRAP_SUCCESS':
      return { ...state, status: 'ready', error: null };
    case 'BOOTSTRAP_FAILURE':
      return { ...state, status: 'authenticated', error: action.error || null };
    case 'TOKEN_REFRESH_START':
      return { ...state, isRefreshing: true, error: null };
    case 'TOKEN_REFRESH_SUCCESS':
      return {
        ...state,
        token: action.token,
        isRefreshing: false,
        status: state.status === 'logged-out' ? 'authenticated' : state.status,
      };
    case 'TOKEN_REFRESH_FAILURE':
      return { status: 'logged-out', token: '', error: action.error || null, isRefreshing: false };
    case 'LOGOUT':
      return { status: 'logged-out', token: '', error: null, isRefreshing: false };
    case 'RESET_ERROR':
      return { ...state, error: null };
    default:
      return state;
  }
};

const AppStateProvider = ({ children }) => {
  const [state, dispatch] = useReducer(appStateReducer, initialAppState);

  useEffect(() => {
    const token = state.token || '';
    if (token) {
      api.defaults.headers.common.Authorization = `Bearer ${token}`;
      window.localStorage.setItem('papercrate_token', token);
    } else {
      delete api.defaults.headers.common.Authorization;
      window.localStorage.removeItem('papercrate_token');
    }
  }, [state.token]);

  const stateValue = useMemo(() => state, [state]);

  return (
    <AppStateContext.Provider value={stateValue}>
      <AppDispatchContext.Provider value={dispatch}>
        {children}
      </AppDispatchContext.Provider>
    </AppStateContext.Provider>
  );
};

const useAppState = () => {
  const context = useContext(AppStateContext);
  if (!context) {
    throw new Error('useAppState must be used within an AppStateProvider.');
  }
  return context;
};

const useAppDispatch = () => {
  const context = useContext(AppDispatchContext);
  if (!context) {
    throw new Error('useAppDispatch must be used within an AppStateProvider.');
  }
  return context;
};

const DEFAULT_FOLDER_NAME = 'All Documents';

const resolveApiPath = (path = '') => (API_ROOT ? `${API_ROOT}${path}` : path);

const hasFiles = (event) =>
  Array.from(event.dataTransfer?.types || []).includes('Files');

const createRootNode = () => ({
  id: 'root',
  name: DEFAULT_FOLDER_NAME,
  parentId: null,
  children: [],
  expanded: true,
  loaded: false,
});

const StatusBanner = ({ status }) => {
  if (!status) return null;
  return <div className={`status-banner ${status.variant}`}>{status.message}</div>;
};

const DropOverlay = ({ active, folderName }) => (
  <div className={`drop-overlay${active ? ' active' : ''}`}>
    <div className="drop-overlay__content">
      Drop files to upload to <strong>{folderName}</strong>
    </div>
  </div>
);

const LoginView = ({ onSubmit, status }) => (
  <div className="login-screen">
    <div className="login-card">
      <h1>Papercrate</h1>
      <p>Authenticate to manage your documents.</p>
      <form onSubmit={onSubmit}>
        <label htmlFor="username">Username</label>
        <input
          id="username"
          name="username"
          placeholder="admin"
          autoComplete="username"
          required
        />
        <label htmlFor="password">Password</label>
        <input
          id="password"
          name="password"
          type="password"
          placeholder="••••••"
          autoComplete="current-password"
          required
        />
        <button type="submit">Sign in</button>
      </form>
      <StatusBanner status={status} />
    </div>
  </div>
);



const computeStackAngle = (docId, index) => {
  if (index === 0) return 0;
  let hash = 0;
  const source = docId || `stack-${index}`;
  for (let i = 0; i < source.length; i += 1) {
    hash = (hash * 31 + source.charCodeAt(i)) % 997;
  }
  const magnitude = Math.max(3, (hash % 13) + 3); // 3..15
  const sign = index % 2 === 0 ? 1 : -1;
  return magnitude * sign;
};

const MAX_PREVIEW_STACK_ITEMS = 15;

const PreviewStack = ({
  items = [],
  maxItems = MAX_PREVIEW_STACK_ITEMS,
  emptyMessage = 'Preview unavailable',
  onItemActivate,
  onOpenPreview,
  activeItemId = null,
}) => {
  if (!items.length) {
    return <span className="meta">{emptyMessage}</span>;
  }

  const limited = items.slice(0, maxItems);
  const hasMultiple = limited.length > 1;
  const preparedItems = useMemo(
    () =>
      limited.map((entry, index) => ({
        entry,
        angle: index === 0 ? 0 : computeStackAngle(entry.id, index),
        offset: 0,
      })),
    [limited],
  );

  return (
    <div className="preview-stack preview-stack--stacked">
      {preparedItems.map(({ entry, angle, offset }, index) => {
        const transform = hasMultiple
          ? `translate(-50%, -50%) rotate(${angle}deg)`
          : 'translate(-50%, -50%)';
        const isFront = index === 0;
        return (
          <div
            key={entry.id || index}
            className={`preview-stack__item orientation-${entry.orientation || 'landscape'}`}
            style={{
              zIndex: preparedItems.length - index,
              transform,
            }}
            aria-hidden={
              hasMultiple && !onItemActivate && !onOpenPreview ? 'true' : undefined
            }
          >
            <img
              src={entry.url}
              alt={entry.alt || ''}
              className="preview-stack__image"
              onClick={(event) => {
                event.stopPropagation();
                if (isFront && onOpenPreview) {
                  onOpenPreview(entry.id);
                } else if (onItemActivate) {
                  onItemActivate(entry.id);
                }
              }}
              onKeyDown={(event) => {
                if (!onItemActivate && !onOpenPreview) return;
                if (event.key === 'Enter' || event.key === ' ') {
                  event.preventDefault();
                  event.stopPropagation();
                  if (isFront && onOpenPreview) {
                    onOpenPreview(entry.id);
                  } else {
                    onItemActivate?.(entry.id);
                  }
                }
              }}
            />
          </div>
        );
      })}
    </div>
  );
};

const DetailPanel = ({
  selectedDocuments = [],
  tags = [],
  tagLookupById = new Map(),
  tagLookupByLabel = new Map(),
  onTagAdd,
  onTagRemove,
  onRegenerateThumbnails,
  previewEntry,
  onOpenPreview,
  onBulkTagAdd,
  onBulkTagRemove,
  onBulkMove,
  onBulkReanalyze,
  folderOptions = [],
  defaultMoveTarget = 'root',
  onPromoteSelection,
  activePreviewId = null,
  onUpdateTitle = async () => false,
  ensureAssetUrl = null,
  getDocumentAsset = () => null,
}) => {
  const selectedCount = selectedDocuments.length;
  const singleDoc = selectedCount === 1 ? selectedDocuments[0] : null;

  const [titleEditDocId, setTitleEditDocId] = useState(null);
  const [titleDraft, setTitleDraft] = useState('');
  const [titleSaving, setTitleSaving] = useState(false);
  const [titleError, setTitleError] = useState(null);

  useEffect(() => {
    if (!singleDoc) {
      setTitleEditDocId(null);
      setTitleDraft('');
      setTitleError(null);
      setTitleSaving(false);
      return;
    }

    if (titleEditDocId && titleEditDocId !== singleDoc.id) {
      setTitleEditDocId(null);
      setTitleDraft('');
      setTitleError(null);
      setTitleSaving(false);
    }
  }, [singleDoc, titleEditDocId]);

  const startTitleEdit = useCallback(() => {
    if (!singleDoc) return;
    setTitleEditDocId(singleDoc.id);
    setTitleDraft(singleDoc.title || singleDoc.original_name || '');
    setTitleError(null);
  }, [singleDoc]);

  const cancelTitleEdit = useCallback(() => {
    setTitleEditDocId(null);
    setTitleDraft('');
    setTitleError(null);
    setTitleSaving(false);
  }, []);

  const submitTitleEdit = useCallback(
    async (event) => {
      event.preventDefault();
      if (!singleDoc) return;
      const trimmed = titleDraft.trim();
      if (!trimmed) {
        setTitleError('Title cannot be empty.');
        return;
      }
      setTitleSaving(true);
      try {
        const ok = await onUpdateTitle(singleDoc.id, trimmed);
        if (ok) {
          setTitleEditDocId(null);
          setTitleDraft('');
          setTitleError(null);
        } else {
          setTitleError('Failed to update title.');
        }
      } finally {
        setTitleSaving(false);
      }
    },
    [singleDoc, titleDraft, onUpdateTitle],
  );

  const handlePreviewActivate = useCallback(
    (docId) => {
      if (!docId) return;
      onPromoteSelection?.(docId);
    },
    [onPromoteSelection],
  );

  const makePreviewItem = useCallback(
    (doc) => {
      if (!doc) return null;
      const url = resolveDocumentAssetUrl(doc, 'preview', {
        ensureAssetUrl,
        getAsset: getDocumentAsset,
      });
      if (!url) {
        return null;
      }
      const asset = getDocumentAsset(doc, 'preview');
      const width = Number(asset?.metadata?.width) || 0;
      const height = Number(asset?.metadata?.height) || 0;
      const orientation = width > 0 && height > 0 ? (width >= height ? 'landscape' : 'portrait') : 'landscape';
      return {
        id: doc.id,
        url,
        orientation,
        alt: doc.title || doc.original_name || 'Document preview',
      };
    },
    [ensureAssetUrl, getDocumentAsset],
  );

  const stackDocuments = useMemo(() => {
    if (!selectedDocuments.length) return [];
    const seen = new Set();
    const ordered = [];
    for (let index = selectedDocuments.length - 1; index >= 0; index -= 1) {
      const doc = selectedDocuments[index];
      if (!doc?.id || seen.has(doc.id)) continue;
      seen.add(doc.id);
      ordered.push(doc);
      if (ordered.length >= MAX_PREVIEW_STACK_ITEMS) {
        break;
      }
    }
    return ordered;
  }, [selectedDocuments]);

  const singlePreviewItems = useMemo(() => {
    if (!singleDoc) return [];
    const item = makePreviewItem(singleDoc);
    return item ? [item] : [];
  }, [singleDoc, makePreviewItem]);

  const stackPreviews = useMemo(
    () =>
      stackDocuments
        .map((doc) => makePreviewItem(doc))
        .filter(Boolean),
    [stackDocuments, makePreviewItem],
  );

  useEffect(() => {
    if (!ensureAssetUrl) {
      return;
    }

    stackDocuments.forEach((doc) => {
      resolveDocumentAssetUrl(doc, 'preview', {
        ensureAssetUrl,
        getAsset: getDocumentAsset,
      });
    });
  }, [stackDocuments, ensureAssetUrl, getDocumentAsset]);

  const commonTags = useMemo(() => {
    if (selectedCount < 2) return [];
    const tagSets = selectedDocuments.map((doc) => new Set((doc.tags || []).map((tag) => tag.label)));
    if (!tagSets.length) return [];
    const intersection = new Set(tagSets[0]);
    tagSets.slice(1).forEach((set) => {
      [...intersection].forEach((label) => {
        if (!set.has(label)) {
          intersection.delete(label);
        }
      });
    });
    return [...intersection];
  }, [selectedDocuments, selectedCount]);

  const stackTotalSizeBytes = useMemo(() => {
    if (!stackPreviews.length) return 0;
    const byId = new Map(selectedDocuments.map((doc) => [doc.id, doc]));
    return stackPreviews.reduce((sum, item) => {
      const source = byId.get(item.id);
      const bytes = source?.current_version?.size_bytes;
      return sum + (typeof bytes === 'number' ? bytes : 0);
    }, 0);
  }, [stackPreviews, selectedDocuments]);

  const renderSingle = () => {
    if (!singleDoc) {
      return <p className="meta">Select a document to view metadata, tags and actions.</p>;
    }

    const displayName = singleDoc.title || singleDoc.original_name;
    const downloadHref = singleDoc.current_version?.download_path
      ? resolveApiPath(singleDoc.current_version.download_path)
      : null;
    const isEditingTitle = titleEditDocId === singleDoc.id;
    const sizeBytes = Number(singleDoc.current_version?.size_bytes) || 0;
    const issuedAt = singleDoc.issued_at
      ? new Date(singleDoc.issued_at).toLocaleString()
      : '—';
    const tagsForDoc = Array.isArray(singleDoc.tags) ? singleDoc.tags : [];
    const metadata =
      singleDoc.metadata && Object.keys(singleDoc.metadata).length > 0 ? singleDoc.metadata : null;

    return (
      <>
        <div>
          <div className="preview-pane preview-pane--stack">
            <PreviewStack
              items={singlePreviewItems}
              maxItems={1}
              emptyMessage="Preview loading…"
              onItemActivate={handlePreviewActivate}
              onOpenPreview={onOpenPreview}
              activeItemId={activePreviewId}
            />
          </div>
        </div>
        <div className="doc-title-row">
          {isEditingTitle ? (
            <form className="doc-title-edit" onSubmit={submitTitleEdit}>
              <input
                value={titleDraft}
                onChange={(event) => {
                  setTitleDraft(event.target.value);
                  if (titleError) {
                    setTitleError(null);
                  }
                }}
                onKeyDown={(event) => {
                  if (event.key === 'Escape') {
                    event.preventDefault();
                    cancelTitleEdit();
                  }
                }}
                aria-label="Document title"
                autoFocus
              />
              <button type="submit" disabled={titleSaving}>
                Save
              </button>
              <button
                type="button"
                className="secondary"
                onClick={cancelTitleEdit}
                disabled={titleSaving}
              >
                Cancel
              </button>
            </form>
          ) : (
            <>
              <h3 style={{ margin: 0 }}>{displayName}</h3>
              <button
                type="button"
                className="icon-button ghost"
                onClick={startTitleEdit}
                aria-label="Edit title"
                title="Edit title"
              >
                <EditIcon className="icon-inline" />
              </button>
            </>
          )}
        </div>
        {titleError ? <div className="status-inline error">{titleError}</div> : null}
        <div className="meta">
          <div>
            <strong>Uploaded:</strong>{' '}
            {singleDoc.uploaded_at ? new Date(singleDoc.uploaded_at).toLocaleString() : '—'}
          </div>
          <div>
            <strong>Size:</strong>{' '}
            {sizeBytes ? `${(sizeBytes / 1024).toFixed(1)} KB` : '—'}
          </div>
          <div>
            <strong>Type:</strong> {singleDoc.content_type || 'Unknown'}
          </div>
          <div>
            <strong>Issued:</strong> {issuedAt}
          </div>
          <div>
            <strong>Original filename:</strong>{' '}
            {singleDoc.original_name}
          </div>
        </div>
        <div className="detail-actions">
          <a
            className="button-link with-icon"
            href={downloadHref || '#'}
            target="_blank"
            rel="noopener noreferrer"
            aria-disabled={!downloadHref}
            onClick={(event) => {
              if (!downloadHref) {
                event.preventDefault();
              }
            }}
          >
            <DownloadIcon className="icon-inline" />
            <span>Download</span>
          </a>
          <button
            type="button"
            className="secondary"
            onClick={() => onOpenPreview(singleDoc.id)}
          >
            Open preview
          </button>
          <button
            type="button"
            className="secondary"
            onClick={() => onRegenerateThumbnails(singleDoc.id)}
          >
            Re-run analysis
          </button>
        </div>
        <div>
          <dt>Tags</dt>
          <div className="tag-list">
            {tagsForDoc.length ? (
              tagsForDoc.map((tag) => {
                const colorSource = tag?.color || tagLookupById.get(tag.id)?.color;
                const style = getTagColorStyle(colorSource);
                return (
                  <span key={tag.id} className="tag-pill" style={style || undefined}>
                    {tag.label}{' '}
                    <button type="button" onClick={() => onTagRemove(singleDoc.id, tag.id)}>
                      ×
                    </button>
                  </span>
                );
              })
            ) : (
              <span className="meta">No tags yet.</span>
            )}
          </div>
          <form
            className="inline"
            onSubmit={(event) => {
              event.preventDefault();
              const input = event.currentTarget.elements.tag;
              const value = input.value.trim();
              if (!value) return;
              onTagAdd(singleDoc, value, input);
            }}
          >
            <input name="tag" placeholder="Add or create tag" list="tag-catalog" />
            <button type="submit">Add</button>
            <datalist id="tag-catalog">
              {tags.map((tag) => (
                <option key={tag.id} value={tag.label} />
              ))}
            </datalist>
          </form>
        </div>
        {metadata && (
          <div>
            <dt>Metadata</dt>
            <pre>{JSON.stringify(metadata, null, 2)}</pre>
          </div>
        )}
      </>
    );
  };

  const renderBulk = () => {
    const countLabel = `${selectedCount} document${selectedCount === 1 ? '' : 's'}`;
    const sizeLabel = stackTotalSizeBytes
      ? `${(stackTotalSizeBytes / 1024).toFixed(1)} KB`
      : '—';

    return (
      <>
        <div>
          <div className="preview-pane preview-pane--stack">
            <PreviewStack
              items={stackPreviews}
              emptyMessage="No previews available."
              onItemActivate={handlePreviewActivate}
              onOpenPreview={onOpenPreview}
              activeItemId={activePreviewId}
            />
          </div>
        </div>
        <h3 style={{ margin: 0 }}>{countLabel}</h3>
        <div className="meta">
          <div>
            <strong>Total size (stack):</strong> {sizeLabel}
          </div>
          <div>
            <strong>Common tags:</strong>{' '}
            {commonTags.length ? commonTags.join(', ') : 'None'}
          </div>
        </div>
        {commonTags.length > 0 && (
          <div className="bulk-tags">
            <strong>Bulk tag operations</strong>
            <form
              className="inline"
              onSubmit={(event) => {
                event.preventDefault();
                const input = event.currentTarget.elements.tag;
                const value = input.value.trim();
                if (!value) return;
                onBulkTagAdd?.({ label: value, input });
              }}
            >
              <input name="tag" placeholder="Add tag to selection" list="tag-catalog" />
              <button type="submit">Add tag</button>
            </form>
            <form
              className="inline"
              onSubmit={(event) => {
                event.preventDefault();
                const input = event.currentTarget.elements.tag;
                const value = input.value.trim();
                if (!value) return;
                onBulkTagRemove?.({ label: value, input });
              }}
            >
              <input name="tag" placeholder="Remove tag from selection" list="tag-catalog" />
              <button type="submit" className="secondary">
                Remove tag
              </button>
            </form>
          </div>
        )}
        <datalist id="tag-catalog">
          {tags.map((tag) => (
            <option key={tag.id} value={tag.label} />
          ))}
        </datalist>
        <div className="bulk-move">
          <label htmlFor="detail-bulk-move" className="meta">
            Move selection to folder
          </label>
          <select
            id="detail-bulk-move"
            name="target"
            defaultValue={defaultMoveTarget || 'root'}
            onChange={(event) => onBulkMove?.({ target: event.target.value })}
          >
            {folderOptions.map((option) => (
              <option key={option.id} value={option.id}>
                {option.label}
              </option>
            ))}
          </select>
        </div>
        <button
          type="button"
          className="secondary"
          onClick={() => onBulkReanalyze?.()}
        >
          Re-analyze selection
        </button>
      </>
    );
  };

  return (
    <aside className="detail-panel column">
      <div className="column-header">
        <h2>Details</h2>
      </div>
      <div className="column-body scrollable">
        {selectedCount <= 1 ? renderSingle() : renderBulk()}
      </div>
    </aside>
  );
};

const PreviewWorkspace = ({
  document,
  previewEntry,
  onClose,
  onRegenerateThumbnails,
}) => {
  if (!document) {
    return null;
  }

  const title = document.title || document.original_name || 'Document';
  const mime = previewEntry?.contentType || document.content_type || 'application/pdf';
  const downloadHref = document.current_version?.download_path
    ? resolveApiPath(document.current_version.download_path)
    : null;
  const sizeBytes = Number(document.current_version?.size_bytes) || 0;
  const metadata =
    document.metadata && Object.keys(document.metadata).length > 0 ? document.metadata : null;

  return (
    <section className="preview-workspace">
      <header className="preview-workspace__header">
        <div className="preview-workspace__meta">
          <button
            type="button"
            className="secondary"
            onClick={() => onClose(document.folder_id ?? 'root')}
          >
            ← Back
          </button>
          <div>
            <h2>{title}</h2>
            <span className="meta">
              {document.content_type || mime}
              {sizeBytes ? ` · ${(sizeBytes / 1024 / 1024).toFixed(2)} MB` : ''}
            </span>
          </div>
        </div>
        <div className="preview-workspace__actions">
          <a
            className="button-link with-icon"
            href={downloadHref || '#'}
            target="_blank"
            rel="noopener noreferrer"
            aria-disabled={!downloadHref}
            onClick={(event) => {
              if (!downloadHref) {
                event.preventDefault();
              }
            }}
          >
            <DownloadIcon className="icon-inline" />
            <span>Download</span>
          </a>
          <button
            type="button"
            className="secondary"
            onClick={() => onRegenerateThumbnails(document.id)}
          >
            Re-run analysis
          </button>
        </div>
      </header>
      <div className="preview-workspace__body">
        {!previewEntry?.url ? (
          <div className="preview-workspace__message">Loading preview…</div>
        ) : (
          <iframe
            src={previewEntry.url}
            title={`Preview of ${title}`}
            className="preview-workspace__object"
          />
        )}
      </div>
      {metadata && (
        <section className="preview-workspace__metadata">
          <h3>Metadata</h3>
          <pre>{JSON.stringify(metadata, null, 2)}</pre>
        </section>
      )}
    </section>
  );
};

const TagsPanel = ({ tags, onRefresh, onUpdateTag }) => {
  const [editingId, setEditingId] = useState(null);
  const [draftLabel, setDraftLabel] = useState('');
  const [draftColor, setDraftColor] = useState('');
  const [error, setError] = useState(null);
  const [saving, setSaving] = useState(false);

  const startEdit = useCallback((tag) => {
    setEditingId(tag.id);
    setDraftLabel(tag.label || '');
    setDraftColor(tag.color || '');
    setError(null);
  }, []);

  const cancelEdit = useCallback(() => {
    setEditingId(null);
    setDraftLabel('');
    setDraftColor('');
    setSaving(false);
    setError(null);
  }, []);

  const colorPickerValue = useMemo(() => {
    if (!draftColor) {
      return '#3366ff';
    }
    const match = HEX_COLOR_PATTERN.exec(draftColor.trim());
    if (!match) {
      return '#3366ff';
    }
    return `#${match[1].toLowerCase()}`;
  }, [draftColor]);

  const handleSave = useCallback(async () => {
    if (!editingId) return;

    const trimmedLabel = draftLabel.trim();
    if (!trimmedLabel) {
      setError('Tag label cannot be empty.');
      return;
    }

    const trimmedColor = draftColor.trim();
    const colorPattern = /^#([0-9a-fA-F]{6})$/;
    if (trimmedColor && !colorPattern.test(trimmedColor)) {
      setError('Colors must use the #RRGGBB format.');
      return;
    }

    setSaving(true);
    setError(null);
    try {
      await onUpdateTag(editingId, {
        label: trimmedLabel,
        color: trimmedColor ? trimmedColor : null,
      });
      cancelEdit();
    } catch (updateError) {
      const message = updateError?.message || 'Failed to update tag.';
      setError(message);
    } finally {
      setSaving(false);
    }
  }, [editingId, draftLabel, draftColor, onUpdateTag, cancelEdit]);

  const handleKeyDown = useCallback(
    (event) => {
      if (event.key === 'Enter') {
        event.preventDefault();
        handleSave();
      } else if (event.key === 'Escape') {
        event.preventDefault();
        cancelEdit();
      }
    },
    [handleSave, cancelEdit],
  );

  return (
    <section className="tags-panel column">
      <div className="column-header">
        <div className="column-header__titles">
          <h2>Tags</h2>
          <div className="column-subtitle">{tags.length} total</div>
        </div>
        <div className="header-actions">
          <button className="secondary" type="button" onClick={onRefresh} disabled={saving}>
            Refresh
          </button>
        </div>
      </div>
      <div className="column-body tags-panel__body">
        {error && (
          <div className="tags-panel__error" role="alert">
            {error}
          </div>
        )}
        {tags.length === 0 ? (
          <div className="empty-state">No tags created yet.</div>
        ) : (
          <div className="tags-table">
            <table>
              <thead>
                <tr>
                  <th scope="col">Tag</th>
                  <th scope="col">Color</th>
                  <th scope="col" className="numeric">
                    Documents
                  </th>
                  <th scope="col" className="actions">
                    Actions
                  </th>
                </tr>
              </thead>
              <tbody>
                {tags.map((tag) => {
                  const isEditing = editingId === tag.id;
                  return (
                    <tr key={tag.id} className={isEditing ? 'editing' : ''}>
                  <td className="tags-table__label">
                    {isEditing ? (
                      <input
                        className="tags-table__label-input"
                        value={draftLabel}
                        onChange={(event) => setDraftLabel(event.target.value)}
                        onKeyDown={handleKeyDown}
                        disabled={saving}
                        autoFocus
                      />
                    ) : (
                      <span
                        className="badge tag-chip"
                        style={getTagColorStyle(tag.color) || undefined}
                      >
                        {tag.label}
                      </span>
                    )}
                  </td>
                      <td>
                        {isEditing ? (
                          <div className="tags-table__color-editor">
                            <input
                              type="color"
                              className="tags-table__color-picker"
                              value={colorPickerValue}
                              onChange={(event) => setDraftColor(event.target.value)}
                              disabled={saving}
                              aria-label="Pick tag color"
                            />
                            {draftColor && (
                              <button
                                type="button"
                                className="secondary"
                                onClick={() => setDraftColor('')}
                                disabled={saving}
                              >
                                Clear
                              </button>
                            )}
                          </div>
                        ) : tag.color ? (
                          <span
                            className="tags-table__swatch"
                            style={{ backgroundColor: tag.color }}
                            aria-label={`Tag color ${tag.color}`}
                          />
                        ) : (
                          <span className="meta">—</span>
                        )}
                      </td>
                      <td className="numeric">{tag.usage_count ?? 0}</td>
                      <td className="actions">
                        {isEditing ? (
                          <div className="tags-table__edit-controls">
                            <button
                              type="button"
                              className="secondary"
                              onClick={handleSave}
                              disabled={saving}
                            >
                              Save
                            </button>
                            <button
                              type="button"
                              className="secondary"
                              onClick={cancelEdit}
                              disabled={saving}
                            >
                              Cancel
                            </button>
                          </div>
                        ) : (
                          <button
                            type="button"
                            className="secondary"
                            onClick={() => startEdit(tag)}
                          >
                            Edit
                          </button>
                        )}
                      </td>
                    </tr>
                  );
                })}
              </tbody>
            </table>
          </div>
        )}
      </div>
    </section>
  );
};

const MainLayout = ({ sidebarProps, children, className = 'app-main' }) => (
  <main className={className}>
    <Sidebar {...sidebarProps} />
    {children}
  </main>
);

const AppShellContext = React.createContext(null);

const AppLayout = () => {
  const navigate = useNavigate();
  const location = useLocation();
  const appState = useAppState();
  const appDispatch = useAppDispatch();
  const folderMatch = matchPath('/folders/:folderId', location.pathname);
  const nestedDocMatch = matchPath('/folders/:folderId/documents/:documentId', location.pathname);
  const docMatch = nestedDocMatch || matchPath('/documents/:documentId', location.pathname);
  const routeFolderId =
    folderMatch?.params?.folderId || nestedDocMatch?.params?.folderId || null;
  const routeDocumentId = docMatch?.params?.documentId || null;
  const { status: appStatus, token } = appState;
  const [status, setStatus] = useState(null);
  const setStatusMessage = useCallback((message, variant = 'info') => {
    setStatus(message ? { message, variant } : null);
  }, []);
  const handleApiReport = useCallback(
    ({ message, variant }) => setStatusMessage(message, variant),
    [setStatusMessage],
  );
  const reportApiError = useApiError({
    onReport: handleApiReport,
  });
  const notifyApiError = useCallback(
    (error, fallbackMessage, variant = 'error') =>
      reportApiError(error, { message: fallbackMessage, variant }),
    [reportApiError],
  );
  const [loading, setLoading] = useState(false);
  const [isCreateFolderModalOpen, setCreateFolderModalOpen] = useState(false);
  const [newFolderName, setNewFolderName] = useState('');
  const [createFolderError, setCreateFolderError] = useState('');
  const [creatingFolder, setCreatingFolder] = useState(false);
  const createFolderInputRef = useRef(null);
  const [folderNodes, setFolderNodes] = useState(() => {
    const rootNode = createRootNode();
    return new Map([[rootNode.id, rootNode]]);
  });
  const [folderContents, setFolderContents] = useState(() => new Map());
  const [selectedFolder, setSelectedFolder] = useState(routeFolderId || 'root');
  const [currentFolder, setCurrentFolder] = useState(null);
  const [currentSubfolders, setCurrentSubfolders] = useState([]);
  const [documents, setDocuments] = useState([]);
  const [workspaceMode, setWorkspaceMode] = useState('table');
  const initialSelection = routeDocumentId ? [routeDocumentId] : [];
  const [selectedDocumentIds, setSelectedDocumentIds] = useState(initialSelection);
  const [selectionOrder, setSelectionOrder] = useState(initialSelection);
  const [focusedDocumentId, setFocusedDocumentId] = useState(routeDocumentId);
  const [focusedRowKey, setFocusedRowKey] = useState(() =>
    routeDocumentId ? `document:${routeDocumentId}` : null,
  );
  const tokenRef = useRef(token);
  const refreshPromiseRef = useRef(null);
  const breadcrumbFetchRef = useRef(new Set());
  const refreshAccessToken = useCallback(async () => {
    console.log('[Auth] Attempting to refresh access token…');
    appDispatch({ type: 'TOKEN_REFRESH_START' });
    try {
      const { data } = await api.post('/auth/refresh');
      if (data?.access_token) {
        appDispatch({ type: 'TOKEN_REFRESH_SUCCESS', token: data.access_token });
        console.log('[Auth] Access token refreshed at', new Date().toISOString());
        return data.access_token;
      }
      throw new Error('Missing access token in refresh response');
    } catch (error) {
      console.warn('[Auth] Failed to refresh access token', error);
      appDispatch({ type: 'TOKEN_REFRESH_FAILURE', error: error?.message || null });
      throw error;
    }
  }, [appDispatch]);
  const [searchResults, setSearchResults] = useState(null);
  const [tags, setTags] = useState([]);
  const [searchQuery, setSearchQuery] = useState('');
  const [activeTagFilters, setActiveTagFilters] = useState([]);
  const [draggedDocumentIds, setDraggedDocumentIds] = useState([]);
  const [draggedFolderId, setDraggedFolderId] = useState(null);
  const [dropOverlayState, setDropOverlayState] = useState({
    active: false,
    folderName: DEFAULT_FOLDER_NAME,
  });
  const [activePreviewId, setActivePreviewId] = useState(routeDocumentId || null);
  const [previewDocumentId, setPreviewDocumentId] = useState(null);
  const [previewDocumentLoading, setPreviewDocumentLoading] = useState(false);
  const shellRef = useRef(null);
  const assetManagerRef = useRef(null);
  if (!assetManagerRef.current) {
    assetManagerRef.current = new AssetManager({ api, assetPresignTtlMs: ASSET_PRESIGN_TTL_MS });
  }
  const assetManager = assetManagerRef.current;

  const getDocumentAsset = useCallback((doc, type) => {
    if (!doc || !type) return null;
    return getAssetFromVersion(doc.current_version || null, type);
  }, []);

  const isAssetEquivalent = (lhs, rhs) => {
    if (!lhs || !rhs) return false;
    return (
      lhs.id === rhs.id &&
      lhs.url === rhs.url &&
      lhs?.metadata?.width === rhs?.metadata?.width &&
      lhs?.metadata?.height === rhs?.metadata?.height &&
      lhs.mime_type === rhs.mime_type &&
      lhs.asset_type === rhs.asset_type &&
      lhs.created_at === rhs.created_at
    );
  };

  const mergeAssetIntoGroup = (group, assetData) => {
    if (!assetData || !assetData.asset_type) {
      if (Array.isArray(group)) {
        return group;
      }
      return group || {};
    }

    if (Array.isArray(group) || !group) {
      const list = Array.isArray(group) ? group : [];
      const index = list.findIndex((item) => item?.id === assetData.id);
      if (index >= 0) {
        const existing = list[index];
        if (isAssetEquivalent(existing, assetData)) {
          return list;
        }
        const next = list.slice();
        next[index] = { ...existing, ...assetData };
        return next;
      }
      return list.concat({ ...assetData });
    }

    const key = assetData.asset_type;
    const previous = group?.[key];
    if (previous && isAssetEquivalent(previous, assetData)) {
      return group;
    }

    const next = { ...(group || {}) };
    next[key] = { ...(previous || {}), ...assetData };
    return next;
  };

  const mergeAssetIntoDocument = (doc, assetData) => {
    if (!doc) return doc;
    const existingGroup = doc.current_version?.assets || null;
    const nextGroup = mergeAssetIntoGroup(existingGroup, assetData);
    if (nextGroup === existingGroup) {
      return doc;
    }
    const updatedCurrentVersion = doc.current_version
      ? { ...doc.current_version, assets: nextGroup }
      : { assets: nextGroup };
    return { ...doc, current_version: updatedCurrentVersion };
  };

  const bootstrapInitializedRef = useRef(false);
  const selectionInitializedRef = useRef(false);
  const dragCounterRef = useRef(0);
  const prefetchedFoldersRef = useRef(new Set(['root']));
  const selectionAnchorRef = useRef(routeDocumentId);
  const selectionOrderRef = useRef(initialSelection);

  const resetWorkspaceState = useCallback(() => {
    const rootNode = createRootNode();
    setFolderNodes(new Map([[rootNode.id, rootNode]]));
    setFolderContents(new Map());
    setSelectedFolder('root');
    setCurrentFolder(null);
    setCurrentSubfolders([]);
    setDocuments([]);
    setSelectedDocumentIds([]);
    setSelectionOrder([]);
    selectionOrderRef.current = [];
    setFocusedDocumentId(null);
    selectionAnchorRef.current = null;
    setDraggedDocumentIds([]);
    setDraggedFolderId(null);
    setSearchResults(null);
    setTags([]);
    setSearchQuery('');
    setActiveTagFilters([]);
    setDropOverlayState({ active: false, folderName: DEFAULT_FOLDER_NAME });
    setActivePreviewId(null);
    setPreviewDocumentId(null);
    setPreviewDocumentLoading(false);
    assetManager.reset();
    setPreviewEntries(() => new Map());
    previewInflightRef.current = new Map();
    dragCounterRef.current = 0;
    prefetchedFoldersRef.current = new Set(['root']);
    breadcrumbFetchRef.current = new Set();
    bootstrapInitializedRef.current = false;
    selectionInitializedRef.current = false;
  }, [assetManager]);

  const tagLookupById = useMemo(() => {
    const map = new Map();
    tags.forEach((tag) => {
      if (tag?.id) {
        map.set(tag.id, tag);
      }
    });
    return map;
  }, [tags]);

  const tagLookupByLabel = useMemo(() => {
    const map = new Map();
    tags.forEach((tag) => {
      if (tag?.label) {
        map.set(tag.label.toLowerCase(), tag);
      }
    });
    return map;
  }, [tags]);

  const updateSelectionOrder = useCallback((nextSelection, interactedIds = []) => {
    const nextSet = new Set(nextSelection);
    const previousOrder = selectionOrderRef.current.filter((id) => nextSet.has(id));
    const interacted = (interactedIds || []).filter((id, index, array) => array.indexOf(id) === index);

    const base = previousOrder.filter((id) => !interacted.includes(id));
    const result = [...base];

    interacted.forEach((id) => {
      if (nextSet.has(id) && !result.includes(id)) {
        result.push(id);
      }
    });

    nextSelection.forEach((id) => {
      if (!result.includes(id)) {
        result.push(id);
      }
    });

    if (
      result.length !== selectionOrderRef.current.length ||
      result.some((id, index) => selectionOrderRef.current[index] !== id)
    ) {
      selectionOrderRef.current = result;
      setSelectionOrder(result);
    } else {
      selectionOrderRef.current = result;
    }
  }, []);

  useEffect(() => {
    if (appStatus === 'logged-out') {
      resetWorkspaceState();
    }
  }, [appStatus, resetWorkspaceState]);

  useEffect(() => {
    tokenRef.current = token;
  }, [token]);

  useEffect(() => {
    const requestInterceptor = api.interceptors.request.use((config) => {
      const currentToken = tokenRef.current;
      if (currentToken) {
        config.headers = config.headers || {};
        if (!config.headers.Authorization) {
          config.headers.Authorization = `Bearer ${currentToken}`;
        }
      }
      return config;
    });

    const responseInterceptor = api.interceptors.response.use(
      (response) => response,
      async (error) => {
        const { response, config } = error;
        if (!response || !config) {
          return Promise.reject(error);
        }

        const status = response.status;
        const url = typeof config.url === 'string' ? config.url : '';
        const isAuthRoute = url.includes('/auth/login') || url.includes('/auth/refresh');

        if (status === 401 && !config._retry && !isAuthRoute) {
          console.warn('[Auth] 401 received for', url, '- attempting token refresh');

          if (!refreshPromiseRef.current) {
            refreshPromiseRef.current = (async () => {
              try {
                return await refreshAccessToken();
              } finally {
                refreshPromiseRef.current = null;
              }
            })();
          }

          try {
            const newToken = await refreshPromiseRef.current;
            if (!newToken) {
              throw new Error('No token returned from refresh');
            }
            config._retry = true;
            config.headers = config.headers || {};
            config.headers.Authorization = `Bearer ${newToken}`;
            console.log('[Auth] Retrying original request', url);
            try {
              return await api(config);
            } catch (retryError) {
              if (retryError?.response?.status === 401) {
                notifyApiError(retryError, 'Session expired. Please log in again.');
              }
              throw retryError;
            }
          } catch (refreshError) {
            console.warn('[Auth] Refresh failed, clearing session');
            notifyApiError(refreshError, 'Session expired. Please log in again.');
            return Promise.reject(refreshError);
          }
        }

        return Promise.reject(error);
      },
    );

    return () => {
      api.interceptors.request.eject(requestInterceptor);
      api.interceptors.response.eject(responseInterceptor);
    };
  }, [notifyApiError, refreshAccessToken]);

  useEffect(() => {
    if (!selectedDocumentIds.length) {
      if (activePreviewId !== null) {
        setActivePreviewId(null);
      }
      return;
    }
    if (!selectedDocumentIds.includes(activePreviewId)) {
      setActivePreviewId(selectedDocumentIds[selectedDocumentIds.length - 1]);
    }
    selectionInitializedRef.current = true;
  }, [selectedDocumentIds, activePreviewId]);

  const currentFolderName = useMemo(() => {
    if (selectedFolder === 'root' || !currentFolder) return DEFAULT_FOLDER_NAME;
    return currentFolder.name;
  }, [selectedFolder, currentFolder]);

  const isFilterActive = useMemo(
    () => searchQuery.trim().length > 0 || activeTagFilters.length > 0,
    [searchQuery, activeTagFilters],
  );

  const applySelectedFolder = useCallback(
    (folderId, contents) => {
      const subfolders = contents?.subfolders ?? [];
      const docs = assetManager.hydrateDocuments(contents?.documents ?? []);
      const folderInfo = contents?.folder ?? null;

      setCurrentSubfolders(subfolders);
      setDocuments(docs);
      setCurrentFolder(folderInfo);

      const availableIds = new Set(docs.map((doc) => doc.id));
      let nextSelection = [];

      setSelectedDocumentIds((previous) => {
        if (selectionInitializedRef.current) {
          nextSelection = previous.filter((id) => availableIds.has(id));
          return nextSelection;
        }
        const filtered = previous.filter((id) => availableIds.has(id));
        if (filtered.length) {
          nextSelection = filtered;
          return filtered;
        }
        if (docs.length) {
          nextSelection = [docs[0].id];
          return nextSelection;
        }
        nextSelection = [];
        return [];
      });

      let nextFocus = focusedDocumentId && availableIds.has(focusedDocumentId)
        ? focusedDocumentId
        : null;
      if (!nextFocus && nextSelection.length) {
        nextFocus = nextSelection[nextSelection.length - 1];
      }

      setFocusedDocumentId(nextFocus);
      selectionAnchorRef.current = nextSelection.length
        ? nextSelection[nextSelection.length - 1]
        : null;
      selectionOrderRef.current = nextSelection;
      setSelectionOrder(nextSelection);

      return nextFocus;
    },
    [assetManager, focusedDocumentId, setSelectionOrder],
  );

  const showingSearchResults = searchResults !== null;

  const visibleDocuments = useMemo(
    () => (showingSearchResults ? searchResults : documents),
    [showingSearchResults, searchResults, documents],
  );

  const visibleDocumentIds = useMemo(
    () => visibleDocuments.map((doc) => doc.id),
    [visibleDocuments],
  );

  const applySelection = useCallback(
    (ids, { anchor, interactedIds = [] } = {}) => {
      const visibleSet = new Set(visibleDocumentIds);
      const unique = [];
      ids.forEach((id) => {
        if (visibleSet.has(id) && !unique.includes(id)) {
          unique.push(id);
        }
      });

      let resolvedAnchor = anchor;
      if (resolvedAnchor && !unique.includes(resolvedAnchor)) {
        resolvedAnchor = null;
      }

      const nextFocus =
        (focusedDocumentId && unique.includes(focusedDocumentId) && focusedDocumentId) ||
        resolvedAnchor ||
        (unique.length ? unique[unique.length - 1] : null);

      setSelectedDocumentIds(unique);
      setFocusedDocumentId(nextFocus);
      updateSelectionOrder(unique, interactedIds);

      if (resolvedAnchor) {
        selectionAnchorRef.current = resolvedAnchor;
      } else if (unique.length === 0) {
        selectionAnchorRef.current = null;
      } else if (
        !selectionAnchorRef.current ||
        !unique.includes(selectionAnchorRef.current)
      ) {
        selectionAnchorRef.current = unique[unique.length - 1];
      }

      return { selection: unique, focus: nextFocus };
    },
    [visibleDocumentIds, focusedDocumentId, updateSelectionOrder],
  );

  const promoteSelectionOrder = useCallback(
    (docId) => {
      if (!docId) return;
      if (!selectedDocumentIds.includes(docId)) return;
      updateSelectionOrder(selectedDocumentIds, [docId]);
      selectionAnchorRef.current = docId;
      setFocusedDocumentId(docId);
      setActivePreviewId(docId);
    },
    [selectedDocumentIds, updateSelectionOrder],
  );

  const visibleSelectedCount = useMemo(
    () => selectedDocumentIds.filter((id) => visibleDocumentIds.includes(id)).length,
    [selectedDocumentIds, visibleDocumentIds],
  );

  const allDocumentsSelected =
    visibleDocumentIds.length > 0 &&
    visibleSelectedCount === visibleDocumentIds.length;
  const someDocumentsSelected =
    visibleSelectedCount > 0 && !allDocumentsSelected;

  const folderOptions = useMemo(() => {
    const cache = new Map();
    const computePath = (id) => {
      if (cache.has(id)) {
        return cache.get(id);
      }
      if (!id || id === 'root') {
        cache.set('root', DEFAULT_FOLDER_NAME);
        return DEFAULT_FOLDER_NAME;
      }
      const node = folderNodes.get(id);
      if (!node) {
        return 'Folder';
      }
      const parentId = node.parentId || 'root';
      const parentPath = computePath(parentId);
      const name = node.name || 'Folder';
      const fullPath = parentId === 'root' ? name : `${parentPath}/${name}`;
      cache.set(id, fullPath);
      return fullPath;
    };

    const entries = [];
    folderNodes.forEach((node, id) => {
      if (!node) return;
      entries.push({ id, label: computePath(id) });
    });

    entries.sort((a, b) => {
      if (a.id === 'root') return -1;
      if (b.id === 'root') return 1;
      return a.label.localeCompare(b.label, undefined, { sensitivity: 'base' });
    });

    return entries;
  }, [folderNodes]);

  const folderLabelMap = useMemo(() => {
    const map = new Map();
    folderOptions.forEach((option) => {
      map.set(option.id, option.label);
    });
    return map;
  }, [folderOptions]);

  const handleDocumentRowClick = useCallback(
    (documentId, event) => {
      const { shiftKey, metaKey, ctrlKey } = event;
      const additive = metaKey || ctrlKey;
      if (shiftKey) {
        event.preventDefault();
      }
      if (!visibleDocumentIds.includes(documentId)) {
        return;
      }

      let anchor = selectionAnchorRef.current;
      if (!anchor && shiftKey && selectedDocumentIds.length) {
        anchor = selectedDocumentIds[selectedDocumentIds.length - 1];
      }
      if (!anchor) {
        anchor = documentId;
      }
      let nextIds;
      let interactedIds = [];

      if (shiftKey && anchor) {
        const anchorIndex = visibleDocumentIds.indexOf(anchor);
        const targetIndex = visibleDocumentIds.indexOf(documentId);
        if (anchorIndex !== -1 && targetIndex !== -1) {
          const [start, end] =
            anchorIndex <= targetIndex
              ? [anchorIndex, targetIndex]
              : [targetIndex, anchorIndex];
          const range = visibleDocumentIds.slice(start, end + 1);
          nextIds = range;

          const ordered = anchorIndex <= targetIndex ? range : [...range].reverse();
          const previousSet = new Set(selectedDocumentIds);
          interactedIds = ordered.filter(
            (id) => id === documentId || !previousSet.has(id),
          );
          if (!interactedIds.includes(documentId)) {
            interactedIds.push(documentId);
          }
        } else {
          nextIds = [documentId];
          interactedIds = [documentId];
        }
      } else if (additive) {
        if (selectedDocumentIds.includes(documentId)) {
          nextIds = selectedDocumentIds.filter((id) => id !== documentId);
          interactedIds = [];
        } else {
          nextIds = [...selectedDocumentIds, documentId];
          interactedIds = [documentId];
        }
        anchor = documentId;
      } else {
        nextIds = [documentId];
        interactedIds = [documentId];
        anchor = documentId;
      }

      applySelection(nextIds, { anchor, interactedIds });
    },
    [
      visibleDocumentIds,
      selectedDocumentIds,
      applySelection,
    ],
  );

  const navigableRows = useMemo(() => {
    const entries = [];
    if (!showingSearchResults) {
      currentSubfolders.forEach((folder) => {
        entries.push({ key: `folder:${folder.id}`, type: 'folder', id: folder.id });
      });
    }
    visibleDocuments.forEach((doc) => {
      entries.push({ key: `document:${doc.id}`, type: 'document', id: doc.id });
    });
    return entries;
  }, [showingSearchResults, currentSubfolders, visibleDocuments]);

  const navigableRowKeys = useMemo(
    () => navigableRows.map((entry) => entry.key),
    [navigableRows],
  );

  const prevFocusedDocIdRef = useRef(focusedDocumentId);
  useEffect(() => {
    const previous = prevFocusedDocIdRef.current;
    if (previous === focusedDocumentId) {
      return;
    }
    prevFocusedDocIdRef.current = focusedDocumentId;
    if (focusedDocumentId) {
      setFocusedRowKey(`document:${focusedDocumentId}`);
    } else {
      setFocusedRowKey((current) => (current?.startsWith('folder:') ? current : null));
    }
  }, [focusedDocumentId]);

  useEffect(() => {
    if (!focusedRowKey) {
      return;
    }
    if (navigableRowKeys.includes(focusedRowKey)) {
      return;
    }
    const docKey = focusedDocumentId ? `document:${focusedDocumentId}` : null;
    if (docKey && navigableRowKeys.includes(docKey)) {
      setFocusedRowKey(docKey);
      return;
    }
    if (navigableRowKeys.length) {
      setFocusedRowKey(navigableRowKeys[0]);
    } else {
      setFocusedRowKey(null);
    }
  }, [focusedRowKey, navigableRowKeys, focusedDocumentId]);


  const handleDocumentDragStart = useCallback(
    (event, documentId) => {
      const selection = selectedDocumentIds.includes(documentId)
        ? selectedDocumentIds
        : [documentId];

      if (!selectedDocumentIds.includes(documentId)) {
        applySelection([documentId], {
          anchor: documentId,
          interactedIds: [documentId],
        });
      }

      setDraggedDocumentIds(selection);
      event.dataTransfer.effectAllowed = 'move';
      try {
        event.dataTransfer.setData(
          'application/x-papercrate-doc-list',
          JSON.stringify(selection),
        );
      } catch (
        // eslint-disable-next-line no-empty
        error
      ) {}
      event.currentTarget.classList.add('dragging');
    },
    [selectedDocumentIds, applySelection],
  );

  const handleDocumentDragEnd = useCallback((event) => {
    setDraggedDocumentIds([]);
    event.currentTarget.classList.remove('dragging');
  }, []);

  const ensureFolderData = useCallback(
    async (folderId, { force = false } = {}) => {
      if (!force && folderContents.has(folderId)) {
        return folderContents.get(folderId);
      }

      const path = folderId === 'root' ? 'root' : folderId;
      const { data } = await api.get(`/folders/${path}/contents`);
      const hydrated = assetManager.hydrateFolderContents(data);

      setFolderNodes((prev) => {
        const next = new Map(prev);
        const existingNode = next.get(folderId) || {
          id: folderId,
          name: folderId === 'root' ? DEFAULT_FOLDER_NAME : data.folder?.name || 'Folder',
          parentId: data.folder?.parent_id || 'root',
          children: [],
          expanded: folderId === 'root',
          loaded: false,
        };

        const childIds = (data.subfolders || []).map((child) => child.id);
        next.set(folderId, {
          ...existingNode,
          name: folderId === 'root' ? DEFAULT_FOLDER_NAME : data.folder?.name || existingNode.name,
          parentId: data.folder?.parent_id ?? existingNode.parentId ?? 'root',
          children: childIds,
          expanded: folderId === 'root' ? true : existingNode.expanded,
          loaded: true,
        });

        (data.subfolders || []).forEach((child) => {
          const childNode = next.get(child.id);
          next.set(child.id, {
            id: child.id,
            name: child.name,
            parentId: child.parent_id ?? 'root',
            children: childNode?.children ?? [],
            expanded: childNode?.expanded ?? false,
            loaded: childNode?.loaded ?? false,
          });
        });

        return next;
      });

      setFolderContents((prev) => {
        const next = new Map(prev);
        next.set(folderId, hydrated);
        return next;
      });

      return hydrated;
    },
    [assetManager, folderContents],
  );
  const greedyPrefetchFolders = useCallback(
    async (startIds) => {
      const queue = Array.isArray(startIds) ? [...startIds] : [];
      const visited = prefetchedFoldersRef.current;

      while (queue.length) {
        const nextId = queue.shift();
        if (!nextId || visited.has(nextId)) {
          continue;
        }
        visited.add(nextId);

        try {
          const contents = await ensureFolderData(nextId, { force: false });
          const subfolders = Array.isArray(contents?.subfolders) ? contents.subfolders : [];
          subfolders.forEach((entry) => {
            if (entry?.id && !visited.has(entry.id)) {
              queue.push(entry.id);
            }
          });
        } catch (error) {
          console.warn('[Folders] Failed to prefetch folder tree for', nextId, error);
        }
      }
    },
    [ensureFolderData],
  );

  const isInvalidFolderDrop = useCallback(
    (sourceId, targetId) => {
      if (!sourceId) return false;
      if (!targetId || targetId === 'root') {
        return false;
      }
      if (sourceId === targetId) {
        return true;
      }

      let current = targetId;
      const visited = new Set();
      while (current && current !== 'root' && !visited.has(current)) {
        visited.add(current);
        if (current === sourceId) {
          return true;
        }
        const node = folderNodes.get(current);
        if (!node) break;
        current = node.parentId ?? 'root';
      }
      return false;
    },
    [folderNodes],
  );

  const moveFolder = useCallback(
    async (folderId, targetFolderId) => {
      const node = folderNodes.get(folderId);
      if (!node) {
        setStatusMessage('Folder metadata unavailable. Try refreshing.', 'error');
        return;
      }

      const previousParentKey = node.parentId ?? 'root';
      const targetKey = targetFolderId && targetFolderId !== 'root' ? targetFolderId : 'root';

      if (previousParentKey === targetKey) {
        return;
      }

      const parent_id = targetKey === 'root' ? null : targetKey;

      try {
        await api.patch(`/folders/${folderId}`, { parent_id });

        setFolderNodes((prev) => {
          const next = new Map(prev);
          const currentNode = next.get(folderId);
          if (!currentNode) {
            return prev;
          }

          const updatedNode = { ...currentNode, parentId: parent_id ?? null };
          next.set(folderId, updatedNode);

          const previousParent = next.get(previousParentKey);
          if (previousParent) {
            next.set(previousParentKey, {
              ...previousParent,
              children: (previousParent.children || []).filter((childId) => childId !== folderId),
            });
          }

          if (!next.has(targetKey)) {
            next.set(targetKey, {
              id: targetKey,
              name: targetKey === 'root' ? DEFAULT_FOLDER_NAME : 'Folder',
              parentId: targetKey === 'root' ? null : null,
              children: [],
              expanded: targetKey === 'root',
              loaded: false,
            });
          }

          const targetNode = next.get(targetKey);
          if (targetNode && !targetNode.children.includes(folderId)) {
            next.set(targetKey, {
              ...targetNode,
              children: [...targetNode.children, folderId],
            });
          }

          return next;
        });

        const refreshTargets = new Set([previousParentKey, targetKey]);
        for (const key of refreshTargets) {
          if (key === 'root') {
            await ensureFolderData('root', { force: true });
          } else {
            await ensureFolderData(key, { force: true });
          }
        }

        if (selectedFolder === folderId) {
          await ensureFolderData(folderId, { force: true });
          setSelectedFolder(folderId);
        }

        setStatusMessage('Folder moved.', 'success');
      } catch (error) {
        const message = error.response?.data?.error || 'Failed to move folder.';
        notifyApiError(error, message);

        const refreshTargets = new Set([previousParentKey, targetKey]);
        for (const key of refreshTargets) {
          if (key === 'root') {
            await ensureFolderData('root', { force: true });
          } else {
            await ensureFolderData(key, { force: true });
          }
        }
      }
    },
    [api, folderNodes, ensureFolderData, selectedFolder, setSelectedFolder, setFolderNodes, notifyApiError],
  );

  const handleFolderDragStart = useCallback(
    (event, folderId) => {
      if (folderId === 'root') {
        return;
      }
      event.stopPropagation();
      setDraggedFolderId(folderId);
      event.dataTransfer.effectAllowed = 'move';
      try {
        event.dataTransfer.setData('application/x-papercrate-folder', folderId);
      } catch (
        // eslint-disable-next-line no-empty
        error
      ) {}
    },
    [setDraggedFolderId],
  );

  const handleFolderDragEnd = useCallback(() => {
    setDraggedFolderId(null);
  }, [setDraggedFolderId]);

  const refreshTags = useCallback(async () => {
    try {
      const { data } = await api.get('/tags');
      setTags(data || []);
    } catch (error) {
      notifyApiError(error, 'Unable to load tags.');
    }
  }, [api, notifyApiError]);

  const handleTagUpdate = useCallback(
    async (tagId, changes) => {
      if (!tagId) {
        throw new Error('Missing tag identifier.');
      }

      const payload = {};
      if (typeof changes.label === 'string') {
        payload.label = changes.label;
      }
      if (Object.prototype.hasOwnProperty.call(changes, 'color')) {
        payload.color = changes.color;
      }

      if (Object.keys(payload).length === 0) {
        return false;
      }

      try {
        await api.patch(`/tags/${tagId}`, payload);
        await refreshTags();
        setStatusMessage('Tag updated.', 'success');
        return true;
      } catch (error) {
        const message = error.response?.data?.error || 'Failed to update tag.';
        notifyApiError(error, message);
        throw new Error(message);
      }
    },
    [api, refreshTags, notifyApiError, setStatusMessage],
  );

  const handleTagCreate = useCallback(
    async ({ label, color }) => {
      const trimmed = (label || '').trim();
      if (!trimmed) {
        throw new Error('Tag label is required.');
      }
      const payload = { label: trimmed, color: color || generateRandomTagColor() };
      try {
        await api.post('/tags', payload);
        await refreshTags();
        setStatusMessage('Tag created.', 'success');
      } catch (error) {
        const message = error.response?.data?.error || 'Failed to create tag.';
        notifyApiError(error, message);
        throw new Error(message);
      }
    },
    [api, refreshTags, notifyApiError],
  );

  const loadFolder = useCallback(
    async (folderId, { showLoading = true } = {}) => {
      const targetId = folderId || 'root';
      setSelectedFolder(targetId);
      if (showLoading) setLoading(true);
      try {
        const contents = await ensureFolderData(targetId, { force: true });
        if (targetId !== 'root') {
          try {
            await ensureFolderData('root', { force: false });
          } catch (error) {
            console.warn('Failed to refresh root folder tree', error);
          }
        }
        applySelectedFolder(targetId, contents);
        setSearchResults(null);
      } catch (error) {
        notifyApiError(error, 'Failed to load folder contents.');
      } finally {
        if (showLoading) setLoading(false);
      }
    },
    [ensureFolderData, applySelectedFolder, notifyApiError],
  );

  useEffect(() => {
    if (!folderContents || typeof folderContents.forEach !== 'function') {
      return;
    }

    const pendingIds = [];
    folderContents.forEach((contents) => {
      const subfolders = Array.isArray(contents?.subfolders) ? contents.subfolders : [];
      subfolders.forEach((entry) => {
        if (entry?.id && !prefetchedFoldersRef.current.has(entry.id)) {
          pendingIds.push(entry.id);
        }
      });
    });

    if (!pendingIds.length) {
      return;
    }

    greedyPrefetchFolders(pendingIds).catch(() => {});
  }, [folderContents, greedyPrefetchFolders]);

  const selectFolder = useCallback(
    async (folderId, { replace = false, immediate = false } = {}) => {
      const targetId = folderId && folderId !== 'root' ? folderId : 'root';

      if (!navigate || immediate) {
        await loadFolder(targetId);
        return;
      }

      const path = targetId === 'root' ? '/folders' : `/folders/${targetId}`;
      navigate(path, { replace });
    },
    [loadFolder, navigate],
  );

  const initializeAfterLogin = useCallback(async () => {
    setLoading(true);
    try {
      await refreshTags();
      const initialFolder = routeFolderId && routeFolderId !== 'root' ? routeFolderId : 'root';
      await loadFolder(initialFolder, { showLoading: false });
    } catch (error) {
      notifyApiError(error, 'Failed to initialize data.');
      throw error;
    } finally {
      setLoading(false);
    }
  }, [refreshTags, routeFolderId, loadFolder, notifyApiError]);

  useEffect(() => {
    if (!token) {
      return;
    }
    if (appStatus !== 'ready' && appStatus !== 'bootstrapping') {
      return;
    }

    const targetParam = routeFolderId ?? 'root';

    if (targetParam === 'root' && routeDocumentId) {
      return;
    }

    const hasData = folderContents.has(targetParam);
    if (targetParam !== selectedFolder || !hasData) {
      loadFolder(targetParam, { showLoading: !routeDocumentId });
    }
  }, [
    token,
    appStatus,
    routeFolderId,
    routeDocumentId,
    selectedFolder,
    loadFolder,
    folderContents,
  ]);

  const refreshCurrentFolder = useCallback(async () => {
    setLoading(true);
    try {
      const contents = await ensureFolderData(selectedFolder, { force: true });
      applySelectedFolder(selectedFolder, contents);
    } catch (error) {
      notifyApiError(error, 'Failed to refresh folder.');
    } finally {
      setLoading(false);
    }
  }, [selectedFolder, ensureFolderData, applySelectedFolder, notifyApiError]);

  useEffect(() => {
    if (appStatus !== 'authenticated') {
      return;
    }
    if (bootstrapInitializedRef.current) {
      return;
    }

    let cancelled = false;
    const bootstrap = async () => {
      bootstrapInitializedRef.current = true;
      appDispatch({ type: 'BOOTSTRAP_START' });
      try {
        await initializeAfterLogin();
        if (!cancelled) {
          appDispatch({ type: 'BOOTSTRAP_SUCCESS' });
        }
      } catch (error) {
        if (!cancelled) {
          appDispatch({
            type: 'BOOTSTRAP_FAILURE',
            error: error?.message || 'Failed to initialize data.',
          });
          bootstrapInitializedRef.current = false;
        }
      }
    };

    bootstrap();

    return () => {
      cancelled = true;
    };
  }, [appStatus, appDispatch, initializeAfterLogin]);

  const handleBulkMoveSubmit = useCallback(
    async (event) => {
      event.preventDefault();
      if (!selectedDocumentIds.length) {
        setStatusMessage('Select documents before moving.', 'error');
        return;
      }

      const form = new FormData(event.currentTarget);
      const target = form.get('target')?.toString() || 'root';
      const folderId = target === 'root' ? null : target;

      setLoading(true);
      try {
        await api.post('/documents/bulk/move', {
          document_ids: selectedDocumentIds,
          folder_id: folderId,
        });

        const count = selectedDocumentIds.length;
        const suffix = count === 1 ? '' : 's';
        const folderLabel =
          folderId === null
            ? DEFAULT_FOLDER_NAME
            : folderLabelMap.get(target) || 'target folder';
        setStatusMessage(
          `Moved ${count} document${suffix} to ${folderLabel}.`,
          'success',
        );

        applySelection([], { anchor: null });

        await refreshCurrentFolder();
      if (folderId && folderId !== selectedFolder) {
        await ensureFolderData(folderId, { force: true });
      }

      event.currentTarget.reset();
    } catch (error) {
      const message = error.response?.data?.error || 'Failed to move documents.';
      notifyApiError(error, message);
    } finally {
      setLoading(false);
    }
  },
  [
    api,
    selectedDocumentIds,
    folderLabelMap,
    applySelection,
    refreshCurrentFolder,
    ensureFolderData,
    notifyApiError,
    selectedFolder,
    setStatusMessage,
  ],
  );

  const parseTagInput = useCallback((value) => {
    return value
      .split(',')
      .map((item) => item.trim())
      .filter(Boolean);
  }, []);

  const bulkTagOperation = useCallback(
    async ({ labels, action }) => {
      const normalized = labels.map((label) => label.trim()).filter((label) => label.length > 0);
      if (!normalized.length) {
        return { ok: false, reason: 'no-labels' };
      }
      if (!selectedDocumentIds.length) {
        return { ok: false, reason: 'no-selection' };
      }

      let tagIds = [];

      if (action === 'remove') {
        const missing = normalized.find(
          (label) => !tags.some((tag) => tag.label.toLowerCase() === label.toLowerCase()),
        );
        if (missing) {
          return { ok: false, reason: 'tag-missing', label: missing };
        }

        tagIds = normalized.map((label) => {
          const tag = tags.find((item) => item.label.toLowerCase() === label.toLowerCase());
          return tag?.id;
        }).filter(Boolean);
      }

      setLoading(true);
      try {
        if (action === 'add') {
          const createdIds = [];
          for (const label of normalized) {
            let tag = tags.find((item) => item.label.toLowerCase() === label.toLowerCase()) || null;
            if (!tag) {
              const { data } = await api.post('/tags', { label, color: null });
              tag = data;
              await refreshTags();
            }
            createdIds.push(tag.id);
          }
          tagIds = Array.from(new Set(createdIds));
        }

        tagIds = Array.from(new Set(tagIds));

        if (!tagIds.length) {
          return { ok: false, reason: 'no-tags' };
        }

        await api.post('/documents/bulk/tags', {
          document_ids: selectedDocumentIds,
          tag_ids: tagIds,
          action,
        });

        await refreshCurrentFolder();

        return {
          ok: true,
          tagCount: tagIds.length,
          docsCount: selectedDocumentIds.length,
        };
      } catch (error) {
        const message =
          error.response?.data?.error ||
          (action === 'add' ? 'Failed to assign tags.' : 'Failed to remove tags.');
        notifyApiError(error, message);
        return { ok: false, reason: 'request-failed' };
      } finally {
        setLoading(false);
      }
    },
    [
      selectedDocumentIds,
      tags,
      api,
      refreshTags,
      refreshCurrentFolder,
      notifyApiError,
      setLoading,
    ],
  );

  const handleBulkTagAdd = useCallback(
    async (event) => {
      event.preventDefault();
      if (!selectedDocumentIds.length) {
        setStatusMessage('Select documents before assigning tags.', 'error');
        return;
      }

      const form = new FormData(event.currentTarget);
      const raw = form.get('tags')?.toString().trim() || '';
      const labels = parseTagInput(raw);
      if (!labels.length) {
        setStatusMessage('Enter at least one tag label.', 'error');
        return;
      }
      const result = await bulkTagOperation({ labels, action: 'add' });
      if (result?.ok) {
        const { tagCount, docsCount } = result;
        setStatusMessage(
          `Assigned ${tagCount} tag${tagCount === 1 ? '' : 's'} to ${docsCount} document${
            docsCount === 1 ? '' : 's'
          }.`,
          'success',
        );
        event.currentTarget.reset();
      } else if (result?.reason === 'no-labels') {
        setStatusMessage('Enter at least one tag label.', 'error');
      }
    },
    [
      selectedDocumentIds,
      setStatusMessage,
      parseTagInput,
      bulkTagOperation,
    ],
  );

  const handleBulkTagRemove = useCallback(
    async (event) => {
      event.preventDefault();
      if (!selectedDocumentIds.length) {
        setStatusMessage('Select documents before removing tags.', 'error');
        return;
      }

      const form = new FormData(event.currentTarget);
      const raw = form.get('tags')?.toString().trim() || '';
      const labels = parseTagInput(raw);
      if (!labels.length) {
        setStatusMessage('Enter at least one tag label to remove.', 'error');
        return;
      }

      const result = await bulkTagOperation({ labels, action: 'remove' });
      if (result?.ok) {
        const { docsCount } = result;
        setStatusMessage(
          `Removed tags from ${docsCount} document${docsCount === 1 ? '' : 's'}.`,
          'success',
        );
        event.currentTarget.reset();
      } else if (result?.reason === 'no-labels') {
        setStatusMessage('Enter at least one tag label to remove.', 'error');
      } else if (result?.reason === 'tag-missing') {
        setStatusMessage(`Tag “${result.label}” not found.`, 'error');
      }
    },
    [
      selectedDocumentIds,
      setStatusMessage,
      parseTagInput,
      bulkTagOperation,
    ],
  );

  const handleBulkTagAddFromDetail = useCallback(
    async ({ label, input }) => {
      const trimmed = (label || '').trim();
      if (!trimmed) {
        setStatusMessage('Enter a tag label.', 'error');
        return;
      }
      if (!selectedDocumentIds.length) {
        setStatusMessage('Select documents before assigning tags.', 'error');
        return;
      }
      const result = await bulkTagOperation({ labels: [trimmed], action: 'add' });
      if (result?.ok) {
        const { tagCount, docsCount } = result;
        setStatusMessage(
          `Assigned ${tagCount} tag${tagCount === 1 ? '' : 's'} to ${docsCount} document${
            docsCount === 1 ? '' : 's'
          }.`,
          'success',
        );
        if (input) {
          input.value = '';
        }
      }
    },
    [bulkTagOperation, selectedDocumentIds, setStatusMessage],
  );

  const handleBulkTagRemoveFromDetail = useCallback(
    async ({ label, input }) => {
      const trimmed = (label || '').trim();
      if (!trimmed) {
        setStatusMessage('Enter a tag label to remove.', 'error');
        return;
      }
      if (!selectedDocumentIds.length) {
        setStatusMessage('Select documents before removing tags.', 'error');
        return;
      }
      const result = await bulkTagOperation({ labels: [trimmed], action: 'remove' });
      if (result?.ok) {
        const { docsCount } = result;
        setStatusMessage(
          `Removed tags from ${docsCount} document${docsCount === 1 ? '' : 's'}.`,
          'success',
        );
        if (input) {
          input.value = '';
        }
      } else if (result?.reason === 'tag-missing') {
        setStatusMessage(`Tag “${result.label}” not found.`, 'error');
      }
    },
    [bulkTagOperation, selectedDocumentIds, setStatusMessage],
  );

  const handleBulkSelectionReanalyze = useCallback(async () => {
    if (!selectedDocumentIds.length) {
      setStatusMessage('Select documents before requesting re-analysis.', 'error');
      return;
    }

    setLoading(true);
    try {
      const { data } = await api.post('/documents/bulk/reanalyze', {
        document_ids: selectedDocumentIds,
        force: true,
      });
      const queued = data?.queued ?? selectedDocumentIds.length;
      setStatusMessage(
        `Queued re-analysis for ${queued} document${queued === 1 ? '' : 's'}.`,
        'success',
      );
    } catch (error) {
      const message =
        error.response?.data?.error || 'Failed to queue document re-analysis.';
      notifyApiError(error, message);
    } finally {
      setLoading(false);
    }
  }, [selectedDocumentIds, api, notifyApiError, setStatusMessage]);

  const uploadFile = useCallback(
    async (file, targetFolderId) => {
      if (!file || file.size === 0) {
        setStatusMessage('Skipped empty file.', 'error');
        return null;
      }

      const formData = new FormData();
      formData.append('file', file, file.name);
      if (targetFolderId && targetFolderId !== 'root') {
        formData.append('folder_id', targetFolderId);
      }

      try {
        const { data, status } = await api.post('/documents', formData);
        const duplicate = data?.reused || status === 200;
        setStatusMessage(
          duplicate
            ? `${file.name} already exists; reused existing document.`
            : `Uploaded ${file.name}`,
          duplicate ? 'info' : 'success',
        );
        return data;
      } catch (error) {
        const message = error.response?.data?.error || `Failed to upload ${file.name}.`;
        notifyApiError(error, message);
        throw error;
      }
    },
    [notifyApiError, setStatusMessage],
  );

  const folderPathCacheRef = useRef(new Map());
  const [previewEntries, setPreviewEntries] = useState(() => new Map());
  const previewInflightRef = useRef(new Map());

  const ensureFolderPathOnServer = useCallback(
    async (baseFolderId, segments) => {
      const trimmedSegments = segments.map((segment) => segment.trim()).filter(Boolean);
      if (trimmedSegments.length === 0) {
        return baseFolderId ?? null;
      }

      const cacheKey = `${baseFolderId ?? 'ROOT'}:${trimmedSegments.join('/')}`;
      const cache = folderPathCacheRef.current;
      if (cache.has(cacheKey)) {
        return cache.get(cacheKey);
      }

      const payload = {
        parent_id: baseFolderId && baseFolderId !== 'root' ? baseFolderId : null,
        segments: trimmedSegments,
      };

      const { data } = await api.post('/folders/path', payload);
      const folderId = data.folder.id;
      cache.set(cacheKey, folderId);
      return folderId;
    },
    [],
  );

  const ensureAssetUrl = useCallback(
    async (documentId, asset, { force = false } = {}) => {
      if (!documentId || !asset?.id) {
        return null;
      }

      try {
        const entry = await assetManager.ensureAsset(documentId, asset, { force });

        if (!entry) {
          return null;
        }

        setDocuments((prev) =>
          prev.map((doc) => (doc.id === documentId ? mergeAssetIntoDocument(doc, entry) : doc)),
        );

        setSearchResults((prev) =>
          Array.isArray(prev)
            ? prev.map((doc) => (doc.id === documentId ? mergeAssetIntoDocument(doc, entry) : doc))
            : prev,
        );

        return entry;
      } catch (error) {
        notifyApiError(error, 'Unable to refresh document asset.');
        throw error;
      }
    },
    [
      assetManager,
      setDocuments,
      setSearchResults,
      notifyApiError,
    ],
  );

  const ensurePreviewUrl = useCallback(
    async (documentId, { force = false } = {}) => {
      if (!documentId) return null;

      const existing = previewEntries.get(documentId) || null;
      const now = Date.now();
      const expiresAt = typeof existing?.expiresAt === 'number' ? existing.expiresAt : null;
      if (!force && existing && (!expiresAt || expiresAt > now)) {
        return existing;
      }

      if (!force && previewInflightRef.current.has(documentId)) {
        return previewInflightRef.current.get(documentId);
      }

      const request = (async () => {
        try {
          const { data } = await api.get(`/documents/${documentId}/download`);
          const ttl = data.expires_in ? Math.max(data.expires_in - 60, 30) * 1000 : 5 * 60 * 1000;
          const entry = {
            url: data.url,
            contentType: data.content_type || null,
            filename: data.filename,
            expiresAt: Date.now() + ttl,
          };
          setPreviewEntries((prev) => {
            const next = new Map(prev);
            next.set(documentId, entry);
            return next;
          });
          return entry;
        } catch (error) {
          notifyApiError(error, 'Unable to fetch document preview.');
          throw error;
        } finally {
          previewInflightRef.current.delete(documentId);
        }
      })();

      previewInflightRef.current.set(documentId, request);
      return request;
    },
    [previewEntries, notifyApiError],
  );

  const extractFilesFromDataTransfer = useCallback(async (dataTransfer) => {
    if (!dataTransfer) {
      throw new Error('No drop payload found.');
    }

    const items = Array.from(dataTransfer.items || []);
    console.info('[Uploads] drop start', { items: items.length, files: (dataTransfer.files || []).length });

    const results = [];
    const seenKeys = new Set();

    const pushFile = (file, ancestors = []) => {
      if (!file) return;
      const segments = (ancestors || []).filter(Boolean);
      const key = `${segments.join('/')}/${file.name}:${file.size}`;
      if (seenKeys.has(key)) {
        // skipped duplicate
        return;
      }
      seenKeys.add(key);
      results.push({ file, segments });
      // queued file
    };

    const readAllEntries = async (reader) => {
      const entries = [];
      while (true) {
        // eslint-disable-next-line no-await-in-loop
        const batch = await new Promise((resolve, reject) => reader.readEntries(resolve, reject));
        if (!batch.length) {
          break;
        }
        entries.push(...batch);
      }
      return entries;
    };

    const walkEntry = async (entry, ancestors = []) => {
      if (!entry) return;
      if (entry.isFile) {
        const file = await new Promise((resolve, reject) => {
          try {
            entry.file(resolve, reject);
          } catch (error) {
            console.warn('[Uploads] entry.file failed', error);
            reject(error);
          }
        });
        pushFile(file, ancestors);
        return;
      }
      if (entry.isDirectory) {
        const nextAncestors = entry.name ? [...ancestors, entry.name] : [...ancestors];
        const reader = entry.createReader();
        const entries = await readAllEntries(reader);
        for (const child of entries) {
          // eslint-disable-next-line no-await-in-loop
          await walkEntry(child, nextAncestors);
        }
      }
    };

    await Promise.all(
      items.map(async (item, index) => {
        if (item.kind !== 'file') return;

        const fileFromItem = typeof item.getAsFile === 'function' ? item.getAsFile() : null;
        if (fileFromItem) {
          const relativePath =
            typeof fileFromItem.webkitRelativePath === 'string' ? fileFromItem.webkitRelativePath : '';
          const segments = relativePath
            ? relativePath
                .split('/')
                .slice(0, -1)
                .filter(Boolean)
            : [];
          pushFile(fileFromItem, segments);
        }

        if (typeof item.webkitGetAsEntry === 'function') {
          try {
            const entry = item.webkitGetAsEntry();
            if (entry) {
              // processing entry
              await walkEntry(entry, []);
              return;
            }
          } catch (error) {
            console.warn('[Uploads] webkitGetAsEntry failed', error);
          }
        }

        if (!fileFromItem) {
          console.info('[Uploads] item missing file handle', index);
        }
      }),
    );

    Array.from(dataTransfer.files || []).forEach((file, index) => {
      if (!file) return;
      // FileList entry suppressed
      const relativePath =
        typeof file.webkitRelativePath === 'string' ? file.webkitRelativePath : '';
      const segments = relativePath
        ? relativePath
            .split('/')
            .slice(0, -1)
            .filter(Boolean)
        : [];
      pushFile(file, segments);
    });

    if (!results.length) {
      throw new Error('No files detected in drop payload.');
    }

    console.info('[Uploads] prepared files', results.length);

    return results;
  }, []);


  const handleFileDrop = useCallback(
    async (dataTransfer, targetFolderId) => {
      if (!token) {
        setStatusMessage('Please log in before uploading.', 'error');
        return;
      }

      setLoading(true);

      try {
        folderPathCacheRef.current.clear();

        let extracted;
        try {
          extracted = await extractFilesFromDataTransfer(dataTransfer);
        } catch (error) {
          const message = error.message || 'Failed to process dropped files.';
          notifyApiError(error, message);
          return;
        }

        if (!extracted.length) {
          setStatusMessage('No files to upload.', 'info');
          return;
        }
        const baseFolderId =
          targetFolderId && targetFolderId !== 'root' ? targetFolderId : null;

        for (const { file, segments } of extracted) {
          // eslint-disable-next-line no-await-in-loop
          const destinationId = segments.length
            ? await ensureFolderPathOnServer(baseFolderId, segments)
            : baseFolderId;

          const uploadTarget =
            destinationId ??
            (targetFolderId && targetFolderId !== 'root' ? targetFolderId : 'root');

          // eslint-disable-next-line no-await-in-loop
          await uploadFile(file, uploadTarget);
        }

        await refreshCurrentFolder();

        if (
          targetFolderId &&
          targetFolderId !== 'root' &&
          targetFolderId !== selectedFolder
        ) {
          await ensureFolderData(targetFolderId, { force: true });
        }
      } catch (error) {
        notifyApiError(error, 'Failed to upload files.');
      } finally {
        setLoading(false);
      }
    },
    [
      token,
      extractFilesFromDataTransfer,
      ensureFolderPathOnServer,
      uploadFile,
      refreshCurrentFolder,
      selectedFolder,
      ensureFolderData,
      notifyApiError,
      setStatusMessage,
    ],
  );

  const moveDocumentsToFolder = useCallback(
    async (documentIds, targetFolderId) => {
      const unique = Array.from(new Set(documentIds || [])).filter(Boolean);
      if (!unique.length) return;

      const target = targetFolderId === 'root' ? null : targetFolderId;
      setLoading(true);
      try {
        if (unique.length === 1) {
          await api.patch(`/documents/${unique[0]}/folder`, { folder_id: target });
        } else {
          await api.post('/documents/bulk/move', {
            document_ids: unique,
            folder_id: target,
          });
        }

        const count = unique.length;
        const suffix = count === 1 ? '' : 's';
        const targetLabel =
          target === null
            ? DEFAULT_FOLDER_NAME
            : folderLabelMap.get(targetFolderId) || 'target folder';
        setStatusMessage(
          `Moved ${count} document${suffix} to ${targetLabel}.`,
          'success',
        );

        await refreshCurrentFolder();
      if (targetFolderId && targetFolderId !== selectedFolder) {
        await ensureFolderData(targetFolderId, { force: true });
      }
    } catch (error) {
      const message = error.response?.data?.error || 'Failed to move documents.';
      notifyApiError(error, message);
    } finally {
      setLoading(false);
    }
  },
  [
    api,
    ensureFolderData,
    refreshCurrentFolder,
    selectedFolder,
    folderLabelMap,
    notifyApiError,
    setStatusMessage,
  ],
  );

  const handleBulkMoveFromDetail = useCallback(
    async ({ target }) => {
      const destination = target === 'root' ? 'root' : target;
      if (!selectedDocumentIds.length) {
        setStatusMessage('Select documents before moving.', 'error');
        return;
      }
      await moveDocumentsToFolder(selectedDocumentIds, destination);
    },
    [selectedDocumentIds, moveDocumentsToFolder, setStatusMessage],
  );

  const handleThumbnailRegeneration = useCallback(
    async (documentId) => {
      if (!token) {
        setStatusMessage('Log in to manage assets.', 'error');
        return;
      }
      setLoading(true);
      try {
        await api.post(`/documents/${documentId}/assets`, null, {
          params: { force: true },
        });
        setStatusMessage('Document re-analysis queued.', 'info');
        await refreshCurrentFolder();
      } catch (error) {
        const message =
          error.response?.data?.error || 'Failed to request thumbnail generation.';
        notifyApiError(error, message);
      } finally {
        setLoading(false);
      }
    },
    [token, refreshCurrentFolder, notifyApiError, setStatusMessage],
  );

  const openDocumentPreview = useCallback(
    async (documentId, { replace = false, skipNavigate = false } = {}) => {
      if (!documentId) return;
      setPreviewDocumentId(documentId);
      setPreviewDocumentLoading(true);
      try {
        const pool = searchResults ?? documents;
        const doc = pool.find((item) => item.id === documentId);
        if (!doc) {
          throw new Error('Document metadata unavailable.');
        }

        const currentVersion = doc.current_version || null;
        const previewAsset = getAssetFromVersion(currentVersion, 'preview');
        const thumbnailAsset = getAssetFromVersion(currentVersion, 'thumbnail');

        const refreshAssetIfNeeded = async (asset) => {
          if (!asset?.id) {
            return;
          }
          const expiresAt = typeof asset.expiresAt === 'number' ? asset.expiresAt : null;
          const shouldForce = Boolean(asset.url && expiresAt && expiresAt <= Date.now());
          if (!asset.url || shouldForce) {
            try {
              await ensureAssetUrl(documentId, asset, { force: shouldForce || !asset.url });
            } catch (
              // eslint-disable-next-line no-empty
              error
            ) {}
          }
        };

        await refreshAssetIfNeeded(previewAsset);
        refreshAssetIfNeeded(thumbnailAsset);

        await ensurePreviewUrl(documentId, { force: false });
        setActivePreviewId(documentId);
        if (!skipNavigate && navigate) {
          navigate(`/documents/${documentId}`, { replace });
        }
      } catch (error) {
        notifyApiError(error, 'Failed to open document preview.');
        setPreviewDocumentId(null);
      } finally {
        setPreviewDocumentLoading(false);
      }
    },
    [
      documents,
      searchResults,
      ensurePreviewUrl,
      ensureAssetUrl,
      navigate,
      notifyApiError,
    ],
  );

  const handleDocumentListFocus = useCallback(() => {
    if (focusedRowKey && navigableRowKeys.includes(focusedRowKey)) {
      return;
    }

    let resolvedKey = null;
    for (let index = selectedDocumentIds.length - 1; index >= 0; index -= 1) {
      const candidate = selectedDocumentIds[index];
      const rowKey = `document:${candidate}`;
      if (navigableRowKeys.includes(rowKey)) {
        resolvedKey = rowKey;
        break;
      }
    }

    if (!resolvedKey && navigableRows.length) {
      resolvedKey = navigableRows[0].key;
    }

    if (!resolvedKey) {
      return;
    }

    setFocusedRowKey(resolvedKey);

    if (resolvedKey.startsWith('document:')) {
      const docId = resolvedKey.slice('document:'.length);
      if (!selectedDocumentIds.includes(docId)) {
        applySelection([docId], { anchor: docId, interactedIds: [docId] });
      }
    }
  }, [
    focusedRowKey,
    navigableRowKeys,
    selectedDocumentIds,
    navigableRows,
    applySelection,
  ]);

  const handleDocumentListKeyDown = useCallback(
    (event) => {
      const { key, shiftKey } = event;
      const triggers = ['ArrowUp', 'ArrowDown', 'Home', 'End', 'Enter', ' ', 'Space', 'Spacebar'];
      if (!triggers.includes(key)) {
        return;
      }

      if (!navigableRows.length) {
        return;
      }

      event.preventDefault();

      let activeKey =
        focusedRowKey && navigableRowKeys.includes(focusedRowKey)
          ? focusedRowKey
          : null;

      if (!activeKey) {
        for (let index = selectedDocumentIds.length - 1; index >= 0; index -= 1) {
          const candidate = selectedDocumentIds[index];
          const rowKey = `document:${candidate}`;
          if (navigableRowKeys.includes(rowKey)) {
            activeKey = rowKey;
            break;
          }
        }
      }

      if (!activeKey) {
        activeKey = navigableRows[0].key;
        setFocusedRowKey(activeKey);
      }

      let currentIndex = navigableRowKeys.indexOf(activeKey);

      if (key === 'Enter' || key === ' ' || key === 'Space' || key === 'Spacebar') {
        const row = currentIndex === -1 ? navigableRows[0] : navigableRows[currentIndex];
        if (!row) {
          return;
        }
        if (row.type === 'folder') {
          setFocusedRowKey(`folder:${row.id}`);
          selectFolder(row.id);
        } else {
          setFocusedRowKey(`document:${row.id}`);
          applySelection([row.id], { anchor: row.id, interactedIds: [row.id] });
          openDocumentPreview(row.id);
        }
        return;
      }

      let nextIndex = currentIndex;

      if (key === 'ArrowDown') {
        nextIndex = currentIndex === -1 ? 0 : Math.min(currentIndex + 1, navigableRows.length - 1);
      } else if (key === 'ArrowUp') {
        nextIndex = currentIndex === -1 ? navigableRows.length - 1 : Math.max(currentIndex - 1, 0);
      } else if (key === 'Home') {
        nextIndex = 0;
      } else if (key === 'End') {
        nextIndex = navigableRows.length - 1;
      }

      if (nextIndex === -1 || nextIndex >= navigableRows.length) {
        return;
      }

      if (nextIndex === currentIndex && key !== 'Home' && key !== 'End') {
        return;
      }

      const targetRow = navigableRows[nextIndex];
      if (!targetRow) {
        return;
      }

      setFocusedRowKey(targetRow.key);

      if (targetRow.type === 'folder') {
        return;
      }

      const targetId = targetRow.id;
      if (!targetId) {
        return;
      }

      if (shiftKey) {
        let anchorId = selectionAnchorRef.current;
        if (!anchorId || !visibleDocumentIds.includes(anchorId)) {
          if (focusedDocumentId && visibleDocumentIds.includes(focusedDocumentId)) {
            anchorId = focusedDocumentId;
          } else {
            anchorId = targetId;
          }
        }

        const anchorIndex = visibleDocumentIds.indexOf(anchorId);
        const targetIndex = visibleDocumentIds.indexOf(targetId);
        if (anchorIndex !== -1 && targetIndex !== -1) {
          const start = Math.min(anchorIndex, targetIndex);
          const end = Math.max(anchorIndex, targetIndex);
          const range = visibleDocumentIds.slice(start, end + 1);
          applySelection(range, { anchor: anchorId, interactedIds: [targetId] });
        } else {
          applySelection([targetId], { anchor: targetId, interactedIds: [targetId] });
        }
      } else {
        applySelection([targetId], { anchor: targetId, interactedIds: [targetId] });
      }
    },
    [
      navigableRows,
      navigableRowKeys,
      focusedRowKey,
      selectedDocumentIds,
      selectFolder,
      openDocumentPreview,
      visibleDocumentIds,
      focusedDocumentId,
      applySelection,
      selectionAnchorRef,
    ],
  );

  const closeDocumentPreview = useCallback(
    (folderId = null) => {
      setPreviewDocumentId(null);
      setPreviewDocumentLoading(false);

      const targetId = folderId || selectedFolder || 'root';

      if (!navigate) {
        loadFolder(targetId, { showLoading: false });
        return;
      }

      const path = targetId === 'root' ? '/folders' : `/folders/${targetId}`;
      navigate(path, { replace: false });
    },
    [navigate, selectedFolder, loadFolder],
  );

  useEffect(() => {
    if (!previewDocumentId) return;
    const handleKeyDown = (event) => {
      if (event.key === 'Escape') {
        closeDocumentPreview();
      }
    };
    window.addEventListener('keydown', handleKeyDown);
    return () => window.removeEventListener('keydown', handleKeyDown);
  }, [previewDocumentId, closeDocumentPreview]);

  useEffect(() => {
    if (!routeDocumentId) {
      if (previewDocumentId) {
        closeDocumentPreview();
      }
      return;
    }

    let cancelled = false;

    const hydratePreview = async () => {
      try {
        const pool = searchResults ?? documents;
        let doc = pool.find((item) => item.id === routeDocumentId) || null;

        if (!doc) {
          const { data } = await api.get(`/documents/${routeDocumentId}`);
          const hydratedDetail = assetManager.hydrateDetail(data);
          const fetched = hydratedDetail?.document || data.document || data;
          doc = fetched ? assetManager.hydrateDocument(fetched) : null;
        }

        const targetFolder = doc?.folder_id || routeFolderId || 'root';
        if (targetFolder && targetFolder !== selectedFolder) {
          await loadFolder(targetFolder, { showLoading: false });
        }
        if (!cancelled) {
          await openDocumentPreview(routeDocumentId, { replace: true, skipNavigate: true });
        }
      } catch (error) {
        if (!cancelled) {
          notifyApiError(error, 'Failed to open document preview.');
        }
      }
    };

    hydratePreview();

    return () => {
      cancelled = true;
    };
  }, [
    routeDocumentId,
    routeFolderId,
    api,
    assetManager,
    selectedFolder,
    loadFolder,
    openDocumentPreview,
    previewDocumentId,
    closeDocumentPreview,
    documents,
    searchResults,
    notifyApiError,
  ]);

  const handleDocumentTitleUpdate = useCallback(
    async (documentId, nextTitle) => {
      const trimmed = nextTitle.trim();
      if (!trimmed) {
        setStatusMessage('Document title cannot be empty.', 'error');
        return false;
      }

      setLoading(true);
      try {
        const { data } = await api.patch(`/documents/${documentId}`, { title: trimmed });
        const hydratedDetail = assetManager.hydrateDetail(data);
        const hydratedDocument = hydratedDetail?.document || data.document || data;

        setDocuments((prev) =>
          prev.map((doc) => {
            if (doc.id !== documentId) {
              return doc;
            }
            if (hydratedDocument) {
              return { ...doc, ...hydratedDocument };
            }
            return { ...doc, title: trimmed };
          }),
        );

        setSearchResults((prev) =>
          prev
            ? prev.map((doc) => {
                if (doc.id !== documentId) {
                  return doc;
                }
                if (hydratedDocument) {
                  return { ...doc, ...hydratedDocument };
                }
                return { ...doc, title: trimmed };
              })
            : null,
        );

        setFolderContents((prev) => {
          let changed = false;
          const next = new Map();
          prev.forEach((contents, key) => {
            if (contents?.documents?.some((doc) => doc.id === documentId)) {
              changed = true;
              next.set(key, {
                ...contents,
                documents: contents.documents.map((doc) =>
                  doc.id === documentId
                    ? hydratedDocument
                      ? { ...doc, ...hydratedDocument }
                      : { ...doc, title: trimmed }
                    : doc,
                ),
              });
            } else {
              next.set(key, contents);
            }
          });
          if (!changed) {
            return prev;
          }
          return next;
        });

        setStatusMessage('Document title updated.', 'success');
        return true;
      } catch (error) {
        const message = error.response?.data?.error || 'Failed to update document title.';
        notifyApiError(error, message);
        return false;
      } finally {
        setLoading(false);
      }
    },
    [assetManager, notifyApiError, setStatusMessage, setDocuments, setSearchResults, setFolderContents],
  );

  const handleTagRemove = useCallback(
    async (documentId, tagId) => {
      try {
        await api.delete(`/documents/${documentId}/tags/${tagId}`);
        setStatusMessage('Tag removed.', 'success');
        await Promise.all([refreshCurrentFolder(), refreshTags()]);
      } catch (error) {
        notifyApiError(error, 'Failed to remove tag.');
      }
    },
    [refreshCurrentFolder, refreshTags, notifyApiError, setStatusMessage],
  );

  const handleTagAdd = useCallback(
    async (document, label, input) => {
      let tag = tags.find((item) => item.label.toLowerCase() === label.toLowerCase()) || null;
      try {
        if (!tag) {
          const { data } = await api.post('/tags', {
            label,
            color: generateRandomTagColor(),
          });
          tag = data;
          await refreshTags();
        }
        await api.post(`/documents/${document.id}/tags`, { tag_ids: [tag.id] });
        setStatusMessage('Tag assigned.', 'success');
        input.value = '';
        await refreshCurrentFolder();
      } catch (error) {
        notifyApiError(error, 'Failed to assign tag.');
      }
    },
    [
      tags,
      refreshTags,
      refreshCurrentFolder,
      notifyApiError,
      setStatusMessage,
    ],
  );

  const handleDocumentTagAttach = useCallback(
    async ({ documentId, tagId }) => {
      if (!documentId || !tagId) {
        return false;
      }

      try {
        await api.post(`/documents/${documentId}/tags`, { tag_ids: [tagId] });
        setStatusMessage('Tag assigned.', 'success');
        await refreshCurrentFolder();
        return true;
      } catch (error) {
        const message = error.response?.data?.error || 'Failed to assign tag.';
        notifyApiError(error, message);
        return false;
      }
    },
    [api, refreshCurrentFolder, notifyApiError, setStatusMessage],
  );

  const handleFolderDelete = useCallback(
    async (folderId) => {
      if (!token) {
        setStatusMessage('Log in to manage folders.', 'error');
        return;
      }
      if (folderId === 'root') {
        setStatusMessage('The root folder cannot be removed.', 'error');
        return;
      }
      setLoading(true);
      try {
        const contents = await ensureFolderData(folderId, { force: true });
        const hasChildren = (contents.subfolders || []).length > 0;
        const hasDocs = (contents.documents || []).length > 0;
        if (hasChildren || hasDocs) {
          setStatusMessage('Folder must be empty before it can be deleted.', 'error');
          return;
        }
        await api.delete(`/folders/${folderId}`);
        setFolderNodes((prev) => {
          const next = new Map(prev);
          const node = next.get(folderId);
          next.delete(folderId);
          if (node) {
            const parentId = node.parentId || 'root';
            const parentNode = next.get(parentId);
            if (parentNode) {
              next.set(parentId, {
                ...parentNode,
                children: parentNode.children.filter((id) => id !== folderId),
              });
            }
          }
          return next;
        });
        setFolderContents((prev) => {
          const next = new Map(prev);
          next.delete(folderId);
          return next;
        });
        if (selectedFolder === folderId) {
          const node = folderNodes.get(folderId);
          const parentId = node?.parentId || 'root';
          setSelectedFolder(parentId);
          const parentContents = await ensureFolderData(parentId, { force: true });
          applySelectedFolder(parentId, parentContents);
        } else if (selectedFolder !== 'root') {
          await ensureFolderData(selectedFolder, { force: true });
      }
      setStatusMessage('Folder deleted.', 'success');
    } catch (error) {
      const message = error.response?.data?.error || 'Failed to delete folder.';
      notifyApiError(error, message);
    } finally {
      setLoading(false);
    }
  },
    [
      token,
      ensureFolderData,
      selectedFolder,
      folderNodes,
      applySelectedFolder,
      notifyApiError,
      setStatusMessage,
    ],
  );

  const handleFolderCreate = useCallback(
    async (name, onSuccess) => {
      if (!token) {
        setStatusMessage('Log in to create folders.', 'error');
        return false;
      }
      if (!name.trim()) {
        setStatusMessage('Folder name cannot be empty.', 'error');
        return false;
      }
      const payload = {
        name: name.trim(),
        parent_id: selectedFolder === 'root' ? null : selectedFolder,
      };
      setLoading(true);
      let succeeded = false;
      try {
        const { data } = await api.post('/folders', payload);
        onSuccess();
        setStatusMessage('Folder created.', 'success');
        setFolderNodes((prev) => {
          const next = new Map(prev);
          const parentId = payload.parent_id || 'root';
          const parentNode = next.get(parentId);
          if (parentNode) {
            next.set(parentId, {
              ...parentNode,
              children: parentNode.children.concat([data.folder.id]),
              loaded: true,
            });
          }
          next.set(data.folder.id, {
            id: data.folder.id,
            name: data.folder.name,
            parentId: parentId,
            children: [],
            expanded: false,
            loaded: false,
          });
          return next;
        });
        await ensureFolderData(selectedFolder, { force: true });
        succeeded = true;
      } catch (error) {
        const message = error.response?.data?.error || 'Failed to create folder.';
        notifyApiError(error, message);
        succeeded = false;
      } finally {
        setLoading(false);
      }
      return succeeded;
    },
    [token, selectedFolder, ensureFolderData, notifyApiError, setStatusMessage],
  );

  const openCreateFolderModal = useCallback(() => {
    setNewFolderName('');
    setCreateFolderError('');
    setCreateFolderModalOpen(true);
  }, []);

  const closeCreateFolderModal = useCallback(() => {
    if (creatingFolder) {
      return;
    }
    setCreateFolderModalOpen(false);
    setNewFolderName('');
    setCreateFolderError('');
  }, [creatingFolder]);

  const handleCreateFolderSubmit = useCallback(
    async (event) => {
      event.preventDefault();
      const trimmed = newFolderName.trim();
      if (!trimmed) {
        setCreateFolderError('Folder name cannot be empty.');
        return;
      }

      if (!token) {
        setCreateFolderError('Log in to create folders.');
        return;
      }

      setCreatingFolder(true);
      setCreateFolderError('');

      try {
        const success = await handleFolderCreate(trimmed, () => {
          setCreateFolderModalOpen(false);
          setNewFolderName('');
          setCreateFolderError('');
        });
        if (!success) {
          setCreateFolderError('Unable to create folder. Check the status message for details.');
        }
      } finally {
        setCreatingFolder(false);
      }
    },
    [newFolderName, handleFolderCreate, token],
  );

  useEffect(() => {
    if (!isCreateFolderModalOpen) {
      return;
    }
    const node = createFolderInputRef.current;
    if (node) {
      node.focus();
      node.select();
    }
  }, [isCreateFolderModalOpen]);

  useEffect(() => {
    if (!isCreateFolderModalOpen) {
      return;
    }
    const handleKeyDown = (event) => {
      if (event.key === 'Escape') {
        event.preventDefault();
        closeCreateFolderModal();
      }
    };
    window.addEventListener('keydown', handleKeyDown);
    return () => {
      window.removeEventListener('keydown', handleKeyDown);
    };
  }, [isCreateFolderModalOpen, closeCreateFolderModal]);

  useEffect(() => {
    if (!token) return undefined;

    if (!isFilterActive) {
      setSearchResults(null);
      return undefined;
    }

    let cancelled = false;
    let started = false;

    const debounce = setTimeout(async () => {
      started = true;
      setLoading(true);
      try {
        const params = {};
        const trimmedQuery = searchQuery.trim();
        if (trimmedQuery.length) {
          params.query = trimmedQuery;
        }
        if (activeTagFilters.length) {
          params.tags = activeTagFilters.join(',');
        }
        const folderIdentifier = selectedFolder === 'root' ? 'root' : selectedFolder;
        const { data } = await api.get(`/folders/${folderIdentifier}/documents`, {
          params,
        });
        if (cancelled) return;

        const results = assetManager.hydrateDocuments(data || []);
        setSearchResults(results);

        if (!results.length) {
          setSelectedDocumentIds([]);
          setFocusedDocumentId(null);
          selectionAnchorRef.current = null;
          return;
        }

        const resultIds = results.map((doc) => doc.id);
        let targetId = null;
        setSelectedDocumentIds((previous) => {
          const filtered = previous.filter((id) => resultIds.includes(id));
          if (filtered.length) {
            targetId = filtered[filtered.length - 1];
            return filtered;
          }
          targetId = resultIds[0];
          return [targetId];
        });

        setFocusedDocumentId((previous) => {
          if (previous && resultIds.includes(previous)) {
            targetId = previous;
            return previous;
          }
          return targetId;
        });

        selectionAnchorRef.current = targetId;

        // rely on hydrated search results; assets refresh on demand
      } catch (error) {
        if (cancelled) return;
        notifyApiError(error, 'Search failed. Please try again.');
        setSearchResults(null);
      } finally {
        if (!cancelled && started) {
          setLoading(false);
        }
      }
    }, 300);

    return () => {
      cancelled = true;
      clearTimeout(debounce);
      if (started) {
        setLoading(false);
      }
    };
  }, [
    token,
    isFilterActive,
    searchQuery,
    activeTagFilters,
    selectedFolder,
    notifyApiError,
    assetManager,
  ]);

  useEffect(() => {
    if (!token) {
      setDropOverlayState((prev) => ({ ...prev, active: false }));
      dragCounterRef.current = 0;
      return undefined;
    }

    const handleDragEnter = (event) => {
      if (!hasFiles(event)) return;
      event.preventDefault();
      dragCounterRef.current += 1;
      setDropOverlayState({ active: true, folderName: currentFolderName });
    };

    const handleDragOver = (event) => {
      if (!hasFiles(event)) return;
      event.preventDefault();
      event.dataTransfer.dropEffect = 'copy';
    };

    const handleDragLeave = (event) => {
      if (!hasFiles(event)) return;
      dragCounterRef.current = Math.max(0, dragCounterRef.current - 1);
      if (dragCounterRef.current === 0) {
        setDropOverlayState((prev) => ({ ...prev, active: false }));
      }
    };

    const handleDrop = async (event) => {
      if (!hasFiles(event)) return;
      event.preventDefault();
      dragCounterRef.current = 0;
      setDropOverlayState((prev) => ({ ...prev, active: false }));
      await handleFileDrop(event.dataTransfer, selectedFolder);
    };

    const dropTarget = shellRef.current;
    if (!dropTarget) {
      return undefined;
    }

    dropTarget.addEventListener('dragenter', handleDragEnter);
    dropTarget.addEventListener('dragover', handleDragOver);
    dropTarget.addEventListener('dragleave', handleDragLeave);
    dropTarget.addEventListener('drop', handleDrop);

    return () => {
      dropTarget.removeEventListener('dragenter', handleDragEnter);
      dropTarget.removeEventListener('dragover', handleDragOver);
      dropTarget.removeEventListener('dragleave', handleDragLeave);
      dropTarget.removeEventListener('drop', handleDrop);
      dragCounterRef.current = 0;
      setDropOverlayState((prev) => ({ ...prev, active: false }));
    };
  }, [token, handleFileDrop, currentFolderName, selectedFolder]);

  const handleLogin = useCallback(
    async (event) => {
      event.preventDefault();
      const form = new FormData(event.currentTarget);
      const payload = {
        username: form.get('username')?.toString().trim(),
        password: form.get('password')?.toString() || '',
      };
      if (!payload.username || !payload.password) {
        setStatusMessage('Username and password are required.', 'error');
        return;
      }
      try {
        setLoading(true);
        appDispatch({ type: 'LOGIN_REQUEST' });
        const { data } = await api.post('/auth/login', payload);
      appDispatch({ type: 'LOGIN_SUCCESS', token: data.access_token });
      setStatusMessage('Login successful.', 'success');
    } catch (error) {
      appDispatch({
        type: 'LOGIN_FAILURE',
        error: error?.response?.data?.error || 'Login failed. Check credentials.',
      });
      notifyApiError(error, 'Login failed. Check credentials.');
    } finally {
      setLoading(false);
    }
  },
  [appDispatch, notifyApiError, setStatusMessage],
  );

  const handleLogout = useCallback(async () => {
    try {
      setLoading(true);
      await api.post('/auth/logout');
    } catch (error) {
      console.warn('[Auth] Failed to revoke refresh token during logout', error);
    } finally {
      setLoading(false);
      appDispatch({ type: 'LOGOUT' });
      setStatusMessage('Logged out.', 'info');
    }
  }, [appDispatch, setStatusMessage]);

  const handleBulkReanalyze = useCallback(async () => {
    try {
      setLoading(true);
      const { data } = await api.post('/documents/reanalyze');
      const total = data?.queued ?? 0;
      const suffix = total === 1 ? '' : 's';
      setStatusMessage(
        `Queued re-analysis for ${total} document${suffix}.`,
        'success',
      );
    } catch (error) {
      const message =
        error.response?.data?.error || 'Failed to queue document re-analysis.';
      notifyApiError(error, message);
    } finally {
      setLoading(false);
    }
  }, [notifyApiError, setStatusMessage]);


  const folderClickHandlers = {
    onToggle: async (folderId) => {
      const node = folderNodes.get(folderId);
      if (node && !node.loaded) {
        try {
          await ensureFolderData(folderId);
        } catch (error) {
          notifyApiError(error, 'Failed to load folder.');
        }
      }
      if (folderId === 'root') {
        return;
      }
      setFolderNodes((prev) => {
        const next = new Map(prev);
        const current = next.get(folderId);
        if (!current) return prev;
        next.set(folderId, { ...current, expanded: !current.expanded });
        return next;
      });
    },
    onSelect: selectFolder,
    onDrop: async (event, folderId) => {
      event.preventDefault();
      event.stopPropagation();
      event.currentTarget.classList.remove('is-drop-target');

      let folderSourceId = draggedFolderId;
      if (!folderSourceId) {
        try {
          if (event.dataTransfer.types?.includes('application/x-papercrate-folder')) {
            folderSourceId = event.dataTransfer.getData('application/x-papercrate-folder');
          }
        } catch (
          // eslint-disable-next-line no-empty
          error
        ) {}
      }

      if (folderSourceId) {
        setDraggedFolderId(null);
        if (isInvalidFolderDrop(folderSourceId, folderId)) {
          setStatusMessage(
            'Cannot move a folder into itself or one of its descendants.',
            'error',
          );
          return;
        }
        await moveFolder(folderSourceId, folderId);
        return;
      }

      if (hasFiles(event)) {
        await handleFileDrop(event.dataTransfer, folderId);
        return;
      }

      let docIds = [];
      try {
        const raw = event.dataTransfer.getData('application/x-papercrate-doc-list');
        if (raw) {
          const parsed = JSON.parse(raw);
          if (Array.isArray(parsed)) {
            docIds = parsed.filter(Boolean);
          }
        }
      } catch (
        // eslint-disable-next-line no-empty
        error
      ) {}

      if (!docIds.length) {
        try {
          const single = event.dataTransfer.getData('application/x-papercrate-doc');
          if (single) {
            docIds = [single];
          }
        } catch (
          // eslint-disable-next-line no-empty
          error
        ) {}
      }

      if (!docIds.length && draggedDocumentIds.length) {
        docIds = draggedDocumentIds;
      }

      if (!docIds.length || folderId === selectedFolder) {
        return;
      }

      setDraggedDocumentIds([]);
      await moveDocumentsToFolder(docIds, folderId);
    },
    onDragOver: (event, folderId) => {
      const folderDragActive = Boolean(draggedFolderId);
      if (folderDragActive && isInvalidFolderDrop(draggedFolderId, folderId)) {
        return;
      }

      if (hasFiles(event)) {
        event.preventDefault();
        event.dataTransfer.dropEffect = 'copy';
        event.currentTarget.classList.add('is-drop-target');
        return;
      }

      if (draggedDocumentIds.length || folderDragActive) {
        event.preventDefault();
        event.dataTransfer.dropEffect = 'move';
        event.currentTarget.classList.add('is-drop-target');
      }
    },
    onDragLeave: (event) => {
      event.currentTarget.classList.remove('is-drop-target');
    },
  };

  const filterBar = (
    <FilterBar
      query={searchQuery}
      onQueryChange={setSearchQuery}
      tags={tags}
      activeTagIds={activeTagFilters}
      onToggleTag={(tagId) =>
        setActiveTagFilters((prev) =>
          prev.includes(tagId)
            ? prev.filter((id) => id !== tagId)
            : prev.concat([tagId]),
        )
      }
      onClear={() => {
        setSearchQuery('');
        setActiveTagFilters([]);
      }}
      hasFilters={isFilterActive}
    />
  );

  const defaultMoveTarget = useMemo(() => {
    return folderOptions.some((option) => option.id === selectedFolder)
      ? selectedFolder
      : 'root';
  }, [folderOptions, selectedFolder]);

  const selectedDocument = useMemo(() => {
    if (!focusedDocumentId) {
      return null;
    }
    const list = searchResults ?? documents;
    return list.find((doc) => doc.id === focusedDocumentId) || null;
  }, [searchResults, documents, focusedDocumentId]);

  const documentLookup = useMemo(() => {
    const map = new Map();
    documents.forEach((doc) => {
      if (doc?.id) {
        map.set(doc.id, doc);
      }
    });
    if (Array.isArray(searchResults)) {
      searchResults.forEach((doc) => {
        if (doc?.id) {
          map.set(doc.id, doc);
        }
      });
    }
    return map;
  }, [documents, searchResults]);

  const handleDocumentDelete = useCallback(
    async (documentId) => {
      if (!documentId) return;
      if (!token) {
        setStatusMessage('Log in to manage documents.', 'error');
        return;
      }

      const doc = documentLookup.get(documentId) || null;
      const label = doc?.title || doc?.original_name || 'this document';

      const confirmed = window.confirm(`Delete "${label}"? This action cannot be undone.`);
      if (!confirmed) {
        return;
      }

      setLoading(true);
      try {
        await api.delete(`/documents/${documentId}`);

        setDocuments((prev) => prev.filter((item) => item.id !== documentId));

        setSearchResults((prev) => (prev ? prev.filter((item) => item.id !== documentId) : null));

        setFolderContents((prev) => {
          let changed = false;
          const next = new Map();
          prev.forEach((contents, key) => {
            if (!contents?.documents) {
              next.set(key, contents);
              return;
            }
            const filteredDocs = contents.documents.filter((item) => item.id !== documentId);
            if (filteredDocs.length !== contents.documents.length) {
              changed = true;
              next.set(key, { ...contents, documents: filteredDocs });
            } else {
              next.set(key, contents);
            }
          });
          return changed ? next : prev;
        });

        setPreviewEntries((prev) => {
          if (!prev.has(documentId)) {
            return prev;
          }
          const next = new Map(prev);
          next.delete(documentId);
          return next;
        });
        previewInflightRef.current.delete(documentId);

        if (selectedDocumentIds.includes(documentId)) {
          const remaining = selectedDocumentIds.filter((id) => id !== documentId);
          applySelection(remaining, { anchor: null, interactedIds: [documentId] });
        }

        if (previewDocumentId === documentId) {
          closeDocumentPreview();
        }

        setStatusMessage('Document deleted.', 'success');
      } catch (error) {
        const message = error.response?.data?.error || 'Failed to delete document.';
        notifyApiError(error, message);
      } finally {
        setLoading(false);
      }
    },
    [
      api,
      token,
      documentLookup,
      setStatusMessage,
      setDocuments,
      setSearchResults,
      setFolderContents,
      setPreviewEntries,
      previewInflightRef,
      previewDocumentId,
      closeDocumentPreview,
      selectedDocumentIds,
      applySelection,
      notifyApiError,
    ],
  );

  const orderedSelectedDocuments = useMemo(() => {
    const ordered = [];
    const seen = new Set();
    const pushDoc = (doc) => {
      if (doc?.id && !seen.has(doc.id)) {
        ordered.push(doc);
        seen.add(doc.id);
      }
    };

    selectionOrder.forEach((id) => {
      const doc = documentLookup.get(id) || null;
      pushDoc(doc);
    });

    selectedDocumentIds.forEach((id) => {
      if (seen.has(id)) return;
      const doc = documentLookup.get(id) || null;
      pushDoc(doc);
    });

    return ordered;
  }, [selectionOrder, documentLookup, selectedDocumentIds]);

  const { breadcrumbs, missingBreadcrumbAncestors } = useMemo(() => {
    const chain = [];
    const seen = new Set();
    const pending = new Set();
    let currentId = selectedFolder || 'root';
    let guard = 0;

    while (currentId && !seen.has(currentId) && guard < 32) {
      guard += 1;
      seen.add(currentId);

      if (currentId === 'root') {
        chain.push({ id: 'root', name: DEFAULT_FOLDER_NAME });
        currentId = null;
        break;
      }

      const node = folderNodes.get(currentId);
      if (node) {
        chain.push({ id: currentId, name: node.name || 'Folder' });
        currentId = node.parentId ?? 'root';
        continue;
      }

      let fallbackName = '…';
      let parentId = null;

      if (currentFolder && currentFolder.id === currentId) {
        fallbackName = currentFolder.name;
        parentId = currentFolder.parent_id ?? 'root';
      }

      chain.push({ id: currentId, name: fallbackName });
      pending.add(currentId);
      currentId = parentId;
    }

    if (!chain.some((crumb) => crumb.id === 'root')) {
      chain.push({ id: 'root', name: DEFAULT_FOLDER_NAME });
    }

    const ordered = [];
    const seenOrdered = new Set();
    chain
      .slice()
      .reverse()
      .forEach((crumb) => {
        if (!seenOrdered.has(crumb.id)) {
          seenOrdered.add(crumb.id);
          ordered.push(crumb);
        }
      });

    return { breadcrumbs: ordered, missingBreadcrumbAncestors: Array.from(pending) };
  }, [selectedFolder, folderNodes, currentFolder]);

  useEffect(() => {
    if (!missingBreadcrumbAncestors.length) {
      return;
    }

    missingBreadcrumbAncestors.forEach((folderId) => {
      if (!folderId || folderId === 'root') {
        return;
      }
      if (breadcrumbFetchRef.current.has(folderId)) {
        return;
      }

      breadcrumbFetchRef.current.add(folderId);
      ensureFolderData(folderId, { force: false })
        .catch((error) => {
          console.warn('Failed to preload breadcrumb ancestor', folderId, error);
        })
        .finally(() => {
          breadcrumbFetchRef.current.delete(folderId);
        });
    });
  }, [missingBreadcrumbAncestors, ensureFolderData]);

  const selectedPreviewEntry = useMemo(() => {
    if (!selectedDocument) {
      return null;
    }
    return previewEntries.get(selectedDocument.id) || null;
  }, [selectedDocument, previewEntries]);

  const previewWorkspaceEntry = useMemo(() => {
    if (!previewDocumentId) {
      return null;
    }
    return previewEntries.get(previewDocumentId) || null;
  }, [previewDocumentId, previewEntries]);

  const previewWorkspaceDocument = useMemo(() => {
    if (!previewDocumentId) return null;
    const pool = searchResults ?? documents;
    return pool.find((doc) => doc.id === previewDocumentId) || null;
  }, [previewDocumentId, searchResults, documents]);

  const previewActive = Boolean(previewDocumentId && previewWorkspaceDocument);

  const sidebarProps = {
    folderNodes,
    onToggle: folderClickHandlers.onToggle,
    onSelect: folderClickHandlers.onSelect,
    onDrop: folderClickHandlers.onDrop,
    onDragOver: folderClickHandlers.onDragOver,
    onDragLeave: folderClickHandlers.onDragLeave,
    onDeleteFolder: handleFolderDelete,
    selectedFolder,
    onFolderDragStart: handleFolderDragStart,
    onFolderDragEnd: handleFolderDragEnd,
    draggedFolderId,
    onShowTags: () => navigate('/tags'),
    tags,
  };

  const resolveThumbnailUrlForDoc = useCallback(
    (doc) =>
      resolveDocumentAssetUrl(doc, 'thumbnail', {
        ensureAssetUrl,
        getAsset: getDocumentAsset,
      }),
    [ensureAssetUrl, getDocumentAsset],
  );

  const showSkeuoWorkspace = useCallback(() => setWorkspaceMode('skeuo'), [setWorkspaceMode]);
  const exitSkeuoWorkspace = useCallback(() => setWorkspaceMode('table'), [setWorkspaceMode]);

  const documentsTableProps = {
    currentFolderName,
    breadcrumbs,
    onRefresh: refreshCurrentFolder,
    onShowSkeuoWorkspace: showSkeuoWorkspace,
    onRequestCreateFolder: openCreateFolderModal,
    creatingFolder,
    subfolders: currentSubfolders,
    documents,
    searchResults,
    isFilterActive,
    onFolderSelect: selectFolder,
    onFolderDrop: folderClickHandlers.onDrop,
    onFolderDragOver: folderClickHandlers.onDragOver,
    onFolderDragLeave: folderClickHandlers.onDragLeave,
    onFolderDragStart: handleFolderDragStart,
    onFolderDragEnd: handleFolderDragEnd,
    draggedFolderId,
    onFolderDelete: handleFolderDelete,
    onDocumentRowClick: handleDocumentRowClick,
    onDocumentOpen: openDocumentPreview,
    onDocumentDelete: handleDocumentDelete,
    selectedDocumentIds,
    focusedDocumentId,
    focusedRowKey,
    draggingDocumentIds: draggedDocumentIds,
    onDocumentDragStart: handleDocumentDragStart,
    onDocumentDragEnd: handleDocumentDragEnd,
    filterBar,
    tagLookupById,
    onDocumentListFocus: handleDocumentListFocus,
    onDocumentListKeyDown: handleDocumentListKeyDown,
    onFocusedRowChange: setFocusedRowKey,
    ensureAssetUrl,
    getDocumentAsset,
    getDownloadHref: (doc) =>
      doc?.current_version?.download_path
        ? resolveApiPath(doc.current_version.download_path)
        : null,
  };

  const detailPanelProps = {
    selectedDocuments: orderedSelectedDocuments,
    tags,
    tagLookupById,
    tagLookupByLabel,
    onTagAdd: handleTagAdd,
    onTagRemove: handleTagRemove,
    onRegenerateThumbnails: handleThumbnailRegeneration,
    previewEntry: selectedPreviewEntry,
    onOpenPreview: openDocumentPreview,
    onBulkTagAdd: handleBulkTagAddFromDetail,
    onBulkTagRemove: handleBulkTagRemoveFromDetail,
    onBulkMove: handleBulkMoveFromDetail,
    onBulkReanalyze: handleBulkSelectionReanalyze,
    folderOptions,
    defaultMoveTarget,
    onPromoteSelection: promoteSelectionOrder,
    activePreviewId,
    onUpdateTitle: handleDocumentTitleUpdate,
    ensureAssetUrl,
    getDocumentAsset,
  };

  const skeuoWorkspaceProps = useMemo(
    () => ({
      documents,
      searchResults,
      breadcrumbs,
      currentFolderName,
      onExit: exitSkeuoWorkspace,
      onRefresh: refreshCurrentFolder,
      onDocumentOpen: openDocumentPreview,
      resolveThumbnailUrl: resolveThumbnailUrlForDoc,
      availableTags: tags,
      onCreateTag: handleTagCreate,
      onAssignTagToDocument: handleDocumentTagAttach,
      onRemoveTagFromDocument: handleTagRemove,
      ensureAssetUrl,
      getDocumentAsset,
    }),
    [
      documents,
      searchResults,
      breadcrumbs,
      currentFolderName,
      exitSkeuoWorkspace,
      refreshCurrentFolder,
      openDocumentPreview,
      resolveThumbnailUrlForDoc,
      tags,
      handleTagCreate,
      handleDocumentTagAttach,
      handleTagRemove,
      ensureAssetUrl,
      getDocumentAsset,
    ],
  );

  const contextValue = useMemo(
    () => ({
      token,
      appStatus,
      status,
      dropOverlayState,
      handleBulkReanalyze,
      handleLogout,
      sidebarProps,
      tags,
      refreshTags,
      handleTagUpdate,
      handleTagCreate,
      handleDocumentTagAttach,
      previewActive,
      previewWorkspaceDocument,
      previewWorkspaceEntry,
      closeDocumentPreview,
      handleThumbnailRegeneration,
      documentsTableProps,
      detailPanelProps,
      workspaceMode,
      showSkeuoWorkspace,
      exitSkeuoWorkspace,
      skeuoWorkspaceProps,
    }),
    [
      token,
      appStatus,
      status,
      dropOverlayState,
      handleBulkReanalyze,
      handleLogout,
      sidebarProps,
      tags,
      refreshTags,
      handleTagUpdate,
      handleTagCreate,
      handleDocumentTagAttach,
      previewActive,
      previewWorkspaceDocument,
      previewWorkspaceEntry,
      closeDocumentPreview,
      handleThumbnailRegeneration,
      documentsTableProps,
      detailPanelProps,
      workspaceMode,
      showSkeuoWorkspace,
      exitSkeuoWorkspace,
      skeuoWorkspaceProps,
    ],
  );

  if (appStatus === 'logged-out' || appStatus === 'authenticating') {
    return (
      <Navigate
        to="/account/login"
        replace
        state={{ from: location.pathname + location.search }}
      />
    );
  }

  return (
    <AppShellContext.Provider value={contextValue}>
      <div className="app-shell" ref={shellRef}>
        <DropOverlay
          active={dropOverlayState.active}
          folderName={dropOverlayState.folderName}
        />
        <header className="app-bar">
          <div className="app-bar__main">
            <div className="app-bar__meta">
              <h1>Papercrate</h1>
              <span className="app-bar__hint">
                {appStatus === 'bootstrapping' && loading
                  ? 'Loading your library…'
                  : previewActive
                  ? 'Viewing document preview. Press ← Back to return to the library.'
                  : 'Drag files here to upload.'}
              </span>
            </div>
            {status && (
              <div className="app-bar__status">
                <StatusBanner status={status} />
              </div>
            )}
            <div className="app-bar__actions">
              <button
                className="secondary"
                type="button"
                onClick={handleBulkReanalyze}
              >
                Re-analyze All
              </button>
              <button className="secondary" onClick={handleLogout}>
                Log out
              </button>
            </div>
          </div>
        </header>
        <Outlet />
        {isCreateFolderModalOpen && (
          <div
            className="modal-backdrop"
            role="presentation"
            onClick={closeCreateFolderModal}
          >
            <div
              className="modal"
              role="dialog"
              aria-modal="true"
              aria-labelledby="create-folder-title"
              onClick={(event) => event.stopPropagation()}
            >
              <h3 id="create-folder-title">Create folder</h3>
              <form className="modal__form" onSubmit={handleCreateFolderSubmit}>
                <label htmlFor="new-folder-name">Folder name</label>
                <input
                  id="new-folder-name"
                  ref={createFolderInputRef}
                  value={newFolderName}
                  onChange={(event) => {
                    setNewFolderName(event.target.value);
                    if (createFolderError) {
                      setCreateFolderError('');
                    }
                  }}
                  placeholder="Enter folder name"
                  disabled={creatingFolder}
                  autoComplete="off"
                />
                {createFolderError && <p className="modal__error">{createFolderError}</p>}
                <div className="modal__actions">
                  <button
                    type="button"
                    className="secondary"
                    onClick={closeCreateFolderModal}
                    disabled={creatingFolder}
                  >
                    Cancel
                  </button>
                  <button type="submit" disabled={creatingFolder}>
                    {creatingFolder ? 'Creating…' : 'Create'}
                  </button>
                </div>
              </form>
            </div>
          </div>
        )}
      </div>
    </AppShellContext.Provider>
  );
};

const useAppShell = () => {
  const context = useContext(AppShellContext);
  if (!context) {
    throw new Error('AppShellContext not found. Ensure routes are nested under AppLayout.');
  }
  return context;
};

const DocumentsRoute = () => {
  const {
    sidebarProps,
    previewActive,
    previewWorkspaceDocument,
    previewWorkspaceEntry,
    closeDocumentPreview,
    handleThumbnailRegeneration,
    documentsTableProps,
    detailPanelProps,
    workspaceMode,
    skeuoWorkspaceProps,
  } = useAppShell();

  if (previewActive && previewWorkspaceDocument) {
    return (
      <main className="preview-main">
        <PreviewWorkspace
          document={previewWorkspaceDocument}
          previewEntry={previewWorkspaceEntry}
          onClose={closeDocumentPreview}
          onRegenerateThumbnails={handleThumbnailRegeneration}
        />
      </main>
    );
  }

  if (workspaceMode === 'skeuo') {
    return (
      <main className="skeuo-main">
        <SkeuomorphicWorkspace {...skeuoWorkspaceProps} />
      </main>
    );
  }

  return (
    <MainLayout sidebarProps={sidebarProps}>
      <DocumentsTable {...documentsTableProps} />
      <DetailPanel {...detailPanelProps} />
    </MainLayout>
  );
};

const LoginRoute = () => {
  const { status: appStatus } = useAppState();
  const appDispatch = useAppDispatch();
  const location = useLocation();
  const [status, setStatus] = useState(null);

  const setStatusMessage = useCallback((message, variant = 'info') => {
    setStatus(message ? { message, variant } : null);
  }, []);
  const handleLoginApiReport = useCallback(
    ({ message, variant }) => setStatusMessage(message, variant),
    [setStatusMessage],
  );
  const reportLoginError = useApiError({
    onReport: handleLoginApiReport,
  });
  const notifyLoginError = useCallback(
    (error, fallbackMessage, variant = 'error') =>
      reportLoginError(error, { message: fallbackMessage, variant }),
    [reportLoginError],
  );

  const handleLogin = useCallback(
    async (event) => {
      event.preventDefault();
      const form = new FormData(event.currentTarget);
      const payload = {
        username: form.get('username')?.toString().trim(),
        password: form.get('password')?.toString() || '',
      };

      if (!payload.username || !payload.password) {
        setStatusMessage('Username and password are required.', 'error');
        return;
      }

      try {
        appDispatch({ type: 'LOGIN_REQUEST' });
        const { data } = await api.post('/auth/login', payload);
        appDispatch({ type: 'LOGIN_SUCCESS', token: data.access_token });
        setStatusMessage('Login successful.', 'success');
      } catch (error) {
        const message = error?.response?.data?.error || 'Login failed. Check credentials.';
        appDispatch({ type: 'LOGIN_FAILURE', error: message });
        notifyLoginError(error, message);
      }
    },
    [appDispatch, notifyLoginError, setStatusMessage],
  );

  const redirectTarget = useMemo(() => {
    const target = location.state?.from;
    if (typeof target === 'string' && target.startsWith('/')) {
      return target;
    }
    return '/folders';
  }, [location.state]);

  if (appStatus !== 'logged-out' && appStatus !== 'authenticating') {
    return <Navigate to={redirectTarget} replace />;
  }

  return (
    <div className="app-shell">
      <LoginView onSubmit={handleLogin} status={status} />
    </div>
  );
};

const TagsRoute = () => {
  const { sidebarProps, tags, refreshTags, handleTagUpdate } = useAppShell();
  return (
    <MainLayout sidebarProps={sidebarProps} className="tags-main">
      <TagsPanel tags={tags} onRefresh={refreshTags} onUpdateTag={handleTagUpdate} />
    </MainLayout>
  );
};

const AppRouter = () => (
  <Routes>
    <Route path="/account/login" element={<LoginRoute />} />
    <Route element={<AppLayout />}>
      <Route path="/" element={<Navigate to="/folders" replace />} />
      <Route path="/folders" element={<DocumentsRoute />} />
      <Route path="/folders/:folderId" element={<DocumentsRoute />} />
      <Route path="/documents/:documentId" element={<DocumentsRoute />} />
      <Route
        path="/folders/:folderId/documents/:documentId"
        element={<DocumentsRoute />}
      />
      <Route path="/tags" element={<TagsRoute />} />
      <Route path="*" element={<Navigate to="/folders" replace />} />
    </Route>
  </Routes>
);

const container = document.getElementById('app');
const root = createRoot(container);
root.render(
  <AppStateProvider>
    <HashRouter hashType="hashbang">
      <AppRouter />
    </HashRouter>
  </AppStateProvider>,
);
