// frontend/src/pages/settings/staff/StaffForm.jsx

import { useState, useEffect } from 'react'
import { useParams, useNavigate } from 'react-router-dom'
import api from '@/lib/api'
import { useAuth } from '@/hooks/useAuth'
import { useToast } from '@/components/ui/Toast'
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 Spinner from '@/components/ui/Spinner'

// ─── Default permission sets ────────────────────────────────────────────────

const EDITOR_PERMS = {
  melodies:      { view: true,  add: true,  delete: true,  safe_edit: true,  full_edit: true,  archetype_access: true,  settings_access: true,  compose_access: true  },
  devices:       { view: true,  add: true,  delete: true,  safe_edit: true,  edit_bells: true,  edit_clock: true,  edit_warranty: true,  full_edit: true,  control: true  },
  app_users:     { view: true,  add: true,  delete: true,  safe_edit: true,  full_edit: true  },
  issues_notes:  { view: true,  add: true,  delete: true,  edit: true  },
  mail:          { view: true,  compose: true,  reply: true  },
  crm:           { activity_log: true  },
  crm_customers: { full_access: true, overview: true, orders_view: true, orders_edit: true, quotations_view: true, quotations_edit: true, comms_view: true, comms_log: true, comms_edit: true, comms_compose: true, add: true, delete: true, files_view: true, files_edit: true, devices_view: true, devices_edit: true },
  crm_products:  { view: true,  add: true,  edit: true  },
  mfg:           { view_inventory: true,  edit: true,  provision: true,  firmware_view: true,  firmware_edit: true  },
  api_reference: { access: true  },
  mqtt:          { access: true  },
}

const USER_PERMS = {
  melodies:      { view: true,  add: false, delete: false, safe_edit: false, full_edit: false, archetype_access: false, settings_access: false, compose_access: false },
  devices:       { view: true,  add: false, delete: false, safe_edit: false, edit_bells: false, edit_clock: false, edit_warranty: false, full_edit: false, control: false },
  app_users:     { view: true,  add: false, delete: false, safe_edit: false, full_edit: false },
  issues_notes:  { view: true,  add: false, delete: false, edit: false },
  mail:          { view: true,  compose: false, reply: false },
  crm:           { activity_log: false },
  crm_customers: { full_access: false, overview: true, orders_view: true, orders_edit: false, quotations_view: true, quotations_edit: false, comms_view: true, comms_log: false, comms_edit: false, comms_compose: false, add: false, delete: false, files_view: true, files_edit: false, devices_view: true, devices_edit: false },
  crm_products:  { view: true,  add: false, edit: false },
  mfg:           { view_inventory: true, edit: false, provision: false, firmware_view: true, firmware_edit: false },
  api_reference: { access: false },
  mqtt:          { access: false },
}

function deepClone(obj) { return JSON.parse(JSON.stringify(obj)) }

// ─── Dependency rules ───────────────────────────────────────────────────────

function applyDependencies(section, key, value, prev) {
  const s = { ...prev[section] }
  s[key] = value

  if (value) {
    const VIEW_FORCING = ['add', 'delete', 'safe_edit', 'full_edit', 'edit_bells', 'edit_clock', 'edit_warranty', 'control', 'edit']
    if (VIEW_FORCING.includes(key) && 'view' in s) s.view = true

    if (section === 'melodies'  && key === 'full_edit') s.safe_edit = true
    if (section === 'devices'   && key === 'full_edit') { s.safe_edit = true; s.edit_bells = true; s.edit_clock = true; s.edit_warranty = true; s.view = true }
    if (section === 'app_users' && key === 'full_edit') s.safe_edit = true

    if (section === 'crm_customers') {
      if (key === 'full_access') Object.keys(s).forEach((k) => { s[k] = true })
      if (key === 'orders_edit')      s.orders_view = true
      if (key === 'quotations_edit')  s.quotations_view = true
      if (key === 'files_edit')       s.files_view = true
      if (key === 'devices_edit')     s.devices_view = true
      if (['comms_log', 'comms_edit', 'comms_compose'].includes(key)) s.comms_view = true
    }

    if (section === 'mfg' && key === 'firmware_edit') s.firmware_view = true
    if (section === 'mfg' && key === 'edit')          s.view_inventory = true
    if (section === 'mfg' && key === 'provision')     s.view_inventory = true
  }

  return { ...prev, [section]: s }
}

