'use client'
import { useState, useEffect, useMemo } from 'react'
import { useT } from '@/contexts/LangContext'
import Box from '@mui/material/Box'
import Card from '@mui/material/Card'
import Typography from '@mui/material/Typography'
import TextField from '@mui/material/TextField'
import InputAdornment from '@mui/material/InputAdornment'
import Chip from '@mui/material/Chip'
import Table from '@mui/material/Table'
import TableBody from '@mui/material/TableBody'
import TableCell from '@mui/material/TableCell'
import TableContainer from '@mui/material/TableContainer'
import TableHead from '@mui/material/TableHead'
import TableRow from '@mui/material/TableRow'
import TableSortLabel from '@mui/material/TableSortLabel'
import IconButton from '@mui/material/IconButton'
import Tooltip from '@mui/material/Tooltip'
import CircularProgress from '@mui/material/CircularProgress'
import Collapse from '@mui/material/Collapse'
import Divider from '@mui/material/Divider'
import MenuItem from '@mui/material/MenuItem'
import LinearProgress from '@mui/material/LinearProgress'
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 Button from '@mui/material/Button'
import Alert from '@mui/material/Alert'

// ─── Types ────────────────────────────────────────────────────────────────────

type AiStatus  = 'pending' | 'processing' | 'classified' | 'failed'
type Privilege = 'privileged' | 'non_privileged' | 'work_product'

interface LegalDoc {
  _id: string
  batesNumber: string
  clientFolderId: string
  matterId?: string
  originalName: string
  fileName: string
  mimeType?: string
  fileSize?: number
  title: string
  documentType?: string
  privilege: Privilege
  aiStatus: AiStatus
  summary?: string
  parties?: string[]
  documentDate?: string
  aiConfidence?: number
  detectedLanguage?: string
  tags?: string[]
  uploadedBy?: string
  signed?: boolean
  notes?: string
  createdAt: string
  updatedAt: string
  // Translation
  translatedSummary?: string
  translatedSummaryLang?: string
  isTranslation?: boolean
  translationLanguage?: string
  sourceDocumentId?: string
}

interface ClientStub { _id: string; displayName: string; folderNumber: string }

// ─── Constants ────────────────────────────────────────────────────────────────

const DOC_TYPE_VALUES = [
  'contract', 'pleading', 'correspondence', 'evidence', 'court_order',
  'court_filing', 'identity', 'financial', 'deed', 'power_of_attorney',
  'permit', 'internal', 'other',
] as const

const PRIVILEGE_STYLE: Record<Privilege, { bg: string; color: string }> = {
  privileged:     { bg: '#FFECEC', color: '#E8533A' },
  work_product:   { bg: '#FFF5DB', color: '#C27D00' },
  non_privileged: { bg: '#F0F0F0', color: '#6B7280' },
}

const AI_STYLE: Record<AiStatus, { color: string; icon: string }> = {
  classified: { color: '#2ECC71', icon: 'ri-robot-line' },
  pending:    { color: '#94A3B8', icon: 'ri-time-line' },
  processing: { color: '#4A90D9', icon: 'ri-loader-line' },
  failed:     { color: '#E8533A', icon: 'ri-error-warning-line' },
}

type SortKey = 'batesNumber' | 'title' | 'documentType' | 'privilege' | 'createdAt' | 'fileSize'
type SortDir = 'asc' | 'desc'

// ─── Helpers ──────────────────────────────────────────────────────────────────

