'use client'

import { useState } from 'react'
import { useRouter } from 'next/navigation'
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 Grid from '@mui/material/Grid'
import TextField from '@mui/material/TextField'
import MenuItem from '@mui/material/MenuItem'
import Button from '@mui/material/Button'
import Alert from '@mui/material/Alert'
import Divider from '@mui/material/Divider'
import IconButton from '@mui/material/IconButton'
import Tooltip from '@mui/material/Tooltip'
import ToggleButton from '@mui/material/ToggleButton'
import ToggleButtonGroup from '@mui/material/ToggleButtonGroup'
import PhoneEntryField, { COUNTRIES } from './PhoneEntryField'
import AddressEntryField, { ADDRESS_COUNTRIES } from './AddressEntryField'
import type { ClientFolder, CreateClientFolderDto, UpdateClientFolderDto, ClientType, PhoneEntry, EmailEntry, AddressEntry } from './types'
import { useT } from '@/contexts/LangContext'

const ATTORNEYS   = ['Patchara S.', 'Wirut A.', 'Somchai P.', 'Nattapon K.']
const CURRENCIES  = ['THB', 'USD', 'EUR', 'GBP', 'SGD']
const VISA_TYPES  = ['Tourist', 'Non-B', 'Non-O', 'Non-IM', 'Non-ED', 'SMART Visa', 'LTR Visa', 'Retirement', 'Marriage', 'Other']
const ID_TYPES    = ['Passport', 'National ID', 'Driving License', 'Residence Permit', 'Work Permit', 'Other']
const BOI_STATUSES = ['Promoted', 'Application Pending', 'Rejected', 'Not Applicable']
const EMAIL_TYPES: EmailEntry['type'][] = ['primary', 'secondary', 'billing', 'other']
const REGIONS = ['Thailand', 'Southeast Asia', 'East Asia', 'South Asia', 'Middle East', 'Europe', 'North America', 'Oceania', 'Other']

function defaultPhone(): PhoneEntry {
  return { countryCode: 'TH', dialCode: '+66', number: '', type: 'mobile' }
}
function defaultEmail(): EmailEntry {
  return { address: '', type: 'primary' }
}
function defaultAddress(): AddressEntry {
  return { line1: '', line2: '', city: '', state: '', postal: '', country: 'TH', type: 'primary' }
}

function Section({ title, icon, children, action }: { title: string; icon: string; children: React.ReactNode; action?: React.ReactNode }) {
  return (
    <Box sx={{ mb: 3 }}>
      <Box sx={{ display: 'flex', alignItems: 'center', gap: 1, mb: 2 }}>
        <i className={icon} style={{ fontSize: '1rem', color: '#0D9394' }} />
        <Typography variant='subtitle2' sx={{ fontWeight: 700, color: 'text.primary', flex: 1 }}>{title}</Typography>
        {action}
      </Box>
      <Divider sx={{ mb: 2 }} />
      {children}
    </Box>
  )
}

interface Props {
  mode: 'create' | 'edit'
  existing?: ClientFolder
  lang: string
}