// ─── Permission toggle row ──────────────────────────────────────────────────

function PermToggle({ label, description, value, onChange, disabled }) {
  return (
    <div style={{
      display: 'flex',
      alignItems: 'center',
      justifyContent: 'space-between',
      gap: 'var(--space-4)',
      padding: 'var(--space-2) 0',
      borderBottom: '1px solid var(--color-border)',
      opacity: disabled ? 0.4 : 1,
      pointerEvents: disabled ? 'none' : 'auto',
    }}>
      <div style={{ minWidth: 0 }}>
        <span style={{ fontSize: 'var(--font-size-sm)', color: 'var(--color-text-secondary)' }}>{label}</span>
        {description && (
          <p style={{ fontSize: 'var(--font-size-xs)', color: 'var(--color-text-muted)', marginTop: '2px' }}>
            {description}
          </p>
        )}
      </div>
      <div style={{
        display: 'flex',
        borderRadius: 'var(--radius-md)',
        overflow: 'hidden',
        border: '1px solid var(--color-border-strong)',
        flexShrink: 0,
      }}>
        <button
          type="button"
          onClick={() => onChange(false)}
          style={{
            padding: '4px 10px',
            fontSize: 'var(--font-size-xs)',
            fontWeight: !value ? 'var(--font-weight-semibold)' : 'var(--font-weight-normal)',
            cursor: 'pointer',
            borderRight: '1px solid var(--color-border-strong)',
            background: !value ? 'var(--color-danger-bg)' : 'transparent',
            color: !value ? 'var(--color-danger)' : 'var(--color-text-muted)',
            transition: 'background 0.15s, color 0.15s',
            border: 'none',
            borderRight: '1px solid var(--color-border-strong)',
          }}
        >
          Off
        </button>
        <button
          type="button"
          onClick={() => onChange(true)}
          style={{
            padding: '4px 10px',
            fontSize: 'var(--font-size-xs)',
            fontWeight: value ? 'var(--font-weight-semibold)' : 'var(--font-weight-normal)',
            cursor: 'pointer',
            background: value ? 'var(--color-success-bg)' : 'transparent',
            color: value ? 'var(--color-success)' : 'var(--color-text-muted)',
            transition: 'background 0.15s, color 0.15s',
            border: 'none',
          }}
        >
          On
        </button>
      </div>
    </div>
  )
}

// ─── 3-state segmented row ──────────────────────────────────────────────────

function SegmentedToggle({ label, description, value, onChange, disabled }) {
  return (
    <div style={{
      display: 'flex',
      alignItems: 'center',
      justifyContent: 'space-between',
      gap: 'var(--space-4)',
      padding: 'var(--space-2) 0',
      borderBottom: '1px solid var(--color-border)',
      opacity: disabled ? 0.4 : 1,
      pointerEvents: disabled ? 'none' : 'auto',
    }}>
      <div style={{ minWidth: 0 }}>
        <span style={{ fontSize: 'var(--font-size-sm)', color: 'var(--color-text-secondary)' }}>{label}</span>
        {description && (
          <p style={{ fontSize: 'var(--font-size-xs)', color: 'var(--color-text-muted)', marginTop: '2px' }}>{description}</p>
        )}
      </div>
      <div style={{
        display: 'flex',
        borderRadius: 'var(--radius-md)',
        overflow: 'hidden',
        border: '1px solid var(--color-border-strong)',
        flexShrink: 0,
      }}>
        {[
          { key: 'none', label: 'None',  bg: 'var(--color-danger-bg)',  fg: 'var(--color-danger)' },
          { key: 'view', label: 'View',  bg: 'var(--color-info-bg)',    fg: 'var(--color-info)' },
          { key: 'edit', label: 'Edit',  bg: 'var(--color-success-bg)', fg: 'var(--color-success)' },
        ].map((opt, i, arr) => (
          <button
            key={opt.key}
            type="button"
            onClick={() => onChange(opt.key)}
            style={{
              padding: '4px 10px',
              fontSize: 'var(--font-size-xs)',
              fontWeight: value === opt.key ? 'var(--font-weight-semibold)' : 'var(--font-weight-normal)',
              cursor: 'pointer',
              background: value === opt.key ? opt.bg : 'transparent',
              color: value === opt.key ? opt.fg : 'var(--color-text-muted)',
              transition: 'background 0.15s, color 0.15s',
              border: 'none',
              borderRight: i < arr.length - 1 ? '1px solid var(--color-border-strong)' : 'none',
            }}
          >
            {opt.label}
          </button>
        ))}
      </div>
    </div>
  )
}

