// frontend/src/pages/bellcloud/users/UserListCardView.jsx
//
// Card-based view of the App Users list.
// All colours via design tokens only.

import { useState, useRef, useEffect, useCallback } from 'react'
import { createPortal } from 'react-dom'
import { useNavigate } from 'react-router-dom'
import Icon from '@/components/ui/Icon'
import Spinner from '@/components/ui/Spinner'
import StatusBadge from '@/components/ui/StatusBadge'
import Modal from '@/components/ui/Modal'
import api from '@/lib/api'

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

function statusVariant(status) {
  if (status === 'active')  return 'success'
  if (status === 'blocked') return 'danger'
  return 'neutral'
}

// Maps variant → CSS color token for the watermark tint
const VARIANT_COLOR = {
  success: 'var(--color-success)',
  danger:  'var(--color-danger)',
  neutral: 'var(--color-text-muted)',
}

// Icon paths per status (inline SVG, 24x24 viewBox)
function StatusWatermarkIcon({ status }) {
  const variant = statusVariant(status)
  const color   = VARIANT_COLOR[variant] ?? VARIANT_COLOR.neutral

  const paths = status === 'active' ? (
    <>
      <path d="M22 11.08V12a10 10 0 11-5.93-9.14" />
      <path d="M22 4L12 14.01l-3-3" />
    </>
  ) : status === 'blocked' ? (
    <>
      <circle cx="12" cy="12" r="10" />
      <line x1="4.93" y1="4.93" x2="19.07" y2="19.07" />
    </>
  ) : (
    <>
      <path d="M20 21v-2a4 4 0 00-4-4H8a4 4 0 00-4 4v2" />
      <circle cx="12" cy="7" r="4" />
    </>
  )

  return (
    <svg
      className="ucard__watermark"
      viewBox="0 0 24 24"
      fill="none"
      stroke={color}
      strokeWidth="1.75"
      strokeLinecap="round"
      strokeLinejoin="round"
      aria-hidden="true"
    >
      {paths}
    </svg>
  )
}

function initials(name) {
  if (!name) return '?'
  const parts = name.trim().split(/\s+/)
  if (parts.length === 1) return parts[0][0].toUpperCase()
  return (parts[0][0] + parts[parts.length - 1][0]).toUpperCase()
}

// ─── Phone SVG (not in Icon set) ─────────────────────────────────────────────

function PhoneIcon({ size = 13 }) {
  return (
    <svg width={size} height={size} viewBox="0 0 24 24" fill="none"
      stroke="currentColor" strokeWidth="1.75"
      strokeLinecap="round" strokeLinejoin="round" aria-hidden="true">
      <path d="M22 16.92v3a2 2 0 01-2.18 2 19.79 19.79 0 01-8.63-3.07A19.5 19.5 0 013.07 9.8a19.79 19.79 0 01-3.07-8.7A2 2 0 012 1h3a2 2 0 012 1.72c.127.96.361 1.903.7 2.81a2 2 0 01-.45 2.11L6.09 8.91a16 16 0 006 6l1.27-1.27a2 2 0 012.11-.45c.907.339 1.85.573 2.81.7A2 2 0 0122 16.92z" />
    </svg>
  )
}

// ─── Copy helper ─────────────────────────────────────────────────────────────

function copyToClipboard(val) {
  try {
    navigator.clipboard.writeText(val)
  } catch {
    const el = document.createElement('textarea')
    el.value = val
    document.body.appendChild(el)
    el.select()
    document.execCommand('copy')
    document.body.removeChild(el)
  }
}

// ─── Copyable info cell (email / phone — with background + "Copied!" flash) ──

