'use client'

import { useState, useRef, useCallback, useEffect } from 'react'
import Box from '@mui/material/Box'
import Card from '@mui/material/Card'
import CardContent from '@mui/material/CardContent'
import Typography from '@mui/material/Typography'
import Button from '@mui/material/Button'
import IconButton from '@mui/material/IconButton'
import Chip from '@mui/material/Chip'
import Divider from '@mui/material/Divider'
import Dialog from '@mui/material/Dialog'
import DialogTitle from '@mui/material/DialogTitle'
import DialogContent from '@mui/material/DialogContent'
import DialogActions from '@mui/material/DialogActions'
import TextField from '@mui/material/TextField'
import MenuItem from '@mui/material/MenuItem'
import Tooltip from '@mui/material/Tooltip'
import Alert from '@mui/material/Alert'
import LinearProgress from '@mui/material/LinearProgress'
import CircularProgress from '@mui/material/CircularProgress'
import type { ClientFolder, DocFolder, LegalDocument, DocType } from './types'
import { useT } from '@/contexts/LangContext'

// ─── Recursive folder reader (drag-dropped directories) ───────────────────────

async function collectFilesFromEntry(entry: FileSystemEntry): Promise<File[]> {
  if (entry.isFile) {
    return new Promise(resolve => (entry as FileSystemFileEntry).file(f => resolve([f])))
  }
  if (entry.isDirectory) {
    const reader = (entry as FileSystemDirectoryEntry).createReader()
    const entries: FileSystemEntry[] = []
    await new Promise<void>(resolve => {
      const readBatch = () => reader.readEntries(batch => {
        if (!batch.length) { resolve(); return }
        entries.push(...batch)
        readBatch()
      })
      readBatch()
    })
    const nested = await Promise.all(entries.map(collectFilesFromEntry))
    return nested.flat()
  }
  return []
}

// ─── Default system folders ───────────────────────────────────────────────────

export const DEFAULT_DOC_FOLDER_IDS = [
  { _id: 'correspondence',  key: 'correspondence' as const, icon: 'ri-mail-line',                color: '#0D9394' },
  { _id: 'contracts',       key: 'contracts'      as const, icon: 'ri-file-paper-2-line',        color: '#7C6AF7' },
  { _id: 'court-filings',   key: 'courtFilings'   as const, icon: 'ri-scales-3-line',            color: '#FF4C51' },
  { _id: 'identity',        key: 'identity'       as const, icon: 'ri-id-card-line',             color: '#FFB400' },
  { _id: 'financial',       key: 'financial'      as const, icon: 'ri-money-dollar-circle-line', color: '#71DD37' },
  { _id: 'reports',         key: 'reports'        as const, icon: 'ri-file-chart-2-line',        color: '#03C3EC' },
  { _id: 'evidence',        key: 'evidence'       as const, icon: 'ri-file-search-line',         color: '#FF7849' },
  { _id: 'misc',            key: 'misc'           as const, icon: 'ri-folder-3-line',            color: '#8A92A3' },
]

const DOC_TYPE_KEYS: DocType[] = [
  'contract', 'agreement', 'court_filing', 'pleading', 'affidavit',
  'correspondence', 'identity', 'financial', 'evidence', 'deed',
  'power_of_attorney', 'report', 'opinion', 'permit', 'other',
]

const AI_STATUS_CONFIG = {
  pending:    { color: '#8A92A3', bg: '#F0F0F0' },
  processing: { color: '#FFB400', bg: '#FFF5DB' },
  classified: { color: '#0D9394', bg: '#E8F7F7' },
  failed:     { color: '#FF4C51', bg: '#FFECEC' },
}

function fmtBytes(b: number) {
  if (b < 1024) return `${b} B`
  if (b < 1024 * 1024) return `${(b / 1024).toFixed(0)} KB`
  return `${(b / (1024 * 1024)).toFixed(1)} MB`
}
function fmtDate(iso?: string) {
  if (!iso) return '—'
  return new Date(iso).toLocaleDateString('en-GB', { day: 'numeric', month: 'short', year: 'numeric' })
}
function mimeIcon(mime: string) {
  if (mime.includes('pdf'))   return 'ri-file-pdf-2-line'
  if (mime.includes('word') || mime.includes('document')) return 'ri-file-word-line'
  if (mime.includes('sheet') || mime.includes('excel'))   return 'ri-file-excel-line'
  if (mime.includes('image')) return 'ri-image-line'
  return 'ri-file-line'
}
const isPdf   = (m: string) => m.includes('pdf')
const isImage = (m: string) => m.startsWith('image/')

// ─── Full-width preview card ──────────────────────────────────────────────────

