// frontend/src/pages/manufacturing/DeviceInventoryDetail.jsx

import { useState, useEffect, useCallback } from 'react'
import { useParams, useNavigate } 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 StatusBadge from '@/components/ui/StatusBadge'
import Spinner from '@/components/ui/Spinner'
import Icon from '@/components/ui/Icon'
import Modal from '@/components/ui/Modal'
import FormField from '@/components/ui/FormField'
import ConfirmDialog from '@/components/ui/ConfirmDialog'
import { fmtDateTimeMedium, toDatetimeLocal as toDatetimeLocalFmt } from '@/lib/formatters'
import DeleteDeviceModal from '@/modals/engineering/manufacturing/DeleteDeviceModal'

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

const BOARD_TYPE_LABELS = {
  vesper: 'Vesper', vesper_plus: 'Vesper+', vesper_pro: 'Vesper Pro',
  agnus: 'Agnus', agnus_mini: 'Agnus Mini',
  chronos: 'Chronos', chronos_pro: 'Chronos Pro',
}

const STATUS_VARIANT = {
  manufactured: 'neutral', flashed: 'info', provisioned: 'warning',
  sold: 'success', claimed: 'success', decommissioned: 'danger',
}

// Each step has CSS var refs for color + per-step hex accents for gradient connectors
const LIFECYCLE = [
  { key: 'manufactured',   label: 'Manufactured',   icon: '🔩', colorVar: 'var(--color-info)',    bgVar: 'var(--color-info-bg)',          accentHex: '#4da8c8', bgHex: '#1a2e3f' },
  { key: 'flashed',        label: 'Flashed',         icon: '⚡', colorVar: 'var(--color-warning)', bgVar: 'var(--color-warning-bg)',       accentHex: '#c9a83c', bgHex: '#2e2800' },
  { key: 'provisioned',    label: 'Provisioned',     icon: '📡', colorVar: 'var(--color-primary)', bgVar: 'var(--color-primary-subtle)',   accentHex: '#c97a28', bgHex: '#2e1a00' },
  { key: 'sold',           label: 'Sold',            icon: '📦', colorVar: 'var(--color-success)', bgVar: 'var(--color-success-bg)',       accentHex: '#3daa6a', bgHex: '#0e2a1a' },
  { key: 'claimed',        label: 'Claimed',         icon: '✅', colorVar: 'var(--color-success)', bgVar: 'var(--color-success-bg)',       accentHex: '#22c55e', bgHex: '#0a2416' },
  { key: 'decommissioned', label: 'Decommissioned',  icon: '🗑', colorVar: 'var(--color-danger)',  bgVar: 'var(--color-danger-bg)',        accentHex: '#ef4444', bgHex: '#2a0a0a' },
]

const STEP_INDEX = Object.fromEntries(LIFECYCLE.map((s, i) => [s.key, i]))

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

function formatHwVersion(v) {
  if (!v) return '—'
  if (/^\d+\.\d+/.test(v)) return `Rev ${v}`
  const n = parseInt(v, 10)
  return isNaN(n) ? `Rev ${v}` : `Rev ${n}.0`
}

function formatDate(iso) { return fmtDateTimeMedium(iso) }
function toDatetimeLocal(iso) { return toDatetimeLocalFmt(iso) }

// ─── Field display ────────────────────────────────────────────────────────────

function Field({ label, value, mono = false }) {
  return (
    <div>
      <p style={{ fontSize: 'var(--font-size-xs)', fontWeight: 'var(--font-weight-semibold)', color: 'var(--color-text-muted)', textTransform: 'uppercase', letterSpacing: 'var(--tracking-wide)', marginBottom: 'var(--space-1)' }}>
        {label}
      </p>
      <p style={{ fontSize: 'var(--font-size-sm)', fontFamily: mono ? 'var(--font-family-mono)' : undefined, color: 'var(--color-text-primary)' }}>
        {value || '—'}
      </p>
    </div>
  )
}

// ─── Customer Search Modal ────────────────────────────────────────────────────