function FieldTooltip({ value, icon, label, empty = '—' }) {
  const [copied, setCopied]   = useState(false)
  const [visible, setVisible] = useState(false)
  const [pos, setPos]         = useState({ top: 0, left: 0 })
  const cellRef               = useRef(null)
  const hideTimer             = useRef(null)
  const showTimer             = useRef(null)

  function show() {
    clearTimeout(hideTimer.current)
    clearTimeout(showTimer.current)
    showTimer.current = setTimeout(() => {
      if (cellRef.current) {
        const r = cellRef.current.getBoundingClientRect()
        setPos({ top: r.bottom + 6, left: r.left })
      }
      setVisible(true)
    }, 500)
  }
  function hide() {
    clearTimeout(showTimer.current)
    hideTimer.current = setTimeout(() => setVisible(false), 80)
  }

  useEffect(() => {
    if (!visible) return
    function onScroll() { setVisible(false) }
    document.addEventListener('scroll', onScroll, true)
    return () => document.removeEventListener('scroll', onScroll, true)
  }, [visible])

  const hasValue = Boolean(value)

  function handleClick(e) {
    e.stopPropagation()
    if (!hasValue) return
    copyToClipboard(value)
    setCopied(true)
    setTimeout(() => setCopied(false), 1500)
  }

  return (
    <>
      <div
        ref={cellRef}
        className={`ucard__info-cell${hasValue ? ' ucard__info-cell--copyable' : ''}`}
        onMouseEnter={hasValue ? show : undefined}
        onMouseLeave={hasValue ? hide : undefined}
        onClick={handleClick}
        title={hasValue ? `Click to copy ${label}` : undefined}
      >
        <span className="ucard__info-icon" aria-hidden="true">{icon}</span>
        <span className="ucard__info-value">
          {hasValue ? value : <em className="ucard__empty">{empty}</em>}
        </span>
        {copied && <span className="ucard__uid-copied">Copied!</span>}
      </div>

      {visible && hasValue && createPortal(
        <div
          className="ucard__tooltip"
          style={{ position: 'fixed', top: pos.top, left: pos.left, zIndex: 9999 }}
          onMouseEnter={() => clearTimeout(hideTimer.current)}
          onMouseLeave={hide}
        >
          <span className="ucard__tooltip-label">{label}</span>
          <span className="ucard__tooltip-value">{value}</span>
        </div>,
        document.body
      )}
    </>
  )
}

// ─── Copyable cell — click copies value ──────────────────────────────────────

function CopyCell({ value, icon, label, empty = '—' }) {
  const [copied, setCopied] = useState(false)

  const hasValue = Boolean(value)

  function handleClick(e) {
    e.stopPropagation()
    if (!hasValue) return
    copyToClipboard(value)
    setCopied(true)
    setTimeout(() => setCopied(false), 1500)
  }

  return (
    <div
      className="ucard__copy-cell"
      onClick={handleClick}
      title={hasValue ? `Click to copy ${label}` : undefined}
      style={!hasValue ? { cursor: 'default' } : undefined}
    >
      <span className="ucard__copy-cell-icon" aria-hidden="true">{icon}</span>
      <span className="ucard__copy-cell-label">{label}</span>
      <span className="ucard__copy-cell-value">
        {hasValue ? value : <em className="ucard__empty">{empty}</em>}
      </span>
      {copied && <span className="ucard__uid-copied">Copied!</span>}
    </div>
  )
}

// ─── Stat cell — click opens mini modal ──────────────────────────────────────

function StatCell({ icon, label, onClick }) {
  return (
    <div
      role="button"
      tabIndex={0}
      className="ucard__stat-cell"
      onClick={(e) => { e.stopPropagation(); onClick() }}
      onKeyDown={(e) => { if (e.key === 'Enter' || e.key === ' ') { e.stopPropagation(); onClick() } }}
    >
      <span className="ucard__stat-cell-icon" aria-hidden="true">{icon}</span>
      <span className="ucard__stat-cell-label">{label}</span>
      {/* Eye icon — "view list" */}
      <svg className="ucard__stat-cell-eye" width="12" height="12" viewBox="0 0 24 24" fill="none"
        stroke="currentColor" strokeWidth="1.75" strokeLinecap="round" strokeLinejoin="round"
        aria-hidden="true">
        <path d="M1 12s4-8 11-8 11 8 11 8-4 8-11 8-11-8-11-8z" />
        <circle cx="12" cy="12" r="3" />
      </svg>
    </div>
  )
}

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

function StatusDropdown({ userId, status, canEdit, onStatusChanged }) {
  const [open, setOpen]       = useState(false)
  const [loading, setLoading] = useState(false)
  const ref                   = useRef(null)

  useEffect(() => {
    if (!open) return
    function onOutside(e) {
      if (ref.current && !ref.current.contains(e.target)) setOpen(false)
    }
    document.addEventListener('mousedown', onOutside)
    return () => document.removeEventListener('mousedown', onOutside)
  }, [open])

  async function changeStatus(newStatus) {
    setOpen(false)
    if (newStatus === status) return
    setLoading(true)
    try {
      const endpoint = newStatus === 'blocked'
        ? `/users/${userId}/block`
        : `/users/${userId}/unblock`
      await api.post(endpoint, {})
      onStatusChanged?.()
    } catch (err) {
      console.error('Failed to change user status:', err)
    } finally {
      setLoading(false)
    }
  }

  function handleClick(e) {
    e.stopPropagation()
    if (!canEdit) return
    setOpen((v) => !v)
  }

  const variant = statusVariant(status)
  const label   = status ? status.charAt(0).toUpperCase() + status.slice(1) : 'Unknown'

  return (
    <div ref={ref} className="ucard__status-wrap" style={{ position: 'relative' }}>
      <div
        className={canEdit ? 'ucard__status-trigger' : undefined}
        onClick={handleClick}
        style={{ cursor: canEdit ? 'pointer' : 'default' }}
        title={canEdit ? 'Change status' : undefined}
      >
        {loading
          ? <Spinner size="sm" />
          : <StatusBadge variant={variant} dot size="sm">{label}</StatusBadge>
        }
      </div>

      {open && createPortal(
        <StatusDropdownMenu
          anchorRef={ref}
          currentStatus={status}
          onSelect={changeStatus}
          onClose={() => setOpen(false)}
        />,
        document.body
      )}
    </div>
  )
}

