'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 Button from '@mui/material/Button'
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 MenuItem from '@mui/material/MenuItem'
import Alert from '@mui/material/Alert'
import Autocomplete from '@mui/material/Autocomplete'

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

type MatterStatus   = 'open' | 'pending' | 'closed' | 'archived'
type PracticeArea   = 'immigration' | 'corporate' | 'civil_litigation' | 'property' | 'family' | 'employment' | 'criminal' | 'other'
type BillingType    = 'hourly' | 'fixed' | 'retainer' | 'contingency' | 'hybrid'

interface Matter {
  _id: string
  matterNumber: string
  clientFolderId: string
  title: string
  practiceArea: PracticeArea
  subType?: string
  status: MatterStatus
  billingType?: BillingType
  hourlyRate?: number
  fixedFee?: number
  responsibleAttorney: string
  openedDate: string
  closedDate?: string
  closedOutcome?: string
  courtReference?: string
  nextActionDate?: string
  nextActionDescription?: string
  totalBilled: number
  totalPaid: number
  currency: string
  notes?: string
  updatedAt: string
  createdAt: string
}

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

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

const PRACTICE_AREA_VALUES: PracticeArea[] = ['immigration', 'corporate', 'civil_litigation', 'property', 'family', 'employment', 'criminal', 'other']

const PRACTICE_AREA_ICONS: Record<PracticeArea, string> = {
  immigration:      'ri-passport-line',
  corporate:        'ri-building-line',
  civil_litigation: 'ri-scales-line',
  property:         'ri-home-line',
  family:           'ri-team-line',
  employment:       'ri-briefcase-line',
  criminal:         'ri-police-car-line',
  other:            'ri-more-line',
}

const BILLING_TYPE_VALUES: BillingType[] = ['hourly', 'fixed', 'retainer', 'contingency', 'hybrid']

const STATUS_STYLE: Record<MatterStatus, { bg: string; color: string }> = {
  open:     { bg: '#E8F7F7', color: '#0D9394' },
  pending:  { bg: '#FFF5DB', color: '#C27D00' },
  closed:   { bg: '#F0F0F0', color: '#6B7280' },
  archived: { bg: '#F5F0FF', color: '#7B68EE' },
}

const PRACTICE_COLORS: Record<PracticeArea, string> = {
  immigration:      '#4A90D9',
  corporate:        '#7B68EE',
  civil_litigation: '#E8533A',
  property:         '#2ECC71',
  family:           '#F39C12',
  employment:       '#0D9394',
  criminal:         '#E91E63',
  other:            '#95A5A6',
}

const STATUS_FILTER_VALUES: (MatterStatus | 'all')[] = ['all', 'open', 'pending', 'closed', 'archived']

type SortKey = 'matterNumber' | 'title' | 'practiceArea' | 'status' | 'openedDate' | 'nextActionDate' | 'totalBilled'
type SortDir = 'asc' | 'desc'

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

function fmtDate(iso?: string) {
  if (!iso) return '—'
  return new Date(iso).toLocaleDateString('en-GB', { day: 'numeric', month: 'short', year: 'numeric' })
}

function fmtCurrency(n: number, currency = 'THB') {
  return new Intl.NumberFormat('en-TH', { style: 'currency', currency, maximumFractionDigits: 0 }).format(n)
}

function paIcon(pa: PracticeArea) {
  return PRACTICE_AREA_ICONS[pa] ?? 'ri-more-line'
}

function paAreaLabel(pa: PracticeArea, t: ReturnType<typeof useT>) {
  const map: Record<PracticeArea, string> = {
    immigration:      t.matters.areaImmigration,
    corporate:        t.matters.areaCorporate,
    civil_litigation: t.matters.areaCivil,
    property:         t.matters.areaProperty,
    family:           t.matters.areaFamily,
    employment:       t.matters.areaEmployment,
    criminal:         t.matters.areaCriminal,
    other:            t.matters.areaOther,
  }
  return map[pa] ?? pa
}

const emptyDraft = () => ({
  clientFolderId: '',
  title: '',
  practiceArea: 'immigration' as PracticeArea,
  responsibleAttorney: '',
  billingType: 'hourly' as BillingType,
  hourlyRate: '' as string | number,
  fixedFee: '' as string | number,
  courtReference: '',
  notes: '',
  currency: 'THB',
})

// ─── Stat Card ────────────────────────────────────────────────────────────────