function CustomerSearchModal({ onSelect, onClose }) {
  const [query, setQuery] = useState('')
  const [results, setResults] = useState([])
  const [searching, setSearching] = useState(false)

  const search = useCallback(async (q) => {
    setSearching(true)
    try {
      const data = await api.get(`/manufacturing/customers/search?q=${encodeURIComponent(q)}`)
      setResults(data.results || [])
    } catch {
      setResults([])
    } finally {
      setSearching(false)
    }
  }, [])

  useEffect(() => {
    const t = setTimeout(() => search(query), 250)
    return () => clearTimeout(t)
  }, [query, search])

  return (
    <Modal open onClose={onClose} title="Assign to Customer" size="sm">
      <div style={{ display: 'flex', flexDirection: 'column', gap: 'var(--space-3)' }}>
        <FormField
          label="Search"
          name="customer_search"
          type="text"
          value={query}
          onChange={(e) => setQuery(e.target.value)}
          placeholder="Name, email, phone, org…"
          autoFocus
        />
        <div style={{ border: '1px solid var(--color-border)', borderRadius: 'var(--radius-md)', overflow: 'hidden', maxHeight: 260, overflowY: 'auto' }}>
          {results.length === 0 ? (
            <p style={{ padding: 'var(--space-3)', fontSize: 'var(--font-size-sm)', color: 'var(--color-text-muted)' }}>
              {searching ? 'Searching…' : query ? 'No customers found.' : 'Type to search customers…'}
            </p>
          ) : results.map((c) => {
            const fullName = [c.name, c.surname].filter(Boolean).join(' ') || c.email || c.id
            return (
              <button key={c.id} type="button" onClick={() => onSelect(c)}
                style={{
                  display: 'block', width: '100%', textAlign: 'left',
                  padding: 'var(--space-2) var(--space-3)',
                  backgroundColor: 'var(--color-bg-surface)',
                  borderBottom: '1px solid var(--color-border)',
                  cursor: 'pointer', color: 'var(--color-text-primary)',
                  fontSize: 'var(--font-size-sm)',
                }}
                onMouseEnter={(e) => e.currentTarget.style.backgroundColor = 'var(--color-bg-elevated)'}
                onMouseLeave={(e) => e.currentTarget.style.backgroundColor = 'var(--color-bg-surface)'}
              >
                <span style={{ fontWeight: 'var(--font-weight-semibold)' }}>{fullName}</span>
                {c.organization && <span style={{ display: 'block', fontSize: 'var(--font-size-xs)', color: 'var(--color-text-muted)' }}>{c.organization}</span>}
                {c.city && <span style={{ display: 'block', fontSize: 'var(--font-size-xs)', color: 'var(--color-text-muted)' }}>{c.city}</span>}
              </button>
            )
          })}
        </div>
      </div>
    </Modal>
  )
}

// ─── Lifecycle Edit Modal ─────────────────────────────────────────────────────

function LifecycleEditModal({ open, entry, stepMeta, isCurrent, onSave, onDelete, onClose }) {
  const isNew = !entry
  const [dateVal, setDateVal] = useState(() => toDatetimeLocal(isNew ? new Date().toISOString() : entry?.date))
  const [note, setNote]       = useState(entry?.note || '')
  const [saving, setSaving]   = useState(false)
  const [confirmDel, setConfirmDel] = useState(false)

  useEffect(() => {
    if (open) {
      setDateVal(toDatetimeLocal(isNew ? new Date().toISOString() : entry?.date))
      setNote(entry?.note || '')
      setConfirmDel(false)
    }
  }, [open, entry, isNew])

  const handleSave = async () => {
    setSaving(true)
    try {
      const isoDate = dateVal ? new Date(dateVal).toISOString() : new Date().toISOString()
      await onSave(isoDate, note)
      onClose()
    } finally {
      setSaving(false)
    }
  }

  const handleDelete = async () => {
    setSaving(true)
    try {
      await onDelete()
      onClose()
    } finally {
      setSaving(false)
      setConfirmDel(false)
    }
  }

  return (
    <Modal
      open={open}
      onClose={onClose}
      title={isNew ? `Set ${stepMeta?.label}` : `Edit ${stepMeta?.label}`}
      size="sm"
      footer={
        <div style={{ display: 'flex', gap: 'var(--space-3)', justifyContent: 'space-between', width: '100%' }}>
          <div>
            {!isNew && !isCurrent && (
              <Button variant="danger" size="sm" onClick={() => setConfirmDel(true)}>
                Delete Step
              </Button>
            )}
          </div>
          <div style={{ display: 'flex', gap: 'var(--space-3)' }}>
            <Button variant="ghost" onClick={onClose}>Cancel</Button>
            <Button variant="primary" onClick={handleSave} loading={saving}>
              {isNew ? 'Create' : 'Save'}
            </Button>
          </div>
        </div>
      }
    >
      <div style={{ display: 'flex', flexDirection: 'column', gap: 'var(--space-4)' }}>
        <FormField
          label="Date & Time"
          name="lc_date"
          type="datetime-local"
          value={dateVal}
          onChange={(e) => setDateVal(e.target.value)}
        />
        <FormField
          label="Note (optional)"
          name="lc_note"
          type="textarea"
          value={note}
          onChange={(e) => setNote(e.target.value)}
          placeholder="Add a note about this step…"
          maxLength={150}
        />
        {note.length > 0 && (
          <p style={{ fontSize: 'var(--font-size-xs)', textAlign: 'right', color: note.length > 130 ? 'var(--color-warning)' : 'var(--color-text-muted)', marginTop: 'calc(-1 * var(--space-3))' }}>
            {note.length}/150
          </p>
        )}
      </div>

      <ConfirmDialog
        open={confirmDel}
        variant="danger"
        title="Delete lifecycle step?"
        message={`This will permanently remove the ${stepMeta?.label} record.`}
        confirmLabel="Yes, Delete"
        onConfirm={handleDelete}
        onCancel={() => setConfirmDel(false)}
      />
    </Modal>
  )
}

