// frontend/src/pages/bellcloud/devices/tabs/OverviewTab.jsx
// Overview tab — Hero (photo | hw info | subscription+warranty | uptime+issue),
//                Row 2 (auth access 30% | issues & notes 70%), Row 3 (live logs)

import { useState, useEffect, useRef, useCallback } from 'react'
import { useNavigate } from 'react-router-dom'
import api from '@/lib/api'
import { useToast } from '@/components/ui/Toast'
import Button from '@/components/ui/Button'
import StatusBadge from '@/components/ui/StatusBadge'
import Spinner from '@/components/ui/Spinner'
import Icon from '@/components/ui/Icon'
import { fmtDateMedium, fmtRelative } from '@/lib/formatters'
import { useMqttWebSocket } from '@/hooks/useMqttWebSocket'
import {
  parseFirestoreDate,
  addDays,
  daysUntil,
} from './shared'
import DeviceNoteModal from '@/modals/bellcloud/devices/DeviceNoteModal'
import EntryFormModal  from '@/modals/crm/helpdesk/EntryFormModal'

// ─── Glass surface tokens ─────────────────────────────────────────────────────

const GLASS       = 'rgba(28, 32, 38, 0.30)'
const GLASS_INNER = 'rgba(28, 32, 38, 0.40)'
const GLASS_HOVER = 'rgba(49, 53, 60, 0.50)'
const BLUR        = 'blur(12px)'

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

function calcPeriodProgress(start, end) {
  if (!start || !end) return null
  const total = end.getTime() - start.getTime()
  if (total <= 0) return null
  const elapsed = Date.now() - start.getTime()
  return Math.max(0, Math.min(100, (elapsed / total) * 100))
}

function formatUptime(seconds) {
  if (seconds == null) return null
  const d = Math.floor(seconds / 86400)
  const h = Math.floor((seconds % 86400) / 3600)
  const m = Math.floor((seconds % 3600) / 60)
  return [d && `${d}d`, h && `${h}h`, m && `${m}m`].filter(Boolean).join(' ') || '< 1m'
}

function subscrDurationLabel(days) {
  if (!days) return null
  if (days % 365 === 0) return `${days / 365} yr`
  if (days % 30 === 0) return `${days / 30} mo`
  return `${days}d`
}

// ─── Sub-components ───────────────────────────────────────────────────────────

function GlassCard({ children, style = {}, className = '' }) {
  return (
    <div
      className={className}
      style={{
        background: GLASS,
        backdropFilter: BLUR,
        WebkitBackdropFilter: BLUR,
        border: '1px solid var(--color-border)',
        borderRadius: 'var(--radius-xl)',
        boxShadow: 'var(--shadow-card), var(--shadow-md)',
        ...style,
      }}
    >
      {children}
    </div>
  )
}

function SectionLabel({ children }) {
  return (
    <span style={{
      fontSize: 'var(--font-size-xs)',
      fontWeight: 'var(--font-weight-semibold)',
      color: 'var(--color-text-muted)',
      letterSpacing: 'var(--tracking-wide)',
      textTransform: 'uppercase',
    }}>
      {children}
    </span>
  )
}

function InfoField({ label, children, mono = false }) {
  return (
    <div style={{ display: 'flex', flexDirection: 'column', gap: 'var(--space-1)' }}>
      <span style={{
        fontSize: 'var(--font-size-xs)',
        fontWeight: 'var(--font-weight-semibold)',
        color: 'var(--color-text-more-muted)',
        letterSpacing: 'var(--tracking-wide)',
        textTransform: 'uppercase',
      }}>
        {label}
      </span>
      <span style={{
        fontSize: 'var(--font-size-base)',
        fontWeight: 'var(--font-weight-medium)',
        color: 'var(--color-text-primary)',
        fontFamily: mono ? 'var(--font-family-mono)' : 'inherit',
        lineHeight: 1.4,
      }}>
        {children || '—'}
      </span>
    </div>
  )
}

function ProgressTrack({ value, variant = 'primary' }) {
  const pct = Number.isFinite(value) ? Math.max(0, Math.min(100, value)) : 0
  const color =
    variant === 'success' ? 'var(--color-success)' :
    variant === 'danger'  ? 'var(--color-danger)'  :
    variant === 'warning' ? 'var(--color-warning)'  :
    'var(--color-primary)'
  return (
    <div style={{
      height: 4,
      borderRadius: 'var(--radius-full)',
      background: GLASS_INNER,
      overflow: 'hidden',
    }}>
      <div style={{
        height: '100%',
        width: `${pct}%`,
        backgroundColor: color,
        borderRadius: 'var(--radius-full)',
        transition: 'width 0.4s ease',
        boxShadow: `0 0 8px ${color}60`,
      }} />
    </div>
  )
}


// Log level colour map
const LOG_COLORS = {
  ERROR: { text: 'var(--color-danger)',  bg: 'var(--color-danger-bg)'  },
  WARN:  { text: 'var(--color-warning)', bg: 'var(--color-warning-bg)' },
  INFO:  { text: 'var(--color-info)',    bg: 'var(--color-info-bg)'    },
}

// Level slider steps: 0=All, 1=INFO, 2=WARN, 3=ERROR
const LEVEL_STEPS = [
  { value: '',      label: 'ALL',   color: 'var(--color-text-muted)'  },
  { value: 'INFO',  label: 'INFO',  color: 'var(--color-info)'        },
  { value: 'WARN',  label: 'WARN',  color: 'var(--color-warning)'     },
  { value: 'ERROR', label: 'ERROR', color: 'var(--color-danger)'      },
]

// ─── OverviewTab ──────────────────────────────────────────────────────────────