function StatCard({ label, value, icon, color, sub }: {
  label: string; value: string | number; icon: string; color: string; sub?: string
}) {
  return (
    <Card sx={{ flex: 1, p: 2.5, display: 'flex', alignItems: 'center', gap: 2, minWidth: 0 }}>
      <Box sx={{ width: 44, height: 44, borderRadius: 2, bgcolor: color + '18', display: 'flex', alignItems: 'center', justifyContent: 'center', flexShrink: 0 }}>
        <i className={icon} style={{ fontSize: '1.4rem', color }} />
      </Box>
      <Box sx={{ minWidth: 0 }}>
        <Typography variant='h5' sx={{ fontWeight: 700, lineHeight: 1.1, color }}>{value}</Typography>
        <Typography variant='caption' color='text.secondary' sx={{ fontWeight: 500 }}>{label}</Typography>
        {sub && <Typography variant='caption' color='text.disabled' sx={{ display: 'block', fontSize: '0.65rem' }}>{sub}</Typography>}
      </Box>
    </Card>
  )
}

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

export default function MattersView({ lang = 'en' }: { lang?: string }) {
  const t = useT()
  const [matters, setMatters]   = useState<Matter[]>([])
  const [clients, setClients]   = useState<ClientStub[]>([])
  const [total, setTotal]       = useState(0)
  const [loading, setLoading]   = useState(true)
  const [search, setSearch]     = useState('')
  const [statusFilter, setStatusFilter] = useState<MatterStatus | 'all'>('all')
  const [paFilter, setPaFilter] = useState<PracticeArea | 'all'>('all')
  const [sortKey, setSortKey]   = useState<SortKey>('openedDate')
  const [sortDir, setSortDir]   = useState<SortDir>('desc')

  // New matter dialog
  const [newOpen, setNewOpen]   = useState(false)
  const [draft, setDraft]       = useState(emptyDraft())
  const [saving, setSaving]     = useState(false)
  const [err, setErr]           = useState<string | null>(null)

  // Close matter dialog
  const [closeTarget, setCloseTarget] = useState<Matter | null>(null)
  const [outcome, setOutcome]         = useState('')
  const [closing, setClosing]         = useState(false)

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

  // ── Fetch ──
  useEffect(() => {
    const params = new URLSearchParams({ limit: '300' })
    if (statusFilter !== 'all') params.set('status', statusFilter)
    if (paFilter !== 'all') params.set('practiceArea', paFilter)
    setLoading(true)
    fetch(`/api/matters?${params}`)
      .then(r => r.json())
      .then(d => { setMatters(d.items ?? []); setTotal(d.total ?? 0) })
      .catch(() => {})
      .finally(() => setLoading(false))
  }, [statusFilter, paFilter])

  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(() => {})
  }, [])

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

  const today = new Date().toISOString().slice(0, 10)

  const filtered = useMemo(() => {
    const q = search.toLowerCase().trim()
    return matters
      .filter(m => {
        if (!q) return true
        const client = clientMap[m.clientFolderId]
        return (
          m.title.toLowerCase().includes(q) ||
          m.matterNumber.toLowerCase().includes(q) ||
          client?.displayName.toLowerCase().includes(q) ||
          client?.folderNumber.toLowerCase().includes(q) ||
          m.responsibleAttorney.toLowerCase().includes(q)
        )
      })
      .sort((a, b) => {
        let av: any = a[sortKey as keyof Matter] ?? ''
        let bv: any = b[sortKey as keyof Matter] ?? ''
        const cmp = av < bv ? -1 : av > bv ? 1 : 0
        return sortDir === 'asc' ? cmp : -cmp
      })
  }, [matters, search, sortKey, sortDir, clientMap])

  // ── Stats ──
  const allMatters = matters
  const openCount    = allMatters.filter(m => m.status === 'open').length
  const pendingCount = allMatters.filter(m => m.status === 'pending').length
  const overdueCount = allMatters.filter(m =>
    m.nextActionDate && m.nextActionDate < today && (m.status === 'open' || m.status === 'pending')
  ).length
  const totalBilled = allMatters.reduce((s, m) => s + (m.totalBilled ?? 0), 0)

  // ── Create ──
  const handleCreate = async () => {
    if (!draft.clientFolderId) { setErr(t.matters.errSelectClient); return }
    if (!draft.title.trim()) { setErr(t.matters.errTitleRequired); return }
    if (!draft.responsibleAttorney.trim()) { setErr(t.matters.errAttorneyRequired); return }
    setSaving(true); setErr(null)
    try {
      const body: any = {
        clientFolderId: draft.clientFolderId,
        title: draft.title.trim(),
        practiceArea: draft.practiceArea,
        responsibleAttorney: draft.responsibleAttorney.trim(),
        billingType: draft.billingType,
        currency: draft.currency,
      }
      if (draft.courtReference.trim()) body.courtRef = draft.courtReference.trim()
      if (draft.notes.trim()) body.notes = draft.notes.trim()
      if (draft.billingType === 'hourly' && draft.hourlyRate) body.hourlyRate = Number(draft.hourlyRate)
      if (draft.billingType === 'fixed' && draft.fixedFee) body.fixedFee = Number(draft.fixedFee)

      const res = await fetch('/api/matters', {
        method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify(body),
      })
      if (!res.ok) {
        const e = await res.json().catch(() => ({}))
        throw new Error(Array.isArray(e.message) ? e.message.join(', ') : (e.message ?? t.matters.errCreateFailed))
      }
      const created: Matter = await res.json()
      setMatters(prev => [created, ...prev])
      setTotal(n => n + 1)
      setNewOpen(false)
      setDraft(emptyDraft())
    } catch (e: any) { setErr(e.message) } finally { setSaving(false) }
  }

  // ── Close ──
  const handleClose = async () => {
    if (!closeTarget) return
    setClosing(true)
    try {
      const res = await fetch(`/api/matters/${closeTarget._id}/close`, {
        method: 'POST', headers: { 'Content-Type': 'application/json' },
        body: JSON.stringify({ outcome }),
      })
      if (!res.ok) throw new Error('Failed to close matter')
      const updated: Matter = await res.json()
      setMatters(prev => prev.map(m => m._id === updated._id ? updated : m))
      setCloseTarget(null)
      setOutcome('')
    } catch { /* silent */ } finally { setClosing(false) }
  }

  // ── Column header helper ──
  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>
  )

  const selectedClient = clients.find(c => c._id === draft.clientFolderId) ?? null

  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.matters.title}</Typography>
          <Typography variant='body2' color='text.secondary'>
            {t.matters.subtitle(total)}
            {overdueCount > 0 && (
              <Box component='span' sx={{ ml: 1.5, color: '#FF4C51', fontWeight: 600 }}>
                {t.matters.overdueSubtitle(overdueCount)}
              </Box>
            )}
          </Typography>
        </Box>
        <Button
          variant='contained'
          startIcon={<i className='ri-add-line' />}
          onClick={() => { setDraft(emptyDraft()); setErr(null); setNewOpen(true) }}
          sx={{ bgcolor: '#0D9394', '&:hover': { bgcolor: '#096B6C' } }}
        >
          {t.matters.newMatter}
        </Button>
      </Box>

      {/* ── Stat cards ── */}
      <Box sx={{ display: 'flex', gap: 2, flexWrap: 'wrap' }}>
        <StatCard label={t.matters.statOpen}    value={openCount}    icon='ri-folder-open-line'    color='#0D9394' />
        <StatCard label={t.matters.statPending} value={pendingCount} icon='ri-time-line'            color='#C27D00' />
        <StatCard label={t.matters.statOverdue} value={overdueCount} icon='ri-alarm-warning-line'   color='#E8533A' />
        <StatCard label={t.matters.statBilled}  value={fmtCurrency(totalBilled)} icon='ri-money-dollar-circle-line' color='#7B68EE'
          sub={t.matters.statBilledSub} />
      </Box>

      {/* ── Filters ── */}
      <Box sx={{ display: 'flex', gap: 2, alignItems: 'center', flexWrap: 'wrap' }}>
        <TextField
          placeholder={t.matters.searchPlaceholderFull}
          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,
          }}
        />

        {/* Status chips */}
        <Box sx={{ display: 'flex', gap: 1, flexWrap: 'wrap' }}>
          {STATUS_FILTER_VALUES.map(v => {
            const label = v === 'all' ? t.matters.filterAll
              : v === 'open' ? t.matters.filterOpen
              : v === 'pending' ? t.matters.filterPending
              : v === 'closed' ? t.matters.filterClosed
              : t.matters.filterArchived
            return (
              <Chip key={v} label={label} size='small'
                onClick={() => setStatusFilter(v)}
                variant={statusFilter === v ? 'filled' : 'outlined'}
                sx={statusFilter === v
                  ? { bgcolor: '#0D9394', color: '#fff', fontWeight: 600, border: 'none' }
                  : { cursor: 'pointer' }}
              />
            )
          })}
        </Box>

        {/* Practice area filter */}
        <TextField select size='small' value={paFilter} onChange={e => setPaFilter(e.target.value as any)}
          sx={{ minWidth: 160 }} label={t.matters.colArea}>
          <MenuItem value='all'>{t.matters.areaAll}</MenuItem>
          {PRACTICE_AREA_VALUES.map(v => (
            <MenuItem key={v} value={v}>
              <Box sx={{ display: 'flex', alignItems: 'center', gap: 1 }}>
                <i className={PRACTICE_AREA_ICONS[v]} style={{ fontSize: '0.9rem', color: PRACTICE_COLORS[v] }} />
                {paAreaLabel(v, t)}
              </Box>
            </MenuItem>
          ))}
        </TextField>

        <Typography variant='caption' color='text.disabled' sx={{ ml: 'auto' }}>
          {filtered.length} {t.matters.shown}
        </Typography>
      </Box>

      {/* ── Table ── */}
      <Card>
        <TableContainer>
          <Table size='small'>
            <TableHead>
              <TableRow sx={{ '& th': { bgcolor: 'action.hover', borderBottom: '1px solid', borderColor: 'divider' } }}>
                {col('matterNumber', t.matters.colMatterNumber)}
                {col('title', t.matters.labelTitle)}
                <TableCell sx={{ fontWeight: 600, fontSize: '0.75rem', color: 'text.secondary' }}>{t.matters.colClient}</TableCell>
                {col('practiceArea', t.matters.colArea)}
                {col('status', t.matters.colStatus)}
                <TableCell sx={{ fontWeight: 600, fontSize: '0.75rem', color: 'text.secondary' }}>{t.matters.colAttorney}</TableCell>
                {col('nextActionDate', t.matters.colNextAction)}
                {col('totalBilled', t.matters.colBilled, 'right')}
                {col('openedDate', t.matters.colOpened)}
                <TableCell width={56} />
              </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: 6 }}>
                    <Typography color='text.secondary'>{t.matters.noMatters}</Typography>
                  </TableCell>
                </TableRow>
              ) : (
                filtered.map(matter => {
                  const st = STATUS_STYLE[matter.status]
                  const client = clientMap[matter.clientFolderId]
                  const isOverdue = matter.nextActionDate && matter.nextActionDate < today
                    && (matter.status === 'open' || matter.status === 'pending')
                  const paColor = PRACTICE_COLORS[matter.practiceArea]

                  return (
                    <TableRow
                      key={matter._id}
                      hover
                      sx={{ cursor: 'pointer', '&:last-child td': { border: 0 } }}
                      onClick={() => window.location.href = `/${lang}/matters/${matter._id}`}
                    >
                      <TableCell>
                        <Typography variant='caption' sx={{ fontFamily: 'monospace', color: 'text.secondary' }}>
                          {matter.matterNumber}
                        </Typography>
                      </TableCell>
                      <TableCell sx={{ maxWidth: 240 }}>
                        <Typography variant='body2' sx={{ fontWeight: 600, lineHeight: 1.3 }}>{matter.title}</Typography>
                        {matter.courtReference && (
                          <Typography variant='caption' color='text.disabled'>
                            <i className='ri-government-line' style={{ marginRight: 3 }} />{matter.courtReference}
                          </Typography>
                        )}
                      </TableCell>
                      <TableCell>
                        {client ? (
                          <Box>
                            <Typography variant='body2' sx={{ fontWeight: 500, fontSize: '0.8rem' }}>{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>
                        <Box sx={{ display: 'flex', alignItems: 'center', gap: 0.75 }}>
                          <i className={paIcon(matter.practiceArea)} style={{ fontSize: '0.9rem', color: paColor }} />
                          <Chip label={paAreaLabel(matter.practiceArea, t)} size='small'
                            sx={{ bgcolor: paColor + '18', color: paColor, fontSize: '0.65rem', height: 20, fontWeight: 600 }} />
                        </Box>
                      </TableCell>
                      <TableCell>
                        <Chip label={t.status[matter.status as keyof typeof t.status] ?? matter.status} size='small'
                          sx={{ bgcolor: st.bg, color: st.color, fontWeight: 600, fontSize: '0.7rem', height: 20 }} />
                      </TableCell>
                      <TableCell>
                        <Typography variant='caption' color='text.secondary'>{matter.responsibleAttorney}</Typography>
                      </TableCell>
                      <TableCell sx={{ minWidth: 140 }}>
                        {matter.nextActionDate ? (
                          <Box>
                            <Typography variant='body2'
                              sx={{ fontWeight: isOverdue ? 700 : 400, color: isOverdue ? '#E8533A' : 'text.primary', fontSize: '0.8rem' }}>
                              {isOverdue && <i className='ri-alarm-warning-line' style={{ marginRight: 3, fontSize: '0.85rem' }} />}
                              {fmtDate(matter.nextActionDate)}
                            </Typography>
                            {matter.nextActionDescription && (
                              <Typography variant='caption' color='text.disabled'
                                sx={{ display: 'block', maxWidth: 160, overflow: 'hidden', textOverflow: 'ellipsis', whiteSpace: 'nowrap' }}>
                                {matter.nextActionDescription}
                              </Typography>
                            )}
                          </Box>
                        ) : (
                          <Typography variant='caption' color='text.disabled'>—</Typography>
                        )}
                      </TableCell>
                      <TableCell align='right'>
                        <Typography variant='body2' sx={{ fontWeight: 500 }}>
                          {fmtCurrency(matter.totalBilled ?? 0, matter.currency)}
                        </Typography>
                        {(matter.totalPaid ?? 0) > 0 && matter.totalPaid < matter.totalBilled && (
                          <Typography variant='caption' color='text.disabled'>
                            {fmtCurrency(matter.totalPaid, matter.currency)} {t.matters.paid}
                          </Typography>
                        )}
                      </TableCell>
                      <TableCell>
                        <Typography variant='caption' color='text.disabled'>{fmtDate(matter.openedDate)}</Typography>
                      </TableCell>
                      <TableCell align='right' onClick={e => e.stopPropagation()}>
                        <Box sx={{ display: 'flex', gap: 0.25 }}>
                          {(matter.status === 'open' || matter.status === 'pending') && (
                            <Tooltip title={t.matters.closeMatter}>
                              <IconButton size='small'
                                onClick={e => { e.stopPropagation(); setCloseTarget(matter); setOutcome('') }}>
                                <i className='ri-check-line' style={{ fontSize: '0.9rem', color: '#6B7280' }} />
                              </IconButton>
                            </Tooltip>
                          )}
                          <Tooltip title={t.matters.openMatterTooltip}>
                            <IconButton size='small'
                              onClick={() => window.location.href = `/${lang}/matters/${matter._id}`}>
                              <i className='ri-arrow-right-line' style={{ fontSize: '1rem' }} />
                            </IconButton>
                          </Tooltip>
                        </Box>
                      </TableCell>
                    </TableRow>
                  )
                })
              )}
            </TableBody>
          </Table>
        </TableContainer>
      </Card>

      {/* ── New Matter Dialog ── */}
      <Dialog open={newOpen} onClose={() => !saving && setNewOpen(false)} maxWidth='sm' fullWidth>
        <DialogTitle>{t.matters.openNewMatterTitle}</DialogTitle>
        <DialogContent sx={{ display: 'flex', flexDirection: 'column', gap: 2, pt: '12px !important' }}>
          {err && <Alert severity='error'>{err}</Alert>}

          <Autocomplete
            options={clients}
            getOptionLabel={c => `${c.displayName} (${c.folderNumber})`}
            value={selectedClient}
            onChange={(_, v) => setDraft(d => ({ ...d, clientFolderId: v?._id ?? '' }))}
            renderInput={params => <TextField {...params} required size='small' label={t.matters.labelClient} />}
            size='small'
          />

          <TextField required size='small' label={t.matters.labelMatterTitle} value={draft.title}
            onChange={e => setDraft(d => ({ ...d, title: e.target.value }))}
            placeholder='e.g. TM.7 Non-Immigrant B Visa Extension' />

          <Box sx={{ display: 'flex', gap: 2 }}>
            <TextField select required fullWidth size='small' label={t.matters.labelArea} value={draft.practiceArea}
              onChange={e => setDraft(d => ({ ...d, practiceArea: e.target.value as PracticeArea }))}>
              {PRACTICE_AREA_VALUES.map(v => (
                <MenuItem key={v} value={v}>
                  <Box sx={{ display: 'flex', alignItems: 'center', gap: 1 }}>
                    <i className={PRACTICE_AREA_ICONS[v]} style={{ fontSize: '0.9rem', color: PRACTICE_COLORS[v] }} />
                    {paAreaLabel(v, t)}
                  </Box>
                </MenuItem>
              ))}
            </TextField>
            <TextField select required fullWidth size='small' label={t.matters.labelBilling} value={draft.billingType}
              onChange={e => setDraft(d => ({ ...d, billingType: e.target.value as BillingType }))}>
              {BILLING_TYPE_VALUES.map(v => (
                <MenuItem key={v} value={v}>
                  {v === 'hourly' ? t.matters.billingHourly
                    : v === 'fixed' ? t.matters.billingFixed
                    : v === 'retainer' ? t.matters.billingRetainer
                    : v === 'contingency' ? t.matters.billingContingency
                    : t.matters.billingHybrid}
                </MenuItem>
              ))}
            </TextField>
          </Box>

          <Box sx={{ display: 'flex', gap: 2 }}>
            <TextField required fullWidth size='small' label={t.matters.labelAttorney} value={draft.responsibleAttorney}
              onChange={e => setDraft(d => ({ ...d, responsibleAttorney: e.target.value }))} />
            <TextField fullWidth size='small' label={t.matters.labelCurrency} value={draft.currency}
              onChange={e => setDraft(d => ({ ...d, currency: e.target.value }))} />
          </Box>

          {draft.billingType === 'hourly' && (
            <TextField size='small' label={t.matters.labelHourly} type='number' value={draft.hourlyRate}
              onChange={e => setDraft(d => ({ ...d, hourlyRate: e.target.value }))}
              InputProps={{ startAdornment: <InputAdornment position='start'>{draft.currency}</InputAdornment> }} />
          )}
          {draft.billingType === 'fixed' && (
            <TextField size='small' label={t.matters.labelFixed} type='number' value={draft.fixedFee}
              onChange={e => setDraft(d => ({ ...d, fixedFee: e.target.value }))}
              InputProps={{ startAdornment: <InputAdornment position='start'>{draft.currency}</InputAdornment> }} />
          )}

          <TextField size='small' label={t.matters.courtAgencyRef} value={draft.courtReference}
            onChange={e => setDraft(d => ({ ...d, courtReference: e.target.value }))}
            placeholder='e.g. Black case no., BOI application no.' />

          <TextField size='small' label={t.matters.labelNotes} multiline rows={2} value={draft.notes}
            onChange={e => setDraft(d => ({ ...d, notes: e.target.value }))} />
        </DialogContent>
        <DialogActions>
          <Button onClick={() => setNewOpen(false)} disabled={saving}>{t.common.cancel}</Button>
          <Button variant='contained' onClick={handleCreate} disabled={saving || !draft.title.trim() || !draft.clientFolderId}
            sx={{ bgcolor: '#0D9394', '&:hover': { bgcolor: '#096B6C' } }}>
            {saving ? t.matters.creating : t.matters.openMatterBtn}
          </Button>
        </DialogActions>
      </Dialog>

      {/* ── Close Matter Dialog ── */}
      <Dialog open={Boolean(closeTarget)} onClose={() => !closing && setCloseTarget(null)} maxWidth='xs' fullWidth>
        <DialogTitle>{t.matters.closeDialogTitle}</DialogTitle>
        <DialogContent sx={{ pt: '12px !important' }}>
          {closeTarget && (
            <Typography variant='body2' color='text.secondary' sx={{ mb: 2 }}>
              {t.matters.closingNote(closeTarget.title, closeTarget.matterNumber)}
            </Typography>
          )}
          <TextField fullWidth size='small' label={t.matters.outcomeNotes} multiline rows={3}
            value={outcome} onChange={e => setOutcome(e.target.value)}
            placeholder='e.g. Visa approved, client notified. File archived.' />
        </DialogContent>
        <DialogActions>
          <Button onClick={() => setCloseTarget(null)} disabled={closing}>{t.common.cancel}</Button>
          <Button variant='contained' onClick={handleClose} disabled={closing}
            sx={{ bgcolor: '#6B7280', '&:hover': { bgcolor: '#4B5563' } }}>
            {closing ? t.matters.closingStatus : t.matters.closeMatterBtn}
          </Button>
        </DialogActions>
      </Dialog>

    </Box>
  )
}