function StatusDropdownMenu({ anchorRef, currentStatus, onSelect, onClose }) {
  const [pos, setPos] = useState({ top: 0, left: 0 })

  useEffect(() => {
    if (anchorRef.current) {
      const r = anchorRef.current.getBoundingClientRect()
      setPos({ top: r.bottom + 4, left: r.right - 140 })
    }
  }, [anchorRef])

  useEffect(() => {
    function onScroll() { onClose() }
    document.addEventListener('scroll', onScroll, true)
    return () => document.removeEventListener('scroll', onScroll, true)
  }, [onClose])

  const options = [
    { value: 'active',  label: 'Active',  variant: 'success' },
    { value: 'blocked', label: 'Blocked', variant: 'danger'  },
  ]

  return (
    <div
      className="ucard__status-menu"
      style={{ position: 'fixed', top: pos.top, left: pos.left, zIndex: 9999 }}
      onClick={(e) => e.stopPropagation()}
    >
      {options.map((opt) => (
        <button
          key={opt.value}
          className={`ucard__status-option${currentStatus === opt.value ? ' ucard__status-option--active' : ''}`}
          onClick={() => onSelect(opt.value)}
        >
          <StatusBadge variant={opt.variant} dot size="sm">{opt.label}</StatusBadge>
          {currentStatus === opt.value && (
            <svg width="12" height="12" viewBox="0 0 24 24" fill="none"
              stroke="currentColor" strokeWidth="2.5" strokeLinecap="round" strokeLinejoin="round">
              <polyline points="20 6 9 17 4 12" />
            </svg>
          )}
        </button>
      ))}
    </div>
  )
}

// ─── Linked Devices mini modal ────────────────────────────────────────────────

function LinkedDevicesModal({ userId, userName, open, onClose }) {
  const [devices, setDevices] = useState([])
  const [loading, setLoading] = useState(false)
  const navigate = useNavigate()

  useEffect(() => {
    if (!open || !userId) return
    setLoading(true)
    api.get(`/users/${userId}/devices`)
      .then((d) => setDevices(Array.isArray(d) ? d : []))
      .catch(() => setDevices([]))
      .finally(() => setLoading(false))
  }, [open, userId])

  return (
    <Modal
      open={open}
      onClose={onClose}
      title={`Linked Devices — ${userName}`}
      size="sm"
    >
      {loading ? (
        <div style={{ display: 'flex', justifyContent: 'center', padding: 'var(--space-8)' }}>
          <Spinner />
        </div>
      ) : devices.length === 0 ? (
        <p style={{ color: 'var(--color-text-muted)', fontSize: 'var(--font-size-sm)', textAlign: 'center', padding: 'var(--space-6) 0', margin: 0 }}>
          No linked devices.
        </p>
      ) : (
        <div style={{ display: 'flex', flexDirection: 'column', gap: 'var(--space-2)' }}>
          {devices.map((d) => (
            <div
              key={d.id}
              onClick={() => { onClose(); navigate(`/devices/${d.id}`) }}
              style={{
                display: 'flex', alignItems: 'center', gap: 'var(--space-3)',
                padding: 'var(--space-3)',
                borderRadius: 'var(--radius-md)',
                background: 'var(--color-bg-elevated)',
                border: '1px solid var(--color-border)',
                fontSize: 'var(--font-size-sm)',
                cursor: 'pointer',
                transition: 'background 150ms ease, border-color 150ms ease',
              }}
              onMouseEnter={e => {
                e.currentTarget.style.background = 'var(--color-bg-hover)'
                e.currentTarget.style.borderColor = 'var(--color-border-strong)'
              }}
              onMouseLeave={e => {
                e.currentTarget.style.background = 'var(--color-bg-elevated)'
                e.currentTarget.style.borderColor = 'var(--color-border)'
              }}
            >
              <Icon name="device" size={14} color="var(--color-primary)" />
              <div style={{ flex: 1, minWidth: 0 }}>
                <div style={{ fontWeight: 'var(--font-weight-medium)', color: 'var(--color-text-primary)', overflow: 'hidden', textOverflow: 'ellipsis', whiteSpace: 'nowrap' }}>
                  {d.device_name || d.device_id || d.id}
                </div>
                {d.device_id && (
                  <div style={{ color: 'var(--color-text-muted)', fontSize: 'var(--font-size-xs)', fontFamily: 'var(--font-family-mono)' }}>
                    {d.device_id}
                  </div>
                )}
              </div>
              <Icon name="chevron-right" size={14} color="var(--color-text-muted)" />
            </div>
          ))}
        </div>
      )}
    </Modal>
  )
}