export default function ClientForm({ mode, existing, lang }: Props) {
  const router = useRouter()
  const t = useT()

  const [clientType, setClientType] = useState<ClientType>(existing?.clientType ?? 'individual')
  const [submitting, setSubmitting] = useState(false)
  const [error, setError]           = useState<string | null>(null)

  // Status conversion (edit mode only — prospect → active)
  const [convertToActive,     setConvertToActive]     = useState(false)
  const [engagementLetterRef, setEngagementLetterRef] = useState('')

  // Phones
  const [phones, setPhones] = useState<PhoneEntry[]>(() => {
    if (existing?.phones?.length) return existing.phones
    if (existing?.phone) {
      const c = COUNTRIES.find(x => existing.phone!.startsWith(x.dialCode)) ?? COUNTRIES[0]
      return [{ countryCode: c.code, dialCode: c.dialCode, number: existing.phone.replace(c.dialCode, '').trim(), type: 'mobile' }]
    }
    return [defaultPhone()]
  })

  // Emails
  const [emails, setEmails] = useState<EmailEntry[]>(() => {
    if (existing?.emails?.length) return existing.emails
    if (existing?.email) return [{ address: existing.email, type: 'primary' }]
    return [defaultEmail()]
  })

  // Addresses
  const [addresses, setAddresses] = useState<AddressEntry[]>(() => {
    if ((existing as any)?.addresses?.length) return (existing as any).addresses
    return [defaultAddress()]
  })

  const [form, setForm] = useState({
    firstName:           existing?.firstName ?? '',
    lastName:            existing?.lastName ?? '',
    nationality:         existing?.nationality ?? '',
    idType:              (existing as any)?.idType ?? 'Passport',
    passportNumber:      existing?.passportNumber ?? '',
    visaType:            existing?.visaType ?? '',
    visaNumber:          (existing as any)?.visaNumber ?? '',
    visaExpiry:          existing?.visaExpiry?.split('T')[0] ?? '',
    dateOfBirth:         existing?.dateOfBirth?.split('T')[0] ?? '',
    companyName:         existing?.companyName ?? '',
    registrationNumber:  existing?.registrationNumber ?? '',
    boiStatus:           existing?.boiStatus ?? '',
    lineId:              existing?.lineId ?? '',
    region:              existing?.region ?? '',
    originatingAttorney: existing?.originatingAttorney ?? 'Patchara S.',
    responsibleAttorney: existing?.responsibleAttorney ?? 'Patchara S.',
    retainerThreshold:   String(existing?.retainerThreshold ?? 20000),
    currency:            existing?.currency ?? 'THB',
    notes:               existing?.notes ?? '',
  })

  const set = (field: keyof typeof form) => (e: React.ChangeEvent<HTMLInputElement>) =>
    setForm(f => ({ ...f, [field]: e.target.value }))

  // Phone helpers
  const updatePhone = (i: number, v: PhoneEntry) => setPhones(p => p.map((x, idx) => idx === i ? v : x))
  const addPhone    = () => setPhones(p => [...p, defaultPhone()])
  const removePhone = (i: number) => setPhones(p => p.filter((_, idx) => idx !== i))

  // Email helpers
  const updateEmail = (i: number, v: EmailEntry) => setEmails(e => e.map((x, idx) => idx === i ? v : x))
  const addEmail    = () => setEmails(e => [...e, { address: '', type: 'secondary' }])
  const removeEmail = (i: number) => setEmails(e => e.filter((_, idx) => idx !== i))

  // Address helpers
  const updateAddress = (i: number, v: AddressEntry) => setAddresses(a => a.map((x, idx) => idx === i ? v : x))
  const addAddress    = () => setAddresses(a => [...a, { ...defaultAddress(), type: a.length === 0 ? 'primary' : 'foreign' }])
  const removeAddress = (i: number) => setAddresses(a => a.filter((_, idx) => idx !== i))

  // Validation
  const phoneErrors    = phones.map(p => { const d = p.number.replace(/\D/g, ''); return d.length > 0 && (d.length < 6 || d.length > 13) })
  const emailErrors    = emails.map(e => e.address.length > 0 && !/^[^\s@]+@[^\s@]+\.[^\s@]+$/.test(e.address))
  const firstNameError = clientType === 'individual' && !form.firstName.trim()
  const lastNameError  = clientType === 'individual' && !form.lastName.trim()
  const companyError   = clientType === 'corporate'  && !form.companyName.trim()
  const noPrimaryPhone = !phones.some(p => p.number.trim().length > 0)

  const handleSubmit = async () => {
    if (firstNameError) { setError(t.clientForm.errFirstName); return }
    if (lastNameError)  { setError(t.clientForm.errLastName); return }
    if (companyError)   { setError(t.clientForm.errCompany); return }
    if (noPrimaryPhone) { setError(t.clientForm.errPhone); return }
    if (phoneErrors.some(Boolean))  { setError(t.clientForm.errPhoneInvalid); return }
    if (emailErrors.some(Boolean))  { setError(t.clientForm.errEmailInvalid); return }

    setError(null)
    setSubmitting(true)

    const primaryPhone = phones[0] ? `${phones[0].dialCode} ${phones[0].number}`.trim() : undefined
    const primaryEmail = emails[0]?.address || undefined

    // Build legacy address string from first address entry
    const a0 = addresses[0]
    const addrParts = a0 ? [a0.line1, a0.line2, [a0.city, a0.state].filter(Boolean).join(', '), a0.postal, a0.country].filter(Boolean) : []
    const addressString = addrParts.length ? addrParts.join(', ') : undefined

    const body: CreateClientFolderDto | UpdateClientFolderDto = {
      clientType,
      ...(clientType === 'individual'
        ? {
            firstName:      form.firstName,
            lastName:       form.lastName,
            nationality:    form.nationality || undefined,
            idType:         form.idType || undefined,
            passportNumber: form.passportNumber || undefined,
            visaType:       form.visaType || undefined,
            visaNumber:     form.visaNumber || undefined,
            visaExpiry:     form.visaExpiry || undefined,
            dateOfBirth:    form.dateOfBirth || undefined,
          }
        : {
            companyName:        form.companyName,
            registrationNumber: form.registrationNumber || undefined,
            boiStatus:          form.boiStatus || undefined,
          }),
      phone:   primaryPhone,
      email:   primaryEmail,
      lineId:  form.lineId || undefined,
      address: addressString,
      addresses: addresses.filter(a => a.line1.trim() || (a.city ?? '').trim()),
      phones:  phones.filter(p => p.number.trim()),
      emails:  emails.filter(e => e.address.trim()),
      region:  form.region || undefined,
      originatingAttorney: form.originatingAttorney,
      responsibleAttorney: form.responsibleAttorney,
      retainerThreshold:   form.retainerThreshold ? Number(form.retainerThreshold) : undefined,
      currency:            form.currency,
      notes:               form.notes || undefined,
    }

    try {
      const url    = mode === 'create' ? '/api/clients' : `/api/clients/${existing!._id}`
      const method = mode === 'create' ? 'POST' : 'PATCH'
      const res = await fetch(url, {
        method,
        headers: { 'Content-Type': 'application/json' },
        body: JSON.stringify(body),
      })
      if (!res.ok) {
        const err = await res.json().catch(() => ({}))
        throw new Error(Array.isArray(err.message) ? err.message.join(', ') : err.message ?? `Request failed (${res.status})`)
      }
      const data = await res.json()

      // Convert prospect → active client if toggled
      if (mode === 'edit' && convertToActive && existing?.status === 'prospect') {
        const cvRes = await fetch(`/api/clients/${existing._id}/convert`, {
          method: 'POST',
          headers: { 'Content-Type': 'application/json' },
          body: JSON.stringify({ engagementLetterRef: engagementLetterRef || '' }),
        })
        if (!cvRes.ok) {
          const err = await cvRes.json().catch(() => ({}))
          throw new Error(err.message ?? t.clientForm.errConversionFailed)
        }
      }

      router.push(`/${lang}/clients/${data._id}`)
    } catch (e: any) {
      setError(e.message ?? t.clientForm.errGeneric)
    } finally {
      setSubmitting(false)
    }
  }

  const isIndividual = clientType === 'individual'

  return (
    <Box sx={{ display: 'flex', flexDirection: 'column', gap: 2, maxWidth: 960 }}>
      {/* Header */}
      <Box sx={{ display: 'flex', justifyContent: 'space-between', alignItems: 'center' }}>
        <Box>
          <Typography variant='h4' sx={{ fontWeight: 600 }}>
            {mode === 'create' ? t.clientForm.createFolderTitle : `Edit — ${existing?.displayName}`}
          </Typography>
          <Typography variant='body2' color='text.secondary'>
            {mode === 'create'
              ? t.clientForm.createFolderSubtitle
              : t.clientForm.editFolderSubtitle(existing?.folderNumber ?? '')}
          </Typography>
        </Box>
        <Button variant='outlined' size='small' onClick={() => router.back()}
          startIcon={<i className='ri-arrow-left-line' />}>{t.common.back}</Button>
      </Box>

      {error && <Alert severity='error' onClose={() => setError(null)}>{error}</Alert>}

      {/* ── Status toggle — prospect → active client (edit mode only) ── */}
      {mode === 'edit' && existing?.status === 'prospect' && (
        <Card>
          <CardContent sx={{ p: 2.5, '&:last-child': { pb: 2.5 } }}>
            <Box sx={{ display: 'flex', alignItems: 'center', gap: 1, mb: 1.5 }}>
              <i className='ri-user-star-line' style={{ fontSize: '1rem', color: '#0D9394' }} />
              <Typography variant='subtitle2' sx={{ fontWeight: 700 }}>{t.clientForm.clientStatusTitle}</Typography>
            </Box>
            <Divider sx={{ mb: 2 }} />
            <Typography variant='body2' color='text.secondary' sx={{ mb: 1.5 }}>
              {t.clientForm.statusNoteProspect}
            </Typography>
            <ToggleButtonGroup
              value={convertToActive ? 'active' : 'prospect'}
              exclusive
              onChange={(_, v) => { if (v) setConvertToActive(v === 'active') }}
              size='small'>
              <ToggleButton value='prospect' sx={{ px: 2, fontSize: '0.78rem' }}>
                <i className='ri-user-search-line' style={{ marginRight: 6, color: '#7C6AF7' }} />
                {t.status.prospect}
              </ToggleButton>
              <ToggleButton value='active' sx={{ px: 2, fontSize: '0.78rem', '&.Mui-selected': { bgcolor: '#E8F7F7', color: '#0D9394', borderColor: '#0D9394' } }}>
                <i className='ri-checkbox-circle-line' style={{ marginRight: 6 }} />
                {t.clientForm.activeClient}
              </ToggleButton>
            </ToggleButtonGroup>
            {convertToActive && (
              <Box sx={{ mt: 2 }}>
                <TextField
                  fullWidth size='small'
                  label={t.clientForm.engagementLetterRef}
                  placeholder='e.g. EL-2025-0042'
                  value={engagementLetterRef}
                  onChange={e => setEngagementLetterRef(e.target.value)}
                  helperText={t.clientForm.engagementLetterRefHint}
                />
              </Box>
            )}
          </CardContent>
        </Card>
      )}

      <Card>
        <CardContent sx={{ p: 3 }}>

          {/* ─── Client Type ─────────────────────────────────────── */}
          <Section title={t.clientForm.clientType} icon='ri-user-settings-line'>
            <ToggleButtonGroup value={clientType} exclusive
              onChange={(_, v) => v && setClientType(v)} size='small'>
              <ToggleButton value='individual' sx={{ px: 3, gap: 1 }}>
                <i className='ri-user-line' /> {t.clientForm.individual}
              </ToggleButton>
              <ToggleButton value='corporate' sx={{ px: 3, gap: 1 }}>
                <i className='ri-building-line' /> {t.clientForm.corporate}
              </ToggleButton>
            </ToggleButtonGroup>
          </Section>

          {/* ─── Identity ────────────────────────────────────────── */}
          <Section title={isIndividual ? t.clientForm.sectionPersonal : t.clientForm.sectionCompany} icon='ri-id-card-line'>
            <Grid container spacing={2}>
              {isIndividual ? (
                <>
                  <Grid size={{ xs: 12, sm: 6 }}>
                    <TextField fullWidth required label={t.clientForm.firstName} size='small'
                      value={form.firstName} onChange={set('firstName')}
                      error={firstNameError} helperText={firstNameError ? t.common.required : undefined} />
                  </Grid>
                  <Grid size={{ xs: 12, sm: 6 }}>
                    <TextField fullWidth required label={t.clientForm.lastName} size='small'
                      value={form.lastName} onChange={set('lastName')}
                      error={lastNameError} helperText={lastNameError ? t.common.required : undefined} />
                  </Grid>
                  <Grid size={{ xs: 12, sm: 3 }}>
                    <TextField fullWidth select label={t.clientForm.nationality} size='small'
                      value={form.nationality} onChange={set('nationality')}>
                      <MenuItem value=''><em>{t.clientForm.notSpecified}</em></MenuItem>
                      {ADDRESS_COUNTRIES.map(c => (
                        <MenuItem key={c.code} value={c.name}>
                          <Box sx={{ display: 'flex', alignItems: 'center', gap: 1 }}>
                            <span>{c.flag}</span><span>{c.name}</span>
                          </Box>
                        </MenuItem>
                      ))}
                    </TextField>
                  </Grid>
                  <Grid size={{ xs: 12, sm: 3 }}>
                    <TextField fullWidth select label={t.clientForm.idType} size='small'
                      value={form.idType} onChange={set('idType')}>
                      {ID_TYPES.map(v => <MenuItem key={v} value={v}>{v}</MenuItem>)}
                    </TextField>
                  </Grid>
                  <Grid size={{ xs: 12, sm: 3 }}>
                    <TextField fullWidth label={t.clientForm.idNumber} size='small'
                      value={form.passportNumber} onChange={set('passportNumber')} />
                  </Grid>
                  <Grid size={{ xs: 12, sm: 3 }}>
                    <TextField fullWidth label={t.clientForm.dateOfBirth} size='small' type='date'
                      InputLabelProps={{ shrink: true }}
                      value={form.dateOfBirth} onChange={set('dateOfBirth')} />
                  </Grid>
                  <Grid size={{ xs: 12, sm: 4 }}>
                    <TextField fullWidth select label={t.clientForm.visaType} size='small'
                      value={form.visaType} onChange={set('visaType')}>
                      <MenuItem value=''><em>{t.clientForm.noneOption}</em></MenuItem>
                      {VISA_TYPES.map(v => <MenuItem key={v} value={v}>{v}</MenuItem>)}
                    </TextField>
                  </Grid>
                  <Grid size={{ xs: 12, sm: 4 }}>
                    <TextField fullWidth label={t.clientForm.visaNumber} size='small'
                      value={form.visaNumber} onChange={set('visaNumber')}
                      placeholder='e.g. A1234567' />
                  </Grid>
                  <Grid size={{ xs: 12, sm: 4 }}>
                    <TextField fullWidth label={t.clientForm.visaExpiry} size='small' type='date'
                      InputLabelProps={{ shrink: true }}
                      value={form.visaExpiry} onChange={set('visaExpiry')} />
                  </Grid>
                </>
              ) : (
                <>
                  <Grid size={{ xs: 12, sm: 8 }}>
                    <TextField fullWidth required label={t.clientForm.companyName} size='small'
                      value={form.companyName} onChange={set('companyName')}
                      error={companyError} helperText={companyError ? t.common.required : undefined} />
                  </Grid>
                  <Grid size={{ xs: 12, sm: 4 }}>
                    <TextField fullWidth label={t.clientForm.registrationNumber} size='small'
                      value={form.registrationNumber} onChange={set('registrationNumber')} />
                  </Grid>
                  <Grid size={{ xs: 12, sm: 4 }}>
                    <TextField fullWidth select label={t.clientForm.boiStatus} size='small'
                      value={form.boiStatus} onChange={set('boiStatus')}>
                      <MenuItem value=''><em>{t.clientForm.noneOption}</em></MenuItem>
                      {BOI_STATUSES.map(b => <MenuItem key={b} value={b}>{b}</MenuItem>)}
                    </TextField>
                  </Grid>
                </>
              )}
            </Grid>
          </Section>

          {/* ─── Addresses ───────────────────────────────────────── */}
          <Section
            title={t.clientForm.sectionAddresses}
            icon='ri-map-pin-line'
            action={
              <Button size='small' onClick={addAddress} startIcon={<i className='ri-add-line' />}
                sx={{ fontSize: '0.72rem' }}>
                {t.clientForm.addAddress}
              </Button>
            }
          >
            <Box sx={{ display: 'flex', flexDirection: 'column', gap: 2 }}>
              {addresses.map((a, i) => (
                <AddressEntryField
                  key={i}
                  entry={a}
                  index={i}
                  onChange={updated => updateAddress(i, updated)}
                  onRemove={() => removeAddress(i)}
                  canRemove={addresses.length > 1}
                />
              ))}
            </Box>
            <Typography variant='caption' color='text.disabled' sx={{ mt: 1, display: 'block' }}>
              {t.clientForm.addAddressHint}
            </Typography>
          </Section>

          {/* ─── Phone Numbers ────────────────────────────────────── */}
          <Section
            title={t.clientForm.sectionPhones}
            icon='ri-phone-line'
            action={
              <Button size='small' onClick={addPhone} startIcon={<i className='ri-add-line' />}
                sx={{ fontSize: '0.72rem' }}>
                {t.clientForm.addPhone}
              </Button>
            }
          >
            <Box sx={{ display: 'flex', flexDirection: 'column', gap: 1.5 }}>
              {phones.map((p, i) => (
                <PhoneEntryField
                  key={i}
                  entry={p}
                  onChange={updated => updatePhone(i, updated)}
                  onRemove={() => removePhone(i)}
                  canRemove={phones.length > 1}
                />
              ))}
            </Box>
            <Typography variant='caption' color='text.disabled' sx={{ mt: 1, display: 'block' }}>
              {t.clientForm.addPhoneHint}
            </Typography>
          </Section>

          {/* ─── Email Addresses ──────────────────────────────────── */}
          <Section
            title={t.clientForm.sectionEmails}
            icon='ri-mail-line'
            action={
              <Button size='small' onClick={addEmail} startIcon={<i className='ri-add-line' />}
                sx={{ fontSize: '0.72rem' }}>
                {t.clientForm.addEmail}
              </Button>
            }
          >
            <Box sx={{ display: 'flex', flexDirection: 'column', gap: 1.5 }}>
              {emails.map((e, i) => (
                <Box key={i} sx={{ display: 'flex', gap: 1 }}>
                  <TextField
                    size='small' label={t.clientForm.emailAddress} type='email'
                    value={e.address}
                    onChange={ev => updateEmail(i, { ...e, address: ev.target.value })}
                    error={!!emailErrors[i]}
                    helperText={emailErrors[i] ? t.clientForm.errEmailInvalid : undefined}
                    sx={{ flex: 1 }}
                  />
                  <TextField select size='small' label={t.clientForm.emailType} value={e.type}
                    onChange={ev => updateEmail(i, { ...e, type: ev.target.value as EmailEntry['type'] })}
                    sx={{ width: 130 }}>
                    {EMAIL_TYPES.map(et => (
                      <MenuItem key={et} value={et} sx={{ textTransform: 'capitalize' }}>{et}</MenuItem>
                    ))}
                  </TextField>
                  {emails.length > 1 && (
                    <Tooltip title={t.common.delete}>
                      <IconButton size='small' onClick={() => removeEmail(i)} sx={{ mt: 0.5 }}>
                        <i className='ri-delete-bin-line' style={{ fontSize: '1rem', color: '#FF4C51' }} />
                      </IconButton>
                    </Tooltip>
                  )}
                </Box>
              ))}
            </Box>
            <Typography variant='caption' color='text.disabled' sx={{ mt: 1, display: 'block' }}>
              {t.clientForm.addEmailHint}
            </Typography>
          </Section>

          {/* ─── Other Contact ───────────────────────────────────── */}
          <Section title={t.clientForm.sectionOtherContact} icon='ri-contacts-line'>
            <Grid container spacing={2}>
              <Grid size={{ xs: 12, sm: 4 }}>
                <TextField fullWidth label={t.clientForm.lineId} size='small' value={form.lineId} onChange={set('lineId')}
                  InputProps={{ startAdornment: <span style={{ marginRight: 4, color: '#00C300', fontSize: '1rem' }}>💬</span> }} />
              </Grid>
              <Grid size={{ xs: 12, sm: 4 }}>
                <TextField fullWidth select label={t.clientForm.businessRegion} size='small' value={form.region} onChange={set('region')}>
                  <MenuItem value=''><em>{t.clientForm.notSpecified}</em></MenuItem>
                  {REGIONS.map(r => <MenuItem key={r} value={r}>{r}</MenuItem>)}
                </TextField>
                <Typography variant='caption' color='text.disabled' sx={{ mt: 0.5, display: 'block' }}>
                  {t.clientForm.regionHint}
                </Typography>
              </Grid>
            </Grid>
          </Section>

          {/* ─── Attorneys ────────────────────────────────────────── */}
          <Section title={t.clientForm.sectionAttorneys} icon='ri-user-star-line'>
            <Grid container spacing={2}>
              <Grid size={{ xs: 12, sm: 6 }}>
                <TextField fullWidth select required label={t.clientForm.originatingAttorney} size='small'
                  value={form.originatingAttorney} onChange={set('originatingAttorney')}>
                  {ATTORNEYS.map(a => <MenuItem key={a} value={a}>{a}</MenuItem>)}
                </TextField>
                <Typography variant='caption' color='text.disabled' sx={{ mt: 0.5, display: 'block' }}>
                  {t.clientForm.originatingHint}
                </Typography>
              </Grid>
              <Grid size={{ xs: 12, sm: 6 }}>
                <TextField fullWidth select required label={t.clientForm.responsibleAttorney} size='small'
                  value={form.responsibleAttorney} onChange={set('responsibleAttorney')}>
                  {ATTORNEYS.map(a => <MenuItem key={a} value={a}>{a}</MenuItem>)}
                </TextField>
                <Typography variant='caption' color='text.disabled' sx={{ mt: 0.5, display: 'block' }}>
                  {t.clientForm.responsibleHint}
                </Typography>
              </Grid>
            </Grid>
          </Section>

          {/* ─── Retainer & Billing ──────────────────────────────── */}
          <Section title={t.clientForm.sectionBilling} icon='ri-money-baht-circle-line'>
            <Grid container spacing={2}>
              <Grid size={{ xs: 12, sm: 4 }}>
                <TextField fullWidth select label={t.clientForm.currency} size='small'
                  value={form.currency} onChange={set('currency')}>
                  {CURRENCIES.map(c => <MenuItem key={c} value={c}>{c}</MenuItem>)}
                </TextField>
              </Grid>
              <Grid size={{ xs: 12, sm: 4 }}>
                <TextField fullWidth label={t.clientForm.retainerThreshold} size='small' type='number'
                  value={form.retainerThreshold} onChange={set('retainerThreshold')}
                  helperText={t.clientForm.retainerHint} />
              </Grid>
            </Grid>
          </Section>

          {/* ─── Notes ───────────────────────────────────────────── */}
          <Section title={t.clientForm.sectionNotes} icon='ri-sticky-note-line'>
            <TextField fullWidth label={t.clientForm.internalNotes} size='small' multiline rows={3}
              value={form.notes} onChange={set('notes')}
              placeholder={t.clientForm.notesPlaceholder} />
          </Section>

          {/* ─── Actions ─────────────────────────────────────────── */}
          <Box sx={{ display: 'flex', gap: 2, justifyContent: 'flex-end', pt: 1 }}>
            <Button variant='outlined' onClick={() => router.back()} disabled={submitting}>{t.common.cancel}</Button>
            <Button variant='contained' onClick={handleSubmit} disabled={submitting}
              startIcon={<i className={submitting ? 'ri-loader-line' : 'ri-save-line'} />}
              sx={{ bgcolor: '#0D9394', '&:hover': { bgcolor: '#096B6C' } }}>
              {submitting ? t.common.saving : mode === 'create' ? t.clientForm.submitCreate : t.clientForm.submitEdit}
            </Button>
          </Box>

        </CardContent>
      </Card>
    </Box>
  )
}
