// frontend/src/pages/crm/customers/CustomerForm.jsx

import { useState, useEffect, useRef } from 'react'
import { useNavigate, useParams } from 'react-router-dom'
import api from '@/lib/api'
import { useAuth }    from '@/hooks/useAuth'
import PageHeader     from '@/components/ui/PageHeader'
import Button         from '@/components/ui/Button'
import Card           from '@/components/ui/Card'
import FormField      from '@/components/ui/FormField'
import Icon           from '@/components/ui/Icon'
import Spinner        from '@/components/ui/Spinner'
import ConfirmDialog  from '@/components/ui/ConfirmDialog'
import { fmtDate } from '@/lib/formatters'

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

const CONTACT_TYPES = ['email', 'phone', 'whatsapp', 'other']

const LANGUAGES = [
  { value: 'el', label: 'Greek' },
  { value: 'en', label: 'English' },
  { value: 'de', label: 'German' },
  { value: 'fr', label: 'French' },
  { value: 'it', label: 'Italian' },
  { value: 'ru', label: 'Russian' },
  { value: 'ar', label: 'Arabic' },
  { value: 'tr', label: 'Turkish' },
  { value: 'sr', label: 'Serbian' },
]

const TITLES = [
  { value: '',        label: '—' },
  { value: 'Fr.',     label: 'Father' },
  { value: 'Rev.',    label: 'Reverend' },
  { value: 'Archim.', label: 'Archimandrite' },
  { value: 'Bp.',     label: 'Bishop' },
  { value: 'Abp.',    label: 'Archbishop' },
  { value: 'Met.',    label: 'Metropolitan' },
  { value: 'Mr.',     label: 'Mister' },
  { value: 'Mrs.',    label: 'Missus' },
  { value: 'Ms.',     label: 'Ms.' },
  { value: 'Dr.',     label: 'Doctor' },
  { value: 'Prof.',   label: 'Professor' },
]

const PRESET_TAGS = [
  'church', 'municipality', 'monastery', 'priest', 'church council',
  'technician', 'donor', 'repeat-customer', 'vip', 'promoter',
]

const RELIGIONS = [
  { value: '',               label: '— Unknown' },
  { value: 'Orthodox',       label: 'Orthodox' },
  { value: 'Catholic',       label: 'Catholic' },
  { value: 'Christian Other',label: 'Christian Other' },
  { value: 'Other',          label: 'Other' },
]

const REL_STATUS_OPTIONS = [
  { value: 'lead',     label: 'Lead' },
  { value: 'prospect', label: 'Prospect' },
  { value: 'active',   label: 'Active' },
  { value: 'inactive', label: 'Archived' },
  { value: 'churned',  label: 'Went Cold' },
]

const CONTACT_TYPE_LABEL = {
  email:    'Email',
  phone:    'Phone',
  whatsapp: 'WhatsApp',
  other:    'Other',
}

const DEFAULT_FORM = {
  title:               '',
  name:                '',
  surname:             '',
  organization:        '',
  religion:            '',
  language:            'el',
  relationship_status: 'lead',
  tags:                [],
  folder_id:           '',
  location: {
    address:     '',
    city:        '',
    postal_code: '',
    region:      '',
    country:     '',
  },
  contacts: [],
  notes:    [],
}

const emptyContact = () => ({ type: 'email', label: '', value: '', primary: false })

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

function SectionDivider({ label }) {
  return (
    <div style={{ display: 'flex', alignItems: 'center', gap: 'var(--space-3)', margin: 'var(--space-5) 0 var(--space-4)' }}>
      <span style={{
        fontSize:      'var(--font-size-xs)',
        fontWeight:    'var(--font-weight-semibold)',
        color:         'var(--color-text-muted)',
        textTransform: 'uppercase',
        letterSpacing: 'var(--tracking-wide)',
        whiteSpace:    'nowrap',
      }}>
        {label}
      </span>
      <div style={{ flex: 1, height: '1px', backgroundColor: 'var(--color-border)' }} />
    </div>
  )
}

// ─── CustomerForm ─────────────────────────────────────────────────────────────