// ─── User Notes mini modal ────────────────────────────────────────────────────

function UserNotesModal({ userId, userName, open, onClose }) {
  const [notes, setNotes]     = useState([])
  const [loading, setLoading] = useState(false)

  useEffect(() => {
    if (!open || !userId) return
    setLoading(true)
    api.get(`/equipment/notes?user_id=${userId}`)
      .then((d) => setNotes(d.notes ?? []))
      .catch(() => setNotes([]))
      .finally(() => setLoading(false))
  }, [open, userId])

  return (
    <Modal
      open={open}
      onClose={onClose}
      title={`User Notes — ${userName}`}
      size="sm"
    >
      {loading ? (
        <div style={{ display: 'flex', justifyContent: 'center', padding: 'var(--space-8)' }}>
          <Spinner />
        </div>
      ) : notes.length === 0 ? (
        <p style={{ color: 'var(--color-text-muted)', fontSize: 'var(--font-size-sm)', textAlign: 'center', padding: 'var(--space-6) 0', margin: 0 }}>
          No notes recorded.
        </p>
      ) : (
        <div style={{ display: 'flex', flexDirection: 'column', gap: 'var(--space-3)' }}>
          {notes.map((n) => (
            <div key={n.id} style={{
              padding: 'var(--space-3)',
              borderRadius: 'var(--radius-md)',
              background: 'var(--color-bg-elevated)',
              border: '1px solid var(--color-border)',
            }}>
              {n.title && (
                <div style={{ fontWeight: 'var(--font-weight-medium)', color: 'var(--color-text-primary)', fontSize: 'var(--font-size-sm)', marginBottom: 'var(--space-1)' }}>
                  {n.title}
                </div>
              )}
              <div style={{ color: 'var(--color-text-secondary)', fontSize: 'var(--font-size-sm)', lineHeight: 'var(--line-height-relaxed)' }}>
                {n.content}
              </div>
            </div>
          ))}
        </div>
      )}
    </Modal>
  )
}

// ─── Single User Card ─────────────────────────────────────────────────────────