function PermSection({ title, children }) {
  return (
    <Card title={title} variant="flat">
      <div style={{ display: 'flex', flexDirection: 'column' }}>
        {children}
      </div>
    </Card>
  )
}

// ─── Main ─────────────────────────────────────────────────────────────────

export default function StaffForm() {
  const { id }   = useParams()
  const navigate = useNavigate()
  const { user } = useAuth()
  const toast    = useToast()
  const isEdit   = !!id

  const [form,        setForm]        = useState({ name: '', email: '', password: '', role: 'user', is_active: true })
  const [permissions, setPermissions] = useState(deepClone(USER_PERMS))
  const [loading,     setLoading]     = useState(false)
  const [saving,      setSaving]      = useState(false)
  const [error,       setError]       = useState('')

  useEffect(() => {
    if (!isEdit) return
    setLoading(true)
    api.get(`/staff/${id}`)
      .then((data) => {
        setForm({ name: data.name, email: data.email, password: '', role: data.role, is_active: data.is_active })
        if (data.permissions) {
          const base   = data.role === 'editor' ? deepClone(EDITOR_PERMS) : deepClone(USER_PERMS)
          const merged = {}
          Object.keys(base).forEach((sec) => { merged[sec] = { ...base[sec], ...(data.permissions[sec] || {}) } })
          setPermissions(merged)
        } else if (data.role === 'editor') {
          setPermissions(deepClone(EDITOR_PERMS))
        } else {
          setPermissions(deepClone(USER_PERMS))
        }
      })
      .catch((err) => { setError(err.message); toast.danger('Failed to load', err.message) })
      .finally(() => setLoading(false))
  }, [id])

  const handleRoleChange = (newRole) => {
    setForm((f) => ({ ...f, role: newRole }))
    if (newRole === 'editor') setPermissions(deepClone(EDITOR_PERMS))
    else if (newRole === 'user') setPermissions(deepClone(USER_PERMS))
  }

  const setPerm = (section, key, value) =>
    setPermissions((prev) => applyDependencies(section, key, value, prev))

  const setSegmented = (section, viewKey, editKey, val) => {
    setPermissions((prev) => {
      const next = { ...prev, [section]: { ...prev[section] } }
      next[section][viewKey] = val !== 'none'
      next[section][editKey] = val === 'edit'
      return next
    })
  }

  const segVal = (section, viewKey, editKey) => {
    const s = permissions[section] || {}
    if (s[editKey]) return 'edit'
    if (s[viewKey]) return 'view'
    return 'none'
  }

  const handleSubmit = async (e) => {
    e.preventDefault()
    setError('')
    setSaving(true)
    try {
      const body = { name: form.name, email: form.email, role: form.role }
      if (isEdit) {
        body.is_active   = form.is_active
        body.permissions = (form.role === 'editor' || form.role === 'user') ? permissions : null
        await api.put(`/staff/${id}`, body)
        toast.success('Saved', 'Staff member updated successfully.')
        navigate(`/settings/staff/${id}`)
      } else {
        body.password    = form.password
        if (form.role === 'editor' || form.role === 'user') body.permissions = permissions
        const result = await api.post('/staff', body)
        toast.success('Created', `${form.name} has been added to the team.`)
        navigate(`/settings/staff/${result.id}`)
      }
    } catch (err) {
      setError(err.message || 'Something went wrong.')
    } finally {
      setSaving(false)
    }
  }

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

  const roleOptions = user?.role === 'sysadmin'
    ? ['sysadmin', 'admin', 'editor', 'user']
    : ['editor', 'user']

  const showPerms = form.role === 'editor' || form.role === 'user'

  const mel   = permissions.melodies       || {}
  const dev   = permissions.devices         || {}
  const usr   = permissions.app_users       || {}
  const iss   = permissions.issues_notes    || {}
  const mail  = permissions.mail            || {}
  const crm   = permissions.crm             || {}
  const cc    = permissions.crm_customers   || {}
  const cprod = permissions.crm_products    || {}
  const mfg   = permissions.mfg             || {}
  const apir  = permissions.api_reference   || {}
  const mqtt  = permissions.mqtt            || {}
  const ccLocked = !!cc.full_access

  return (
    <div className="page-wrapper">
      <PageHeader
        title={isEdit ? 'Edit Staff Member' : 'Add Staff Member'}
        subtitle={isEdit ? 'Update account details and permissions' : 'Create a new team member account'}
      >
        <Button variant="ghost" onClick={() => navigate(isEdit ? `/settings/staff/${id}` : '/settings/staff')}>
          Cancel
        </Button>
        <Button variant="primary" loading={saving} onClick={handleSubmit}>
          {isEdit ? 'Save Changes' : 'Create Staff Member'}
        </Button>
      </PageHeader>

      <form onSubmit={handleSubmit} style={{ display: 'contents' }}>

        {/* Account Information */}
        <Card title="Account Information" variant="flat">
          {error && (
            <div style={{
              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-sm)',
              marginBottom: 'var(--space-4)',
            }}>
              {error}
            </div>
          )}
          <div style={{ display: 'grid', gridTemplateColumns: 'repeat(auto-fit, minmax(240px, 1fr))', gap: 'var(--space-4)' }}>
            <FormField
              label="Name"
              name="name"
              type="text"
              value={form.name}
              onChange={(e) => setForm((f) => ({ ...f, name: e.target.value }))}
              required
              placeholder="Full name"
            />
            <FormField
              label="Email"
              name="email"
              type="email"
              value={form.email}
              onChange={(e) => setForm((f) => ({ ...f, email: e.target.value }))}
              required
              placeholder="work@example.com"
            />
            {!isEdit && (
              <FormField
                label="Password"
                name="password"
                type="password"
                value={form.password}
                onChange={(e) => setForm((f) => ({ ...f, password: e.target.value }))}
                required
                placeholder="Min. 6 characters"
                hint="The staff member can change this after logging in."
              />
            )}
            <FormField
              label="Role"
              name="role"
              type="select"
              value={form.role}
              onChange={(e) => handleRoleChange(e.target.value)}
            >
              {roleOptions.map((r) => (
                <option key={r} value={r}>{r.charAt(0).toUpperCase() + r.slice(1)}</option>
              ))}
            </FormField>
            {isEdit && (
              <FormField
                label="Status"
                name="is_active"
                type="select"
                value={form.is_active ? 'active' : 'inactive'}
                onChange={(e) => setForm((f) => ({ ...f, is_active: e.target.value === 'active' }))}
              >
                <option value="active">Active</option>
                <option value="inactive">Inactive</option>
              </FormField>
            )}
          </div>
        </Card>

        {/* Admin/Sysadmin — no granular permissions */}
        {(form.role === 'sysadmin' || form.role === 'admin') && (
          <Card title="Permissions" variant="flat">
            <p style={{ fontSize: 'var(--font-size-sm)', color: 'var(--color-text-secondary)' }}>
              {form.role === 'sysadmin'
                ? 'SysAdmin has full god-mode access to all features and settings. No permission customization needed.'
                : 'Admin has full access to all features, except managing SysAdmin accounts and system-level settings. No permission customization needed.'}
            </p>
          </Card>
        )}

        {/* Granular permissions */}
        {showPerms && (
          <>
            <div style={{ display: 'grid', gridTemplateColumns: 'repeat(auto-fit, minmax(320px, 1fr))', gap: 'var(--space-4)' }}>

              <PermSection title="Melodies">
                <PermToggle label="View"             value={mel.view}             onChange={(v) => setPerm('melodies', 'view', v)} />
                <PermToggle label="Add"              value={mel.add}              onChange={(v) => setPerm('melodies', 'add', v)} />
                <PermToggle label="Delete"           value={mel.delete}           onChange={(v) => setPerm('melodies', 'delete', v)} />
                <PermToggle label="Safe Edit"        value={mel.safe_edit}        onChange={(v) => setPerm('melodies', 'safe_edit', v)}        description="Name, Description, Tone, Type, Steps, Colour, Tags" disabled={mel.full_edit} />
                <PermToggle label="Full Edit"        value={mel.full_edit}        onChange={(v) => setPerm('melodies', 'full_edit', v)}        description="Enables Safe Edit automatically" />
                <PermToggle label="Archetype Access" value={mel.archetype_access} onChange={(v) => setPerm('melodies', 'archetype_access', v)} description="Access the Archetype Editor" />
                <PermToggle label="Settings Access"  value={mel.settings_access}  onChange={(v) => setPerm('melodies', 'settings_access', v)}  description="View & change global melody settings" />
                <PermToggle label="Compose Access"   value={mel.compose_access}   onChange={(v) => setPerm('melodies', 'compose_access', v)}   description="Use the Composer to create melodies" />
              </PermSection>

              <PermSection title="Devices">
                <PermToggle label="View"                value={dev.view}          onChange={(v) => setPerm('devices', 'view', v)} />
                <PermToggle label="Add"                 value={dev.add}           onChange={(v) => setPerm('devices', 'add', v)} />
                <PermToggle label="Delete"              value={dev.delete}        onChange={(v) => setPerm('devices', 'delete', v)} />
                <PermToggle label="Safe Edit"           value={dev.safe_edit}     onChange={(v) => setPerm('devices', 'safe_edit', v)}     description="Edit General Info tab only"       disabled={dev.full_edit} />
                <PermToggle label="Edit Bells"          value={dev.edit_bells}    onChange={(v) => setPerm('devices', 'edit_bells', v)}    description="Bell Mechanisms tab"              disabled={dev.full_edit} />
                <PermToggle label="Edit Clock & Alerts" value={dev.edit_clock}    onChange={(v) => setPerm('devices', 'edit_clock', v)}    description="Clock & Alerts tab"               disabled={dev.full_edit} />
                <PermToggle label="Edit Warranty / Sub" value={dev.edit_warranty} onChange={(v) => setPerm('devices', 'edit_warranty', v)} description="Warranty and Subscription tab"    disabled={dev.full_edit} />
                <PermToggle label="Full Edit"           value={dev.full_edit}     onChange={(v) => setPerm('devices', 'full_edit', v)}     description="Enables all edit options above" />
                <PermToggle label="Control"             value={dev.control}       onChange={(v) => setPerm('devices', 'control', v)}       description="Send commands via the Control tab" />
              </PermSection>

              <PermSection title="App Users">
                <PermToggle label="View"      value={usr.view}      onChange={(v) => setPerm('app_users', 'view', v)} />
                <PermToggle label="Add"       value={usr.add}       onChange={(v) => setPerm('app_users', 'add', v)} />
                <PermToggle label="Delete"    value={usr.delete}    onChange={(v) => setPerm('app_users', 'delete', v)} />
                <PermToggle label="Safe Edit" value={usr.safe_edit} onChange={(v) => setPerm('app_users', 'safe_edit', v)} description="Photo, Name, Email, Phone, Title only" disabled={usr.full_edit} />
                <PermToggle label="Full Edit" value={usr.full_edit} onChange={(v) => setPerm('app_users', 'full_edit', v)} description="Edit everything — enables Safe Edit automatically" />
              </PermSection>

              <PermSection title="Issues & Notes">
                <p style={{ fontSize: 'var(--font-size-xs)', color: 'var(--color-text-muted)', marginBottom: 'var(--space-2)', paddingBottom: 'var(--space-2)', borderBottom: '1px solid var(--color-border)' }}>
                  Also applies to Notes linked from Device and User pages.
                </p>
                <PermToggle label="View"   value={iss.view}   onChange={(v) => setPerm('issues_notes', 'view', v)} />
                <PermToggle label="Add"    value={iss.add}    onChange={(v) => setPerm('issues_notes', 'add', v)} />
                <PermToggle label="Delete" value={iss.delete} onChange={(v) => setPerm('issues_notes', 'delete', v)} />
                <PermToggle label="Edit"   value={iss.edit}   onChange={(v) => setPerm('issues_notes', 'edit', v)} />
              </PermSection>

              <PermSection title="Mail">
                <PermToggle label="View Inbox" value={mail.view}    onChange={(v) => setPerm('mail', 'view', v)} />
                <PermToggle label="Compose"    value={mail.compose} onChange={(v) => setPerm('mail', 'compose', v)} description="Send new emails" />
                <PermToggle label="Reply"      value={mail.reply}   onChange={(v) => setPerm('mail', 'reply', v)}   description="Reply to existing emails" />
              </PermSection>

              <PermSection title="CRM">
                <PermToggle label="View Activity Log" value={crm.activity_log} onChange={(v) => setPerm('crm', 'activity_log', v)} />
              </PermSection>

              <PermSection title="CRM Products">
                <PermToggle label="View"         value={cprod.view} onChange={(v) => setPerm('crm_products', 'view', v)} />
                <PermToggle label="Add"          value={cprod.add}  onChange={(v) => setPerm('crm_products', 'add', v)} />
                <PermToggle label="Edit / Delete" value={cprod.edit} onChange={(v) => setPerm('crm_products', 'edit', v)} />
              </PermSection>

              <PermSection title="Manufacturing">
                <PermToggle label="View Inventory"   value={mfg.view_inventory} onChange={(v) => setPerm('mfg', 'view_inventory', v)} />
                <PermToggle label="Edit"             value={mfg.edit}           onChange={(v) => setPerm('mfg', 'edit', v)}           description="Change device status, delete, download NVS Binary" />
                <PermToggle label="Provision Device" value={mfg.provision}      onChange={(v) => setPerm('mfg', 'provision', v)}      description="Flash devices via the Provisioning page" />
                <SegmentedToggle
                  label="Firmware"
                  value={segVal('mfg', 'firmware_view', 'firmware_edit')}
                  onChange={(val) => setSegmented('mfg', 'firmware_view', 'firmware_edit', val)}
                />
              </PermSection>

            </div>

            {/* CRM Customers — full width */}
            <Card variant="flat">
              <div style={{ marginBottom: 'var(--space-4)' }}>
                <h3 style={{ fontSize: 'var(--font-size-base)', fontWeight: 'var(--font-weight-semibold)', color: 'var(--color-text-primary)', margin: '0 0 var(--space-1)' }}>
                  CRM Customers
                </h3>
              </div>

              {/* Full Access master toggle */}
              <div style={{
                display: 'flex',
                alignItems: 'flex-start',
                justifyContent: 'space-between',
                gap: 'var(--space-4)',
                padding: 'var(--space-3)',
                borderRadius: 'var(--radius-md)',
                border: `1px solid ${cc.full_access ? 'var(--color-success)' : 'var(--color-border-strong)'}`,
                backgroundColor: cc.full_access ? 'rgba(74,222,128,0.06)' : 'transparent',
                marginBottom: 'var(--space-4)',
              }}>
                <div>
                  <span style={{
                    fontSize: 'var(--font-size-sm)',
                    fontWeight: 'var(--font-weight-semibold)',
                    color: cc.full_access ? 'var(--color-success)' : 'var(--color-text-primary)',
                  }}>
                    Full Access
                  </span>
                  <p style={{ fontSize: 'var(--font-size-xs)', color: 'var(--color-text-muted)', marginTop: '2px' }}>
                    Enables all CRM Customer permissions. Individual settings are locked when active.
                  </p>
                </div>
                <div style={{
                  display: 'flex',
                  borderRadius: 'var(--radius-md)',
                  overflow: 'hidden',
                  border: '1px solid var(--color-border-strong)',
                  flexShrink: 0,
                }}>
                  <button type="button" onClick={() => setPerm('crm_customers', 'full_access', false)}
                    style={{
                      padding: '4px 10px', fontSize: 'var(--font-size-xs)', cursor: 'pointer', border: 'none',
                      borderRight: '1px solid var(--color-border-strong)',
                      background: !cc.full_access ? 'var(--color-danger-bg)' : 'transparent',
                      color: !cc.full_access ? 'var(--color-danger)' : 'var(--color-text-muted)',
                      fontWeight: !cc.full_access ? 'var(--font-weight-semibold)' : 'var(--font-weight-normal)',
                    }}>
                    Off
                  </button>
                  <button type="button" onClick={() => setPerm('crm_customers', 'full_access', true)}
                    style={{
                      padding: '4px 10px', fontSize: 'var(--font-size-xs)', cursor: 'pointer', border: 'none',
                      background: cc.full_access ? 'var(--color-success-bg)' : 'transparent',
                      color: cc.full_access ? 'var(--color-success)' : 'var(--color-text-muted)',
                      fontWeight: cc.full_access ? 'var(--font-weight-semibold)' : 'var(--font-weight-normal)',
                    }}>
                    On
                  </button>
                </div>
              </div>

              <div style={{ display: 'grid', gridTemplateColumns: '1fr 1fr', gap: '0 var(--space-8)' }}>
                <div>
                  <PermToggle label="Overview Tab"  value={cc.overview}         onChange={(v) => setPerm('crm_customers', 'overview', v)}         disabled={ccLocked} />
                  <SegmentedToggle label="Orders"    value={segVal('crm_customers', 'orders_view', 'orders_edit')}      onChange={(v) => setSegmented('crm_customers', 'orders_view', 'orders_edit', v)}           disabled={ccLocked} />
                  <SegmentedToggle label="Quotations" value={segVal('crm_customers', 'quotations_view', 'quotations_edit')} onChange={(v) => setSegmented('crm_customers', 'quotations_view', 'quotations_edit', v)} disabled={ccLocked} />
                  <SegmentedToggle label="Files & Media" value={segVal('crm_customers', 'files_view', 'files_edit')}    onChange={(v) => setSegmented('crm_customers', 'files_view', 'files_edit', v)}             disabled={ccLocked} />
                  <SegmentedToggle label="Devices Tab"   value={segVal('crm_customers', 'devices_view', 'devices_edit')} onChange={(v) => setSegmented('crm_customers', 'devices_view', 'devices_edit', v)}       disabled={ccLocked} />
                </div>
                <div>
                  <PermToggle label="Add Customer"           value={cc.add}          onChange={(v) => setPerm('crm_customers', 'add', v)}          disabled={ccLocked} />
                  <PermToggle label="Delete Customer"        value={cc.delete}       onChange={(v) => setPerm('crm_customers', 'delete', v)}       disabled={ccLocked} />
                  <PermToggle label="Comms: View"            value={cc.comms_view}   onChange={(v) => setPerm('crm_customers', 'comms_view', v)}   disabled={ccLocked} />
                  <PermToggle label="Comms: Log Entry"       value={cc.comms_log}    onChange={(v) => setPerm('crm_customers', 'comms_log', v)}    disabled={ccLocked} />
                  <PermToggle label="Comms: Edit Entries"    value={cc.comms_edit}   onChange={(v) => setPerm('crm_customers', 'comms_edit', v)}   disabled={ccLocked} />
                  <PermToggle label="Comms: Compose & Send"  value={cc.comms_compose} onChange={(v) => setPerm('crm_customers', 'comms_compose', v)} disabled={ccLocked} />
                </div>
              </div>
            </Card>

            {/* API + MQTT */}
            <div style={{ display: 'grid', gridTemplateColumns: 'repeat(auto-fit, minmax(320px, 1fr))', gap: 'var(--space-4)' }}>
              <PermSection title="API Reference">
                <PermToggle label="Access API Reference Page" value={apir.access} onChange={(v) => setPerm('api_reference', 'access', v)} />
              </PermSection>
              <PermSection title="MQTT">
                <PermToggle label="MQTT Access" value={mqtt.access} onChange={(v) => setPerm('mqtt', 'access', v)} description="Dashboard, Commands, Logs, WebSocket" />
              </PermSection>
            </div>
          </>
        )}

        {/* Sticky bottom action bar */}
        <div style={{
          display: 'flex',
          gap: 'var(--space-3)',
          paddingBottom: 'var(--space-8)',
          paddingTop: 'var(--space-2)',
        }}>
          <Button type="submit" variant="primary" loading={saving}>
            {isEdit ? 'Save Changes' : 'Create Staff Member'}
          </Button>
          <Button
            type="button"
            variant="ghost"
            onClick={() => navigate(isEdit ? `/settings/staff/${id}` : '/settings/staff')}
          >
            Cancel
          </Button>
        </div>

      </form>
    </div>
  )
}