export default function CustomerForm() {
  const { id } = useParams()
  const isEdit  = Boolean(id)
  const navigate = useNavigate()
  const { user, hasPermission } = useAuth()
  const canEdit = hasPermission('crm_customers', isEdit ? 'full_access' : 'add')

  // Form state
  const [form,    setForm]    = useState(DEFAULT_FORM)
  const [loading, setLoading] = useState(isEdit)
  const [saving,  setSaving]  = useState(false)
  const [error,   setError]   = useState('')

  // Tag state
  const [tagInput, setTagInput] = useState('')
  const [allTags,  setAllTags]  = useState([])
  const tagInputRef = useRef(null)

  // Note state
  const [newNoteText,    setNewNoteText]    = useState('')
  const [editingNoteIdx, setEditingNoteIdx] = useState(null)
  const [editingNoteText,setEditingNoteText]= useState('')

  // Delete dialog
  const [showDeleteDialog, setShowDeleteDialog] = useState(false)
  const [deleting,         setDeleting]          = useState(false)

  // ── Fetch ────────────────────────────────────────────────────────────────

  useEffect(() => {
    api.get('/crm/customers/tags').then(setAllTags).catch(() => {})
  }, [])

  useEffect(() => {
    if (!isEdit) return
    api.get(`/crm/customers/${id}`)
      .then((data) => {
        setForm({
          title:               data.title               || '',
          name:                data.name                || '',
          surname:             data.surname             || '',
          organization:        data.organization        || '',
          religion:            data.religion            || '',
          language:            data.language            || 'el',
          relationship_status: data.relationship_status || 'lead',
          tags:                data.tags                || [],
          folder_id:           data.folder_id           || '',
          location: {
            address:     data.location?.address     || '',
            city:        data.location?.city        || '',
            postal_code: data.location?.postal_code || '',
            region:      data.location?.region      || '',
            country:     data.location?.country     || '',
          },
          contacts: data.contacts || [],
          notes:    data.notes    || [],
        })
      })
      .catch((err) => setError(err.message))
      .finally(() => setLoading(false))
  }, [id, isEdit])

  // ── Field setters ────────────────────────────────────────────────────────

  const set    = (field, value) => setForm((f) => ({ ...f, [field]: value }))
  const setLoc = (field, value) => setForm((f) => ({ ...f, location: { ...f.location, [field]: value } }))

  // ── Tags ─────────────────────────────────────────────────────────────────

  const addTag = (raw) => {
    const tag = raw.trim()
    if (tag && !form.tags.includes(tag)) set('tags', [...form.tags, tag])
    setTagInput('')
  }

  const removeTag = (tag) => set('tags', form.tags.filter((t) => t !== tag))

  // ── Contacts ─────────────────────────────────────────────────────────────

  const addContact    = () => set('contacts', [...form.contacts, emptyContact()])
  const removeContact = (i) => set('contacts', form.contacts.filter((_, idx) => idx !== i))

  const setContact = (i, field, value) => {
    set('contacts', form.contacts.map((c, idx) => idx === i ? { ...c, [field]: value } : c))
  }

  const setPrimaryContact = (i) => {
    const type = form.contacts[i].type
    set('contacts', form.contacts.map((c, idx) => ({
      ...c,
      primary: c.type === type ? idx === i : c.primary,
    })))
  }

  // ── Notes ────────────────────────────────────────────────────────────────

  const addNote = () => {
    if (!newNoteText.trim()) return
    set('notes', [...form.notes, {
      text: newNoteText.trim(),
      by:   user?.name || 'unknown',
      at:   new Date().toISOString(),
    }])
    setNewNoteText('')
  }

  const removeNote = (i) => {
    set('notes', form.notes.filter((_, idx) => idx !== i))
    if (editingNoteIdx === i) setEditingNoteIdx(null)
  }

  const startEditNote = (i) => {
    setEditingNoteIdx(i)
    setEditingNoteText(form.notes[i].text)
  }

  const saveEditNote = (i) => {
    if (!editingNoteText.trim()) return
    set('notes', form.notes.map((n, idx) =>
      idx === i ? { ...n, text: editingNoteText.trim(), at: new Date().toISOString() } : n
    ))
    setEditingNoteIdx(null)
  }

  // ── Save ─────────────────────────────────────────────────────────────────

  const buildPayload = () => ({
    title:               form.title.trim() || null,
    name:                form.name.trim(),
    surname:             form.surname.trim() || null,
    organization:        form.organization.trim() || null,
    religion:            form.religion.trim() || null,
    language:            form.language,
    relationship_status: form.relationship_status || 'lead',
    tags:                form.tags,
    ...(!isEdit && { folder_id: form.folder_id.trim().toLowerCase() }),
    location: {
      address:     form.location.address.trim()     || null,
      city:        form.location.city.trim()        || null,
      postal_code: form.location.postal_code.trim() || null,
      region:      form.location.region.trim()      || null,
      country:     form.location.country.trim()     || null,
    },
    contacts: form.contacts.filter((c) => c.value.trim()),
    notes:    form.notes,
  })

  const handleSave = async () => {
    if (!form.name.trim()) { setError('Customer name is required.'); return }
    if (!isEdit && !form.folder_id.trim()) { setError('Internal Folder ID is required.'); return }
    if (!isEdit && !/^[a-z0-9][a-z0-9\-]*[a-z0-9]$/.test(form.folder_id.trim().toLowerCase())) {
      setError('Folder ID must contain only lowercase letters, numbers, and hyphens, and cannot start or end with a hyphen.')
      return
    }
    setSaving(true)
    setError('')
    try {
      if (isEdit) {
        await api.put(`/crm/customers/${id}`, buildPayload())
        navigate(`/crm/customers/${id}`)
      } else {
        const res = await api.post('/crm/customers', buildPayload())
        navigate(`/crm/customers/${res.id}`)
      }
    } catch (err) {
      setError(err.message)
    } finally {
      setSaving(false)
    }
  }

  const handleDelete = async () => {
    setDeleting(true)
    try {
      await api.delete(`/crm/customers/${id}`)
      navigate('/crm/customers')
    } catch (err) {
      setError(err.message)
      setDeleting(false)
    }
  }

  // ── Loading state ────────────────────────────────────────────────────────

  if (loading) {
    return (
      <div className="page-wrapper">
        <div style={{ display: 'flex', alignItems: 'center', justifyContent: 'center', padding: 'var(--space-16)' }}>
          <Spinner size="lg" />
        </div>
      </div>
    )
  }

  // ─────────────────────────────────────────────────────────────────────────

  const tagSuggestions = allTags.filter(
    (t) => t.toLowerCase().startsWith(tagInput.toLowerCase()) && !form.tags.includes(t)
  )

  return (
    <div className="page-wrapper page-wrapper--capped">

      <PageHeader
        title={isEdit ? 'Edit Customer' : 'New Customer'}
        subtitle={isEdit && form.name ? `${[form.title, form.name, form.surname].filter(Boolean).join(' ')}` : undefined}
      >
        <Button
          variant="ghost"
          size="md"
          onClick={() => navigate(isEdit ? `/crm/customers/${id}` : '/crm/customers')}
        >
          Cancel
        </Button>
        {canEdit && (
          <Button
            variant="primary"
            size="md"
            loading={saving}
            onClick={handleSave}
          >
            {isEdit ? 'Save Changes' : 'Create Customer'}
          </Button>
        )}
      </PageHeader>

      {/* Error banner */}
      {error && (
        <div
          role="alert"
          style={{
            backgroundColor: 'var(--color-danger-bg)',
            border:          '1px solid var(--color-danger)',
            borderRadius:    'var(--radius-md)',
            padding:         'var(--space-3) var(--space-4)',
            color:           'var(--color-danger)',
            fontSize:        'var(--font-size-sm)',
          }}
        >
          {error}
        </div>
      )}

      {/* ── Two-column form layout ─────────────────────────────────────────── */}
      <div className="masonry-grid masonry-grid--2">

        {/* ── Basic Info card ───────────────────────────────────────────────── */}
        <Card title="Basic Info">

          {/* Row: Title + Name + Surname */}
          <div style={{ display: 'grid', gridTemplateColumns: '140px 1fr 1fr', gap: 'var(--space-4)', marginBottom: 'var(--space-4)' }}>
            <FormField
              label="Title"
              name="title"
              type="select"
              value={form.title}
              onChange={(e) => set('title', e.target.value)}
            >
              {TITLES.map((t) => <option key={t.value} value={t.value}>{t.label}</option>)}
            </FormField>

            <FormField
              label="First Name *"
              name="name"
              type="text"
              value={form.name}
              onChange={(e) => set('name', e.target.value)}
              placeholder="First name"
              required
            />

            <FormField
              label="Surname"
              name="surname"
              type="text"
              value={form.surname}
              onChange={(e) => set('surname', e.target.value)}
              placeholder="Last name"
            />
          </div>

          {/* Row: Relationship Status + Organization */}
          <div style={{ display: 'grid', gridTemplateColumns: '1fr 1fr', gap: 'var(--space-4)', marginBottom: 'var(--space-4)' }}>
            <FormField
              label="Relationship Status"
              name="relationship_status"
              type="select"
              value={form.relationship_status}
              onChange={(e) => set('relationship_status', e.target.value)}
            >
              {REL_STATUS_OPTIONS.map((o) => <option key={o.value} value={o.value}>{o.label}</option>)}
            </FormField>

            <FormField
              label="Organization"
              name="organization"
              type="text"
              value={form.organization}
              onChange={(e) => set('organization', e.target.value)}
              placeholder="Church, company, etc."
            />
          </div>

          {/* Row: Religion + Language */}
          <div style={{ display: 'grid', gridTemplateColumns: '1fr 1fr', gap: 'var(--space-4)', marginBottom: 'var(--space-4)' }}>
            <FormField
              label="Religion"
              name="religion"
              type="select"
              value={form.religion}
              onChange={(e) => set('religion', e.target.value)}
            >
              {RELIGIONS.map((r) => <option key={r.value} value={r.value}>{r.label}</option>)}
            </FormField>

            <FormField
              label="Language"
              name="language"
              type="select"
              value={form.language}
              onChange={(e) => set('language', e.target.value)}
            >
              {LANGUAGES.map((l) => <option key={l.value} value={l.value}>{l.label}</option>)}
            </FormField>
          </div>

          {/* Folder ID — only on create */}
          {!isEdit ? (
            <>
              <FormField
                label="Internal Folder ID *"
                name="folder_id"
                type="text"
                value={form.folder_id}
                onChange={(e) => set('folder_id', e.target.value.toLowerCase().replace(/[^a-z0-9\-]/g, ''))}
                placeholder="e.g. saint-john-corfu"
                hint="Lowercase letters, numbers and hyphens only. Becomes the Nextcloud folder name and cannot be changed."
                required
              />
            </>
          ) : (
            <div style={{ marginBottom: 'var(--space-4)' }}>
              <span style={{
                display:       'block',
                fontSize:      'var(--font-size-sm)',
                fontWeight:    'var(--font-weight-medium)',
                color:         'var(--color-text-secondary)',
                marginBottom:  'var(--space-1)',
              }}>
                Folder ID
              </span>
              <span style={{
                fontFamily: 'var(--font-family-mono)',
                fontSize:   'var(--font-size-sm)',
                color:      'var(--color-text-muted)',
              }}>
                {form.folder_id || '—'}
              </span>
            </div>
          )}

          {/* Tags */}
          <SectionDivider label="Tags" />

          {/* Active tags */}
          {form.tags.length > 0 && (
            <div style={{ display: 'flex', flexWrap: 'wrap', gap: 'var(--space-1)', marginBottom: 'var(--space-3)' }}>
              {form.tags.map((tag) => (
                <button
                  key={tag}
                  type="button"
                  onClick={() => removeTag(tag)}
                  title="Click to remove"
                  style={{
                    display:         'inline-flex',
                    alignItems:      'center',
                    gap:             'var(--space-1)',
                    padding:         '3px var(--space-2)',
                    fontSize:        'var(--font-size-xs)',
                    borderRadius:    'var(--radius-full)',
                    backgroundColor: 'var(--color-primary-subtle)',
                    color:           'var(--color-primary)',
                    border:          '1px solid rgba(192,193,255,0.2)',
                    cursor:          'pointer',
                  }}
                >
                  {tag}
                  <Icon name="close" size={10} color="var(--color-primary)" />
                </button>
              ))}
            </div>
          )}

          {/* Preset quick-add tags */}
          <div style={{ display: 'flex', flexWrap: 'wrap', gap: 'var(--space-1)', marginBottom: 'var(--space-3)' }}>
            {PRESET_TAGS.filter((t) => !form.tags.includes(t)).map((t) => (
              <button
                key={t}
                type="button"
                onClick={() => addTag(t)}
                style={{
                  padding:         '3px var(--space-2)',
                  fontSize:        'var(--font-size-xs)',
                  borderRadius:    'var(--radius-full)',
                  border:          '1px solid var(--color-border-strong)',
                  color:           'var(--color-text-muted)',
                  backgroundColor: 'transparent',
                  cursor:          'pointer',
                }}
              >
                + {t}
              </button>
            ))}
          </div>

          {/* Tag input with autocomplete */}
          <div ref={tagInputRef} style={{ position: 'relative' }}>
            <FormField
              label=""
              name="tag_input"
              type="text"
              value={tagInput}
              onChange={(e) => setTagInput(e.target.value)}
              inputProps={{
                onKeyDown: (e) => {
                  if (e.key === 'Tab' && tagSuggestions.length > 0) {
                    e.preventDefault()
                    addTag(tagSuggestions[0])
                  } else if (e.key === 'Enter' || e.key === ',') {
                    e.preventDefault()
                    addTag(tagInput)
                  } else if (e.key === 'Escape') {
                    setTagInput('')
                  }
                },
                onBlur: () => { setTimeout(() => { if (tagInput.trim()) addTag(tagInput) }, 150) },
              }}
              placeholder="Type a tag — Enter or comma to add, Tab to autocomplete…"
            />
            {tagInput.trim().length > 0 && tagSuggestions.length > 0 && (() => {
              const rect = tagInputRef.current?.getBoundingClientRect()
              return (
                <div style={{
                  position:        'fixed',
                  top:             rect ? rect.bottom + 4 : 0,
                  left:            rect ? rect.left : 0,
                  width:           rect ? rect.width : 'auto',
                  zIndex:          9999,
                  border:          '1px solid var(--color-border)',
                  borderRadius:    'var(--radius-lg)',
                  backgroundColor: 'var(--color-bg-elevated)',
                  boxShadow:       'var(--shadow-lg)',
                  overflow:        'hidden',
                }}>
                  {tagSuggestions.map((s, idx) => (
                    <div
                      key={s}
                      onMouseDown={(e) => { e.preventDefault(); addTag(s) }}
                      style={{
                        padding:         'var(--space-2) var(--space-3)',
                        fontSize:        'var(--font-size-sm)',
                        cursor:          'pointer',
                        color:           'var(--color-text-primary)',
                        borderBottom:    '1px solid var(--color-border)',
                        backgroundColor: 'transparent',
                        display:         'flex',
                        justifyContent:  'space-between',
                        alignItems:      'center',
                      }}
                      onMouseEnter={(e) => { e.currentTarget.style.backgroundColor = 'var(--color-bg-island)' }}
                      onMouseLeave={(e) => { e.currentTarget.style.backgroundColor = 'transparent' }}
                    >
                      {s}
                      {idx === 0 && (
                        <span style={{ fontSize: 'var(--font-size-xs)', color: 'var(--color-text-muted)' }}>
                          Tab
                        </span>
                      )}
                    </div>
                  ))}
                </div>
              )
            })()}
          </div>
        </Card>

        {/* ── Location card ──────────────────────────────────────────────────── */}
        <Card title="Location">
          <div style={{ display: 'grid', gridTemplateColumns: '2fr 1fr 1fr', gap: 'var(--space-4)', marginBottom: 'var(--space-4)' }}>
            <FormField
              label="Address"
              name="address"
              type="text"
              value={form.location.address}
              onChange={(e) => setLoc('address', e.target.value)}
              placeholder="Street address"
            />
            <FormField
              label="City"
              name="city"
              type="text"
              value={form.location.city}
              onChange={(e) => setLoc('city', e.target.value)}
              placeholder="City"
            />
            <FormField
              label="Postal Code"
              name="postal_code"
              type="text"
              value={form.location.postal_code}
              onChange={(e) => setLoc('postal_code', e.target.value)}
              placeholder="Postal code"
            />
          </div>

          <div style={{ display: 'grid', gridTemplateColumns: '1fr 1fr', gap: 'var(--space-4)' }}>
            <FormField
              label="Region"
              name="region"
              type="text"
              value={form.location.region}
              onChange={(e) => setLoc('region', e.target.value)}
              placeholder="Region / State"
            />
            <FormField
              label="Country"
              name="country"
              type="text"
              value={form.location.country}
              onChange={(e) => setLoc('country', e.target.value)}
              placeholder="Country"
            />
          </div>
        </Card>

        {/* ── Contacts card ──────────────────────────────────────────────────── */}
        <Card title="Contacts">
          {form.contacts.length === 0 && (
            <p style={{ fontSize: 'var(--font-size-sm)', color: 'var(--color-text-muted)', marginBottom: 'var(--space-4)' }}>
              No contacts added yet.
            </p>
          )}

          <div style={{ display: 'flex', flexDirection: 'column', gap: 'var(--space-3)' }}>
            {form.contacts.map((c, i) => (
              <div
                key={i}
                style={{
                  display:         'grid',
                  gridTemplateColumns: '130px 120px 1fr auto auto',
                  gap:             'var(--space-2)',
                  alignItems:      'center',
                  backgroundColor: 'var(--color-bg-abyss)',
                  border:          '1px solid var(--color-border)',
                  borderRadius:    'var(--radius-md)',
                  padding:         'var(--space-2) var(--space-3)',
                }}
              >
                {/* Type */}
                <FormField
                  label=""
                  name={`contact_type_${i}`}
                  type="select"
                  value={c.type}
                  onChange={(e) => setContact(i, 'type', e.target.value)}
                >
                  {CONTACT_TYPES.map((t) => (
                    <option key={t} value={t}>{CONTACT_TYPE_LABEL[t] || t}</option>
                  ))}
                </FormField>

                {/* Label */}
                <FormField
                  label=""
                  name={`contact_label_${i}`}
                  type="text"
                  value={c.label}
                  onChange={(e) => setContact(i, 'label', e.target.value)}
                  placeholder="label (e.g. work)"
                />

                {/* Value */}
                <FormField
                  label=""
                  name={`contact_value_${i}`}
                  type="text"
                  value={c.value}
                  onChange={(e) => setContact(i, 'value', e.target.value)}
                  placeholder="value"
                />

                {/* Primary */}
                <label
                  style={{
                    display:    'flex',
                    alignItems: 'center',
                    gap:        'var(--space-1)',
                    fontSize:   'var(--font-size-xs)',
                    color:      'var(--color-text-muted)',
                    cursor:     'pointer',
                    whiteSpace: 'nowrap',
                    flexShrink: 0,
                  }}
                >
                  <input
                    type="radio"
                    name={`primary-${c.type}`}
                    checked={!!c.primary}
                    onChange={() => setPrimaryContact(i)}
                    style={{ accentColor: 'var(--color-primary)', cursor: 'pointer' }}
                  />
                  Primary
                </label>

                {/* Remove */}
                <button
                  type="button"
                  onClick={() => removeContact(i)}
                  aria-label="Remove contact"
                  style={{
                    background: 'none',
                    border:     'none',
                    cursor:     'pointer',
                    padding:    'var(--space-1)',
                    color:      'var(--color-danger)',
                    display:    'flex',
                    alignItems: 'center',
                    flexShrink: 0,
                    opacity:    0.7,
                  }}
                  onMouseEnter={(e) => { e.currentTarget.style.opacity = '1' }}
                  onMouseLeave={(e) => { e.currentTarget.style.opacity = '0.7' }}
                >
                  <Icon name="close" size={14} />
                </button>
              </div>
            ))}
          </div>

          <Button
            variant="ghost"
            size="sm"
            onClick={addContact}
            style={{ marginTop: form.contacts.length > 0 ? 'var(--space-3)' : 0 }}
          >
            <Icon name="plus" size={14} />
            Add Contact
          </Button>
        </Card>

        {/* ── Notes card ─────────────────────────────────────────────────────── */}
        <Card title="Notes">
          {form.notes.length > 0 && (
            <div style={{ display: 'flex', flexDirection: 'column', gap: 'var(--space-2)', marginBottom: 'var(--space-4)' }}>
              {form.notes.map((note, i) => (
                <div
                  key={i}
                  style={{
                    backgroundColor: 'var(--color-bg-abyss)',
                    border:          '1px solid var(--color-border)',
                    borderRadius:    'var(--radius-md)',
                    padding:         'var(--space-3)',
                  }}
                >
                  {editingNoteIdx === i ? (
                    <div style={{ display: 'flex', flexDirection: 'column', gap: 'var(--space-2)' }}>
                      <FormField
                        label=""
                        name={`edit_note_${i}`}
                        type="textarea"
                        value={editingNoteText}
                        onChange={(e) => setEditingNoteText(e.target.value)}
                        rows={3}
                        inputProps={{
                          autoFocus: true,
                          onKeyDown: (e) => {
                            if (e.key === 'Enter' && (e.ctrlKey || e.metaKey)) saveEditNote(i)
                            if (e.key === 'Escape') setEditingNoteIdx(null)
                          },
                        }}
                      />
                      <div style={{ display: 'flex', gap: 'var(--space-2)' }}>
                        <Button variant="primary" size="sm" onClick={() => saveEditNote(i)}>Save</Button>
                        <Button variant="ghost"   size="sm" onClick={() => setEditingNoteIdx(null)}>Cancel</Button>
                      </div>
                    </div>
                  ) : (
                    <>
                      <p style={{ fontSize: 'var(--font-size-sm)', color: 'var(--color-text-primary)', marginBottom: 'var(--space-1)' }}>
                        {note.text}
                      </p>
                      <div style={{ display: 'flex', alignItems: 'center', justifyContent: 'space-between' }}>
                        <span style={{ fontSize: 'var(--font-size-xs)', color: 'var(--color-text-muted)' }}>
                          {note.by} · {note.at ? fmtDate(note.at) : ''}
                        </span>
                        <div style={{ display: 'flex', gap: 'var(--space-3)' }}>
                          <button
                            type="button"
                            onClick={() => startEditNote(i)}
                            style={{
                              background: 'none', border: 'none', cursor: 'pointer',
                              fontSize:   'var(--font-size-xs)', color: 'var(--color-text-accent)', padding: 0,
                            }}
                          >
                            Edit
                          </button>
                          <button
                            type="button"
                            onClick={() => removeNote(i)}
                            style={{
                              background: 'none', border: 'none', cursor: 'pointer',
                              fontSize:   'var(--font-size-xs)', color: 'var(--color-danger)', padding: 0,
                            }}
                          >
                            Remove
                          </button>
                        </div>
                      </div>
                    </>
                  )}
                </div>
              ))}
            </div>
          )}

          {/* New note */}
          <div style={{ display: 'flex', gap: 'var(--space-3)', alignItems: 'flex-end' }}>
            <div style={{ flex: 1 }}>
              <FormField
                label=""
                name="new_note"
                type="textarea"
                value={newNoteText}
                onChange={(e) => setNewNoteText(e.target.value)}
                rows={2}
                placeholder="Add a note…"
                inputProps={{
                  onKeyDown: (e) => {
                    if (e.key === 'Enter' && (e.ctrlKey || e.metaKey)) addNote()
                  },
                }}
              />
            </div>
            <Button
              variant="secondary"
              size="md"
              onClick={addNote}
              disabled={!newNoteText.trim()}
              style={{ flexShrink: 0 }}
            >
              Add
            </Button>
          </div>
        </Card>

      </div>

      {/* ── Danger Zone ───────────────────────────────────────────────────────── */}
      {isEdit && canEdit && (
        <Card variant="outlined">
          <div style={{ display: 'flex', alignItems: 'center', justifyContent: 'space-between', flexWrap: 'wrap', gap: 'var(--space-4)' }}>
            <div>
              <h3 style={{
                fontSize:   'var(--font-size-base)',
                fontWeight: 'var(--font-weight-semibold)',
                color:      'var(--color-danger)',
                margin:     0,
              }}>
                Danger Zone
              </h3>
              <p style={{
                fontSize: 'var(--font-size-sm)',
                color:    'var(--color-text-muted)',
                marginTop:'var(--space-1)',
              }}>
                Permanently delete this customer record. This action cannot be undone.
              </p>
            </div>
            <Button
              variant="danger"
              size="md"
              onClick={() => setShowDeleteDialog(true)}
            >
              Delete Customer
            </Button>
          </div>
        </Card>
      )}

      {/* ── Delete confirmation ───────────────────────────────────────────────── */}
      <ConfirmDialog
        open={showDeleteDialog}
        variant="danger"
        title="Delete Customer"
        message={`Are you sure you want to delete ${[form.name, form.surname].filter(Boolean).join(' ') || 'this customer'}? This action cannot be undone.`}
        confirmLabel="Delete"
        loading={deleting}
        onConfirm={handleDelete}
        onCancel={() => setShowDeleteDialog(false)}
      />

    </div>
  )
}