function UserCard({ user, canEdit, onView, onEdit, onStatusChanged, onMiddleClick }) {
  const name   = user.display_name || 'Unnamed User'
  const status = user.status || 'unknown'

  const [devicesOpen, setDevicesOpen] = useState(false)
  const [notesOpen, setNotesOpen]     = useState(false)

  const deviceCount = user.device_count ?? user.linked_device_count ?? null
  const noteCount   = user.note_count   ?? null

  return (
    <>
      <article
        className="ucard"
        onClick={onView}
        onMouseDown={(e) => { if (e.button === 1) { e.preventDefault(); onMiddleClick?.() } }}
      >
        {/* ── Background watermark icon ── */}
        <StatusWatermarkIcon status={status} />

        {/* ── Status badge: absolute top-right ── */}
        <div className="ucard__status-corner" onClick={(e) => e.stopPropagation()}>
          <StatusDropdown
            userId={user.id}
            status={status}
            canEdit={canEdit}
            onStatusChanged={onStatusChanged}
          />
        </div>


        {/* ── Header: avatar + identity ── */}
        <header className="ucard__header">
          <div className="ucard__avatar" aria-hidden="true">
            {user.photo_url ? (
              <img
                src={user.photo_url}
                alt={name}
                className="ucard__avatar-img"
                onError={(e) => { e.currentTarget.style.display = 'none'; e.currentTarget.nextSibling.style.display = 'flex' }}
              />
            ) : null}
            <span
              className="ucard__avatar-initials"
              style={user.photo_url ? { display: 'none' } : undefined}
            >
              {initials(name)}
            </span>
          </div>

          <div className="ucard__identity">
            <span className="ucard__name">{name}</span>
            {user.userTitle && (
              <span className="ucard__title">{user.userTitle}</span>
            )}
          </div>
        </header>

        {/* ── Info section ── */}
        <div className="ucard__info-section" onClick={(e) => e.stopPropagation()}>

          {/* Row 1: Email + Phone (with background) */}
          <div className="ucard__info-row">
            <FieldTooltip
              value={user.email}
              label="Email"
              icon={<Icon name="mail" size={13} />}
              empty="No email"
            />
            <FieldTooltip
              value={user.phone_number}
              label="Phone"
              icon={<PhoneIcon size={13} />}
              empty="No phone"
            />
          </div>

          {/* Row 2: UID (full width, transparent, copy on click) */}
          <CopyCell
            value={user.uid || user.firebase_uid}
            label="UID"
            icon={
              <svg width="11" height="11" viewBox="0 0 24 24" fill="none"
                stroke="currentColor" strokeWidth="1.75" strokeLinecap="round" strokeLinejoin="round">
                <rect x="9" y="9" width="13" height="13" rx="2" />
                <path d="M5 15H4a2 2 0 01-2-2V4a2 2 0 012-2h9a2 2 0 012 2v1" />
              </svg>
            }
            empty="No UID"
          />

          {/* Row 3: Linked Devices + User Notes (no border, plain flat rows) */}
          <div className="ucard__info-row ucard__info-row--stats">
            <StatCell
              icon={
                <svg width="12" height="12" viewBox="0 0 24 24" fill="none"
                  stroke="currentColor" strokeWidth="1.75" strokeLinecap="round" strokeLinejoin="round">
                  <rect x="4" y="4" width="16" height="16" rx="2" />
                  <line x1="4" y1="9" x2="20" y2="9" />
                  <line x1="9" y1="4" x2="9" y2="20" />
                </svg>
              }
              label="Linked Devices"
              onClick={() => setDevicesOpen(true)}
            />
            <StatCell
              icon={
                <svg width="12" height="12" viewBox="0 0 24 24" fill="none"
                  stroke="currentColor" strokeWidth="1.75" strokeLinecap="round" strokeLinejoin="round">
                  <path d="M14 2H6a2 2 0 00-2 2v16a2 2 0 002 2h12a2 2 0 002-2V8z" />
                  <polyline points="14 2 14 8 20 8" />
                  <line x1="16" y1="13" x2="8" y2="13" />
                  <line x1="16" y1="17" x2="8" y2="17" />
                  <polyline points="10 9 9 9 8 9" />
                </svg>
              }
              label="User Notes"
              onClick={() => setNotesOpen(true)}
            />
          </div>

        </div>

        {/* ── Last active ── */}
        {user.lastActive && (
          <div className="ucard__last-active">
            <Icon name="eye" size={12} />
            <span>Last active: {user.lastActive}</span>
          </div>
        )}
      </article>

      {/* ── Mini modals (rendered outside card to avoid stacking context issues) ── */}
      <LinkedDevicesModal
        userId={user.id}
        userName={name}
        open={devicesOpen}
        onClose={() => setDevicesOpen(false)}
      />
      <UserNotesModal
        userId={user.id}
        userName={name}
        open={notesOpen}
        onClose={() => setNotesOpen(false)}
      />
    </>
  )
}

// ─── Skeleton card ────────────────────────────────────────────────────────────

function SkeletonCard() {
  return (
    <div className="ucard ucard--skeleton" aria-hidden="true">
      <div className="ucard__header">
        <div className="ucard__avatar">
          <div className="ucard-skel" style={{ width: 52, height: 52, borderRadius: 'var(--radius-xl)' }} />
        </div>
        <div className="ucard__identity" style={{ gap: 'var(--space-2)' }}>
          <div className="ucard-skel" style={{ width: '70%', height: 18 }} />
          <div className="ucard-skel" style={{ width: '45%', height: 13 }} />
        </div>
      </div>
      <div className="ucard__info-section">
        <div className="ucard__info-row">
          <div className="ucard__info-cell"><div className="ucard-skel" style={{ width: '80%', height: 13 }} /></div>
          <div className="ucard__info-cell"><div className="ucard-skel" style={{ width: '60%', height: 13 }} /></div>
        </div>
        <div className="ucard__copy-cell"><div className="ucard-skel" style={{ width: '90%', height: 13 }} /></div>
        <div className="ucard__info-row">
          <div className="ucard__stat-cell" style={{ pointerEvents: 'none' }}><div className="ucard-skel" style={{ width: '70%', height: 13 }} /></div>
          <div className="ucard__stat-cell" style={{ pointerEvents: 'none' }}><div className="ucard-skel" style={{ width: '70%', height: 13 }} /></div>
        </div>
      </div>
    </div>
  )
}