export default function OverviewTab({
  device,
  canEdit,
  sub,
  stats,
  sn,
  isOnline,
  mqttStatus,
  staffNotes,
  setStaffNotes,
  deviceUsers,
  usersLoading,
  onNavigateToManage,
}) {
  const navigate  = useNavigate()
  const { toast } = useToast()
  const id        = device?.id || device?.device_id

  // ── Quick note ────────────────────────────────────────────────────────────
  const [editingNote, setEditingNote] = useState(false)
  const [noteText, setNoteText]       = useState(staffNotes || '')
  const [savingNote, setSavingNote]   = useState(false)
  const noteRef = useRef(null)

  useEffect(() => { setNoteText(staffNotes || '') }, [staffNotes])

  const saveNote = async (val) => {
    setSavingNote(true)
    try {
      await api.put(`/devices/${id}`, { staffNotes: val })
      setStaffNotes(val)
      setEditingNote(false)
      toast.success('Saved', 'Quick note updated.')
    } catch (err) {
      toast.danger('Error', err.message || 'Failed to save note.')
    } finally {
      setSavingNote(false)
    }
  }

  // ── Hardware image ────────────────────────────────────────────────────────
  const [hwImage, setHwImage]     = useState('/devices/VesperPlus.png')
  const [hwVariant, setHwVariant] = useState('VesperPlus')
  const [hwRevision, setHwRevision] = useState(null)

  useEffect(() => {
    if (!sn) return
    Promise.all([
      api.get(`/manufacturing/devices/${sn}`).catch(() => null),
      api.get('/crm/products').catch(() => null),
    ]).then(([mfgItem, productsRes]) => {
      if (mfgItem?.revision) setHwRevision(mfgItem.revision)
      const hwType = mfgItem?.hw_type || ''
      if (!hwType) return
      const products = productsRes?.products || []
      const norm = s => (s || '').toLowerCase().replace(/[^a-z0-9]/g, '')
      const normHw = norm(hwType)
      const match = products.find(
        p => norm(p.name) === normHw || norm(p.sku) === normHw ||
             norm(p.name).includes(normHw) || normHw.includes(norm(p.name))
      )
      if (match) {
        setHwVariant(match.name)
        if (match.photo_url) setHwImage(`/api${match.photo_url}`)
      }
    }).catch(() => {})
  }, [sn])

  // ── Issues + Notes ────────────────────────────────────────────────────────
  const [notes, setNotes]             = useState([])
  const [notesLoading, setNotesLoading] = useState(false)

  const loadNotes = useCallback(async () => {
    if (!id) return
    setNotesLoading(true)
    try {
      const data = await api.get(`/devices/${id}/notes`)
      setNotes(data.notes || [])
    } catch {
      setNotes([])
    } finally {
      setNotesLoading(false)
    }
  }, [id])

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

  const [issues, setIssues]             = useState([])
  const [issuesLoading, setIssuesLoading] = useState(false)

  const loadIssues = useCallback(async () => {
    if (!id) return
    setIssuesLoading(true)
    try {
      const data = await api.get(`/notes/by-entity/device/${id}`)
      setIssues(Array.isArray(data) ? data : [])
    } catch {
      setIssues([])
    } finally {
      setIssuesLoading(false)
    }
  }, [id])

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

  const [noteModal,  setNoteModal]  = useState({ open: false })
  const [issueModal, setIssueModal] = useState({ open: false, entry: null })
  const [viewNote,   setViewNote]   = useState(null)

  const handleNoteSaved = () => {
    setNoteModal({ open: false })
    loadNotes()
  }

  const handleIssueSaved = () => {
    setIssueModal({ open: false, entry: null })
    loadIssues()
  }

  // ── Live logs ─────────────────────────────────────────────────────────────
  const [logs, setLogs]               = useState([])
  const [logsLoading, setLogsLoading] = useState(false)
  const [levelStep, setLevelStep]     = useState(0)   // index into LEVEL_STEPS
  const [searchText, setSearchText]   = useState('')
  const [autoScroll, setAutoScroll]   = useState(true)
  const [autoRefresh, setAutoRefresh] = useState(false)
  const [liveLogs, setLiveLogs]       = useState([])
  const logsContainerRef = useRef(null)
  const LIMIT = 50

  const levelFilter = LEVEL_STEPS[levelStep].value

  const fetchLogs = useCallback(async () => {
    if (!sn) return
    setLogsLoading(true)
    try {
      const params = new URLSearchParams({ limit: LIMIT, offset: 0 })
      if (levelFilter) params.set('level', levelFilter)
      if (searchText)  params.set('search', searchText)
      const data = await api.get(`/mqtt/logs/${sn}?${params}`)
      setLogs(data.logs || [])
    } catch {
      // silent
    } finally {
      setLogsLoading(false)
    }
  }, [sn, levelFilter, searchText])

  useEffect(() => { if (sn) fetchLogs() }, [sn, fetchLogs])

  useEffect(() => {
    if (!autoRefresh || !sn) return
    const t = setInterval(fetchLogs, 5000)
    return () => clearInterval(t)
  }, [autoRefresh, sn, fetchLogs])

  const handleWsMessage = useCallback((data) => {
    if (data.type === 'logs' && data.device_serial === sn) {
      const entry = {
        id: Date.now(),
        level: data.payload?.level?.includes('EROR') ? 'ERROR' :
               data.payload?.level?.includes('WARN') ? 'WARN'  : 'INFO',
        message: data.payload?.message || '',
        received_at: new Date().toISOString(),
        _live: true,
      }
      setLiveLogs(prev => [entry, ...prev].slice(0, 50))
    }
  }, [sn])

  useMqttWebSocket({ enabled: true, onMessage: handleWsMessage })

  const allLogs = [
    ...liveLogs.filter(l => {
      if (levelFilter && l.level !== levelFilter) return false
      if (searchText && !l.message.toLowerCase().includes(searchText.toLowerCase())) return false
      return true
    }),
    ...logs,
  ]

  useEffect(() => {
    if (autoScroll && logsContainerRef.current) {
      logsContainerRef.current.scrollTop = 0
    }
  }, [allLogs.length, autoScroll])

  // ── Service lifecycle ─────────────────────────────────────────────────────
  const subscrStart    = parseFirestoreDate(sub?.subscrStart)
  const subscrEnd      = subscrStart && sub?.subscrDuration ? addDays(subscrStart, sub.subscrDuration) : null
  const subscrDaysLeft = subscrEnd ? daysUntil(subscrEnd) : null
  const subscrProgress = calcPeriodProgress(subscrStart, subscrEnd)

  const warrantyStart    = parseFirestoreDate(stats?.warrantyStart)
  const warrantyEnd      = warrantyStart && stats?.warrantyPeriod ? addDays(warrantyStart, stats.warrantyPeriod) : null
  const warrantyDaysLeft = warrantyEnd ? daysUntil(warrantyEnd) : null
  const warrantyProgress = calcPeriodProgress(warrantyStart, warrantyEnd)

  const warrantyIsVoid = stats?.warrantyActive === false
  const warrantyOk     = warrantyIsVoid ? false : (warrantyDaysLeft === null ? stats?.warrantyActive : warrantyDaysLeft > 0)
  const warrantyVariant = warrantyIsVoid ? 'warning' : warrantyOk ? 'success' : 'danger'
  const warrantyLabel   = warrantyIsVoid ? 'Void' : warrantyOk ? 'Active' : 'Expired'

  const subscrVariant = subscrDaysLeft === null ? 'neutral' :
    subscrDaysLeft > 30 ? 'success' :
    subscrDaysLeft > 0  ? 'warning' : 'danger'

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

  return (
    <div style={{ display: 'flex', flexDirection: 'column', gap: 'var(--space-6)', width: '100%', maxWidth: 2000, margin: '0 auto' }}>

      {/* ── ROW 1: Hero card ────────────────────────────────────────────── */}
      <GlassCard style={{ display: 'flex', alignItems: 'stretch', overflow: 'hidden' }}>

        {/* ── Online accent line (left edge of entire hero) ── */}
        <div style={{
          width: 3,
          flexShrink: 0,
          borderRadius: 'var(--radius-xl) 0 0 var(--radius-xl)',
          background: isOnline
            ? 'linear-gradient(to bottom, transparent, var(--color-success) 30%, var(--color-success) 70%, transparent)'
            : 'transparent',
          boxShadow: isOnline ? '0 0 12px rgba(74,222,128,0.50)' : 'none',
          transition: 'background 0.4s, box-shadow 0.4s',
        }} />

        {/* ── Section A: Device photo ── */}
        <div style={{
          width: 197,
          flexShrink: 0,
          display: 'flex',
          alignItems: 'center',
          justifyContent: 'center',
          padding: 'var(--space-6)',
          position: 'relative',
        }}>
          {/* Pulsating glow when online */}
          {isOnline && (
            <>
              <div style={{
                position: 'absolute',
                inset: 0,
                background: 'radial-gradient(ellipse at center, rgba(74,222,128,0.22) 0%, transparent 68%)',
                pointerEvents: 'none',
                animation: 'ov-glow 2.8s ease-in-out infinite',
              }} />
              {/* Expanding ring */}
              <div style={{
                position: 'absolute',
                top: '50%',
                left: '50%',
                transform: 'translate(-50%, -50%)',
                width: 110,
                height: 110,
                borderRadius: '50%',
                border: '1.5px solid rgba(74,222,128,0.35)',
                pointerEvents: 'none',
                animation: 'ov-ring 2.8s ease-out infinite',
              }} />
            </>
          )}
          <div style={{ position: 'relative' }}>
            <img
              src={hwImage}
              alt={hwVariant}
              style={{ width: 130, height: 130, objectFit: 'contain', display: 'block' }}
              onError={e => { e.target.src = '/devices/VesperPlus.png' }}
            />
          </div>
        </div>


        {/* ── Section B: Hardware info ── */}
        <div style={{
          flex: 1,
          padding: 'var(--space-6)',
          display: 'flex',
          flexDirection: 'column',
          justifyContent: 'center',
          gap: 'var(--space-4)',
          minWidth: 0,
        }}>
          <div style={{ display: 'grid', gridTemplateColumns: '1fr 1fr', gap: 'var(--space-5) var(--space-8)', maxWidth: 480 }}>
            <InfoField label="Serial Number" mono>{sn || '—'}</InfoField>
            <InfoField label="Hardware Family">{hwVariant}</InfoField>
            <InfoField label="Location">{device.device_location || '—'}</InfoField>
            <InfoField label="Hardware Revision">{hwRevision || device.device_attributes?.firmwareVersion || '—'}</InfoField>
          </div>
        </div>


        {/* ── Section D: Uptime + Latest Issue ── */}
        <div style={{
          width: 220,
          flexShrink: 0,
          padding: 'var(--space-6)',
          display: 'flex',
          flexDirection: 'column',
          justifyContent: 'center',
          gap: 'var(--space-5)',
          minWidth: 0,
        }}>
          <InfoField label="Device Uptime">
            {mqttStatus?.uptime_seconds != null
              ? <span style={{ fontFamily: 'var(--font-family-mono)', fontSize: 'var(--font-size-base)' }}>{formatUptime(mqttStatus.uptime_seconds)}</span>
              : <span style={{ color: 'var(--color-text-muted)', fontStyle: 'italic', fontWeight: 'var(--font-weight-normal)' }}>Unavailable</span>}
          </InfoField>

          <div style={{ display: 'flex', flexDirection: 'column', gap: 'var(--space-3)' }}>
            <span style={{ fontSize: 'var(--font-size-xs)', fontWeight: 'var(--font-weight-semibold)', color: 'var(--color-text-more-muted)', letterSpacing: 'var(--tracking-wide)', textTransform: 'uppercase' }}>Latest Device Issue</span>
            {mqttStatus?.last_warn_message ? (
              <div style={{ display: 'flex', flexDirection: 'column', gap: 'var(--space-1)' }}>
                <span style={{
                  fontSize: 'var(--font-size-xs)',
                  color: 'var(--color-warning)',
                  fontWeight: 'var(--font-weight-semibold)',
                  letterSpacing: 'var(--tracking-wide)',
                  textTransform: 'uppercase',
                }}>
                  MQTT · WARN · Health Monitor
                </span>
                <span style={{
                  fontSize: 'var(--font-size-sm)',
                  color: 'var(--color-text-secondary)',
                  lineHeight: 1.5,
                }}>
                  {mqttStatus.last_warn_message}
                </span>
              </div>
            ) : (
              <span style={{ fontSize: 'var(--font-size-sm)', color: 'var(--color-text-muted)', fontStyle: 'italic' }}>
                No recent issues
              </span>
            )}
          </div>
        </div>


        {/* ── Section C: Subscription + Warranty ── */}
        <div style={{
          flex: 1,
          padding: 'var(--space-6)',
          display: 'flex',
          flexDirection: 'column',
          justifyContent: 'center',
          gap: 'var(--space-5)',
          minWidth: 0,
        }}>
          {/* Subscription row */}
          <div style={{ display: 'flex', flexDirection: 'column', gap: 'var(--space-3)' }}>
            <div style={{ display: 'flex', alignItems: 'center', justifyContent: 'space-between' }}>
              <span style={{ fontSize: 'var(--font-size-sm)', color: 'var(--color-text-secondary)', fontWeight: 'var(--font-weight-medium)' }}>
                Subscription
              </span>
              <div style={{ display: 'flex', alignItems: 'center', gap: 'var(--space-2)' }}>
                {sub?.subscrTier ? (
                  <StatusBadge variant={subscrVariant}>
                    {sub.subscrTier}
                    {sub.subscrDuration ? ` · ${subscrDurationLabel(sub.subscrDuration)}` : ''}
                  </StatusBadge>
                ) : (
                  <StatusBadge variant="neutral">Not set</StatusBadge>
                )}
              </div>
            </div>
            <ProgressTrack value={subscrProgress ?? 0} variant={subscrVariant === 'neutral' ? 'primary' : subscrVariant} />
            <div style={{ display: 'flex', justifyContent: 'space-between' }}>
              <span style={{ fontSize: 'var(--font-size-xs)', color: 'var(--color-text-muted)' }}>
                {subscrStart ? fmtDateMedium(subscrStart) : '—'}
              </span>
              <span style={{
                fontSize: 'var(--font-size-xs)',
                fontWeight: 'var(--font-weight-semibold)',
                color: subscrDaysLeft === null ? 'var(--color-text-muted)' :
                       subscrDaysLeft > 30 ? 'var(--color-success)' :
                       subscrDaysLeft > 0  ? 'var(--color-warning)' : 'var(--color-danger)',
              }}>
                {subscrDaysLeft === null ? '—' : subscrDaysLeft > 0 ? `${subscrDaysLeft}d left` : 'Expired'}
              </span>
              <span style={{ fontSize: 'var(--font-size-xs)', color: 'var(--color-text-muted)' }}>
                {subscrEnd ? fmtDateMedium(subscrEnd) : '—'}
              </span>
            </div>
          </div>

          {/* Warranty row */}
          <div style={{ display: 'flex', flexDirection: 'column', gap: 'var(--space-3)' }}>
            <div style={{ display: 'flex', alignItems: 'center', justifyContent: 'space-between' }}>
              <span style={{ fontSize: 'var(--font-size-sm)', color: 'var(--color-text-secondary)', fontWeight: 'var(--font-weight-medium)' }}>
                Warranty
              </span>
              <StatusBadge variant={warrantyVariant}>{warrantyLabel}</StatusBadge>
            </div>
            <ProgressTrack value={warrantyProgress ?? 0} variant={warrantyVariant} />
            <div style={{ display: 'flex', justifyContent: 'space-between' }}>
              <span style={{ fontSize: 'var(--font-size-xs)', color: 'var(--color-text-muted)' }}>
                {warrantyStart ? fmtDateMedium(warrantyStart) : '—'}
              </span>
              <span style={{
                fontSize: 'var(--font-size-xs)',
                fontWeight: 'var(--font-weight-semibold)',
                color: warrantyOk ? 'var(--color-success)' : warrantyIsVoid ? 'var(--color-warning)' : 'var(--color-danger)',
              }}>
                {warrantyDaysLeft === null ? '—' : warrantyDaysLeft > 0 ? `${warrantyDaysLeft}d left` : 'Expired'}
              </span>
              <span style={{ fontSize: 'var(--font-size-xs)', color: 'var(--color-text-muted)' }}>
                {warrantyEnd ? fmtDateMedium(warrantyEnd) : '—'}
              </span>
            </div>
          </div>
        </div>

      </GlassCard>

      {/* ── ROW 1.5: Quick Note (full width, compact) ────────────────────── */}
      <GlassCard style={{ padding: 'var(--space-4) var(--space-5)' }}>
        <div style={{ display: 'flex', alignItems: 'flex-start', gap: 'var(--space-4)' }}>
          <div style={{ display: 'flex', alignItems: 'center', gap: 'var(--space-2)', paddingTop: 2, flexShrink: 0 }}>
            <Icon name="edit" size={14} color="var(--color-primary)" />
            <SectionLabel>Quick Note</SectionLabel>
          </div>

          {editingNote ? (
            <div style={{ flex: 1, display: 'flex', flexDirection: 'column', gap: 'var(--space-3)' }}>
              <textarea
                ref={noteRef}
                value={noteText}
                onChange={e => setNoteText(e.target.value)}
                placeholder="Add a quick note to help identify this device…"
                rows={3}
                onKeyDown={e => {
                  if (e.key === 'Escape') setEditingNote(false)
                  if (e.key === 'Enter' && (e.ctrlKey || e.metaKey)) saveNote(noteText)
                }}
                style={{
                  resize: 'vertical',
                  background: GLASS_INNER,
                  backdropFilter: BLUR,
                  WebkitBackdropFilter: BLUR,
                  border: '1px solid var(--color-border-strong)',
                  borderRadius: 'var(--radius-md)',
                  padding: 'var(--space-3)',
                  fontSize: 'var(--font-size-sm)',
                  color: 'var(--color-text-primary)',
                  fontFamily: 'var(--font-family-base)',
                  lineHeight: 1.6,
                  outline: 'none',
                  width: '100%',
                }}
              />
              <div style={{ display: 'flex', gap: 'var(--space-2)' }}>
                <Button variant="ghost" size="sm" onClick={() => setEditingNote(false)}>Cancel</Button>
                <Button variant="primary" size="sm" loading={savingNote} onClick={() => saveNote(noteText)}>Save</Button>
              </div>
            </div>
          ) : (
            <p
              onClick={canEdit ? () => { setEditingNote(true); setTimeout(() => noteRef.current?.focus(), 0) } : undefined}
              style={{
                flex: 1,
                fontSize: 'var(--font-size-sm)',
                color: noteText ? 'var(--color-text-secondary)' : 'var(--color-text-muted)',
                lineHeight: 1.6,
                cursor: canEdit ? 'text' : 'default',
                fontStyle: noteText ? 'normal' : 'italic',
                paddingTop: 2,
              }}
            >
              {noteText || 'No quick note set. Click to add one…'}
            </p>
          )}

          {canEdit && !editingNote && (
            <Button variant="ghost" size="sm" onClick={() => { setEditingNote(true); setTimeout(() => noteRef.current?.focus(), 0) }} style={{ flexShrink: 0 }}>
              Edit
            </Button>
          )}
        </div>
      </GlassCard>

      {/* ── ROW 2: Auth Access (30%) + Issues & Notes (70%) ─────────────── */}
      <div style={{ display: 'grid', gridTemplateColumns: '30fr 70fr', gap: 'var(--space-6)' }} className="overview-row2">

        {/* Auth Access */}
        <GlassCard style={{ padding: 'var(--space-5)', display: 'flex', flexDirection: 'column', gap: 'var(--space-4)' }}>
          <div style={{ display: 'flex', alignItems: 'center', justifyContent: 'space-between' }}>
            <SectionLabel>Auth Access</SectionLabel>
            {deviceUsers.length > 0 && (
              <span style={{
                fontSize: 'var(--font-size-xs)',
                color: 'var(--color-text-muted)',
                background: GLASS_INNER,
                padding: '2px var(--space-2)',
                borderRadius: 'var(--radius-full)',
                border: '1px solid var(--color-border)',
              }}>
                {deviceUsers.length}
              </span>
            )}
          </div>

          <div style={{ display: 'flex', flexDirection: 'column', gap: 'var(--space-2)' }}>
            {usersLoading ? (
              <div style={{ display: 'flex', justifyContent: 'center', padding: 'var(--space-4)' }}>
                <Spinner size="sm" />
              </div>
            ) : deviceUsers.length === 0 ? (
              <p style={{ fontSize: 'var(--font-size-sm)', color: 'var(--color-text-muted)', fontStyle: 'italic' }}>
                No users assigned to this device.
              </p>
            ) : (
              deviceUsers.map((user, i) => (
                <div
                  key={user.user_id || i}
                  onClick={() => user.user_id && navigate(`/users/${user.user_id}`)}
                  style={{
                    display: 'flex',
                    alignItems: 'center',
                    gap: 'var(--space-3)',
                    padding: 'var(--space-2) var(--space-3)',
                    borderRadius: 'var(--radius-md)',
                    background: GLASS_INNER,
                    border: '1px solid var(--color-border)',
                    cursor: user.user_id ? 'pointer' : 'default',
                    transition: 'background 0.15s',
                  }}
                  onMouseEnter={e => e.currentTarget.style.background = GLASS_HOVER}
                  onMouseLeave={e => e.currentTarget.style.background = GLASS_INNER}
                >
                  <div style={{
                    width: 32,
                    height: 32,
                    borderRadius: '50%',
                    overflow: 'hidden',
                    background: 'var(--color-primary-subtle)',
                    flexShrink: 0,
                    display: 'flex',
                    alignItems: 'center',
                    justifyContent: 'center',
                    fontSize: 'var(--font-size-sm)',
                    fontWeight: 'var(--font-weight-semibold)',
                    color: 'var(--color-primary)',
                    border: '1px solid rgba(192,193,255,0.20)',
                  }}>
                    {user.photo_url ? (
                      <img src={user.photo_url} alt="" style={{ width: '100%', height: '100%', objectFit: 'cover' }} />
                    ) : (
                      (user.display_name || user.email || '?').charAt(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)', overflow: 'hidden', textOverflow: 'ellipsis', whiteSpace: 'nowrap' }}>
                      {user.display_name || user.email || 'Unknown User'}
                    </p>
                    {user.email && user.display_name && (
                      <p style={{ fontSize: 'var(--font-size-xs)', color: 'var(--color-text-muted)', overflow: 'hidden', textOverflow: 'ellipsis', whiteSpace: 'nowrap' }}>
                        {user.email}
                      </p>
                    )}
                  </div>
                  {user.role && <StatusBadge variant="info">{user.role}</StatusBadge>}
                </div>
              ))
            )}
          </div>
        </GlassCard>

        {/* Issues & Notes */}
        <GlassCard style={{ padding: 'var(--space-5)', display: 'flex', flexDirection: 'column', gap: 'var(--space-4)' }}>
          <div style={{ display: 'flex', alignItems: 'center', justifyContent: 'space-between', gap: 'var(--space-3)' }}>
            <div style={{ display: 'flex', alignItems: 'center', gap: 'var(--space-3)' }}>
              <SectionLabel>Issues &amp; Notes</SectionLabel>
              {(notes.length + issues.length) > 0 && (
                <span style={{
                  fontSize: 'var(--font-size-xs)',
                  color: 'var(--color-text-muted)',
                  background: GLASS_INNER,
                  padding: '2px var(--space-2)',
                  borderRadius: 'var(--radius-full)',
                  border: '1px solid var(--color-border)',
                }}>
                  {notes.length + issues.length}
                </span>
              )}
            </div>
            <div style={{ display: 'flex', gap: 'var(--space-2)', flexShrink: 0 }}>
              {canEdit && (
                <>
                  <Button variant="ghost" size="sm" icon={<Icon name="plus" size={12} />} onClick={() => setNoteModal({ open: true })}>
                    Add Note
                  </Button>
                  <Button variant="ghost" size="sm" icon={<Icon name="plus" size={12} />} onClick={() => setIssueModal({ open: true, entry: null })}>
                    Record Issue
                  </Button>
                </>
              )}
              <Button variant="ghost" size="sm" onClick={onNavigateToManage}>
                Edit
              </Button>
            </div>
          </div>

          {/* Notes */}
          <div style={{ display: 'flex', flexDirection: 'column', gap: 'var(--space-2)' }}>
            {notesLoading ? (
              <div style={{ display: 'flex', justifyContent: 'center', padding: 'var(--space-4)' }}>
                <Spinner size="sm" />
              </div>
            ) : notes.length === 0 ? (
              <p style={{ fontSize: 'var(--font-size-sm)', color: 'var(--color-text-muted)', fontStyle: 'italic' }}>
                No notes for this device.
              </p>
            ) : (
              <div style={{
                display: 'grid',
                gridTemplateColumns: notes.length === 1 ? '1fr' : notes.length === 2 ? '1fr 1fr' : 'repeat(3, 1fr)',
                gap: 'var(--space-3)',
              }}>
                {notes.map((note, i) => (
                  <div
                    key={note.id || i}
                    onClick={() => setViewNote(note)}
                    style={{
                      padding: 'var(--space-3)',
                      borderRadius: 'var(--radius-md)',
                      background: GLASS_INNER,
                      border: '1px solid var(--color-border)',
                      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)'}
                  >
                    <p style={{
                      fontSize: 'var(--font-size-sm)',
                      color: 'var(--color-text-primary)',
                      lineHeight: 1.5,
                      marginBottom: note.created_at ? 'var(--space-2)' : 0,
                      overflow: 'hidden',
                      display: '-webkit-box',
                      WebkitLineClamp: 3,
                      WebkitBoxOrient: 'vertical',
                    }}>
                      {note.content || note.text || '—'}
                    </p>
                    {note.created_at && (
                      <p style={{ fontSize: 'var(--font-size-xs)', color: 'var(--color-text-muted)' }}>
                        {fmtRelative(note.created_at)}
                        {note.created_by ? ` · ${note.created_by}` : ''}
                      </p>
                    )}
                  </div>
                ))}
              </div>
            )}
          </div>

          {/* Issues */}
          {(issuesLoading || issues.length > 0) && (
            <div style={{ display: 'flex', flexDirection: 'column', gap: 'var(--space-2)', borderTop: '1px solid var(--color-border)', paddingTop: 'var(--space-3)' }}>
              <SectionLabel>Linked Issues</SectionLabel>
              {issuesLoading ? (
                <div style={{ display: 'flex', justifyContent: 'center', padding: 'var(--space-4)' }}>
                  <Spinner size="sm" />
                </div>
              ) : (
                <div style={{ display: 'flex', flexDirection: 'column', gap: 'var(--space-2)' }}>
                  {issues.map((issue, i) => {
                    const statusColors = {
                      open:        { color: 'var(--color-danger)',  bg: 'var(--color-danger-bg)'  },
                      researching: { color: 'var(--color-warning)', bg: 'var(--color-warning-bg)' },
                      resolved:    { color: 'var(--color-success)', bg: 'var(--color-success-bg)' },
                    }
                    const sc = statusColors[issue.status] || statusColors.open
                    return (
                      <div
                        key={issue.id || i}
                        onClick={() => setIssueModal({ open: true, entry: issue })}
                        style={{
                          display: 'flex',
                          alignItems: 'center',
                          gap: 'var(--space-3)',
                          padding: 'var(--space-2) var(--space-3)',
                          borderRadius: 'var(--radius-md)',
                          background: GLASS_INNER,
                          border: '1px solid var(--color-border)',
                          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)'}
                      >
                        <span style={{
                          display: 'inline-flex', alignItems: 'center', gap: 5,
                          padding: '2px 8px',
                          borderRadius: 'var(--radius-full)',
                          backgroundColor: sc.bg,
                          border: `1px solid ${sc.color}33`,
                          fontSize: 'var(--font-size-xs)',
                          fontWeight: 'var(--font-weight-semibold)',
                          color: sc.color,
                          whiteSpace: 'nowrap',
                          flexShrink: 0,
                        }}>
                          <span style={{ width: 5, height: 5, borderRadius: '50%', backgroundColor: sc.color, flexShrink: 0 }} />
                          {issue.status || 'open'}
                        </span>
                        <span style={{ flex: 1, fontSize: 'var(--font-size-sm)', color: 'var(--color-text-primary)', overflow: 'hidden', textOverflow: 'ellipsis', whiteSpace: 'nowrap' }}>
                          {issue.title}
                        </span>
                        {issue.created_at && (
                          <span style={{ fontSize: 'var(--font-size-xs)', color: 'var(--color-text-muted)', whiteSpace: 'nowrap', flexShrink: 0 }}>
                            {fmtRelative(issue.created_at)}
                          </span>
                        )}
                      </div>
                    )
                  })}
                </div>
              )}
            </div>
          )}
        </GlassCard>
      </div>

      {/* ── ROW 3: Live Logs ─────────────────────────────────────────────── */}
      <GlassCard style={{ overflow: 'hidden' }}>

        {/* Log panel header */}
        <div style={{
          display: 'flex',
          alignItems: 'center',
          gap: 'var(--space-4)',
          padding: 'var(--space-3) var(--space-5)',
          borderBottom: '1px solid var(--color-border)',
          flexWrap: 'wrap',
        }}>
          {/* Terminal traffic-light dots */}
          <div style={{ display: 'flex', gap: 5, marginRight: 'var(--space-2)', flexShrink: 0 }}>
            {['var(--color-danger)', 'var(--color-warning)', 'var(--color-success)'].map((c, i) => (
              <span key={i} style={{ width: 10, height: 10, borderRadius: '50%', background: c, opacity: 0.55 }} />
            ))}
          </div>

          <div style={{ display: 'flex', alignItems: 'center', gap: 'var(--space-2)', flexShrink: 0 }}>
            <SectionLabel>Live Logs</SectionLabel>
          </div>

          {/* Live pulse indicator */}
          {liveLogs.length > 0 && (
            <div style={{ display: 'flex', alignItems: 'center', gap: 'var(--space-1)', flexShrink: 0 }}>
              <span style={{
                width: 6, height: 6, borderRadius: '50%',
                background: 'var(--color-success)',
                boxShadow: '0 0 6px var(--color-success)',
                animation: 'ov-pulse 1.5s ease-in-out infinite',
                display: 'block',
              }} />
              <span style={{ fontSize: 'var(--font-size-xs)', color: 'var(--color-success)', fontWeight: 'var(--font-weight-semibold)', letterSpacing: 'var(--tracking-wide)' }}>
                LIVE
              </span>
            </div>
          )}

          <div style={{ flex: 1 }} />

          {/* Level colour slider */}
          <div style={{ display: 'flex', alignItems: 'center', gap: 'var(--space-3)', flexShrink: 0 }}>
            <SectionLabel>Level</SectionLabel>
            <div style={{ display: 'flex', gap: 'var(--space-1)', alignItems: 'center' }}>
              {LEVEL_STEPS.map((step, idx) => (
                <button
                  key={step.value}
                  onClick={() => { setLevelStep(idx); setLogs([]) }}
                  title={step.label}
                  style={{
                    height: 24,
                    paddingInline: 'var(--space-2)',
                    borderRadius: 'var(--radius-sm)',
                    border: `1px solid ${levelStep === idx ? step.color : 'var(--color-border)'}`,
                    background: levelStep === idx
                      ? `${step.color}22`
                      : GLASS_INNER,
                    color: levelStep === idx ? step.color : 'var(--color-text-muted)',
                    fontSize: 'var(--font-size-xs)',
                    fontWeight: 'var(--font-weight-semibold)',
                    letterSpacing: 'var(--tracking-wide)',
                    cursor: 'pointer',
                    transition: 'all 0.15s',
                    fontFamily: 'var(--font-family-base)',
                  }}
                >
                  {step.label}
                </button>
              ))}
            </div>
          </div>

          {/* Search */}
          <input
            type="text"
            value={searchText}
            onChange={e => setSearchText(e.target.value)}
            placeholder="Filter messages…"
            style={{
              height: 28,
              padding: '0 var(--space-3)',
              borderRadius: 'var(--radius-md)',
              border: '1px solid var(--color-border-strong)',
              background: GLASS_INNER,
              backdropFilter: BLUR,
              WebkitBackdropFilter: BLUR,
              color: 'var(--color-text-primary)',
              fontSize: 'var(--font-size-xs)',
              fontFamily: 'var(--font-family-base)',
              width: 160,
              outline: 'none',
              flexShrink: 0,
            }}
          />

          {/* Toggle: AUTO-SCROLL */}
          <button
            onClick={() => setAutoScroll(p => !p)}
            style={{
              height: 28,
              paddingInline: 'var(--space-3)',
              borderRadius: 'var(--radius-md)',
              border: `1px solid ${autoScroll ? 'var(--color-primary)' : 'var(--color-border-strong)'}`,
              background: autoScroll ? 'var(--color-primary-subtle)' : GLASS_INNER,
              color: autoScroll ? 'var(--color-primary)' : 'var(--color-text-muted)',
              fontSize: 'var(--font-size-xs)',
              fontWeight: 'var(--font-weight-semibold)',
              cursor: 'pointer',
              letterSpacing: 'var(--tracking-wide)',
              fontFamily: 'var(--font-family-base)',
              flexShrink: 0,
            }}
          >
            AUTO-SCROLL
          </button>

          {/* Toggle: AUTO-SYNC */}
          <button
            onClick={() => setAutoRefresh(p => !p)}
            style={{
              height: 28,
              paddingInline: 'var(--space-3)',
              borderRadius: 'var(--radius-md)',
              border: `1px solid ${autoRefresh ? 'var(--color-success)' : 'var(--color-border-strong)'}`,
              background: autoRefresh ? 'rgba(74,222,128,0.10)' : GLASS_INNER,
              color: autoRefresh ? 'var(--color-success)' : 'var(--color-text-muted)',
              fontSize: 'var(--font-size-xs)',
              fontWeight: 'var(--font-weight-semibold)',
              cursor: 'pointer',
              letterSpacing: 'var(--tracking-wide)',
              fontFamily: 'var(--font-family-base)',
              flexShrink: 0,
            }}
          >
            AUTO-SYNC
          </button>

          {/* Refresh — same visual style as the toggle buttons */}
          <button
            onClick={fetchLogs}
            disabled={logsLoading}
            style={{
              height: 28,
              paddingInline: 'var(--space-3)',
              borderRadius: 'var(--radius-md)',
              border: '1px solid var(--color-border-strong)',
              background: GLASS_INNER,
              color: 'var(--color-text-secondary)',
              fontSize: 'var(--font-size-xs)',
              fontWeight: 'var(--font-weight-semibold)',
              cursor: logsLoading ? 'not-allowed' : 'pointer',
              letterSpacing: 'var(--tracking-wide)',
              fontFamily: 'var(--font-family-base)',
              opacity: logsLoading ? 0.5 : 1,
              flexShrink: 0,
              display: 'flex',
              alignItems: 'center',
              gap: 'var(--space-1)',
            }}
          >
            {logsLoading ? <Spinner size="sm" /> : null}
            REFRESH
          </button>
        </div>

        {/* Log rows */}
        <div ref={logsContainerRef} style={{ maxHeight: 320, overflowY: 'auto', fontFamily: 'var(--font-family-mono)', fontSize: 'var(--font-size-sm)' }}>
          {logsLoading && allLogs.length === 0 ? (
            <div style={{ display: 'flex', justifyContent: 'center', padding: 'var(--space-8)' }}>
              <Spinner size="sm" />
            </div>
          ) : allLogs.length === 0 ? (
            <p style={{ padding: 'var(--space-8)', textAlign: 'center', color: 'var(--color-text-muted)', fontSize: 'var(--font-size-sm)', fontFamily: 'var(--font-family-base)', fontStyle: 'italic' }}>
              No logs found.
            </p>
          ) : (
            <table style={{ width: '100%', borderCollapse: 'collapse' }}>
              <thead>
                <tr style={{
                  position: 'sticky', top: 0,
                  background: GLASS_INNER, backdropFilter: BLUR, WebkitBackdropFilter: BLUR,
                  borderBottom: '1px solid var(--color-border)', zIndex: 1,
                }}>
                  {['Time', 'Level', 'Message'].map((h, i) => (
                    <th key={h} style={{
                      padding: 'var(--space-2) var(--space-4)',
                      textAlign: 'left',
                      width: i === 0 ? 160 : i === 1 ? 72 : undefined,
                      fontSize: 'var(--font-size-xs)',
                      color: 'var(--color-text-muted)',
                      fontWeight: 'var(--font-weight-semibold)',
                      letterSpacing: 'var(--tracking-wide)',
                      textTransform: 'uppercase',
                      fontFamily: 'var(--font-family-base)',
                    }}>
                      {h}
                    </th>
                  ))}
                </tr>
              </thead>
              <tbody>
                {allLogs.map((log, idx) => {
                  const s = LOG_COLORS[log.level] || LOG_COLORS.INFO
                  return (
                    <tr
                      key={log._live ? `live-${log.id}` : (log.id || idx)}
                      style={{
                        borderBottom: idx < allLogs.length - 1 ? '1px solid var(--color-border)' : 'none',
                        background: log._live ? 'rgba(74,222,128,0.04)' : 'transparent',
                      }}
                    >
                      <td style={{ padding: 'var(--space-2) var(--space-4)', color: 'var(--color-text-muted)', whiteSpace: 'nowrap' }}>
                        {log.received_at?.replace('T', ' ').substring(0, 19)}
                        {log._live && (
                          <span style={{ marginLeft: 'var(--space-2)', fontSize: 'var(--font-size-xs)', color: 'var(--color-success)', fontWeight: 'var(--font-weight-semibold)' }}>LIVE</span>
                        )}
                      </td>
                      <td style={{ padding: 'var(--space-2) var(--space-4)' }}>
                        <span style={{
                          display: 'inline-block',
                          padding: '1px var(--space-2)',
                          borderRadius: 'var(--radius-sm)',
                          fontSize: 'var(--font-size-xs)',
                          fontWeight: 'var(--font-weight-semibold)',
                          background: s.bg,
                          color: s.text,
                          letterSpacing: 'var(--tracking-wide)',
                        }}>
                          {log.level}
                        </span>
                      </td>
                      <td style={{ padding: 'var(--space-2) var(--space-4)', color: 'var(--color-text-primary)' }}>
                        {log.message}
                      </td>
                    </tr>
                  )
                })}
              </tbody>
            </table>
          )}
        </div>
      </GlassCard>

      {/* ── Responsive + animation styles ─────────────────────────────── */}
      <style>{`
        @media (max-width: 1280px) {
          .overview-row2 { grid-template-columns: 1fr 1fr !important; }
        }
        @media (max-width: 900px) {
          .overview-row2 { grid-template-columns: 1fr !important; }
        }
        @keyframes ov-pulse {
          0%, 100% { opacity: 1; }
          50%       { opacity: 0.35; }
        }
        @keyframes ov-glow {
          0%, 100% { opacity: 0.7; }
          50%       { opacity: 1; }
        }
        @keyframes ov-ring {
          0%   { transform: translate(-50%, -50%) scale(0.75); opacity: 0.6; }
          100% { transform: translate(-50%, -50%) scale(1.55); opacity: 0; }
        }
      `}</style>

      <DeviceNoteModal
        open={noteModal.open}
        deviceId={id}
        note={null}
        onClose={() => setNoteModal({ open: false })}
        onSaved={handleNoteSaved}
      />

      <EntryFormModal
        open={issueModal.open}
        entry={issueModal.entry}
        defaultType="issue"
        prefilledLinks={issueModal.entry ? undefined : [{ entity_type: 'device', entity_id: id, display_name: device?.device_name || sn, locked: true }]}
        knownEntities={id ? { [id]: device?.device_name || sn } : undefined}
        onClose={() => setIssueModal({ open: false, entry: null })}
        onSaved={handleIssueSaved}
      />

      {/* ── Note full-view mini modal ──────────────────────────────────────── */}
      {viewNote && (
        <div
          onClick={() => setViewNote(null)}
          style={{
            position: 'fixed', inset: 0, zIndex: 9999,
            background: 'rgba(0,0,0,0.55)',
            backdropFilter: 'blur(4px)',
            display: 'flex', alignItems: 'center', justifyContent: 'center',
            padding: 'var(--space-6)',
          }}
        >
          <div
            onClick={e => e.stopPropagation()}
            style={{
              background: 'var(--color-bg-card)',
              border: '1px solid var(--color-border)',
              borderRadius: 'var(--radius-xl)',
              boxShadow: 'var(--shadow-xl)',
              maxWidth: 560,
              width: '100%',
              display: 'flex',
              flexDirection: 'column',
              gap: 0,
              overflow: 'hidden',
            }}
          >
            <div style={{
              display: 'flex', alignItems: 'center', justifyContent: 'space-between',
              padding: 'var(--space-4) var(--space-5)',
              borderBottom: '1px solid var(--color-border)',
            }}>
              <SectionLabel>Note</SectionLabel>
              <button
                onClick={() => setViewNote(null)}
                style={{ background: 'none', border: 'none', cursor: 'pointer', color: 'var(--color-text-muted)', display: 'flex', alignItems: 'center', padding: 4, borderRadius: 'var(--radius-sm)' }}
              >
                <svg width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round">
                  <line x1="18" y1="6" x2="6" y2="18"/><line x1="6" y1="6" x2="18" y2="18"/>
                </svg>
              </button>
            </div>
            <div style={{ padding: 'var(--space-5)', overflowY: 'auto', maxHeight: '60vh' }}>
              <p style={{ margin: 0, fontSize: 'var(--font-size-sm)', color: 'var(--color-text-primary)', lineHeight: 1.7, whiteSpace: 'pre-wrap' }}>
                {viewNote.content || viewNote.text || '—'}
              </p>
            </div>
            {viewNote.created_at && (
              <div style={{ padding: 'var(--space-3) var(--space-5)', borderTop: '1px solid var(--color-border)' }}>
                <span style={{ fontSize: 'var(--font-size-xs)', color: 'var(--color-text-muted)' }}>
                  {fmtRelative(viewNote.created_at)}
                  {viewNote.created_by ? ` · ${viewNote.created_by}` : ''}
                </span>
              </div>
            )}
          </div>
        </div>
      )}
    </div>
  )
}