function PreviewCard({ doc, clientId, onTranslate }: { doc: LegalDocument | null; clientId: string; onTranslate?: (doc: LegalDocument) => void }) {
  const t = useT()
  const [showTranslated, setShowTranslated] = useState(false)
  const aiCfg      = doc ? AI_STATUS_CONFIG[doc.aiStatus] : null
  const typeLabel  = doc?.documentType ? t.docTypes[doc.documentType as keyof typeof t.docTypes] : null
  const previewUrl = doc ? `/api/clients/${clientId}/documents/${doc._id}/preview` : null

  if (!doc) {
    return (
      <Card sx={{ border: '1px dashed', borderColor: 'divider' }}>
        <CardContent sx={{ py: 4, display: 'flex', flexDirection: 'column', alignItems: 'center', gap: 1.5, textAlign: 'center' }}>
          <i className='ri-file-search-line' style={{ fontSize: '2.5rem', color: 'rgba(128,128,128,0.25)' }} />
          <Typography variant='body2' color='text.disabled' sx={{ fontWeight: 500 }}>{t.documentsTab.previewEmpty}</Typography>
          <Typography variant='caption' color='text.disabled' sx={{ maxWidth: 480 }}>
            {t.documentsTab.previewEmptyHint}
          </Typography>
          <Divider sx={{ width: '100%', maxWidth: 400 }} />
          <Box sx={{ display: 'flex', alignItems: 'center', gap: 1 }}>
            <i className='ri-archive-stack-line' style={{ color: '#7C6AF7', fontSize: '1rem' }} />
            <Typography variant='caption' color='text.secondary'>
              {t.documentsTab.bundleHint}
            </Typography>
          </Box>
        </CardContent>
      </Card>
    )
  }

  return (
    <Card>
      {/* Toolbar */}
      <Box sx={{ px: 2, py: 1.25, display: 'flex', alignItems: 'center', gap: 1.5, borderBottom: '1px solid', borderColor: 'divider', flexWrap: 'wrap' }}>
        <Typography sx={{ fontFamily: 'monospace', fontWeight: 700, fontSize: '0.82rem', color: '#0D9394' }}>
          {doc.batesNumber}
        </Typography>
        <Typography variant='body2' sx={{ fontWeight: 600, flex: 1, minWidth: 0, overflow: 'hidden', textOverflow: 'ellipsis', whiteSpace: 'nowrap' }}>
          {doc.originalName}
        </Typography>
        <Box sx={{ display: 'flex', alignItems: 'center', gap: 0.5, flexShrink: 0 }}>
          {typeLabel && <Chip label={typeLabel} size='small' sx={{ fontSize: '0.62rem', height: 20, bgcolor: '#EEF2FF', color: '#7C6AF7', fontWeight: 600 }} />}
          {aiCfg   && <Chip label={t.aiStatus[doc!.aiStatus]} size='small' sx={{ fontSize: '0.62rem', height: 20, bgcolor: aiCfg.bg, color: aiCfg.color, fontWeight: 600 }} />}
          <Chip label={fmtBytes(doc.fileSize)} size='small' sx={{ fontSize: '0.62rem', height: 20 }} />
          <Tooltip title={t.common.download}><IconButton size='small' href={previewUrl ?? '#'} target='_blank'><i className='ri-download-line' style={{ fontSize: '0.9rem' }} /></IconButton></Tooltip>
          {!doc.isTranslation && onTranslate && (
            <Tooltip title={t.common.translate}>
              <IconButton size='small' onClick={() => onTranslate(doc)}>
                <i className='ri-translate-2' style={{ fontSize: '0.9rem', color: '#0D9394' }} />
              </IconButton>
            </Tooltip>
          )}
          <Tooltip title={t.documentsTab.moveToFolder}><IconButton size='small'><i className='ri-folder-transfer-line' style={{ fontSize: '0.9rem' }} /></IconButton></Tooltip>
          <Tooltip title={t.documentsTab.addToBundle}><IconButton size='small'><i className='ri-archive-stack-line' style={{ fontSize: '0.9rem', color: '#7C6AF7' }} /></IconButton></Tooltip>
        </Box>
      </Box>

      {/* Viewer + metadata side by side */}
      <Box sx={{ display: 'flex', minHeight: 560 }}>

        {/* Viewer — takes all remaining width */}
        <Box sx={{ flex: 1, minWidth: 0, bgcolor: 'action.hover', borderRight: '1px solid', borderColor: 'divider' }}>
          {isPdf(doc.mimeType) && previewUrl ? (
            <Box component='iframe'
              src={`${previewUrl}#toolbar=1&navpanes=0&scrollbar=1`}
              sx={{ width: '100%', height: '100%', minHeight: 560, border: 'none', display: 'block' }} />
          ) : isImage(doc.mimeType) && previewUrl ? (
            <Box sx={{ display: 'flex', alignItems: 'center', justifyContent: 'center', height: '100%', minHeight: 560, p: 2 }}>
              <Box component='img' src={previewUrl} alt={doc.originalName}
                sx={{ maxWidth: '100%', maxHeight: 540, objectFit: 'contain', borderRadius: 1, boxShadow: 2 }} />
            </Box>
          ) : (
            <Box sx={{ display: 'flex', flexDirection: 'column', alignItems: 'center', justifyContent: 'center', height: '100%', minHeight: 560, gap: 2 }}>
              <i className={mimeIcon(doc.mimeType)} style={{ fontSize: '4rem', color: '#7C6AF7' }} />
              <Typography variant='body2' color='text.secondary'>{t.documentsTab.previewNA}</Typography>
              <Button variant='outlined' startIcon={<i className='ri-download-line' />}
                href={previewUrl ?? '#'} target='_blank' sx={{ fontSize: '0.78rem' }}>
                {t.documentsTab.downloadToView}
              </Button>
            </Box>
          )}
        </Box>

        {/* Metadata panel — fixed width */}
        <Box sx={{ width: 260, flexShrink: 0, p: 2, display: 'flex', flexDirection: 'column', gap: 1.5, overflowY: 'auto' }}>
          <Typography variant='caption' sx={{ fontWeight: 700, color: 'text.disabled', letterSpacing: '0.08em' }}>{t.documentsTab.sectionDetails}</Typography>

          {[
            { label: t.documentsTab.labelDocDate,    value: fmtDate(doc.documentDate) },
            { label: t.documentsTab.labelUploaded,   value: fmtDate(doc.uploadedAt) },
            { label: t.documentsTab.labelUploadedBy, value: doc.uploadedBy },
            ...(doc.matterId ? [{ label: t.documentsTab.labelMatter, value: doc.matterId }] : []),
          ].map(r => (
            <Box key={r.label}>
              <Typography variant='caption' color='text.disabled' sx={{ display: 'block' }}>{r.label}</Typography>
              <Typography variant='body2' sx={{ fontWeight: 500 }}>{r.value}</Typography>
            </Box>
          ))}

          {doc.parties?.length ? (
            <Box>
              <Typography variant='caption' color='text.disabled' sx={{ display: 'block' }}>{t.documentsTab.labelParties}</Typography>
              {doc.parties.map(p => (
                <Typography key={p} variant='body2' sx={{ fontWeight: 500, lineHeight: 1.6 }}>{p}</Typography>
              ))}
            </Box>
          ) : null}

          {doc.tags?.length ? (
            <Box>
              <Typography variant='caption' color='text.disabled' sx={{ display: 'block', mb: 0.5 }}>{t.documentsTab.labelTags}</Typography>
              <Box sx={{ display: 'flex', flexWrap: 'wrap', gap: 0.5 }}>
                {doc.tags.map(t => <Chip key={t} label={t} size='small' sx={{ fontSize: '0.6rem', height: 18 }} />)}
              </Box>
            </Box>
          ) : null}

          {doc.summary && (
            <>
              <Divider />
              <Box>
                <Box sx={{ display: 'flex', alignItems: 'center', gap: 0.5, mb: 0.75 }}>
                  <i className='ri-robot-line' style={{ fontSize: '0.85rem', color: '#0D9394' }} />
                  <Typography variant='caption' sx={{ fontWeight: 700, color: 'text.disabled', letterSpacing: '0.08em', flex: 1 }}>{t.documentsTab.sectionSummary}</Typography>
                  {doc.translatedSummary && (
                    <Box sx={{ display: 'flex', gap: 0.5 }}>
                      <Chip label='EN' size='small' onClick={() => setShowTranslated(false)}
                        sx={{ fontSize: '0.55rem', height: 16, cursor: 'pointer',
                          bgcolor: !showTranslated ? '#0D9394' : 'transparent',
                          color: !showTranslated ? '#fff' : 'text.disabled' }} />
                      <Chip label={doc.translatedSummaryLang?.toUpperCase() ?? 'TH'} size='small' onClick={() => setShowTranslated(true)}
                        sx={{ fontSize: '0.55rem', height: 16, cursor: 'pointer',
                          bgcolor: showTranslated ? '#0D9394' : 'transparent',
                          color: showTranslated ? '#fff' : 'text.disabled' }} />
                    </Box>
                  )}
                </Box>
                <Typography variant='caption' color='text.secondary' sx={{ lineHeight: 1.7 }}>
                  {showTranslated && doc.translatedSummary ? doc.translatedSummary : doc.summary}
                </Typography>
              </Box>
            </>
          )}
        </Box>
      </Box>
    </Card>
  )
}