// ─── UserListCardView (exported) ─────────────────────────────────────────────

export default function UserListCardView({ users, loading, canEdit, onView, onEdit, onDelete, onMiddleClick, onRefresh }) {

  if (loading) {
    return (
      <>
        <style>{CARD_STYLES}</style>
        <div className="ucard-grid">
          {Array.from({ length: 8 }).map((_, i) => <SkeletonCard key={i} />)}
        </div>
      </>
    )
  }

  if (!users.length) {
    return (
      <>
        <style>{CARD_STYLES}</style>
        <div className="ucard-empty">
          <div className="ucard-empty__icon" aria-hidden="true">
            <Icon name="staff" size={36} color="var(--color-text-muted)" />
          </div>
          <p className="ucard-empty__title">No users found</p>
          <p className="ucard-empty__sub">Try adjusting your search or filters.</p>
        </div>
      </>
    )
  }

  return (
    <>
      <style>{CARD_STYLES}</style>
      <div className="ucard-grid">
        {users.map((user) => (
          <UserCard
            key={user.id}
            user={user}
            canEdit={canEdit}
            onView={() => onView(user)}
            onEdit={() => onEdit(user)}
            onDelete={() => onDelete(user)}
            onStatusChanged={onRefresh}
            onMiddleClick={() => onMiddleClick?.(user)}
          />
        ))}
      </div>
    </>
  )
}

// ─── Styles (scoped, injected via <style> tag) ───────────────────────────────

