import { useEffect, useMemo, useRef, useState } from 'react';
import LoadingButton from './LoadingButton';
import SortTh from './SortTh';
import { supabase } from '../lib/supabase';
import { popupMenuStyle } from '../lib/popupStyles';

const TABLE_TH = { fontSize: 10, fontWeight: 500, color: 'var(--text-muted)', letterSpacing: 0.6, textTransform: 'uppercase', padding: '0 0 12px', border: 'none', background: 'transparent', verticalAlign: 'top' };
const TABLE_TD = { padding: '5px', fontSize: 13, color: 'var(--text-primary)', border: 'none', background: 'transparent' };
const LABEL = { fontSize: 11, fontWeight: 500, color: 'var(--text-secondary)', letterSpacing: 0.8, textTransform: 'uppercase' };
const ITEM_STYLE = { display: 'flex', alignItems: 'center', gap: 8, padding: '7px 14px', fontSize: 13, cursor: 'pointer', color: 'var(--text-primary)', background: 'none', border: 'none', width: '100%', textAlign: 'left', borderRadius: 4, whiteSpace: 'nowrap' };
const SEP = { height: 1, background: 'var(--border)', margin: '4px 0' };

function formatBytes(bytes) {
  const value = Number(bytes || 0);
  if (!value) return '—';
  const units = ['B', 'KB', 'MB', 'GB'];
  const index = Math.min(Math.floor(Math.log(value) / Math.log(1024)), units.length - 1);
  return `${(value / (1024 ** index)).toFixed(index === 0 ? 0 : 1)} ${units[index]}`;
}

function formatDate(dt) {
  if (!dt) return '—';
  const d = new Date(dt);
  return d.toLocaleDateString('en-US', { month: 'short', day: 'numeric', year: 'numeric' }) + ' ' + d.toLocaleTimeString('en-US', { hour: 'numeric', minute: '2-digit', hour12: true });
}

function fileIconStyle(ext) {
  const e = ext.toLowerCase();
  if (['jpg','jpeg','png','gif','webp','svg','ico','bmp','tiff','avif','heic'].includes(e)) return { bg: '#16a34a', color: '#fff' };
  if (['mp4','mov','avi','mkv','webm','m4v','wmv','flv'].includes(e)) return { bg: '#7c3aed', color: '#fff' };
  if (['mp3','wav','ogg','flac','aac','m4a'].includes(e)) return { bg: '#db2777', color: '#fff' };
  if (e === 'pdf') return { bg: '#dc2626', color: '#fff' };
  if (['doc','docx','rtf'].includes(e)) return { bg: '#2563eb', color: '#fff' };
  if (['txt','md'].includes(e)) return { bg: '#64748b', color: '#fff' };
  if (['xls','xlsx','csv'].includes(e)) return { bg: '#16a34a', color: '#fff' };
  if (['ppt','pptx'].includes(e)) return { bg: '#ea580c', color: '#fff' };
  if (['zip','rar','7z','tar','gz'].includes(e)) return { bg: '#92400e', color: '#fff' };
  if (['ai','eps'].includes(e)) return { bg: '#ff6c00', color: '#fff' };
  if (['psd','psb'].includes(e)) return { bg: '#001e36', color: '#31a8ff' };
  if (['indd','idml'].includes(e)) return { bg: '#49021f', color: '#ff3366' };
  if (['fig','sketch'].includes(e)) return { bg: '#7c3aed', color: '#fff' };
  return { bg: '#475569', color: '#fff' };
}

function FileIcon({ entry }) {
  if (entry.type === 'dir') {
    return (
      <div style={{ width: 24, height: 24, display: 'flex', alignItems: 'center', justifyContent: 'center', flexShrink: 0 }}>
        <svg width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="var(--accent)" strokeWidth="1.5" strokeLinecap="round" strokeLinejoin="round">
          <path d="M22 19a2 2 0 01-2 2H4a2 2 0 01-2-2V5a2 2 0 012-2h5l2 3h9a2 2 0 012 2z" />
        </svg>
      </div>
    );
  }
  const ext = (entry.name.includes('.') ? entry.name.split('.').pop() : '').toUpperCase().slice(0, 4) || 'FILE';
  const { bg, color } = fileIconStyle(ext);
  return (
    <div style={{ width: 24, height: 24, borderRadius: 4, background: bg, display: 'flex', alignItems: 'center', justifyContent: 'center', flexShrink: 0 }}>
      <span style={{ color, fontSize: 7, fontWeight: 600, letterSpacing: 0.3, fontFamily: 'monospace' }}>{ext}</span>
    </div>
  );
}