// ─── Props ────────────────────────────────────────────────────────────────────

interface Props {
  folder: ClientFolder
  onUpdate: (f: ClientFolder) => void
  openUpload?: boolean
  onUploadClose?: () => void
}

// ─── Main component ───────────────────────────────────────────────────────────

export default function DocumentsTab({ folder, onUpdate, openUpload, onUploadClose }: Props) {
  const t = useT()

  const DEFAULT_DOC_FOLDERS: DocFolder[] = DEFAULT_DOC_FOLDER_IDS.map(f => ({
    _id: f._id, name: t.docFolders[f.key], icon: f.icon, color: f.color,
    isSystem: true, createdAt: '', createdBy: 'system',
  }))

  const DOC_TYPES: { value: DocType; label: string }[] = DOC_TYPE_KEYS.map(k => ({
    value: k, label: t.docTypes[k as keyof typeof t.docTypes],
  }))

  const [selectedFolderId, setSelectedFolderId] = useState<string | null>(null)
  const [selectedDoc,      setSelectedDoc]      = useState<LegalDocument | null>(null)
  const [newFolderDialog,  setNewFolderDialog]  = useState(false)
  const [newFolderName,    setNewFolderName]    = useState('')
  const [newFolderErr,     setNewFolderErr]     = useState<string | null>(null)
  const [savingFolder,     setSavingFolder]     = useState(false)
  const [uploadDialog,     setUploadDialog]     = useState(openUpload ?? false)
  const [uploadFiles,      setUploadFiles]      = useState<File[]>([])
  const [uploadFolderId,   setUploadFolderId]   = useState<string>('inbox')
  const [uploading,        setUploading]        = useState(false)
  const [uploadErr,        setUploadErr]        = useState<string | null>(null)
  const [uploadDone,       setUploadDone]       = useState<number>(0)   // count after success
  const [dragOver,         setDragOver]         = useState(false)
  const [bundleDialog,     setBundleDialog]     = useState(false)
  const [translateDoc,     setTranslateDoc]     = useState<LegalDocument | null>(null)
  const [translateState,   setTranslateState]   = useState<'idle' | 'translating' | 'done' | 'saving' | 'saved' | 'error'>('idle')
  const [translateResult,  setTranslateResult]  = useState<{ translatedText: string; translatedSummary: string; sourceLang: string; targetLang: string; hasFullText: boolean } | null>(null)
  const [translateErr,     setTranslateErr]     = useState<string | null>(null)
  const fileInputRef   = useRef<HTMLInputElement>(null)
  const folderInputRef = useRef<HTMLInputElement>(null)

  const serverFolders: DocFolder[]   = (folder as any).docFolders ?? []
  const docFolders: DocFolder[] = [
    ...DEFAULT_DOC_FOLDERS.filter(d => !serverFolders.find(s => s._id === d._id)),
    ...serverFolders,
  ]
  const documents: LegalDocument[]  = (folder as any).documents ?? []
  const inbox      = documents.filter(d => !d.folderId || d.folderId === 'inbox')
  const inFolder   = (id: string) => documents.filter(d => d.folderId === id)
  const processing = documents.filter(d => d.aiStatus === 'processing' || d.aiStatus === 'pending')

  if (openUpload && !uploadDialog) setUploadDialog(true)

  // ── Helpers ────────────────────────────────────────────────────────────────
  const saveNewFolder = async () => {
    if (!newFolderName.trim()) { setNewFolderErr(t.documentsTab.folderNameRequired); return }
    setSavingFolder(true); setNewFolderErr(null)
    const nf = { name: newFolderName.trim(), icon: 'ri-folder-3-line', color: '#7C6AF7', isSystem: false, createdAt: new Date().toISOString(), createdBy: 'Patchara S.' }
    try {
      const res = await fetch(`/api/clients/${folder._id}`, { method: 'PATCH', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify({ docFolders: [...serverFolders, nf] }) })
      if (!res.ok) throw new Error(t.documentsTab.errSaveFailed)
      onUpdate(await res.json()); setNewFolderDialog(false); setNewFolderName('')
    } catch (e: any) { setNewFolderErr(e.message) }
    finally { setSavingFolder(false) }
  }

  // Merge new files into the pending list, deduplicating by name+size
  const addFiles = useCallback((incoming: File[]) => {
    setUploadFiles(prev => {
      const seen = new Set(prev.map(f => `${f.name}:${f.size}`))
      return [...prev, ...incoming.filter(f => !seen.has(`${f.name}:${f.size}`))]
    })
  }, [])

  const removeFile = (idx: number) => setUploadFiles(prev => prev.filter((_, i) => i !== idx))

  // Drag-and-drop handlers (support files and dropped directories)
  const onDrop = useCallback(async (e: React.DragEvent) => {
    e.preventDefault(); setDragOver(false)
    const items = Array.from(e.dataTransfer.items)
    const collected: File[] = []
    for (const item of items) {
      const entry = item.webkitGetAsEntry?.()
      if (entry) {
        const files = await collectFilesFromEntry(entry)
        collected.push(...files)
      } else if (item.kind === 'file') {
        const f = item.getAsFile()
        if (f) collected.push(f)
      }
    }
    addFiles(collected)
  }, [addFiles])

  const submitUpload = async () => {
    if (!uploadFiles.length) { setUploadErr(t.documentsTab.errSelectFile); return }
    setUploading(true); setUploadErr(null); setUploadDone(0)
    try {
      const fd = new FormData()
      uploadFiles.forEach(f => fd.append('files', f))
      fd.append('uploadedBy', 'Patchara S.')
      const res = await fetch(`/api/clients/${folder._id}/documents/upload`, { method: 'POST', body: fd })
      if (!res.ok) throw new Error((await res.json().catch(() => ({}))).message ?? t.documentsTab.errUploadFailed)
      const uploaded = (await res.json()) as unknown[]
      setUploadDone(uploaded.length)
      // Re-fetch folder + documents so the UI reflects the new Bates numbers
      const [folderRes, docsRes] = await Promise.all([
        fetch(`/api/clients/${folder._id}`),
        fetch(`/api/clients/${folder._id}/documents`),
      ])
      if (folderRes.ok) {
        const freshFolder = await folderRes.json()
        const freshDocs   = docsRes.ok ? (await docsRes.json()).items ?? [] : []
        onUpdate({ ...freshFolder, documents: freshDocs })
      }
    } catch (e: any) { setUploadErr(e.message) }
    finally { setUploading(false) }
  }

  // Auto-close 2 s after a successful upload
  useEffect(() => {
    if (!uploadDone) return
    const t = setTimeout(() => {
      setUploadDialog(false); setUploadFiles([]); setUploadDone(0); setUploadErr(null); onUploadClose?.()
    }, 2000)
    return () => clearTimeout(t)
  }, [uploadDone, onUploadClose])

  const closeUpload = () => {
    setUploadDialog(false); setUploadFiles([]); setUploadDone(0); setUploadErr(null); onUploadClose?.()
  }

  // ── Translation ────────────────────────────────────────────────────────────
  const handleTranslate = (doc: LegalDocument) => {
    setTranslateDoc(doc)
    setTranslateState('idle')
    setTranslateResult(null)
    setTranslateErr(null)
  }

  const startTranslation = async () => {
    if (!translateDoc) return
    setTranslateState('translating')
    setTranslateResult(null)
    setTranslateErr(null)
    try {
      const res = await fetch(`/api/documents/${translateDoc._id}/translate`, { method: 'POST' })
      const data = await res.json()
      if (!res.ok) throw new Error(data.message ?? t.documentsTab.errTranslateFailed)
      setTranslateResult(data)
      setTranslateState('done')
    } catch (e: any) {
      setTranslateErr(e.message)
      setTranslateState('error')
    }
  }

  const handleSaveTranslation = async () => {
    if (!translateDoc || !translateResult) return
    setTranslateState('saving')
    try {
      const res = await fetch(`/api/documents/${translateDoc._id}/save-translation`, {
        method: 'POST',
        headers: { 'Content-Type': 'application/json' },
        body: JSON.stringify({ translatedText: translateResult.translatedText, targetLang: translateResult.targetLang }),
      })
      if (!res.ok) throw new Error(t.documentsTab.errSaveFailed)
      setTranslateState('saved')
      const [folderRes, docsRes] = await Promise.all([
        fetch(`/api/clients/${folder._id}`),
        fetch(`/api/clients/${folder._id}/documents`),
      ])
      if (folderRes.ok) {
        const freshFolder = await folderRes.json()
        const freshDocs   = docsRes.ok ? (await docsRes.json()).items ?? [] : []
        onUpdate({ ...freshFolder, documents: freshDocs })
      }
    } catch (e: any) {
      setTranslateErr(e.message)
      setTranslateState('error')
    }
  }

  const closeTranslate = () => {
    if (translateState === 'translating' || translateState === 'saving') return
    setTranslateDoc(null); setTranslateState('idle'); setTranslateResult(null); setTranslateErr(null)
  }

  // ── Document row ───────────────────────────────────────────────────────────
  const DocRow = ({ doc }: { doc: LegalDocument }) => {
    const aiCfg   = AI_STATUS_CONFIG[doc.aiStatus]
    const typeLabel = doc.documentType ? t.docTypes[doc.documentType as keyof typeof t.docTypes] : null
    const active = selectedDoc?._id === doc._id
    return (
      <Box component='tr' onClick={() => setSelectedDoc(active ? null : doc)}
        sx={{ borderTop: '1px solid', borderColor: 'divider', cursor: 'pointer',
          bgcolor: active ? '#E8F7F7' : 'transparent',
          '&:hover': { bgcolor: active ? '#E8F7F7' : 'action.hover' } }}>
        <Box component='td' sx={{ px: 2, py: 1.25, whiteSpace: 'nowrap' }}>
          <Typography variant='caption' sx={{ fontFamily: 'monospace', fontWeight: 700, color: '#0D9394' }}>
            {doc.batesNumber}
          </Typography>
        </Box>
        <Box component='td' sx={{ px: 2, py: 1.25 }}>
          <Box sx={{ display: 'flex', alignItems: 'center', gap: 1 }}>
            <i className={mimeIcon(doc.mimeType)} style={{ fontSize: '1rem', color: '#7C6AF7', flexShrink: 0 }} />
            <Box>
              <Typography variant='body2' sx={{ fontWeight: 500, lineHeight: 1.3 }}>{doc.originalName}</Typography>
              {doc.summary && (
                <Typography variant='caption' color='text.secondary'
                  sx={{ display: '-webkit-box', WebkitLineClamp: 1, WebkitBoxOrient: 'vertical', overflow: 'hidden' }}>
                  {doc.summary}
                </Typography>
              )}
            </Box>
          </Box>
        </Box>
        <Box component='td' sx={{ px: 2, py: 1.25, whiteSpace: 'nowrap' }}>
          {typeLabel && <Chip label={typeLabel} size='small' sx={{ fontSize: '0.62rem', height: 18, bgcolor: '#EEF2FF', color: '#7C6AF7', fontWeight: 600 }} />}
        </Box>
        <Box component='td' sx={{ px: 2, py: 1.25, whiteSpace: 'nowrap' }}>
          <Chip label={t.aiStatus[doc.aiStatus]} size='small' sx={{ fontSize: '0.62rem', height: 18, bgcolor: aiCfg.bg, color: aiCfg.color, fontWeight: 600 }} />
        </Box>
        <Box component='td' sx={{ px: 2, py: 1.25, whiteSpace: 'nowrap' }}>
          <Typography variant='caption' color='text.disabled'>{fmtDate(doc.documentDate ?? doc.uploadedAt)}</Typography>
        </Box>
        <Box component='td' sx={{ px: 2, py: 1.25, whiteSpace: 'nowrap' }}>
          <Typography variant='caption' color='text.disabled'>{fmtBytes(doc.fileSize)}</Typography>
        </Box>
        <Box component='td' sx={{ px: 1, py: 1.25, whiteSpace: 'nowrap' }} onClick={e => e.stopPropagation()}>
          {!doc.isTranslation && (
            <Tooltip title={t.common.translate}>
              <IconButton size='small' onClick={() => handleTranslate(doc)}>
                <i className='ri-translate-2' style={{ fontSize: '0.85rem', color: '#0D9394' }} />
              </IconButton>
            </Tooltip>
          )}
        </Box>
      </Box>
    )
  }

  // ── Dialogs ────────────────────────────────────────────────────────────────
  const dialogs = (
    <>
      <Dialog open={newFolderDialog} onClose={() => setNewFolderDialog(false)} maxWidth='xs' fullWidth>
        <DialogTitle>{t.documentsTab.newFolder}</DialogTitle>
        <DialogContent sx={{ pt: '12px !important' }}>
          {newFolderErr && <Alert severity='error' sx={{ mb: 1.5 }}>{newFolderErr}</Alert>}
          <TextField fullWidth size='small' label={t.documentsTab.newFolder} autoFocus
            value={newFolderName} onChange={e => setNewFolderName(e.target.value)}
            onKeyDown={e => e.key === 'Enter' && saveNewFolder()}
            placeholder={t.documentsTab.folderNamePlaceholder} />
          <Typography variant='caption' color='text.disabled' sx={{ mt: 1, display: 'block' }}>
            {t.documentsTab.aiCanCreate}
          </Typography>
        </DialogContent>
        <DialogActions>
          <Button onClick={() => setNewFolderDialog(false)} disabled={savingFolder}>{t.common.cancel}</Button>
          <Button variant='contained' onClick={saveNewFolder} disabled={savingFolder}
            sx={{ bgcolor: '#0D9394', '&:hover': { bgcolor: '#096B6C' } }}>
            {savingFolder ? t.documentsTab.creating : t.documentsTab.createFolder}
          </Button>
        </DialogActions>
      </Dialog>

      <Dialog open={uploadDialog} onClose={uploadDone ? closeUpload : (uploading ? undefined : closeUpload)} maxWidth='sm' fullWidth>
        <DialogTitle sx={{ pb: 1 }}>
          <Box sx={{ display: 'flex', alignItems: 'center', gap: 1 }}>
            <i className='ri-upload-cloud-2-line' style={{ color: '#0D9394' }} />
            {t.documentsTab.importDocuments}
          </Box>
        </DialogTitle>
        <DialogContent sx={{ display: 'flex', flexDirection: 'column', gap: 1.5, pt: '8px !important' }}>

          {/* ── Success state ── */}
          {uploadDone > 0 ? (
            <Box sx={{ py: 3, textAlign: 'center' }}>
              <Box sx={{ width: 56, height: 56, borderRadius: '50%', bgcolor: '#E8F7F7', display: 'flex', alignItems: 'center', justifyContent: 'center', mx: 'auto', mb: 1.5 }}>
                <i className='ri-checkbox-circle-line' style={{ fontSize: '2rem', color: '#0D9394' }} />
              </Box>
              <Typography variant='body1' sx={{ fontWeight: 600 }}>{t.documentsTab.uploadDoneMsg(uploadDone)}</Typography>
              <Typography variant='body2' color='text.secondary' sx={{ mt: 0.5 }}>
                {t.documentsTab.aiRunning}
              </Typography>
            </Box>
          ) : (
          <>
            {uploadErr && <Alert severity='error' sx={{ py: 0.5 }}>{uploadErr}</Alert>}

            {/* ── Drop zone ── */}
            <Box
              onDragOver={e => { e.preventDefault(); setDragOver(true) }}
              onDragLeave={() => setDragOver(false)}
              onDrop={onDrop}
              sx={{
                border: '2px dashed',
                borderColor: dragOver ? '#0D9394' : uploadFiles.length ? '#0D9394' : 'divider',
                borderRadius: 2, p: 2.5, textAlign: 'center',
                bgcolor: dragOver ? '#C8F0F0' : uploadFiles.length ? '#E8F7F7' : 'action.hover',
                transition: 'all 0.15s',
              }}>
              <i className='ri-upload-cloud-2-line' style={{ fontSize: '2rem', color: dragOver ? '#0D9394' : '#8A92A3', display: 'block', marginBottom: 4 }} />
              <Typography variant='body2' sx={{ fontWeight: 500, mb: 0.25 }}>
                {dragOver ? t.documentsTab.dropHere : t.documentsTab.dragHere}
              </Typography>
              <Typography variant='caption' color='text.disabled' sx={{ display: 'block', mb: 1.5 }}>
                {t.documentsTab.fileTypes}
              </Typography>
              <Box sx={{ display: 'flex', gap: 1, justifyContent: 'center' }}>
                <Button size='small' variant='outlined' startIcon={<i className='ri-file-add-line' />}
                  onClick={() => fileInputRef.current?.click()}
                  sx={{ fontSize: '0.72rem' }}>
                  {t.documentsTab.selectFiles}
                </Button>
                <Button size='small' variant='outlined' startIcon={<i className='ri-folder-open-line' />}
                  onClick={() => folderInputRef.current?.click()}
                  sx={{ fontSize: '0.72rem' }}>
                  {t.documentsTab.selectFolder}
                </Button>
              </Box>
              <input ref={fileInputRef} type='file' multiple hidden
                onChange={e => { if (e.target.files) addFiles(Array.from(e.target.files)) }} />
              {/* webkitdirectory lets user pick an entire folder */}
              <input ref={folderInputRef} type='file' multiple hidden
                {...{ webkitdirectory: '' } as React.InputHTMLAttributes<HTMLInputElement>}
                onChange={e => { if (e.target.files) addFiles(Array.from(e.target.files)) }} />
            </Box>

            {/* ── File list ── */}
            {uploadFiles.length > 0 && (
              <Box>
                <Box sx={{ display: 'flex', alignItems: 'center', mb: 0.5 }}>
                  <Typography variant='caption' sx={{ fontWeight: 700, color: 'text.disabled', letterSpacing: '0.06em', flex: 1 }}>
                    {t.documentsTab.filesTotal(uploadFiles.length, fmtBytes(uploadFiles.reduce((s, f) => s + f.size, 0)))}
                  </Typography>
                  <Button size='small' sx={{ fontSize: '0.65rem', p: 0, minWidth: 0, color: 'text.disabled' }}
                    onClick={() => setUploadFiles([])}>
                    {t.documentsTab.clearAll}
                  </Button>
                </Box>
                <Box sx={{ maxHeight: 200, overflowY: 'auto', border: '1px solid', borderColor: 'divider', borderRadius: 1 }}>
                  {uploadFiles.map((f, i) => (
                    <Box key={i} sx={{ display: 'flex', alignItems: 'center', px: 1.5, py: 0.75, borderBottom: i < uploadFiles.length - 1 ? '1px solid' : 'none', borderColor: 'divider' }}>
                      <i className={mimeIcon(f.type || f.name)} style={{ fontSize: '1rem', color: '#7C6AF7', marginRight: 8, flexShrink: 0 }} />
                      <Typography variant='caption' sx={{ flex: 1, overflow: 'hidden', textOverflow: 'ellipsis', whiteSpace: 'nowrap', fontWeight: 500 }}>
                        {f.name}
                      </Typography>
                      <Typography variant='caption' color='text.disabled' sx={{ mx: 1, flexShrink: 0 }}>
                        {fmtBytes(f.size)}
                      </Typography>
                      <IconButton size='small' onClick={() => removeFile(i)} sx={{ p: 0.25 }}>
                        <i className='ri-close-line' style={{ fontSize: '0.85rem', color: '#8A92A3' }} />
                      </IconButton>
                    </Box>
                  ))}
                </Box>
              </Box>
            )}

            {/* ── Destination folder ── */}
            <TextField select fullWidth size='small' label={t.documentsTab.destinationFolder}
              value={uploadFolderId} onChange={e => setUploadFolderId(e.target.value)}>
              <MenuItem value='inbox'>
                <Box sx={{ display: 'flex', alignItems: 'center', gap: 1 }}>
                  <i className='ri-robot-line' style={{ color: '#0D9394' }} />
                  <Box>
                    <Typography variant='body2' sx={{ fontWeight: 500, lineHeight: 1.2 }}>{t.documentsTab.letAiClassify}</Typography>
                    <Typography variant='caption' color='text.disabled'>{t.documentsTab.aiWillFile}</Typography>
                  </Box>
                </Box>
              </MenuItem>
              <Divider />
              {docFolders.map(f => (
                <MenuItem key={f._id} value={f._id}>
                  <Box sx={{ display: 'flex', alignItems: 'center', gap: 1 }}>
                    <i className={f.icon} style={{ color: f.color }} />{f.name}
                  </Box>
                </MenuItem>
              ))}
            </TextField>

            <Typography variant='caption' color='text.disabled'>
              {t.documentsTab.batesNote(folder.folderNumber)}
            </Typography>

            {uploading && <LinearProgress sx={{ borderRadius: 1 }} />}
          </>
          )}
        </DialogContent>
        <DialogActions>
          {uploadDone > 0 ? (
            <Button onClick={closeUpload} variant='contained' sx={{ bgcolor: '#0D9394', '&:hover': { bgcolor: '#096B6C' } }}>{t.common.done}</Button>
          ) : (
          <>
            <Button onClick={closeUpload} disabled={uploading}>{t.common.cancel}</Button>
            <Button variant='contained' onClick={submitUpload} disabled={uploading || !uploadFiles.length}
              sx={{ bgcolor: '#0D9394', '&:hover': { bgcolor: '#096B6C' } }}>
              {uploading ? t.common.uploading : t.documentsTab.uploadingN(uploadFiles.length)}
            </Button>
          </>
          )}
        </DialogActions>
      </Dialog>

      <Dialog open={!!translateDoc} onClose={closeTranslate} maxWidth='md' fullWidth>
        <DialogTitle sx={{ display: 'flex', alignItems: 'center', gap: 1.5, pb: 1 }}>
          <i className='ri-translate-2' style={{ fontSize: '1.3rem', color: '#0D9394' }} />
          <Box>
            <Typography variant='h6' sx={{ fontWeight: 700, lineHeight: 1.2 }}>{t.translationDialog.title}</Typography>
            {translateDoc && (
              <Typography variant='caption' color='text.secondary'>
                {translateDoc.detectedLanguage === 'th' ? t.translationDialog.thToEn : t.translationDialog.enToTh} · {translateDoc.originalName}
              </Typography>
            )}
          </Box>
        </DialogTitle>
        <DialogContent dividers sx={{ minHeight: 180 }}>
          {translateState === 'idle' && translateDoc && (
            <Box sx={{ display: 'flex', flexDirection: 'column', alignItems: 'center', justifyContent: 'center', py: 4, gap: 2 }}>
              <i className='ri-translate-2' style={{ fontSize: '3rem', color: '#CBD5E1' }} />
              <Typography color='text.secondary' sx={{ textAlign: 'center', maxWidth: 360 }}>
                {t.translationDialog.idleHint(
                  translateDoc.detectedLanguage === 'th' ? t.translationDialog.thai : t.translationDialog.english,
                  translateDoc.detectedLanguage === 'th' ? t.translationDialog.english : t.translationDialog.thai,
                )}
                {translateDoc.mimeType?.includes('pdf') ? t.translationDialog.pdfHint : t.translationDialog.summaryHint}
              </Typography>
            </Box>
          )}
          {translateState === 'translating' && (
            <Box sx={{ display: 'flex', flexDirection: 'column', alignItems: 'center', justifyContent: 'center', py: 6, gap: 2 }}>
              <CircularProgress size={36} sx={{ color: '#0D9394' }} />
              <Typography color='text.secondary'>{t.common.translating}</Typography>
            </Box>
          )}
          {translateState === 'error' && (
            <Alert severity='error' sx={{ mt: 1 }}>{translateErr}</Alert>
          )}
          {(translateState === 'done' || translateState === 'saving' || translateState === 'saved') && translateResult && (
            <Box sx={{ display: 'flex', flexDirection: 'column', gap: 2 }}>
              {!translateResult.hasFullText && (
                <Alert severity='info' sx={{ fontSize: '0.8rem' }}>
                  {t.translationDialog.summaryOnly}
                </Alert>
              )}
              {translateState === 'saved' && (
                <Alert severity='success' sx={{ fontSize: '0.8rem' }}>
                  {t.translationDialog.savedSuccess}
                </Alert>
              )}
              {translateResult.translatedText ? (
                <Box>
                  <Typography variant='caption' sx={{ fontWeight: 700, textTransform: 'uppercase', color: 'text.disabled', letterSpacing: 0.6 }}>
                    {t.translationDialog.translationLabel(translateResult.targetLang === 'th' ? t.translationDialog.thai : t.translationDialog.english)}
                  </Typography>
                  <Box sx={{ mt: 1, p: 2, bgcolor: 'action.hover', borderRadius: 1.5, maxHeight: 400, overflowY: 'auto', fontSize: '0.875rem', lineHeight: 1.7, whiteSpace: 'pre-wrap', border: '1px solid', borderColor: 'divider' }}>
                    {translateResult.translatedText}
                  </Box>
                </Box>
              ) : translateResult.translatedSummary ? (
                <Box>
                  <Typography variant='caption' sx={{ fontWeight: 700, textTransform: 'uppercase', color: 'text.disabled', letterSpacing: 0.6 }}>
                    {t.translationDialog.summaryLabel(translateResult.targetLang === 'th' ? t.translationDialog.thai : t.translationDialog.english)}
                  </Typography>
                  <Box sx={{ mt: 1, p: 2, bgcolor: 'action.hover', borderRadius: 1.5, fontSize: '0.875rem', lineHeight: 1.7, border: '1px solid', borderColor: 'divider' }}>
                    {translateResult.translatedSummary}
                  </Box>
                </Box>
              ) : null}
            </Box>
          )}
        </DialogContent>
        <DialogActions sx={{ px: 3, py: 2, gap: 1 }}>
          <Button onClick={closeTranslate} color='inherit' size='small'>
            {translateState === 'saved' ? t.common.close : t.common.cancel}
          </Button>
          {translateState === 'idle' && (
            <Button onClick={startTranslation} variant='contained' size='small'
              sx={{ bgcolor: '#0D9394', '&:hover': { bgcolor: '#096B6C' } }}
              startIcon={<i className='ri-translate-2' style={{ fontSize: '1rem' }} />}>
              {t.common.translate}
            </Button>
          )}
          {translateState === 'error' && (
            <Button onClick={startTranslation} variant='outlined' size='small'>{t.common.retry}</Button>
          )}
          {(translateState === 'done' || translateState === 'saving') && translateResult && (
            <>
              <Button variant='outlined' size='small'
                startIcon={<i className='ri-clipboard-line' style={{ fontSize: '0.9rem' }} />}
                onClick={() => navigator.clipboard.writeText(translateResult.translatedText || translateResult.translatedSummary || '')}>
                {t.common.copy}
              </Button>
              {translateResult.translatedText && translateState !== 'saving' && (
                <Button onClick={handleSaveTranslation} variant='contained' size='small'
                  sx={{ bgcolor: '#0D9394', '&:hover': { bgcolor: '#096B6C' } }}
                  startIcon={<i className='ri-save-line' style={{ fontSize: '0.9rem' }} />}>
                  {t.translationDialog.saveToFolder}
                </Button>
              )}
              {translateState === 'saving' && <CircularProgress size={20} sx={{ color: '#0D9394' }} />}
            </>
          )}
          {translateState === 'saved' && translateResult && (
            <Button variant='outlined' size='small'
              startIcon={<i className='ri-clipboard-line' style={{ fontSize: '0.9rem' }} />}
              onClick={() => navigator.clipboard.writeText(translateResult.translatedText || translateResult.translatedSummary || '')}>
              {t.common.copy}
            </Button>
          )}
        </DialogActions>
      </Dialog>

      <Dialog open={bundleDialog} onClose={() => setBundleDialog(false)} maxWidth='sm' fullWidth>
        <DialogTitle>
          <Box sx={{ display: 'flex', alignItems: 'center', gap: 1 }}>
            <i className='ri-archive-stack-line' style={{ color: '#7C6AF7' }} />
            {t.documentsTab.bundleTitle}
          </Box>
        </DialogTitle>
        <DialogContent>
          <Alert severity='info' sx={{ mb: 2 }}>{t.documentsTab.bundleSoon}</Alert>
          <Box sx={{ display: 'flex', flexDirection: 'column', gap: 1.5 }}>
            {[
              { icon: 'ri-calendar-event-line',    color: '#0D9394', title: t.documentsTab.bundleStep1, desc: t.documentsTab.bundleStep1desc },
              { icon: 'ri-checkbox-multiple-line',  color: '#7C6AF7', title: t.documentsTab.bundleStep2, desc: t.documentsTab.bundleStep2desc },
              { icon: 'ri-drag-move-line',          color: '#FFB400', title: t.documentsTab.bundleStep3, desc: t.documentsTab.bundleStep3desc },
              { icon: 'ri-file-list-3-line',        color: '#03C3EC', title: t.documentsTab.bundleStep4, desc: t.documentsTab.bundleStep4desc },
              { icon: 'ri-printer-line',            color: '#FF4C51', title: t.documentsTab.bundleStep5, desc: t.documentsTab.bundleStep5desc },
            ].map(s => (
              <Box key={s.title} sx={{ display: 'flex', gap: 1.5, alignItems: 'flex-start' }}>
                <Box sx={{ width: 32, height: 32, borderRadius: 1.5, bgcolor: `${s.color}22`, display: 'flex', alignItems: 'center', justifyContent: 'center', flexShrink: 0 }}>
                  <i className={s.icon} style={{ color: s.color, fontSize: '1rem' }} />
                </Box>
                <Box>
                  <Typography variant='body2' sx={{ fontWeight: 600 }}>{s.title}</Typography>
                  <Typography variant='caption' color='text.secondary'>{s.desc}</Typography>
                </Box>
              </Box>
            ))}
          </Box>
        </DialogContent>
        <DialogActions>
          <Button onClick={() => setBundleDialog(false)}>{t.common.close}</Button>
        </DialogActions>
      </Dialog>
    </>
  )

  // ── Folder detail view ─────────────────────────────────────────────────────
  if (selectedFolderId !== null) {
    const isInbox = selectedFolderId === 'inbox'
    const meta    = isInbox ? null : docFolders.find(f => f._id === selectedFolderId)
    const docs    = isInbox ? inbox : inFolder(selectedFolderId)
    const label   = isInbox ? t.documentsTab.inboxLabel : (meta?.name ?? t.documentsTab.folderFallback)
    const iconCls = isInbox ? 'ri-inbox-line' : (meta?.icon ?? 'ri-folder-3-line')
    const color   = isInbox ? '#8A92A3' : (meta?.color ?? '#7C6AF7')

    return (
      <Box sx={{ display: 'flex', flexDirection: 'column', gap: 2 }}>

        {/* Breadcrumb */}
        <Box sx={{ display: 'flex', alignItems: 'center', gap: 1 }}>
          <Button size='small' variant='text' startIcon={<i className='ri-arrow-left-line' />}
            onClick={() => { setSelectedFolderId(null); setSelectedDoc(null) }}
            sx={{ fontSize: '0.75rem', color: 'text.secondary', p: 0, minWidth: 0 }}>
            {t.nav.documents}
          </Button>
          <Typography variant='caption' color='text.disabled'>/</Typography>
          <i className={iconCls} style={{ color, fontSize: '0.9rem' }} />
          <Typography variant='body2' sx={{ fontWeight: 600 }}>{label}</Typography>
          <Box sx={{ flex: 1 }} />
          <Button size='small' variant='outlined' startIcon={<i className='ri-upload-2-line' />}
            onClick={() => { setUploadFolderId(isInbox ? 'inbox' : selectedFolderId); setUploadDialog(true) }}
            sx={{ fontSize: '0.72rem' }}>
            {t.documentsTab.uploadHere}
          </Button>
        </Box>

        {/* Document list */}
        <Card>
          <CardContent sx={{ p: 0, '&:last-child': { pb: 0 } }}>
            {docs.length === 0 ? (
              <Box sx={{ py: 5, textAlign: 'center' }}>
                <i className={iconCls} style={{ fontSize: '2.5rem', color: 'rgba(128,128,128,0.25)', display: 'block', marginBottom: 8 }} />
                <Typography variant='body2' color='text.disabled'>{t.documentsTab.emptyFolder}</Typography>
                <Typography variant='caption' color='text.disabled'>{t.documentsTab.emptyFolderHint}</Typography>
              </Box>
            ) : (
              <Box component='table' sx={{ width: '100%', borderCollapse: 'collapse' }}>
                <Box component='thead'>
                  <Box component='tr' sx={{ bgcolor: 'action.hover' }}>
                    {[t.documentsTab.colBates, t.documentsTab.colDocument, t.documentsTab.colType, t.documentsTab.colAiStatus, t.documentsTab.colDate, t.documentsTab.colSize, ''].map(h => (
                      <Box component='th' key={h} sx={{ textAlign: 'left', px: h ? 2 : 1, py: 0.75, fontSize: '0.7rem', fontWeight: 600, color: 'text.secondary', whiteSpace: 'nowrap' }}>{h}</Box>
                    ))}
                  </Box>
                </Box>
                <Box component='tbody'>
                  {docs.map(doc => <DocRow key={doc._id} doc={doc} />)}
                </Box>
              </Box>
            )}
          </CardContent>
        </Card>

        {/* Full-width preview */}
        <PreviewCard doc={selectedDoc} clientId={folder._id} onTranslate={handleTranslate} />

        {dialogs}
      </Box>
    )
  }

  // ── Folder grid view ───────────────────────────────────────────────────────
  return (
    <Box sx={{ display: 'flex', flexDirection: 'column', gap: 2 }}>

      {/* Header */}
      <Box sx={{ display: 'flex', alignItems: 'center', gap: 1 }}>
        <Typography variant='body2' color='text.secondary' sx={{ flex: 1 }}>
          {t.documentsTab.documentsCount(documents.length)} · {t.documentsTab.batesPrefix}:{' '}
          <Typography component='span' sx={{ fontFamily: 'monospace', fontWeight: 600, fontSize: '0.78rem' }}>{folder.folderNumber}</Typography>
        </Typography>
        {processing.length > 0 && (
          <Chip label={t.documentsTab.classifying(processing.length)} size='small'
            sx={{ bgcolor: '#FFF5DB', color: '#FFB400', fontWeight: 600, fontSize: '0.65rem', height: 20 }} />
        )}
        <Button size='small' variant='outlined' startIcon={<i className='ri-archive-stack-line' />}
          onClick={() => setBundleDialog(true)}
          sx={{ fontSize: '0.72rem', color: '#7C6AF7', borderColor: '#7C6AF7', '&:hover': { borderColor: '#6355D8', bgcolor: '#EEF2FF' } }}>
          {t.documentsTab.buildBundle}
        </Button>
        <Button size='small' variant='outlined' startIcon={<i className='ri-folder-add-line' />}
          onClick={() => { setNewFolderName(''); setNewFolderErr(null); setNewFolderDialog(true) }}
          sx={{ fontSize: '0.72rem' }}>
          {t.documentsTab.newFolder}
        </Button>
        <Button size='small' variant='contained' startIcon={<i className='ri-upload-2-line' />}
          onClick={() => { setUploadFolderId('inbox'); setUploadDialog(true) }}
          sx={{ bgcolor: '#0D9394', '&:hover': { bgcolor: '#096B6C' }, fontSize: '0.72rem' }}>
          {t.common.upload}
        </Button>
      </Box>

      {/* Inbox */}
      {inbox.length > 0 && (
        <Card onClick={() => { setSelectedFolderId('inbox'); setSelectedDoc(null) }}
          sx={{ cursor: 'pointer', border: '1px solid', borderColor: '#FFB400', '&:hover': { bgcolor: 'action.hover' } }}>
          <CardContent sx={{ py: 1.5, '&:last-child': { pb: 1.5 }, display: 'flex', alignItems: 'center', gap: 2 }}>
            <Box sx={{ width: 36, height: 36, borderRadius: 1.5, bgcolor: '#FFF5DB', display: 'flex', alignItems: 'center', justifyContent: 'center', flexShrink: 0 }}>
              <i className='ri-inbox-line' style={{ fontSize: '1.2rem', color: '#FFB400' }} />
            </Box>
            <Box sx={{ flex: 1 }}>
              <Typography variant='body2' sx={{ fontWeight: 600 }}>{t.documentsTab.inbox}</Typography>
              <Typography variant='caption' color='text.secondary'>{t.documentsTab.documentsCount(inbox.length)}</Typography>
            </Box>
            <Chip label={t.documentsTab.needsReview} size='small' sx={{ bgcolor: '#FFF5DB', color: '#FFB400', fontWeight: 600, fontSize: '0.62rem', height: 18 }} />
            <i className='ri-arrow-right-s-line' style={{ color: '#8A92A3' }} />
          </CardContent>
        </Card>
      )}

      {/* Folder grid */}
      <Box sx={{ display: 'grid', gridTemplateColumns: 'repeat(auto-fill, minmax(180px, 1fr))', gap: 1.5 }}>
        {docFolders.map(f => {
          const count   = inFolder(f._id).length
          const pending = inFolder(f._id).filter(d => d.aiStatus === 'processing' || d.aiStatus === 'pending').length
          return (
            <Card key={f._id} onClick={() => { setSelectedFolderId(f._id); setSelectedDoc(null) }}
              sx={{ cursor: 'pointer', transition: 'all 0.15s', border: '1px solid', borderColor: 'divider',
                '&:hover': { borderColor: f.color, transform: 'translateY(-1px)', boxShadow: 2 } }}>
              <CardContent sx={{ p: 1.75, '&:last-child': { pb: 1.75 } }}>
                <Box sx={{ display: 'flex', alignItems: 'flex-start', justifyContent: 'space-between', mb: 1.25 }}>
                  <Box sx={{ width: 34, height: 34, borderRadius: 1.5, display: 'flex', alignItems: 'center', justifyContent: 'center', bgcolor: `${f.color}22` }}>
                    <i className={f.icon} style={{ fontSize: '1.15rem', color: f.color }} />
                  </Box>
                  {!f.isSystem && <Chip label={t.documentsTab.customFolder} size='small' sx={{ fontSize: '0.55rem', height: 15, bgcolor: '#EEF2FF', color: '#7C6AF7' }} />}
                </Box>
                <Typography variant='body2' sx={{ fontWeight: 600, lineHeight: 1.3, mb: 0.25, fontSize: '0.82rem' }}>{f.name}</Typography>
                <Typography variant='caption' color='text.disabled'>{t.documentsTab.docsCount(count)}</Typography>
                {pending > 0 && (
                  <Box sx={{ mt: 0.5 }}>
                    <Chip label={t.documentsTab.classifying(pending)} size='small' sx={{ fontSize: '0.55rem', height: 15, bgcolor: '#FFF5DB', color: '#FFB400', fontWeight: 600 }} />
                  </Box>
                )}
              </CardContent>
            </Card>
          )
        })}
      </Box>

      {/* Full-width preview — replaces the old empty-state upload card */}
      <PreviewCard doc={selectedDoc} clientId={folder._id} />

      {dialogs}
    </Box>
  )
}