const CARD_STYLES = `

/* ── Grid ─────────────────────────────────────────────────────────────────── */
.ucard-grid {
  display: grid;
  grid-template-columns: repeat(auto-fill, minmax(460px, 1fr));
  gap: var(--space-4);
  align-items: flex-start;
}

/* ── Card shell — glass ───────────────────────────────────────────────────── */
.ucard {
  display: flex;
  flex-direction: column;
  gap: var(--space-4);
  background-color: rgba(28, 32, 38, 0.30);
  backdrop-filter: var(--blur-modal);
  -webkit-backdrop-filter: var(--blur-modal);
  border: 1px solid var(--color-border);
  border-radius: var(--radius-lg);
  box-shadow: var(--shadow-card), var(--shadow-sm);
  padding: var(--space-6);
  cursor: pointer;
  transition: background-color 200ms ease, border-color 200ms ease,
              box-shadow 200ms ease, transform 200ms;
  overflow: hidden;
  user-select: none;
  box-sizing: border-box;
  position: relative;
}
.ucard:hover {
  background-color: rgba(49, 53, 60, 0.45);
  border-color: rgba(192, 193, 255, 0.20);
  box-shadow: var(--shadow-card), var(--shadow-md);
  transform: scale(1.03);
}
.ucard:active { transform: scale(1); }

/* ── Watermark icon ──────────────────────────────────────────────────────── */
.ucard__watermark {
  position: absolute;
  bottom: -50%;
  right: -40%;
  width: 200%;
  height: 200%;
  opacity: 0.04;
  pointer-events: none;
  z-index: 0;
}

/* Ensure card content sits above the watermark — exclude absolutely-positioned overlays */
.ucard__header,
.ucard__info-section,
.ucard__last-active {
  position: relative;
  z-index: 1;
}

/* ── Status badge: absolute top-right corner ─────────────────────────────── */
.ucard__status-corner {
  position: absolute;
  top: var(--space-6);
  right: var(--space-6);
  z-index: 3;
}

/* ── Status badge hover — brighter background hint it's clickable ───────── */
.ucard__status-trigger {
  border-radius: var(--radius-md);
  transition: filter 150ms ease, transform 150ms ease;
}
.ucard__status-trigger:hover {
  filter: brightness(1.35);
  transform: scale(1.06);
}

/* ── Header: avatar + identity ───────────────────────────────────────────── */
.ucard__header {
  display: flex;
  align-items: center;
  gap: var(--space-4);
  /* Right padding so text doesn't run under the status badge */
  padding-right: 80px;
}

/* Avatar — rounded rectangle */
.ucard__avatar {
  flex-shrink: 0;
  width: 52px;
  height: 52px;
  border-radius: var(--radius-xl);
  background: var(--color-primary-subtle);
  border: 1.5px solid rgba(192, 193, 255, 0.20);
  display: flex;
  align-items: center;
  justify-content: center;
  overflow: hidden;
  position: relative;
}
.ucard__avatar-img {
  width: 100%;
  height: 100%;
  object-fit: cover;
  display: block;
}
.ucard__avatar-initials {
  display: flex;
  align-items: center;
  justify-content: center;
  width: 100%;
  height: 100%;
  font-family: var(--font-family-display);
  font-size: var(--font-size-lg);
  font-weight: var(--font-weight-bold);
  color: var(--color-primary);
  letter-spacing: var(--tracking-snug);
}

.ucard__identity {
  flex: 1;
  min-width: 0;
  display: flex;
  flex-direction: column;
  gap: 3px;
}
.ucard__name {
  display: block;
  font-family: var(--font-family-display);
  font-size: var(--font-size-xl);
  font-weight: var(--font-weight-bold);
  color: var(--color-text-primary);
  letter-spacing: var(--tracking-tight);
  line-height: var(--line-height-tight);
  white-space: nowrap;
  overflow: hidden;
  text-overflow: ellipsis;
}
.ucard__title {
  display: block;
  font-size: var(--font-size-sm);
  color: var(--color-text-muted);
  white-space: nowrap;
  overflow: hidden;
  text-overflow: ellipsis;
}

/* ── Info section wrapper ────────────────────────────────────────────────── */
/* Three distinct rows, each independently styled. No shared background.     */
.ucard__info-section {
  display: flex;
  flex-direction: column;
  gap: var(--space-2);
}

/* ── Row: two side-by-side cells ─────────────────────────────────────────── */
.ucard__info-row {
  display: flex;
  gap: var(--space-2);
}
.ucard__info-row > * {
  flex: 1;
  min-width: 0;
}
/* Stat row — same flex layout as email/phone row */
.ucard__info-row--stats {
  margin-top: var(--space-1);
}

/* ── Base info cell (email / phone — with background) ────────────────────── */
.ucard__info-cell {
  background: var(--color-bg-elevated);
  border: 1px solid var(--color-border);
  border-radius: var(--radius-md);
  padding: var(--space-2) var(--space-3);
  display: flex;
  align-items: center;
  gap: var(--space-2);
  min-width: 0;
  cursor: default;
  transition: background-color var(--transition-fast);
  position: relative;
}
.ucard__info-cell--copyable {
  cursor: pointer;
}
.ucard__info-cell:hover {
  background: rgba(49, 53, 60, 0.60);
}

/* ── Copy cell (UID — transparent, full-width) ───────────────────────────── */
.ucard__copy-cell {
  background: transparent;
  border: 1px solid var(--color-border);
  border-radius: var(--radius-md);
  padding: var(--space-2) var(--space-3);
  display: flex;
  align-items: center;
  gap: var(--space-2);
  min-width: 0;
  cursor: pointer;
  transition: background-color var(--transition-fast);
  position: relative;
}
.ucard__copy-cell:hover {
  background: rgba(49, 53, 60, 0.40);
}

/* ── Stat cell — identical layout to .ucard__info-cell, transparent until hover */
.ucard__stat-cell {
  box-sizing: border-box;
  background: transparent;
  border: 1px solid transparent;
  border-radius: var(--radius-md);
  padding: var(--space-2) var(--space-3);
  display: flex;
  align-items: center;
  gap: var(--space-2);
  min-width: 0;
  cursor: pointer;
  transition: background-color var(--transition-fast);
  /* Reset any browser button defaults */
  appearance: none;
  -webkit-appearance: none;
  font-family: var(--font-family-base);
  text-align: left;
}
.ucard__stat-cell:hover {
  background: var(--color-bg-elevated);
}
.ucard__stat-cell:hover .ucard__stat-cell-label {
  color: var(--color-text-primary);
}

/* Shared icon / label / value styles */
.ucard__info-icon {
  flex-shrink: 0;
  color: var(--color-primary);
  display: flex;
  align-items: center;
}
.ucard__info-value {
  flex: 1;
  font-size: var(--font-size-sm);
  color: var(--color-text-secondary);
  white-space: nowrap;
  overflow: hidden;
  text-overflow: ellipsis;
}
.ucard__empty {
  font-style: normal;
  color: var(--color-text-muted);
}

/* Stat cell icon / label / eye */
.ucard__stat-cell-icon {
  flex-shrink: 0;
  color: var(--color-primary);
  display: flex;
  align-items: center;
}
.ucard__stat-cell-label {
  font-size: var(--font-size-sm);
  color: var(--color-text-secondary);
  white-space: nowrap;
}
.ucard__stat-cell-eye {
  flex-shrink: 0;
  color: var(--color-text-muted);
  opacity: 0.55;
  transition: opacity var(--transition-fast), color var(--transition-fast);
}
.ucard__stat-cell:hover .ucard__stat-cell-eye {
  opacity: 1;
  color: var(--color-primary);
}

/* Copy cell icon / label / value */
.ucard__copy-cell-icon {
  flex-shrink: 0;
  color: var(--color-text-muted);
  display: flex;
  align-items: center;
}
.ucard__copy-cell-label {
  font-size: var(--font-size-xs);
  font-weight: var(--font-weight-semibold);
  color: var(--color-text-muted);
  text-transform: uppercase;
  letter-spacing: var(--tracking-wide);
  flex-shrink: 0;
}
.ucard__copy-cell-value {
  flex: 1;
  font-family: var(--font-family-mono);
  font-size: var(--font-size-xs);
  color: var(--color-text-secondary);
  white-space: nowrap;
  overflow: hidden;
  text-overflow: ellipsis;
}

/* Copied flash badge */
.ucard__uid-copied {
  position: absolute;
  right: var(--space-3);
  font-size: var(--font-size-xs);
  font-weight: var(--font-weight-semibold);
  color: var(--color-success);
  pointer-events: none;
  background: inherit;
}

/* ── Hover tooltip (portal-rendered) ────────────────────────────────────── */
.ucard__tooltip {
  display: flex;
  flex-direction: column;
  gap: 2px;
  background: var(--color-bg-elevated);
  border: 1px solid var(--color-border-strong);
  border-radius: var(--radius-md);
  box-shadow: var(--shadow-lg);
  padding: var(--space-2) var(--space-3);
  max-width: 320px;
  pointer-events: auto;
}
.ucard__tooltip-label {
  font-size: var(--font-size-xs);
  font-weight: var(--font-weight-semibold);
  color: var(--color-text-muted);
  text-transform: uppercase;
  letter-spacing: var(--tracking-wide);
  line-height: 1.3;
}
.ucard__tooltip-value {
  font-size: var(--font-size-sm);
  color: var(--color-text-primary);
  word-break: break-all;
  line-height: 1.5;
}

/* ── Status change dropdown (portal-rendered) ────────────────────────────── */
.ucard__status-menu {
  min-width: 140px;
  background: var(--color-bg-elevated);
  border: 1px solid var(--color-border-strong);
  border-radius: var(--radius-md);
  box-shadow: var(--shadow-lg);
  overflow: hidden;
}
.ucard__status-option {
  display: flex;
  align-items: center;
  justify-content: space-between;
  gap: var(--space-2);
  width: 100%;
  padding: var(--space-2) var(--space-3);
  background: transparent;
  border: none;
  cursor: pointer;
  transition: background-color var(--transition-fast);
  font-family: var(--font-family-base);
}
.ucard__status-option:hover {
  background: var(--color-bg-island);
}
.ucard__status-option--active {
  background: var(--color-bg-island);
}

/* ── Last active strip ───────────────────────────────────────────────────── */
.ucard__last-active {
  display: flex;
  align-items: center;
  gap: var(--space-2);
  font-size: var(--font-size-sm);
  color: var(--color-text-muted);
}

/* ── Empty state ─────────────────────────────────────────────────────────── */
.ucard-empty {
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  gap: var(--space-3);
  padding: var(--space-16) var(--space-8);
  text-align: center;
  width: 100%;
}
.ucard-empty__icon {
  display: flex;
  align-items: center;
  justify-content: center;
  width: 64px;
  height: 64px;
  border-radius: var(--radius-xl);
  background: var(--color-bg-elevated);
  margin-bottom: var(--space-2);
}
.ucard-empty__title {
  font-size: var(--font-size-base);
  font-weight: var(--font-weight-semibold);
  color: var(--color-text-secondary);
  margin: 0;
}
.ucard-empty__sub {
  font-size: var(--font-size-sm);
  color: var(--color-text-muted);
  margin: 0;
}

/* ── Skeleton shimmer ────────────────────────────────────────────────────── */
.ucard--skeleton {
  cursor: default;
  pointer-events: none;
}
.ucard-skel {
  background: linear-gradient(
    90deg,
    var(--color-bg-elevated) 0%,
    var(--color-bg-island)   50%,
    var(--color-bg-elevated) 100%
  );
  background-size: 200% 100%;
  animation: ucard-shimmer 1.4s ease-in-out infinite;
  border-radius: var(--radius-sm);
}
.ucard-skel--circle { border-radius: var(--radius-full); }
@keyframes ucard-shimmer {
  0%   { background-position: 200% 0; }
  100% { background-position: -200% 0; }
}

/* ── Responsive ──────────────────────────────────────────────────────────── */
@media (max-width: 768px) {
  .ucard-grid {
    grid-template-columns: 1fr;
    gap: var(--space-3);
  }
}
`