// ─── Lifecycle Tracker ────────────────────────────────────────────────────────

function LifecycleTracker({ device, canEdit, onStatusChange, onEditEntry, statusError }) {
  const currentIndex = STEP_INDEX[device.mfg_status] ?? 0
  const [hoveredIndex, setHoveredIndex] = useState(null)

  const history = device.lifecycle_history || []
  const historyMap = {}
  history.forEach((entry) => { historyMap[entry.status_id || entry.status] = entry })

  return (
    <div>
      {statusError && (
        <div style={{ marginBottom: 'var(--space-3)', padding: 'var(--space-3)', borderRadius: 'var(--radius-md)', backgroundColor: 'var(--color-danger-bg)', border: '1px solid var(--color-danger)', color: 'var(--color-danger)', fontSize: 'var(--font-size-xs)' }}>
          {statusError}
        </div>
      )}

      <div style={{ display: 'flex', flexDirection: 'column', gap: 0 }}>
        {LIFECYCLE.map((step, i) => {
          const isCurrent = i === currentIndex
          const isPast    = i < currentIndex
          const isFuture  = i > currentIndex
          const isLast    = i === LIFECYCLE.length - 1
          const entry     = historyMap[step.key]
          const hasData   = !!entry
          const isHovered = hoveredIndex === i

          return (
            <div key={step.key} style={{ display: 'flex', alignItems: 'stretch', gap: 0 }}>
              {/* Left rail */}
              <div style={{ display: 'flex', flexDirection: 'column', alignItems: 'center', width: 44, flexShrink: 0 }}>
                {/* Step circle */}
                <div
                  style={{
                    marginTop: 3,
                    width: 38,
                    height: 38,
                    borderRadius: '50%',
                    border: `2px solid ${isCurrent ? step.accentHex : isPast ? `${step.accentHex}90` : isHovered && canEdit ? `${step.accentHex}60` : `${step.accentHex}30`}`,
                    backgroundColor: isCurrent ? step.bgVar : isPast ? step.bgVar : isHovered && canEdit ? `${step.bgHex}99` : `${step.bgHex}55`,
                    display: 'flex',
                    alignItems: 'center',
                    justifyContent: 'center',
                    fontSize: isCurrent ? '1rem' : '0.85rem',
                    flexShrink: 0,
                    opacity: isFuture && !isHovered ? 0.35 : 1,
                    boxShadow: isCurrent ? `0 0 0 3px ${step.accentHex}40, 0 0 14px ${step.accentHex}30` : 'none',
                    position: 'relative',
                    transition: 'all 0.2s',
                    pointerEvents: 'none',
                  }}
                >
                  {isPast && (
                    <svg width="14" height="14" viewBox="0 0 14 14" fill="none"
                      style={{ position: 'absolute', bottom: -2, right: -2, background: 'var(--color-bg-surface)', borderRadius: '50%' }}>
                      <circle cx="7" cy="7" r="6" fill={step.accentHex} opacity="0.9"/>
                      <path d="M4.5 7L6.2 8.7L9.5 5.3" stroke="white" strokeWidth="1.4" strokeLinecap="round" strokeLinejoin="round"/>
                    </svg>
                  )}
                  <span style={{ fontSize: isCurrent ? '1rem' : '0.85rem' }}>{step.icon}</span>
                </div>

                {/* Connector line */}
                {!isLast && (
                  <div style={{
                    width: 2,
                    flexGrow: 1,
                    minHeight: 8,
                    background: isPast || isCurrent
                      ? `linear-gradient(to bottom, ${step.accentHex}90, ${LIFECYCLE[i+1].accentHex}50)`
                      : `linear-gradient(to bottom, ${step.accentHex}30, ${LIFECYCLE[i+1].accentHex}20)`,
                    margin: '2px 0',
                    borderRadius: 1,
                    transition: 'background 0.3s',
                  }} />
                )}
              </div>

              {/* Right clickable card */}
              <div
                role={canEdit ? 'button' : undefined}
                tabIndex={canEdit ? 0 : undefined}
                onMouseEnter={() => setHoveredIndex(i)}
                onMouseLeave={() => setHoveredIndex(null)}
                onClick={(e) => {
                  if (e.target.closest('[data-edit-btn]')) return
                  if (!canEdit) return
                  onStatusChange(step.key)
                }}
                onKeyDown={(e) => {
                  if ((e.key === 'Enter' || e.key === ' ') && canEdit) onStatusChange(step.key)
                }}
                style={{
                  flex: 1,
                  marginLeft: 10,
                  marginBottom: isLast ? 0 : 6,
                  padding: '10px 12px',
                  borderRadius: 10,
                  border: `1px solid ${
                    isCurrent
                      ? `${step.accentHex}cc`
                      : isHovered && canEdit
                      ? `${step.accentHex}80`
                      : isPast
                      ? `${step.accentHex}40`
                      : `${step.accentHex}30`
                  }`,
                  backgroundColor: isCurrent
                    ? step.bgVar
                    : isHovered && canEdit
                    ? `${step.bgHex}cc`
                    : isPast
                    ? `${step.bgHex}66`
                    : `${step.bgHex}55`,
                  opacity: isFuture && !isHovered ? 0.5 : isPast && !isHovered ? 0.6 : 1,
                  transition: 'border-color 0.18s, background-color 0.18s, opacity 0.18s',
                  cursor: canEdit ? 'pointer' : 'default',
                  display: 'flex',
                  alignItems: hasData ? 'flex-start' : 'center',
                  justifyContent: 'space-between',
                  gap: 8,
                  minHeight: 44,
                }}
              >
                <div style={{ flex: 1, minWidth: 0 }}>
                  {/* Label row */}
                  <div style={{ display: 'flex', alignItems: 'center', gap: 8, marginBottom: hasData ? 3 : 0 }}>
                    <span style={{
                      fontSize: '0.78rem',
                      fontWeight: 700,
                      letterSpacing: '0.05em',
                      textTransform: 'uppercase',
                      color: isCurrent ? step.colorVar : isPast ? `${step.accentHex}bb` : isHovered ? `${step.accentHex}90` : 'var(--color-text-muted)',
                    }}>
                      {step.label}
                    </span>
                    {isCurrent && (
                      <span style={{
                        fontSize: '0.58rem',
                        fontWeight: 700,
                        letterSpacing: '0.1em',
                        textTransform: 'uppercase',
                        color: step.colorVar,
                        backgroundColor: `${step.accentHex}22`,
                        border: `1px solid ${step.accentHex}45`,
                        padding: '1px 6px',
                        borderRadius: 4,
                      }}>CURRENT</span>
                    )}
                  </div>

                  {/* Date + set_by */}
                  {hasData && (
                    <p style={{ fontSize: '0.7rem', color: isCurrent ? step.colorVar : 'var(--color-text-muted)', margin: 0, marginBottom: entry.note ? 2 : 0, opacity: isCurrent ? 0.7 : 1 }}>
                      {formatDate(entry.date)}
                      {entry.set_by && <span style={{ marginLeft: 6, opacity: 0.65 }}>· {entry.set_by}</span>}
                    </p>
                  )}

                  {/* Note */}
                  {entry?.note && (
                    <p style={{ fontSize: '0.7rem', color: 'var(--color-text-secondary)', margin: 0, marginTop: 1, fontStyle: 'italic', whiteSpace: 'pre-wrap', wordBreak: 'break-word' }}>
                      "{entry.note}"
                    </p>
                  )}
                </div>

                {/* Edit button — visible on hover */}
                {canEdit && (
                  <button
                    data-edit-btn
                    type="button"
                    onClick={(e) => {
                      e.stopPropagation()
                      onEditEntry(i, entry || null)
                    }}
                    style={{
                      fontSize: '0.58rem',
                      fontWeight: 700,
                      letterSpacing: '0.1em',
                      textTransform: 'uppercase',
                      color: isHovered ? step.colorVar : 'transparent',
                      backgroundColor: 'transparent',
                      border: `1px solid ${isHovered ? `${step.accentHex}55` : 'transparent'}`,
                      borderRadius: 5,
                      padding: '2px 8px',
                      cursor: 'pointer',
                      flexShrink: 0,
                      alignSelf: 'flex-start',
                      transition: 'all 0.15s',
                      pointerEvents: isHovered ? 'auto' : 'none',
                    }}
                    onMouseEnter={(e) => {
                      e.currentTarget.style.backgroundColor = step.bgVar
                      e.currentTarget.style.borderColor = `${step.accentHex}80`
                    }}
                    onMouseLeave={(e) => {
                      e.currentTarget.style.backgroundColor = 'transparent'
                    }}
                  >
                    EDIT
                  </button>
                )}
              </div>
            </div>
          )
        })}
      </div>
    </div>
  )
}