function fmtSize(bytes?: number) {
  if (!bytes) return '—'
  if (bytes < 1024) return `${bytes} B`
  if (bytes < 1048576) return `${(bytes / 1024).toFixed(0)} KB`
  return `${(bytes / 1048576).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, fileName?: string) {
  const ext = fileName?.split('.').pop()?.toLowerCase()
  if (mime?.includes('pdf') || ext === 'pdf')                                        return 'ri-file-pdf-line'
  if (mime?.includes('word') || ext === 'docx' || ext === 'doc')                    return 'ri-file-word-line'
  if (mime?.includes('excel') || ['xlsx','xls','csv'].includes(ext ?? ''))          return 'ri-file-excel-line'
  if (mime?.includes('image') || ['jpg','jpeg','png','gif','webp','tiff'].includes(ext ?? '')) return 'ri-image-line'
  if (mime?.includes('text') || ext === 'txt')                                       return 'ri-file-text-line'
  if (mime?.includes('zip') || mime?.includes('archive'))                            return 'ri-file-zip-line'
  return 'ri-file-line'
}

function mimeColor(mime?: string, fileName?: string) {
  const ext = fileName?.split('.').pop()?.toLowerCase()
  if (mime?.includes('pdf') || ext === 'pdf')                  return '#E8533A'
  if (mime?.includes('word') || ext === 'docx' || ext === 'doc') return '#4A90D9'
  if (mime?.includes('excel') || ['xlsx','xls','csv'].includes(ext ?? '')) return '#2ECC71'
  if (mime?.includes('image'))                                 return '#F39C12'
  return '#94A3B8'
}


// ─── Translation Dialog ───────────────────────────────────────────────────────

function TranslateDialog({ doc, open, onClose, onSaved }: {
  doc: LegalDoc
  open: boolean
  onClose: () => void
  onSaved: (newDoc: LegalDoc) => void
}) {
  const t = useT()
  const [state, setState] = useState<'idle' | 'translating' | 'done' | 'saving' | 'saved' | 'error'>('idle')
  const [result, setResult] = useState<{
    translatedText: string | null
    translatedSummary: string | null
    targetLang: string
    hasFullText: boolean
  } | null>(null)
  const [errorMsg, setErrorMsg] = useState('')

  const sourceLang = doc.detectedLanguage === 'th' ? t.translationDialog.thai : t.translationDialog.english
  const targetLangLabel = result
    ? (result.targetLang === 'th' ? t.translationDialog.thai : t.translationDialog.english)
    : (doc.detectedLanguage === 'th' ? t.translationDialog.english : t.translationDialog.thai)

  const handleTranslate = async () => {
    setState('translating')
    setResult(null)
    setErrorMsg('')
    try {
      const res = await fetch(`/api/documents/${doc._id}/translate`, { method: 'POST' })
      if (!res.ok) throw new Error(await res.text())
      const data = await res.json()
      setResult(data)
      setState('done')
    } catch (e: any) {
      setErrorMsg(e.message ?? t.documentsTab.errTranslateFailed)
      setState('error')
    }
  }

  const handleSave = async () => {
    if (!result?.translatedText) return
    setState('saving')
    try {
      const res = await fetch(`/api/documents/${doc._id}/save-translation`, {
        method: 'POST',
        headers: { 'Content-Type': 'application/json' },
        body: JSON.stringify({ translatedText: result.translatedText, targetLang: result.targetLang }),
      })
      if (!res.ok) throw new Error(await res.text())
      const newDoc = await res.json()
      setState('saved')
      onSaved(newDoc)
    } catch (e: any) {
      setErrorMsg(e.message ?? t.documentsTab.errSaveFailed)
      setState('error')
    }
  }

  const handleCopy = () => {
    navigator.clipboard.writeText(result?.translatedText ?? result?.translatedSummary ?? '')
  }

  const handleClose = () => {
    setState('idle')
    setResult(null)
    setErrorMsg('')
    onClose()
  }

  return (
    <Dialog open={open} onClose={handleClose} 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>
          <Typography variant='caption' color='text.secondary'>
            {sourceLang} → {targetLangLabel} · {doc.title}
          </Typography>
        </Box>
      </DialogTitle>

      <DialogContent dividers sx={{ minHeight: 200 }}>
        {state === 'idle' && (
          <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(sourceLang, targetLangLabel)}
              {doc.mimeType?.includes('pdf') || doc.fileName?.endsWith('.pdf')
                ? t.translationDialog.pdfHint
                : t.translationDialog.summaryHint}
            </Typography>
          </Box>
        )}

        {state === '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>
        )}

        {(state === 'done' || state === 'saving' || state === 'saved') && result && (
          <Box sx={{ display: 'flex', flexDirection: 'column', gap: 2 }}>
            {!result.hasFullText && (
              <Alert severity='info' sx={{ fontSize: '0.8rem' }}>
                {t.translationDialog.summaryOnly}
              </Alert>
            )}
            {state === 'saved' && (
              <Alert severity='success' sx={{ fontSize: '0.8rem' }}>
                {t.translationDialog.savedSuccess}
              </Alert>
            )}
            {result.translatedText ? (
              <Box>
                <Typography variant='caption' sx={{ fontWeight: 700, textTransform: 'uppercase', color: 'text.disabled', letterSpacing: 0.6 }}>
                  {t.translationDialog.translationLabel(targetLangLabel)}
                </Typography>
                <Box sx={{
                  mt: 1, p: 2, bgcolor: 'action.hover', borderRadius: 1.5,
                  maxHeight: 400, overflowY: 'auto',
                  fontFamily: 'inherit', fontSize: '0.875rem', lineHeight: 1.7,
                  whiteSpace: 'pre-wrap', border: '1px solid', borderColor: 'divider',
                }}>
                  {result.translatedText}
                </Box>
              </Box>
            ) : result.translatedSummary ? (
              <Box>
                <Typography variant='caption' sx={{ fontWeight: 700, textTransform: 'uppercase', color: 'text.disabled', letterSpacing: 0.6 }}>
                  {t.translationDialog.summaryLabel(targetLangLabel)}
                </Typography>
                <Box sx={{ mt: 1, p: 2, bgcolor: 'action.hover', borderRadius: 1.5, fontSize: '0.875rem', lineHeight: 1.7, border: '1px solid', borderColor: 'divider' }}>
                  {result.translatedSummary}
                </Box>
              </Box>
            ) : null}
          </Box>
        )}

        {state === 'error' && (
          <Alert severity='error' sx={{ mt: 1 }}>{errorMsg}</Alert>
        )}
      </DialogContent>

      <DialogActions sx={{ px: 3, py: 2, gap: 1 }}>
        <Button onClick={handleClose} color='inherit' size='small'>{t.common.close}</Button>
        {state === 'idle' && (
          <Button onClick={handleTranslate} variant='contained' size='small'
            sx={{ bgcolor: '#0D9394', '&:hover': { bgcolor: '#096B6C' } }}
            startIcon={<i className='ri-translate-2' style={{ fontSize: '1rem' }} />}>
            {t.common.translate}
          </Button>
        )}
        {state === 'error' && (
          <Button onClick={handleTranslate} variant='outlined' size='small'>{t.common.retry}</Button>
        )}
        {(state === 'done' || state === 'saving') && result && (
          <>
            <Button onClick={handleCopy} variant='outlined' size='small'
              startIcon={<i className='ri-clipboard-line' style={{ fontSize: '0.9rem' }} />}>
              {t.common.copy}
            </Button>
            {result.translatedText && state !== 'saving' && (
              <Button onClick={handleSave} variant='contained' size='small'
                sx={{ bgcolor: '#0D9394', '&:hover': { bgcolor: '#096B6C' } }}
                startIcon={<i className='ri-save-line' style={{ fontSize: '0.9rem' }} />}>
                {t.translationDialog.saveToFolder}
              </Button>
            )}
            {state === 'saving' && <CircularProgress size={20} sx={{ color: '#0D9394' }} />}
          </>
        )}
        {state === 'saved' && result?.translatedText && (
          <Button onClick={handleCopy} variant='outlined' size='small'
            startIcon={<i className='ri-clipboard-line' style={{ fontSize: '0.9rem' }} />}>
            {t.common.copy}
          </Button>
        )}
      </DialogActions>
    </Dialog>
  )
}

// ─── Translate button (inline in table row) ───────────────────────────────────

function TranslateButton({ doc, onSaved }: { doc: LegalDoc; onSaved: (d: LegalDoc) => void }) {
  const t = useT()
  const [open, setOpen] = useState(false)
  return (
    <>
      <Tooltip title={t.documentsFiling.translateDoc}>
        <IconButton size='small' onClick={() => setOpen(true)} sx={{ color: '#0D9394' }}>
          <i className='ri-translate-2' style={{ fontSize: '0.9rem' }} />
        </IconButton>
      </Tooltip>
      <TranslateDialog doc={doc} open={open} onClose={() => setOpen(false)} onSaved={onSaved} />
    </>
  )
}

// ─── Doc Detail Panel (list view expand) ─────────────────────────────────────

function DocDetail({ doc, clientName, onDocSaved }: {
  doc: LegalDoc
  clientName?: string
  onDocSaved: (newDoc: LegalDoc) => void
}) {
  const t = useT()
  const [summaryLang, setSummaryLang] = useState<'original' | 'translated'>('original')
  const [translateOpen, setTranslateOpen] = useState(false)

  const hasTranslatedSummary = !!doc.translatedSummary
  const shownSummary = summaryLang === 'translated' && hasTranslatedSummary
    ? doc.translatedSummary
    : doc.summary
  const translatedLangLabel = doc.translatedSummaryLang === 'th' ? t.documentsFiling.langTh : t.documentsFiling.langEn

  const langLabel = (code?: string) => {
    if (!code) return null
    return ({ en: t.documentsFiling.langEn, th: t.documentsFiling.langTh, mixed: t.documentsFiling.langMixed, other: t.documentsFiling.langOther })[code] ?? code
  }

  return (
    <>
    <TranslateDialog
      doc={doc}
      open={translateOpen}
      onClose={() => setTranslateOpen(false)}
      onSaved={onDocSaved}
    />
    <Box sx={{ p: 2, bgcolor: 'action.hover', display: 'flex', flexWrap: 'wrap', gap: 3 }}>
      <Box sx={{ flex: '2 1 300px' }}>
        {/* Summary header with lang toggle */}
        <Box sx={{ display: 'flex', alignItems: 'center', justifyContent: 'space-between', mb: 0.5 }}>
          <Typography variant='caption' sx={{ fontWeight: 700, textTransform: 'uppercase', color: 'text.disabled', letterSpacing: 0.6 }}>
            {t.documentsFiling.sectionSummary}
          </Typography>
          <Box sx={{ display: 'flex', alignItems: 'center', gap: 0.75 }}>
            {hasTranslatedSummary && (
              <Box sx={{ display: 'flex', border: '1px solid', borderColor: 'divider', borderRadius: 1, overflow: 'hidden' }}>
                <Box onClick={() => setSummaryLang('original')} sx={{
                  px: 1, py: 0.25, cursor: 'pointer', fontSize: '0.65rem', fontWeight: 600,
                  bgcolor: summaryLang === 'original' ? '#0D9394' : 'transparent',
                  color: summaryLang === 'original' ? '#fff' : 'text.secondary',
                }}>
                  {doc.detectedLanguage === 'th' ? 'TH' : 'EN'}
                </Box>
                <Box onClick={() => setSummaryLang('translated')} sx={{
                  px: 1, py: 0.25, cursor: 'pointer', fontSize: '0.65rem', fontWeight: 600,
                  bgcolor: summaryLang === 'translated' ? '#0D9394' : 'transparent',
                  color: summaryLang === 'translated' ? '#fff' : 'text.secondary',
                }}>
                  {translatedLangLabel}
                </Box>
              </Box>
            )}
            <Tooltip title={t.documentsFiling.translateDoc}>
              <IconButton size='small' onClick={() => setTranslateOpen(true)}
                sx={{ color: '#0D9394', p: 0.5 }}>
                <i className='ri-translate-2' style={{ fontSize: '0.95rem' }} />
              </IconButton>
            </Tooltip>
          </Box>
        </Box>

        {shownSummary ? (
          <Typography variant='body2' sx={{ lineHeight: 1.6 }}>{shownSummary}</Typography>
        ) : (
          <Typography variant='body2' color='text.disabled' sx={{ fontStyle: 'italic' }}>
            {doc.aiStatus === 'classified' ? t.documentsFiling.noSummary : t.documentsFiling.awaitingAi}
          </Typography>
        )}
        {doc.aiConfidence != null && (
          <Box sx={{ mt: 1.5 }}>
            <Box sx={{ display: 'flex', justifyContent: 'space-between', mb: 0.5 }}>
              <Typography variant='caption' color='text.secondary'>{t.documentsFiling.aiConfidence}</Typography>
              <Typography variant='caption' sx={{ fontWeight: 600 }}>{Math.round(doc.aiConfidence * 100)}%</Typography>
            </Box>
            <LinearProgress variant='determinate' value={doc.aiConfidence * 100}
              sx={{ height: 4, borderRadius: 2, bgcolor: 'divider',
                '& .MuiLinearProgress-bar': { bgcolor: doc.aiConfidence >= 0.7 ? '#2ECC71' : doc.aiConfidence >= 0.4 ? '#F39C12' : '#E8533A' } }} />
          </Box>
        )}
      </Box>

      <Box sx={{ flex: '1 1 200px', display: 'flex', flexDirection: 'column', gap: 0.5 }}>
        <Typography variant='caption' sx={{ fontWeight: 700, textTransform: 'uppercase', color: 'text.disabled', letterSpacing: 0.6, mb: 0.5 }}>
          {t.documentsFiling.sectionDetails}
        </Typography>
        {[
          [t.documentsFiling.labelClient,     clientName],
          [t.documentsFiling.labelDocDate,    doc.documentDate ? fmtDate(doc.documentDate) : null],
          [t.documentsFiling.labelLanguage,   langLabel(doc.detectedLanguage)],
          [t.documentsFiling.labelUploadedBy, doc.uploadedBy],
        ].filter(([,v]) => v).map(([label, val]) => (
          <Box key={label as string} sx={{ display: 'flex', gap: 1 }}>
            <Typography variant='caption' color='text.disabled' sx={{ minWidth: 90 }}>{label}</Typography>
            <Typography variant='caption' sx={{ fontWeight: 500 }}>{val}</Typography>
          </Box>
        ))}
        {doc.signed && (
          <Chip label={t.documentsFiling.signed} size='small' sx={{ height: 18, fontSize: '0.62rem', bgcolor: '#E8F7F7', color: '#0D9394', mt: 0.5, alignSelf: 'flex-start' }} />
        )}
        {doc.notes && (
          <Typography variant='caption' sx={{ fontStyle: 'italic', color: 'text.secondary', mt: 0.5 }}>{doc.notes}</Typography>
        )}
      </Box>

      {((doc.parties?.length ?? 0) > 0 || (doc.tags?.length ?? 0) > 0) && (
        <Box sx={{ flex: '1 1 200px' }}>
          {(doc.parties?.length ?? 0) > 0 && (
            <Box sx={{ mb: 1.5 }}>
              <Typography variant='caption' sx={{ fontWeight: 700, textTransform: 'uppercase', color: 'text.disabled', letterSpacing: 0.6, display: 'block', mb: 0.5 }}>
                {t.documentsFiling.labelParties}
              </Typography>
              <Box sx={{ display: 'flex', flexWrap: 'wrap', gap: 0.5 }}>
                {doc.parties!.map((p, i) => <Chip key={i} label={p} size='small' sx={{ fontSize: '0.65rem', height: 20 }} />)}
              </Box>
            </Box>
          )}
          {(doc.tags?.length ?? 0) > 0 && (
            <Box>
              <Typography variant='caption' sx={{ fontWeight: 700, textTransform: 'uppercase', color: 'text.disabled', letterSpacing: 0.6, display: 'block', mb: 0.5 }}>
                {t.documentsFiling.labelTags}
              </Typography>
              <Box sx={{ display: 'flex', flexWrap: 'wrap', gap: 0.5 }}>
                {doc.tags!.map((tag, i) => <Chip key={i} label={tag} size='small' variant='outlined' sx={{ fontSize: '0.65rem', height: 20 }} />)}
              </Box>
            </Box>
          )}
        </Box>
      )}
    </Box>
    </>
  )
}

// ─── Main View ────────────────────────────────────────────────────────────────

export default function DocumentsView({ lang: _lang = 'en' }: { lang?: string }) {
  const t = useT()
  const [docs, setDocs]       = useState<LegalDoc[]>([])
  const [clients, setClients] = useState<ClientStub[]>([])
  const [total, setTotal]     = useState(0)
  const [loading, setLoading] = useState(true)

  const [search, setSearch]           = useState('')
  const [typeFilter, setTypeFilter]   = useState('all')
  const [privFilter, setPrivFilter]   = useState('all')
  const [aiFilter, setAiFilter]       = useState('all')
  const [sortKey, setSortKey]         = useState<SortKey>('createdAt')
  const [sortDir, setSortDir]         = useState<SortDir>('desc')
  const [expandedId, setExpandedId]   = useState<string | null>(null)

  const handleDocSaved = (newDoc: LegalDoc) => {
    setDocs(prev => [newDoc, ...prev])
    setTotal(t => t + 1)
  }

  const clientMap = useMemo(
    () => Object.fromEntries(clients.map(c => [c._id, c])),
    [clients],
  )

  useEffect(() => {
    setLoading(true)
    const params = new URLSearchParams({ limit: '300' })
    if (typeFilter !== 'all') params.set('documentType', typeFilter)
    if (privFilter !== 'all') params.set('privilege', privFilter)
    fetch(`/api/documents?${params}`)
      .then(r => r.json())
      .then(d => { setDocs(d.items ?? []); setTotal(d.total ?? 0) })
      .catch(() => {})
      .finally(() => setLoading(false))
  }, [typeFilter, privFilter])

  useEffect(() => {
    fetch('/api/clients?limit=300')
      .then(r => r.json())
      .then(d => setClients((d.items ?? []).map((c: any) => ({
        _id: c._id, displayName: c.displayName, folderNumber: c.folderNumber,
      }))))
      .catch(() => {})
  }, [])

  const handleSort = (key: SortKey) => {
    if (sortKey === key) setSortDir(d => d === 'asc' ? 'desc' : 'asc')
    else { setSortKey(key); setSortDir('asc') }
  }

  const filtered = useMemo(() => {
    const q = search.toLowerCase().trim()
    return docs
      .filter(d => {
        if (aiFilter !== 'all' && d.aiStatus !== aiFilter) return false
        if (!q) return true
        const client = clientMap[d.clientFolderId]
        return (
          d.title.toLowerCase().includes(q) ||
          d.batesNumber.toLowerCase().includes(q) ||
          d.originalName.toLowerCase().includes(q) ||
          client?.displayName.toLowerCase().includes(q) ||
          client?.folderNumber.toLowerCase().includes(q) ||
          d.parties?.some(p => p.toLowerCase().includes(q)) ||
          d.tags?.some(t => t.toLowerCase().includes(q))
        )
      })
      .sort((a, b) => {
        const av: any = a[sortKey as keyof LegalDoc] ?? ''
        const bv: any = b[sortKey as keyof LegalDoc] ?? ''
        const cmp = av < bv ? -1 : av > bv ? 1 : 0
        return sortDir === 'asc' ? cmp : -cmp
      })
  }, [docs, search, aiFilter, sortKey, sortDir, clientMap])

  const classifiedCount = docs.filter(d => d.aiStatus === 'classified').length
  const pendingCount    = docs.filter(d => d.aiStatus === 'pending' || d.aiStatus === 'processing').length
  const privilegedCount = docs.filter(d => d.privilege === 'privileged').length

  const col = (key: SortKey, label: string, align: 'left' | 'right' = 'left') => (
    <TableCell align={align} sx={{ fontWeight: 600, fontSize: '0.75rem', color: 'text.secondary', whiteSpace: 'nowrap' }}>
      <TableSortLabel active={sortKey === key} direction={sortKey === key ? sortDir : 'asc'} onClick={() => handleSort(key)}>
        {label}
      </TableSortLabel>
    </TableCell>
  )

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

      {/* ── Header ── */}
      <Box sx={{ display: 'flex', justifyContent: 'space-between', alignItems: 'flex-start' }}>
        <Box>
          <Typography variant='h4' sx={{ fontWeight: 600 }}>{t.documentsFiling.title}</Typography>
          <Typography variant='body2' color='text.secondary'>
            {t.documentsFiling.totalDocs(total)}
          </Typography>
        </Box>
        <Tooltip title={t.documentsFiling.uploadViaFolder}>
          <Box sx={{ display: 'flex', alignItems: 'center', gap: 0.75, px: 1.5, py: 0.75,
            bgcolor: 'action.hover', border: '1px solid', borderColor: 'divider', borderRadius: 2,
            color: 'text.secondary', fontSize: '0.78rem' }}>
            <i className='ri-information-line' />
            <Typography variant='caption'>{t.documentsFiling.uploadViaFolder}</Typography>
          </Box>
        </Tooltip>
      </Box>

      {/* ── Stat cards ── */}
      <Box sx={{ display: 'flex', gap: 2, flexWrap: 'wrap' }}>
        {[
          { label: t.documentsFiling.statTotal,      value: total,           icon: 'ri-file-copy-line',     color: '#0D9394' },
          { label: t.documentsFiling.statClassified, value: classifiedCount, icon: 'ri-robot-line',          color: '#2ECC71' },
          { label: t.documentsFiling.statPending,    value: pendingCount,    icon: 'ri-time-line',           color: '#C27D00' },
          { label: t.documentsFiling.statPrivileged, value: privilegedCount, icon: 'ri-shield-keyhole-line', color: '#E8533A' },
        ].map(s => (
          <Card key={s.label} sx={{ flex: 1, p: 2, display: 'flex', alignItems: 'center', gap: 2, minWidth: 150 }}>
            <Box sx={{ width: 40, height: 40, borderRadius: 2, bgcolor: s.color + '18',
              display: 'flex', alignItems: 'center', justifyContent: 'center', flexShrink: 0 }}>
              <i className={s.icon} style={{ fontSize: '1.3rem', color: s.color }} />
            </Box>
            <Box>
              <Typography variant='h5' sx={{ fontWeight: 700, lineHeight: 1, color: s.color }}>{s.value}</Typography>
              <Typography variant='caption' color='text.secondary'>{s.label}</Typography>
            </Box>
          </Card>
        ))}
      </Box>

      {/* ── Filters ── */}
      <Box sx={{ display: 'flex', gap: 2, alignItems: 'center', flexWrap: 'wrap' }}>
        <TextField
          placeholder={t.documentsFiling.searchPlaceholder}
          size='small' value={search} onChange={e => setSearch(e.target.value)}
          sx={{ minWidth: 300 }}
          InputProps={{
            startAdornment: <InputAdornment position='start'><i className='ri-search-line' style={{ color: '#9CA3AF' }} /></InputAdornment>,
            endAdornment: search ? (
              <InputAdornment position='end'>
                <IconButton size='small' onClick={() => setSearch('')}>
                  <i className='ri-close-line' style={{ fontSize: '0.9rem' }} />
                </IconButton>
              </InputAdornment>
            ) : null,
          }}
        />
        <TextField select size='small' value={typeFilter} onChange={e => setTypeFilter(e.target.value)}
          sx={{ minWidth: 160 }} label={t.documentsFiling.filterDocType}>
          <MenuItem value='all'>{t.documentsFiling.allTypes}</MenuItem>
          {DOC_TYPE_VALUES.map(v => (
            <MenuItem key={v} value={v}>{t.docTypes[v as keyof typeof t.docTypes] ?? v}</MenuItem>
          ))}
        </TextField>
        <TextField select size='small' value={privFilter} onChange={e => setPrivFilter(e.target.value)}
          sx={{ minWidth: 160 }} label={t.documentsFiling.filterPrivilege}>
          <MenuItem value='all'>{t.documentsFiling.allPrivilege}</MenuItem>
          <MenuItem value='privileged'>{t.privilege.privileged}</MenuItem>
          <MenuItem value='work_product'>{t.privilege.work_product}</MenuItem>
          <MenuItem value='non_privileged'>{t.privilege.non_privileged}</MenuItem>
        </TextField>
        <Box sx={{ display: 'flex', gap: 0.75 }}>
          {(['all', 'classified', 'pending', 'failed'] as const).map(v => (
            <Chip key={v} size='small'
              label={v === 'all' ? t.documentsFiling.allAi : t.aiStatus[v as AiStatus] ?? v}
              onClick={() => setAiFilter(v)}
              variant={aiFilter === v ? 'filled' : 'outlined'}
              sx={aiFilter === v
                ? { bgcolor: v === 'all' ? '#0D9394' : AI_STYLE[v as AiStatus]?.color, color: '#fff', fontWeight: 600, border: 'none' }
                : { cursor: 'pointer', fontSize: '0.72rem' }}
            />
          ))}
        </Box>
        <Typography variant='caption' color='text.disabled' sx={{ ml: 'auto' }}>{filtered.length} {t.documentsFiling.shown}</Typography>
      </Box>

      {/* ── Table ── */}
      <Card>
        <TableContainer>
          <Table size='small'>
            <TableHead>
              <TableRow sx={{ '& th': { bgcolor: 'action.hover', borderBottom: '1px solid', borderColor: 'divider' } }}>
                <TableCell width={20} />
                {col('batesNumber', t.documentsFiling.colBatesShort)}
                {col('title', t.documentsFiling.colDocumentShort)}
                <TableCell sx={{ fontWeight: 600, fontSize: '0.75rem', color: 'text.secondary' }}>{t.documentsFiling.colClient}</TableCell>
                {col('documentType', t.documentsFiling.colType)}
                {col('privilege', t.documentsFiling.colPrivilege)}
                <TableCell sx={{ fontWeight: 600, fontSize: '0.75rem', color: 'text.secondary' }}>{t.documentsFiling.colAi}</TableCell>
                {col('fileSize', t.documentsFiling.colSize, 'right')}
                {col('createdAt', t.documentsFiling.colUploaded)}
                <TableCell width={48} />
              </TableRow>
            </TableHead>
            <TableBody>
              {loading ? (
                <TableRow><TableCell colSpan={10} align='center' sx={{ py: 6 }}><CircularProgress size={28} /></TableCell></TableRow>
              ) : filtered.length === 0 ? (
                <TableRow>
                  <TableCell colSpan={10} align='center' sx={{ py: 8 }}>
                    <i className='ri-folder-open-line' style={{ fontSize: '2.5rem', color: '#CBD5E1', display: 'block', marginBottom: 8 }} />
                    <Typography color='text.secondary'>{t.documentsFiling.noDocuments}</Typography>
                  </TableCell>
                </TableRow>
              ) : (
                filtered.map(doc => {
                  const isExpanded = expandedId === doc._id
                  const priv  = PRIVILEGE_STYLE[doc.privilege] ?? PRIVILEGE_STYLE.non_privileged
                  const ai    = AI_STYLE[doc.aiStatus]
                  const client = clientMap[doc.clientFolderId]
                  const icon  = mimeIcon(doc.mimeType, doc.fileName)
                  const icolor = mimeColor(doc.mimeType, doc.fileName)
                  return [
                    <TableRow key={doc._id} hover
                      sx={{ cursor: 'pointer', '&:last-child td': { borderBottom: isExpanded ? 'none' : undefined } }}
                      onClick={() => setExpandedId(isExpanded ? null : doc._id)}>
                      <TableCell sx={{ pr: 0 }}>
                        <i className={isExpanded ? 'ri-arrow-down-s-line' : 'ri-arrow-right-s-line'}
                          style={{ fontSize: '1rem', color: '#94A3B8' }} />
                      </TableCell>
                      <TableCell>
                        <Typography variant='caption' sx={{ fontFamily: 'monospace', color: 'text.secondary', whiteSpace: 'nowrap' }}>
                          {doc.batesNumber}
                        </Typography>
                      </TableCell>
                      <TableCell sx={{ maxWidth: 280 }}>
                        <Box sx={{ display: 'flex', alignItems: 'center', gap: 1 }}>
                          <i className={icon} style={{ fontSize: '1.1rem', color: icolor, flexShrink: 0 }} />
                          <Box sx={{ minWidth: 0 }}>
                            <Typography variant='body2' sx={{ fontWeight: 600, lineHeight: 1.3,
                              overflow: 'hidden', textOverflow: 'ellipsis', whiteSpace: 'nowrap' }}>
                              {doc.title}
                            </Typography>
                            {doc.title !== doc.originalName && (
                              <Typography variant='caption' color='text.disabled'
                                sx={{ overflow: 'hidden', textOverflow: 'ellipsis', whiteSpace: 'nowrap', display: 'block' }}>
                                {doc.originalName}
                              </Typography>
                            )}
                          </Box>
                          {doc.signed && (
                            <Tooltip title={t.documentsFiling.signed}><i className='ri-pen-nib-line' style={{ fontSize: '0.85rem', color: '#0D9394', flexShrink: 0 }} /></Tooltip>
                          )}
                        </Box>
                      </TableCell>
                      <TableCell>
                        {client ? (
                          <Box>
                            <Typography variant='body2' sx={{ fontSize: '0.8rem', fontWeight: 500 }}>{client.displayName}</Typography>
                            <Typography variant='caption' color='text.disabled' sx={{ fontFamily: 'monospace' }}>{client.folderNumber}</Typography>
                          </Box>
                        ) : <Typography variant='caption' color='text.disabled'>—</Typography>}
                      </TableCell>
                      <TableCell>
                        {doc.documentType
                          ? <Chip label={t.docTypes[doc.documentType as keyof typeof t.docTypes] ?? doc.documentType} size='small' sx={{ fontSize: '0.65rem', height: 20, bgcolor: 'action.hover' }} />
                          : <Typography variant='caption' color='text.disabled'>—</Typography>}
                      </TableCell>
                      <TableCell>
                        <Chip label={t.privilege[doc.privilege] ?? doc.privilege} size='small'
                          sx={{ fontSize: '0.65rem', height: 20, bgcolor: priv.bg, color: priv.color, fontWeight: 600 }} />
                      </TableCell>
                      <TableCell>
                        <Box sx={{ display: 'flex', alignItems: 'center', gap: 0.5 }}>
                          <i className={ai.icon} style={{ fontSize: '0.85rem', color: ai.color }} />
                          <Typography variant='caption' sx={{ color: ai.color, fontWeight: 500 }}>{t.aiStatus[doc.aiStatus]}</Typography>
                        </Box>
                      </TableCell>
                      <TableCell align='right'>
                        <Typography variant='caption' color='text.secondary'>{fmtSize(doc.fileSize)}</Typography>
                      </TableCell>
                      <TableCell>
                        <Typography variant='caption' color='text.disabled'>{fmtDate(doc.createdAt)}</Typography>
                      </TableCell>
                      <TableCell align='right' onClick={e => e.stopPropagation()}>
                        <Box sx={{ display: 'flex', alignItems: 'center', justifyContent: 'flex-end' }}>
                          <TranslateButton doc={doc} onSaved={handleDocSaved} />
                          <Tooltip title={t.documentsFiling.downloadView}>
                            <IconButton size='small' onClick={() => window.open(`/api/documents/${doc._id}/content`, '_blank')}>
                              <i className='ri-download-line' style={{ fontSize: '0.9rem' }} />
                            </IconButton>
                          </Tooltip>
                        </Box>
                      </TableCell>
                    </TableRow>,
                    <TableRow key={doc._id + '_d'}>
                      <TableCell colSpan={10} sx={{ p: 0, border: 0 }}>
                        <Collapse in={isExpanded} unmountOnExit>
                          <Divider />
                          <DocDetail doc={doc} clientName={client?.displayName} onDocSaved={handleDocSaved} />
                          <Divider />
                        </Collapse>
                      </TableCell>
                    </TableRow>,
                  ]
                })
              )}
            </TableBody>
          </Table>
        </TableContainer>
      </Card>
    </Box>
  )
}