function pathParts(path) { return String(path || '/').split('/').filter(Boolean); }
function pathTo(index, parts) { return `/${parts.slice(0, index + 1).join('/')}`; }
function joinVirtualPath(...parts) { return ('/' + parts.join('/')).replace(/\/+/g, '/').replace(/\/$/, '') || '/'; }

export default function FileBrowser({ initialPath = '/', rootPath = '/' }) {
  const [currentPath, setCurrentPath] = useState(initialPath);
  const [entries, setEntries] = useState([]);
  const [parentPath, setParentPath] = useState('/');
  const [canGoUp, setCanGoUp] = useState(false);
  const [loading, setLoading] = useState(true);
  const [working, setWorking] = useState('');
  const [dragging, setDragging] = useState(false);
  const [error, setError] = useState('');
  const [readOnly, setReadOnly] = useState(false);
  const [folderName, setFolderName] = useState('');
  const [showFolderInput, setShowFolderInput] = useState(false);
  const [renamingEntry, setRenamingEntry] = useState(null);
  const [renameValue, setRenameValue] = useState('');
  const [uploadProgress, setUploadProgress] = useState(null);
  const [selected, setSelected] = useState(new Set());
  const [sortKey, setSortKey] = useState('name');
  const [sortDir, setSortDir] = useState('asc');
  const [ctxMenu, setCtxMenu] = useState(null);
  const [clipboard, setClipboard] = useState(null);
  const fileInputRef = useRef(null);
  const folderInputRef = useRef(null);

  const breadcrumbs = useMemo(() => pathParts(currentPath), [currentPath]);

  useEffect(() => {
    if (!ctxMenu) return;
    const close = () => setCtxMenu(null);
    window.addEventListener('click', close);
    return () => window.removeEventListener('click', close);
  }, [ctxMenu]);

  const apiFetch = async (url, options = {}) => {
    const { data: { session } } = await supabase.auth.getSession();
    if (!session?.access_token) throw new Error('Session expired. Please sign in again.');
    const response = await fetch(url, {
      ...options,
      headers: {
        Authorization: `Bearer ${session.access_token}`,
        ...(options.body instanceof FormData ? {} : { 'Content-Type': 'application/json' }),
        ...(options.headers || {}),
      },
    });
    const data = await response.json().catch(() => ({}));
    if (!response.ok) throw new Error(data.error || 'File request failed.');
    return data;
  };

  const loadFiles = async (path = currentPath) => {
    setLoading(true); setError(''); setSelected(new Set());
    try {
      const params = new URLSearchParams({ action: 'list', path });
      const data = await apiFetch(`/api/filebrowser?${params}`);
      if (data.configured === false) { setError(data.error || 'File browser not configured.'); return; }
      setEntries(data.entries || []);
      setCurrentPath(data.path || path);
      setParentPath(data.parentPath || '/');
      setCanGoUp(data.canGoUp || false);
      setReadOnly(data.readOnly || false);
    } catch (err) { setError(err.message); }
    finally { setLoading(false); }
  };

  useEffect(() => { loadFiles(initialPath); }, [initialPath]); // eslint-disable-line react-hooks/exhaustive-deps

  const toggleSort = (col) => {
    if (sortKey === col) setSortDir(d => d === 'asc' ? 'desc' : 'asc');
    else { setSortKey(col); setSortDir(col === 'modified' ? 'desc' : 'asc'); }
  };

  const sortedEntries = useMemo(() => {
    return [...entries].sort((a, b) => {
      const aDir = a.type === 'dir'; const bDir = b.type === 'dir';
      if (aDir !== bDir) return aDir ? -1 : 1;
      let av, bv;
      if (sortKey === 'name') { av = (a.name || '').toLowerCase(); bv = (b.name || '').toLowerCase(); }
      else if (sortKey === 'size') { av = Number(a.size || 0); bv = Number(b.size || 0); }
      else if (sortKey === 'modified') { av = new Date(a.mtime || 0).getTime(); bv = new Date(b.mtime || 0).getTime(); }
      else { av = ''; bv = ''; }
      const r = typeof av === 'string' ? av.localeCompare(bv) : (av > bv ? 1 : av < bv ? -1 : 0);
      return sortDir === 'asc' ? r : -r;
    });
  }, [entries, sortKey, sortDir]);

  const downloadFile = async (entry) => {
    setWorking(`dl:${entry.path}`);
    try {
      const data = await apiFetch(`/api/filebrowser?action=download&path=${encodeURIComponent(entry.path)}`);
      if (data.url && data.token) {
        const sep = data.url.includes('?') ? '&' : '?';
        const a = document.createElement('a');
        a.href = `${data.url}${sep}auth=${encodeURIComponent(data.token)}`;
        a.download = entry.name; a.target = '_blank'; a.rel = 'noopener noreferrer';
        document.body.appendChild(a); a.click(); document.body.removeChild(a);
      }
    } catch (err) { setError(err.message); }
    finally { setWorking(''); }
  };

  const downloadSelected = async () => {
    if (!selected.size) return;
    setWorking('dl-sel');
    try {
      for (const name of selected) {
        const entry = entries.find(e => e.name === name);
        if (entry && entry.type !== 'dir') await downloadFile(entry);
      }
    } finally { setWorking(''); }
  };

  const deleteEntry = async (entry) => {
    if (!window.confirm(`Delete "${entry.name}"? This cannot be undone.`)) return;
    setWorking(`del:${entry.path}`);
    try {
      await apiFetch(`/api/filebrowser?action=delete&path=${encodeURIComponent(entry.path)}`, { method: 'DELETE' });
      await loadFiles(currentPath);
    } catch (err) { setError(err.message); }
    finally { setWorking(''); }
  };

  const deleteSelected = async () => {
    if (!selected.size || !window.confirm(`Delete ${selected.size} item(s)?`)) return;
    for (const name of selected) {
      const entry = entries.find(e => e.name === name);
      if (!entry) continue;
      await apiFetch(`/api/filebrowser?action=delete&path=${encodeURIComponent(entry.path)}`, { method: 'DELETE' }).catch(() => {});
    }
    setSelected(new Set());
    await loadFiles(currentPath);
  };

  const createFolder = async (e) => {
    e.preventDefault();
    if (!folderName.trim()) return;
    setWorking('mkdir');
    try {
      await apiFetch('/api/filebrowser?action=mkdir', { method: 'POST', body: JSON.stringify({ path: currentPath, name: folderName }) });
      setFolderName(''); setShowFolderInput(false);
      await loadFiles(currentPath);
    } catch (err) { setError(err.message); }
    finally { setWorking(''); }
  };

  const renameEntry = async (e) => {
    e.preventDefault();
    const newName = renameValue.trim();
    if (!newName || newName === renamingEntry.name) { setRenamingEntry(null); return; }
    setWorking(`ren:${renamingEntry.path}`);
    try {
      await apiFetch('/api/filebrowser?action=rename', { method: 'POST', body: JSON.stringify({ path: renamingEntry.path, name: newName }) });
      setRenamingEntry(null);
      await loadFiles(currentPath);
    } catch (err) { setError(err.message); }
    finally { setWorking(''); }
  };

  const pasteClipboard = async () => {
    if (!clipboard) return;
    setWorking('paste');
    try {
      for (const item of clipboard.items) {
        await apiFetch('/api/filebrowser?action=' + (clipboard.mode === 'copy' ? 'copy' : 'move'), {
          method: 'POST',
          body: JSON.stringify({ srcPath: item.path, dstParentPath: currentPath }),
        });
      }
      if (clipboard.mode === 'move') setClipboard(null);
      await loadFiles(currentPath);
    } catch (err) { setError(err.message); }
    finally { setWorking(''); }
  };

  async function uploadOneFile(vPath, file, retries = 3) {
    for (let attempt = 1; attempt <= retries; attempt++) {
      try {
        await apiFetch(`/api/filebrowser?action=upload&path=${encodeURIComponent(vPath)}`, {
          method: 'POST', headers: { 'Content-Type': 'application/octet-stream' }, body: file,
        });
        return;
      } catch (err) {
        if (attempt === retries) throw err;
        await new Promise(r => setTimeout(r, attempt * 1000));
      }
    }
  }

  const uploadFiles = async (files) => {
    const sel = Array.from(files || []);
    if (!sel.length) return;
    setWorking('upload'); setUploadProgress(0); setError('');
    try {
      for (let i = 0; i < sel.length; i++) {
        await uploadOneFile(joinVirtualPath(currentPath, sel[i].name), sel[i]);
        setUploadProgress(Math.round(((i + 1) / sel.length) * 100));
      }
    } catch (err) { setError(err.message); }
    finally { setWorking(''); setUploadProgress(null); if (fileInputRef.current) fileInputRef.current.value = ''; setDragging(false); await loadFiles(currentPath); }
  };

  const uploadFolder = async (files) => {
    const sel = Array.from(files || []).filter(f => f.webkitRelativePath);
    if (!sel.length) return;
    setWorking('upload'); setUploadProgress(0); setError('');
    try {
      const dirsNeeded = new Set();
      for (const file of sel) {
        const parts = file.webkitRelativePath.split('/').slice(0, -1);
        for (let i = 1; i <= parts.length; i++) dirsNeeded.add(parts.slice(0, i).join('/'));
      }
      for (const dir of [...dirsNeeded].sort((a, b) => a.split('/').length - b.split('/').length)) {
        await apiFetch('/api/filebrowser?action=mkdir', { method: 'POST', body: JSON.stringify({ path: currentPath, name: dir.split('/').pop() }) }).catch(() => {});
      }
      for (let i = 0; i < sel.length; i++) {
        await uploadOneFile(joinVirtualPath(currentPath, sel[i].webkitRelativePath), sel[i]);
        setUploadProgress(Math.round(((i + 1) / sel.length) * 100));
      }
    } catch (err) { setError(err.message); }
    finally { setWorking(''); setUploadProgress(null); if (folderInputRef.current) folderInputRef.current.value = ''; await loadFiles(currentPath); }
  };

  const handleDragEnter = (e) => { e.preventDefault(); if (!readOnly) setDragging(true); };
  const handleDragOver = (e) => { e.preventDefault(); if (!readOnly) { e.dataTransfer.dropEffect = 'copy'; setDragging(true); } };
  const handleDragLeave = (e) => { e.preventDefault(); if (!e.currentTarget.contains(e.relatedTarget)) setDragging(false); };
  const handleDrop = async (e) => {
    e.preventDefault(); setDragging(false);
    if (readOnly) return;
    const items = Array.from(e.dataTransfer.items || []);
    const fsEntries = items.map(i => i.webkitGetAsEntry?.()).filter(Boolean);
    if (fsEntries.some(en => en.isDirectory)) {
      const readFsEntry = (entry) => new Promise(resolve => {
        if (entry.isFile) { entry.file(file => { Object.defineProperty(file, 'webkitRelativePath', { value: entry.fullPath.replace(/^\//, ''), writable: false, configurable: true }); resolve([file]); }); }
        else if (entry.isDirectory) { const reader = entry.createReader(); const readAll = acc => reader.readEntries(async entries => { if (!entries.length) { resolve(acc); return; } const nested = await Promise.all(entries.map(readFsEntry)); readAll([...acc, ...nested.flat()]); }); readAll([]); }
        else { resolve([]); }
      });
      uploadFolder((await Promise.all(fsEntries.map(readFsEntry))).flat());
    } else {
      if (!e.dataTransfer.files?.length) return;
      uploadFiles(e.dataTransfer.files);
    }
  };

  const toggleSelect = (name) => setSelected(prev => { const next = new Set(prev); next.has(name) ? next.delete(name) : next.add(name); return next; });

  const openCtxMenu = (e, entry, childPath) => {
    e.preventDefault(); e.stopPropagation();
    const menuW = 180, menuH = 320;
    const x = e.clientX + menuW > window.innerWidth ? window.innerWidth - menuW - 8 : e.clientX;
    const y = e.clientY + menuH > window.innerHeight ? e.clientY - menuH : e.clientY;
    setCtxMenu({ x: Math.max(4, x), y: Math.max(4, y), entry, childPath });
  };

  return (
    <div
      style={{ display: 'flex', flexDirection: 'column', flex: 1, minHeight: 0, borderRadius: 8, border: `1px solid ${dragging ? 'var(--accent)' : 'var(--border)'}`, transition: 'border-color 140ms ease', position: 'relative', overflow: 'hidden' }}
      onDragEnter={handleDragEnter} onDragOver={handleDragOver} onDragLeave={handleDragLeave} onDrop={handleDrop}
    >
      {dragging && (
        <div style={{ position: 'absolute', inset: 0, zIndex: 10, background: 'rgba(245,165,35,0.08)', display: 'flex', alignItems: 'center', justifyContent: 'center', pointerEvents: 'none' }}>
          <div style={{ textAlign: 'center' }}>
            <div style={{ fontSize: 28, marginBottom: 8 }}>↑</div>
            <div style={{ fontSize: 14, fontWeight: 500, color: 'var(--accent)' }}>Drop files to upload</div>
          </div>
        </div>
      )}

      {/* Toolbar */}
      <div style={{ padding: '18px 21px', borderBottom: '1px solid var(--border)', flexShrink: 0, position: 'relative' }}>
        {/* Selection actions — absolute top-right like FileSharing */}
        {selected.size > 0 && (
          <div style={{ position: 'absolute', top: 18, right: 21, display: 'flex', gap: 8 }}>
            <button className="btn btn-outline" disabled={Boolean(working)} onClick={downloadSelected}>Download ({selected.size})</button>
            {!readOnly && <button className="btn btn-danger" disabled={Boolean(working)} onClick={deleteSelected}>Delete ({selected.size})</button>}
          </div>
        )}

        <div style={{ paddingRight: selected.size > 0 ? 260 : 0 }}>
          <div style={{ display: 'flex', alignItems: 'center', marginBottom: 2 }}>
            <div style={LABEL}>Files</div>
            {uploadProgress !== null && <span style={{ fontSize: 12, color: 'var(--text-muted)', marginLeft: 12 }}>Uploading {uploadProgress}%</span>}
            {!readOnly && (
              <>
                <input ref={folderInputRef} type="file" style={{ display: 'none' }} onChange={e => uploadFolder(e.target.files)} {...{ webkitdirectory: '' }} />
                <input ref={fileInputRef} type="file" multiple style={{ display: 'none' }} onChange={e => uploadFiles(e.target.files)} />
              </>
            )}
          </div>
          <div style={{ fontSize: 12, color: dragging ? 'var(--accent)' : 'var(--text-muted)', marginTop: 2, marginBottom: 14, transition: 'color 140ms ease' }}>
            Drag and drop files or folders here.
          </div>
          {/* Breadcrumbs */}
          <div style={{ fontSize: 11, fontWeight: 500, letterSpacing: 0.6, textTransform: 'uppercase', color: 'var(--text-secondary)', display: 'flex', alignItems: 'center', gap: 4, flexWrap: 'wrap' }}>
            <button type="button" onClick={() => loadFiles(rootPath)} style={{ background: 'none', border: 'none', cursor: 'pointer', fontSize: 11, fontWeight: 500, letterSpacing: 0.6, textTransform: 'uppercase', color: 'var(--text-primary)', fontFamily: 'inherit', padding: 0 }}>Files</button>
            {breadcrumbs.slice(pathParts(rootPath).length).map((part, i) => {
              const absIdx = pathParts(rootPath).length + i;
              return (
                <span key={`${part}-${absIdx}`} style={{ display: 'flex', alignItems: 'center', gap: 4 }}>
                  <span style={{ opacity: 0.4 }}>/</span>
                  <button type="button" onClick={() => loadFiles(pathTo(absIdx, breadcrumbs))} style={{ background: 'none', border: 'none', cursor: 'pointer', fontSize: 11, fontWeight: 500, letterSpacing: 0.6, textTransform: 'uppercase', color: absIdx === breadcrumbs.length - 1 ? 'var(--accent)' : 'var(--text-primary)', fontFamily: 'inherit', padding: 0 }}>{part}</button>
                </span>
              );
            })}
          </div>
        </div>
      </div>

      {uploadProgress !== null && (
        <div style={{ height: 2, background: 'var(--border)', flexShrink: 0 }}>
          <div style={{ height: '100%', background: 'var(--accent)', width: `${uploadProgress}%`, transition: 'width 200ms' }} />
        </div>
      )}

      {/* File table */}
      <div className="scrollbar-thin-theme table-scroll-hidden" style={{ flex: 1, minHeight: 0, overflowY: 'auto', padding: '18px 21px' }}>
        {error && <div style={{ fontSize: 13, color: 'var(--danger)', marginBottom: 12 }}>{error}</div>}
        {loading ? (
          <div className="card-empty-center">Loading…</div>
        ) : entries.length === 0 ? (
          <div className="card-empty-center">This folder is empty.</div>
        ) : (
          <table className="table-sticky-head" style={{ width: '100%', tableLayout: 'fixed', borderCollapse: 'collapse' }}>
            <colgroup>
              <col style={{ width: 32 }} />
              <col />
              <col style={{ width: 90 }} />
              <col style={{ width: 180 }} />
            </colgroup>
            <thead>
              <tr>
                <th style={{ ...TABLE_TH, textAlign: 'center', padding: '0 5px 12px' }}>
                  <input type="checkbox" checked={selected.size === entries.length && entries.length > 0} onChange={e => setSelected(e.target.checked ? new Set(entries.map(en => en.name)) : new Set())} />
                </th>
                <SortTh col="name" sortKey={sortKey} sortDir={sortDir} onSort={toggleSort} style={{ ...TABLE_TH, textAlign: 'left', paddingLeft: 5 }}>Name</SortTh>
                <SortTh col="size" sortKey={sortKey} sortDir={sortDir} onSort={toggleSort} style={{ ...TABLE_TH, textAlign: 'right' }}>Size</SortTh>
                <SortTh col="modified" sortKey={sortKey} sortDir={sortDir} onSort={toggleSort} style={{ ...TABLE_TH, textAlign: 'right' }}>Modified</SortTh>
              </tr>
            </thead>
            <tbody>
              {sortedEntries.map((entry, idx) => {
                const isDir = entry.type === 'dir';
                const childPath = entry.path;
                const isRenaming = renamingEntry?.path === entry.path;
                const rowBg = idx % 2 === 0 ? 'var(--file-row-alt-bg, rgba(255,255,255,0.02))' : 'transparent';
                return (
                  <tr
                    key={`${entry.type}:${entry.path}`}
                    style={{ cursor: isDir ? 'pointer' : 'default' }}
                    onClick={() => isDir && loadFiles(childPath)}
                    onContextMenu={e => openCtxMenu(e, entry, childPath)}
                  >
                    <td style={{ ...TABLE_TD, background: rowBg, textAlign: 'center' }} onClick={e => { e.stopPropagation(); toggleSelect(entry.name); }}>
                      <input type="checkbox" checked={selected.has(entry.name)} onChange={() => toggleSelect(entry.name)} onClick={e => e.stopPropagation()} />
                    </td>
                    <td style={{ ...TABLE_TD, background: rowBg }}>
                      {isRenaming ? (
                        <form style={{ display: 'flex', gap: 6 }} onSubmit={renameEntry} onClick={e => e.stopPropagation()}>
                          <input autoFocus type="text" value={renameValue} onChange={e => setRenameValue(e.target.value)} disabled={Boolean(working)} onKeyDown={e => { if (e.key === 'Escape') setRenamingEntry(null); }} style={{ fontSize: 13, padding: '2px 8px', borderRadius: 4, border: '1px solid var(--border)', background: 'var(--card-bg-2)', color: 'var(--text-primary)', flex: 1, minWidth: 0 }} />
                          <LoadingButton type="submit" className="btn btn-outline" loading={working === `ren:${entry.path}`} disabled={!renameValue.trim()} loadingText="…">Save</LoadingButton>
                          <button type="button" className="btn btn-outline" onClick={() => setRenamingEntry(null)}>Cancel</button>
                        </form>
                      ) : (
                        <div style={{ display: 'flex', alignItems: 'center', gap: 8 }}>
                          <FileIcon entry={entry} />
                          {isDir ? (
                            <button type="button" className="dashboard-inline-link" onClick={e => { e.stopPropagation(); loadFiles(childPath); }} style={{ fontSize: 13, fontWeight: 400, overflow: 'hidden', textOverflow: 'ellipsis', whiteSpace: 'nowrap', textAlign: 'left' }}>{entry.name}</button>
                          ) : (
                            <span style={{ fontSize: 13, color: 'var(--text-primary)', overflow: 'hidden', textOverflow: 'ellipsis', whiteSpace: 'nowrap' }}>{entry.name}</span>
                          )}
                        </div>
                      )}
                    </td>
                    <td style={{ ...TABLE_TD, background: rowBg, textAlign: 'right', fontSize: 12 }}>{isDir ? '—' : formatBytes(entry.size)}</td>
                    <td style={{ ...TABLE_TD, background: rowBg, textAlign: 'right', fontSize: 12 }}>{formatDate(entry.mtime)}</td>
                  </tr>
                );
              })}
            </tbody>
          </table>
        )}
      </div>

      {/* Context menu */}
      {ctxMenu && (
        <div onClick={e => e.stopPropagation()} style={{ ...popupMenuStyle, position: 'fixed', left: ctxMenu.x, top: ctxMenu.y, zIndex: 1000, padding: '4px 0', minWidth: 160 }}>
          {ctxMenu.entry?.type === 'dir' && (
            <button style={ITEM_STYLE} onMouseEnter={e => e.currentTarget.style.background = 'var(--interactive-row-hover)'} onMouseLeave={e => e.currentTarget.style.background = 'none'} onClick={() => { loadFiles(ctxMenu.childPath); setCtxMenu(null); }}>
              <svg width="13" height="13" viewBox="0 0 24 24" fill="none" stroke="var(--accent)" strokeWidth="1.5" strokeLinecap="round" strokeLinejoin="round"><path d="M22 19a2 2 0 01-2 2H4a2 2 0 01-2-2V5a2 2 0 012-2h5l2 3h9a2 2 0 012 2z" /></svg>
              Open
            </button>
          )}
          {ctxMenu.entry?.type !== 'dir' && (
            <button style={ITEM_STYLE} onMouseEnter={e => e.currentTarget.style.background = 'var(--interactive-row-hover)'} onMouseLeave={e => e.currentTarget.style.background = 'none'} onClick={() => { downloadFile(ctxMenu.entry); setCtxMenu(null); }}>
              <svg width="13" height="13" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="1.5" strokeLinecap="round" strokeLinejoin="round"><path d="M21 15v4a2 2 0 01-2 2H5a2 2 0 01-2-2v-4"/><polyline points="7,10 12,15 17,10"/><line x1="12" y1="15" x2="12" y2="3"/></svg>
              Download
            </button>
          )}
          {ctxMenu.entry && !readOnly && (
            <>
              <div style={SEP} />
              <button style={ITEM_STYLE} onMouseEnter={e => e.currentTarget.style.background = 'var(--interactive-row-hover)'} onMouseLeave={e => e.currentTarget.style.background = 'none'} onClick={() => { setRenamingEntry(ctxMenu.entry); setRenameValue(ctxMenu.entry.name); setCtxMenu(null); }}>
                <svg width="13" height="13" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="1.5" strokeLinecap="round" strokeLinejoin="round"><path d="M11 4H4a2 2 0 00-2 2v14a2 2 0 002 2h14a2 2 0 002-2v-7"/><path d="M18.5 2.5a2.121 2.121 0 013 3L12 15l-4 1 1-4 9.5-9.5z"/></svg>
                Rename
              </button>
            </>
          )}
          {ctxMenu.entry && (
            <>
              <div style={SEP} />
              <button style={ITEM_STYLE} onMouseEnter={e => e.currentTarget.style.background = 'var(--interactive-row-hover)'} onMouseLeave={e => e.currentTarget.style.background = 'none'}
                onClick={() => {
                  const items = selected.has(ctxMenu.entry.name)
                    ? [...selected].map(n => { const en = entries.find(e => e.name === n); return { name: n, path: en?.path ?? joinVirtualPath(currentPath, n) }; })
                    : [{ name: ctxMenu.entry.name, path: ctxMenu.childPath }];
                  setClipboard({ items, mode: 'copy' }); setCtxMenu(null);
                }}>
                <svg width="13" height="13" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="1.5" strokeLinecap="round" strokeLinejoin="round"><rect x="9" y="9" width="13" height="13" rx="2"/><path d="M5 15H4a2 2 0 01-2-2V4a2 2 0 012-2h9a2 2 0 012 2v1"/></svg>
                Copy
              </button>
              {!readOnly && (
                <button style={ITEM_STYLE} onMouseEnter={e => e.currentTarget.style.background = 'var(--interactive-row-hover)'} onMouseLeave={e => e.currentTarget.style.background = 'none'}
                  onClick={() => {
                    const items = selected.has(ctxMenu.entry.name)
                      ? [...selected].map(n => { const en = entries.find(e => e.name === n); return { name: n, path: en?.path ?? joinVirtualPath(currentPath, n) }; })
                      : [{ name: ctxMenu.entry.name, path: ctxMenu.childPath }];
                    setClipboard({ items, mode: 'move' }); setCtxMenu(null);
                  }}>
                  <svg width="13" height="13" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="1.5" strokeLinecap="round" strokeLinejoin="round"><circle cx="6" cy="6" r="3"/><circle cx="6" cy="18" r="3"/><line x1="20" y1="4" x2="8.12" y2="15.88"/><line x1="14.47" y1="14.48" x2="20" y2="20"/><line x1="8.12" y1="8.12" x2="12" y2="12"/></svg>
                  Cut
                </button>
              )}
            </>
          )}
          {clipboard && (
            <>
              <div style={SEP} />
              <button style={ITEM_STYLE} onMouseEnter={e => e.currentTarget.style.background = 'var(--interactive-row-hover)'} onMouseLeave={e => e.currentTarget.style.background = 'none'} onClick={() => { pasteClipboard(); setCtxMenu(null); }}>
                <svg width="13" height="13" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="1.5" strokeLinecap="round" strokeLinejoin="round"><path d="M16 4h2a2 2 0 012 2v14a2 2 0 01-2 2H6a2 2 0 01-2-2V6a2 2 0 012-2h2"/><rect x="8" y="2" width="8" height="4" rx="1"/></svg>
                Paste here{clipboard.items.length > 1 ? ` (${clipboard.items.length})` : ''}
              </button>
            </>
          )}
          {!readOnly && ctxMenu.entry && (
            <>
              <div style={SEP} />
              <button style={{ ...ITEM_STYLE, color: 'var(--danger)' }} onMouseEnter={e => e.currentTarget.style.background = 'rgba(255,80,80,0.08)'} onMouseLeave={e => e.currentTarget.style.background = 'none'} onClick={() => { setCtxMenu(null); deleteEntry(ctxMenu.entry); }}>
                <svg width="13" height="13" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="1.5" strokeLinecap="round" strokeLinejoin="round"><polyline points="3,6 5,6 21,6"/><path d="M19 6l-1 14H6L5 6"/><path d="M10 11v6"/><path d="M14 11v6"/><path d="M9 6V4h6v2"/></svg>
                Delete
              </button>
            </>
          )}
        </div>
      )}
    </div>
  );
}