// ─── Main Page ────────────────────────────────────────────────────────────────

export default function DeviceInventoryDetail() {
  const { sn }     = useParams()
  const navigate   = useNavigate()
  const { hasPermission } = useAuth()
  const canEdit    = hasPermission('manufacturing', 'edit')
  const canDelete  = hasPermission('manufacturing', 'delete')

  const [device, setDevice]               = useState(null)
  const [loading, setLoading]             = useState(true)
  const [error, setError]                 = useState('')
  const [assignedCustomer, setAssignedCustomer] = useState(null)
  const [resolvedUsers, setResolvedUsers] = useState([])

  // Assignment
  const [showCustomerModal, setShowCustomerModal] = useState(false)
  const [assignSaving, setAssignSaving]           = useState(false)
  const [assignError, setAssignError]             = useState('')

  // Status
  const [statusSaving, setStatusSaving] = useState(false)
  const [statusError, setStatusError]   = useState('')

  // Lifecycle edit modal
  const [editModalData, setEditModalData] = useState(null) // { stepIndex, entry|null }

  // Delete modal
  const [showDelete, setShowDelete] = useState(false)

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

  const loadDevice = useCallback(async () => {
    setLoading(true); setError('')
    try {
      const data = await api.get(`/manufacturing/devices/${sn}`)
      setDevice(data)
      if (data.customer_id) {
        api.get(`/manufacturing/customers/${data.customer_id}`)
          .then((c) => setAssignedCustomer(c))
          .catch(() => setAssignedCustomer(null))
      } else {
        setAssignedCustomer(null)
      }
      if (data.user_list?.length) {
        Promise.all(
          data.user_list.map((uid) =>
            api.get(`/users/${uid}`)
              .then((u) => ({ uid, display_name: u.display_name || '', email: u.email || '' }))
              .catch(() => ({ uid, display_name: '', email: '' }))
          )
        ).then(setResolvedUsers)
      } else {
        setResolvedUsers([])
      }
    } catch (err) {
      setError(err.message)
    } finally {
      setLoading(false)
    }
  }, [sn])

  useEffect(() => { loadDevice() }, [loadDevice])

  // ─── Status change ───────────────────────────────────────────────────────

  const handleStatusChange = async (newStatus) => {
    if (newStatus === device?.mfg_status) return
    setStatusError(''); setStatusSaving(true)
    try {
      const updated = await api.request(`/manufacturing/devices/${sn}/status`, {
        method: 'PATCH',
        body: JSON.stringify({ status: newStatus }),
      })
      setDevice(updated)
    } catch (err) {
      setStatusError(err.message)
    } finally {
      setStatusSaving(false)
    }
  }

  // ─── Customer assignment ─────────────────────────────────────────────────

  const handleSelectCustomer = async (customer) => {
    setShowCustomerModal(false)
    setAssignError(''); setAssignSaving(true)
    try {
      const updated = await api.request(`/manufacturing/devices/${sn}/assign`, {
        method: 'POST',
        body: JSON.stringify({ customer_id: customer.id }),
      })
      setDevice(updated)
      setAssignedCustomer(customer)
    } catch (err) {
      setAssignError(err.message)
    } finally {
      setAssignSaving(false)
    }
  }

  // ─── Lifecycle edit ──────────────────────────────────────────────────────

  const history = device?.lifecycle_history || []
  const historyIndexMap = {}
  history.forEach((entry, idx) => { historyIndexMap[entry.status_id || entry.status] = idx })

  const handleSaveLifecycle = async (stepIndex, date, note) => {
    const stepKey = LIFECYCLE[stepIndex]?.key
    const arrayIndex = historyIndexMap[stepKey]
    if (arrayIndex === undefined) {
      const updated = await api.request(`/manufacturing/devices/${sn}/lifecycle`, {
        method: 'POST',
        body: JSON.stringify({ status_id: stepKey, date, note }),
      })
      setDevice(updated)
    } else {
      const updated = await api.request(`/manufacturing/devices/${sn}/lifecycle`, {
        method: 'PATCH',
        body: JSON.stringify({ index: arrayIndex, date, note }),
      })
      setDevice(updated)
    }
    setEditModalData(null)
  }

  const handleDeleteLifecycleStep = async (stepIndex) => {
    const stepKey = LIFECYCLE[stepIndex]?.key
    const arrayIndex = historyIndexMap[stepKey]
    if (arrayIndex === undefined) { setEditModalData(null); return }
    const updated = await api.request(`/manufacturing/devices/${sn}/lifecycle/${arrayIndex}`, {
      method: 'DELETE',
    })
    setDevice(updated)
    setEditModalData(null)
  }

  // ─── Render ──────────────────────────────────────────────────────────────

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

  if (error || !device) {
    return (
      <div className="page-wrapper">
        <div style={{ padding: 'var(--space-8)', textAlign: 'center' }}>
          <p style={{ color: 'var(--color-danger)', fontSize: 'var(--font-size-sm)' }}>{error || 'Device not found.'}</p>
          <Button variant="secondary" onClick={() => navigate('/manufacturing')} style={{ marginTop: 'var(--space-4)' }}>
            Back to Inventory
          </Button>
        </div>
      </div>
    )
  }

  const boardLabel = BOARD_TYPE_LABELS[device.hw_type] || device.hw_type
  const userList   = device.user_list || []

  const editStepMeta  = editModalData ? LIFECYCLE[editModalData.stepIndex] : null
  const editIsCurrent = editModalData ? LIFECYCLE[editModalData.stepIndex]?.key === device.mfg_status : false

  return (
    <div className="page-wrapper page-wrapper--capped">
      <PageHeader
        title={
          <span style={{ display: 'inline-flex', alignItems: 'center', gap: 'var(--space-3)' }}>
            <span style={{ fontFamily: 'var(--font-family-mono)' }}>{device.serial_number}</span>
            <StatusBadge variant={STATUS_VARIANT[device.mfg_status] || 'neutral'}>
              {device.mfg_status}
            </StatusBadge>
          </span>
        }
        subtitle={`${device.name || device.device_name || '—'} · ${boardLabel} · ${formatHwVersion(device.hw_version)}`}
      >
        {canEdit && (
          <Button variant="secondary" size="md" onClick={() => navigate(`/manufacturing/provision?sn=${sn}`)}>
            Flash
          </Button>
        )}
        {canDelete && (
          <Button variant="danger" size="md" onClick={() => setShowDelete(true)}>
            Delete
          </Button>
        )}
      </PageHeader>

      <div style={{ display: 'grid', gridTemplateColumns: '3fr 2fr', gap: 'var(--space-6)', alignItems: 'start' }}>

        {/* ── Left column ────────────────────────────────────────────────── */}
        <div style={{ display: 'flex', flexDirection: 'column', gap: 'var(--space-6)' }}>

          {/* Device Information */}
          <Card title="Device Information">
            <div style={{ display: 'grid', gridTemplateColumns: 'repeat(2, 1fr)', gap: 'var(--space-5)' }}>
              <Field label="Serial Number"   value={device.serial_number}               mono />
              <Field label="Batch ID"        value={device.batch_id || device.mfg_batch_id} mono />
              <Field label="Hardware Family" value={boardLabel} />
              <Field label="HW Version"      value={formatHwVersion(device.hw_version)} mono />
              <Field label="Created At"      value={formatDate(device.created_at)} />
              <Field label="Device Name"     value={device.name || device.device_name} />
              <div style={{ gridColumn: '1 / -1' }}>
                <p style={{ fontSize: 'var(--font-size-xs)', fontWeight: 'var(--font-weight-semibold)', color: 'var(--color-text-muted)', textTransform: 'uppercase', letterSpacing: 'var(--tracking-wide)', marginBottom: 'var(--space-1)' }}>
                  Document ID
                </p>
                <p style={{ fontSize: 'var(--font-size-sm)', fontFamily: 'var(--font-family-mono)', color: 'var(--color-text-muted)' }}>
                  {device.id || '—'}
                </p>
              </div>
            </div>
          </Card>

          {/* Assignment */}
          <Card title="Assignment">
            {assignError && (
              <div style={{ marginBottom: 'var(--space-3)', padding: 'var(--space-3)', borderRadius: 'var(--radius-md)', backgroundColor: 'var(--color-danger-bg)', border: '1px solid var(--color-danger)', color: 'var(--color-danger)', fontSize: 'var(--font-size-xs)' }}>
                {assignError}
              </div>
            )}

            {/* Customer sub-section */}
            <div style={{ marginBottom: 'var(--space-5)' }}>
              <p style={{ fontSize: 'var(--font-size-xs)', fontWeight: 'var(--font-weight-semibold)', color: 'var(--color-text-muted)', textTransform: 'uppercase', letterSpacing: 'var(--tracking-wide)', marginBottom: 'var(--space-2)' }}>
                Customer
              </p>
              {device.customer_id ? (
                <div
                  role="button"
                  tabIndex={0}
                  onClick={(e) => { if (!e.target.closest('[data-reassign-btn]')) navigate(`/crm/customers/${device.customer_id}`) }}
                  onKeyDown={(e) => { if ((e.key === 'Enter' || e.key === ' ') && !e.target.closest('[data-reassign-btn]')) navigate(`/crm/customers/${device.customer_id}`) }}
                  style={{
                    display: 'flex', alignItems: 'center', gap: 'var(--space-3)',
                    padding: 'var(--space-2) var(--space-3)',
                    borderRadius: 'var(--radius-md)',
                    border: '1px solid var(--color-border)',
                    backgroundColor: 'var(--color-bg-surface)',
                    cursor: 'pointer',
                    transition: 'border-color 0.15s',
                  }}
                  onMouseEnter={(e) => e.currentTarget.style.borderColor = 'var(--color-border-strong)'}
                  onMouseLeave={(e) => e.currentTarget.style.borderColor = 'var(--color-border)'}
                >
                  <div style={{
                    width: 28, height: 28, borderRadius: '50%', flexShrink: 0,
                    backgroundColor: 'var(--color-primary-subtle)',
                    border: '1px solid var(--color-border)',
                    display: 'flex', alignItems: 'center', justifyContent: 'center',
                    fontSize: 'var(--font-size-xs)', fontWeight: 'var(--font-weight-bold)',
                    color: 'var(--color-primary)',
                  }}>
                    {(assignedCustomer?.name || '?')[0].toUpperCase()}
                  </div>
                  <div style={{ flex: 1, minWidth: 0 }}>
                    <p style={{ fontSize: 'var(--font-size-sm)', fontWeight: 'var(--font-weight-medium)', color: 'var(--color-text-primary)' }}>
                      {[assignedCustomer?.name, assignedCustomer?.surname].filter(Boolean).join(' ') || 'Customer'}
                    </p>
                    {assignedCustomer?.organization && <p style={{ fontSize: 'var(--font-size-xs)', color: 'var(--color-text-muted)' }}>{assignedCustomer.organization}</p>}
                  </div>
                  {canEdit && (
                    <Button
                      data-reassign-btn
                      variant="ghost"
                      size="sm"
                      disabled={assignSaving}
                      onClick={(e) => { e.stopPropagation(); setShowCustomerModal(true) }}
                    >
                      Reassign
                    </Button>
                  )}
                </div>
              ) : (
                <div>
                  <p style={{ fontSize: 'var(--font-size-sm)', color: 'var(--color-text-muted)', marginBottom: 'var(--space-3)' }}>
                    No customer assigned.
                  </p>
                  {canEdit && (
                    <Button variant="secondary" size="sm" disabled={assignSaving} onClick={() => setShowCustomerModal(true)}>
                      + Assign to Customer
                    </Button>
                  )}
                </div>
              )}
            </div>

            {/* User Assignment sub-section */}
            <div>
              <p style={{ fontSize: 'var(--font-size-xs)', fontWeight: 'var(--font-weight-semibold)', color: 'var(--color-text-muted)', textTransform: 'uppercase', letterSpacing: 'var(--tracking-wide)', marginBottom: 'var(--space-2)' }}>
                Assigned Users {userList.length > 0 && `(${userList.length})`}
              </p>
              {userList.length === 0 ? (
                <p style={{ fontSize: 'var(--font-size-sm)', color: 'var(--color-text-muted)' }}>
                  No users assigned to this device.
                </p>
              ) : (
                <div style={{ display: 'flex', flexDirection: 'column', gap: 'var(--space-2)' }}>
                  {userList.map((uid) => {
                    const resolved    = resolvedUsers.find((u) => u.uid === uid)
                    const displayName = resolved?.display_name || ''
                    const email       = resolved?.email || ''
                    const initials    = (displayName || email || uid)[0]?.toUpperCase() || 'U'
                    return (
                      <div
                        key={uid}
                        role="button"
                        tabIndex={0}
                        onClick={() => navigate(`/users/${uid}`)}
                        onKeyDown={(e) => { if (e.key === 'Enter' || e.key === ' ') navigate(`/users/${uid}`) }}
                        style={{
                          display: 'flex', alignItems: 'center', gap: 'var(--space-3)',
                          padding: 'var(--space-2) var(--space-3)',
                          borderRadius: 'var(--radius-md)',
                          border: '1px solid var(--color-border)',
                          backgroundColor: 'var(--color-bg-surface)',
                          cursor: 'pointer',
                          transition: 'border-color 0.15s',
                        }}
                        onMouseEnter={(e) => e.currentTarget.style.borderColor = 'var(--color-border-strong)'}
                        onMouseLeave={(e) => e.currentTarget.style.borderColor = 'var(--color-border)'}
                      >
                        <div style={{
                          width: 28, height: 28, borderRadius: '50%', flexShrink: 0,
                          backgroundColor: 'var(--color-success-bg)',
                          border: '1px solid var(--color-border)',
                          display: 'flex', alignItems: 'center', justifyContent: 'center',
                          fontSize: 'var(--font-size-xs)', fontWeight: 'var(--font-weight-bold)',
                          color: 'var(--color-success)',
                        }}>
                          {initials}
                        </div>
                        <div style={{ flex: 1, minWidth: 0 }}>
                          {displayName
                            ? <p style={{ fontSize: 'var(--font-size-sm)', fontWeight: 'var(--font-weight-medium)', color: 'var(--color-text-primary)' }}>{displayName}</p>
                            : <p style={{ fontSize: 'var(--font-size-sm)', fontFamily: 'var(--font-family-mono)', color: 'var(--color-text-muted)' }}>{uid}</p>
                          }
                          {email && <p style={{ fontSize: 'var(--font-size-xs)', color: 'var(--color-text-muted)' }}>{email}</p>}
                        </div>
                        <Icon name="chevron-right" size={14} color="var(--color-text-muted)" />
                      </div>
                    )
                  })}
                </div>
              )}
            </div>
          </Card>

        </div>

        {/* ── Right column: lifecycle ─────────────────────────────────────── */}
        <Card
          title="Product Lifecycle"
          subtitle={canEdit ? 'Click a step to edit' : undefined}
        >
          {(statusSaving) && (
            <p style={{ fontSize: 'var(--font-size-xs)', color: 'var(--color-text-muted)', marginBottom: 'var(--space-3)' }}>Saving…</p>
          )}
          <LifecycleTracker
            device={device}
            canEdit={canEdit}
            onStatusChange={handleStatusChange}
            onEditEntry={(stepIndex, entry) => setEditModalData({ stepIndex, entry })}
            statusError={statusError}
          />
        </Card>
      </div>

      {/* ── Modals ─────────────────────────────────────────────────────────── */}
      {showCustomerModal && (
        <CustomerSearchModal
          onSelect={handleSelectCustomer}
          onClose={() => setShowCustomerModal(false)}
        />
      )}

      {editModalData && editStepMeta && (
        <LifecycleEditModal
          open={editModalData !== null}
          entry={editModalData.entry}
          stepMeta={editStepMeta}
          isCurrent={editIsCurrent}
          onSave={(date, note) => handleSaveLifecycle(editModalData.stepIndex, date, note)}
          onDelete={() => handleDeleteLifecycleStep(editModalData.stepIndex)}
          onClose={() => setEditModalData(null)}
        />
      )}

      <DeleteDeviceModal
        open={showDelete}
        device={device}
        onClose={() => setShowDelete(false)}
        onDeleted={() => navigate('/manufacturing')}
      />
    </div>
  )
}
