Files
bellsystems-cp/frontend/src/pages/bellcloud/devices/tabs/OverviewTab.jsx
T
bonaminandClaude Opus 5.5 2e3d7ba062 refactor(devices): store hardware identity as hw_family / hw_revision
The firmware moved its NVS identity keys from hw_type / hw_version to
hw_family / hw_revision (NvsMigration.cpp), and the NVS generator, cloudflash
and the device models already used the new names. Firestore device docs and
the manufacturing code still wrote and read hw_type / hw_version, so the
device API's hw_family / hw_revision were always "" (0 of 14 docs had them)
and the console used two names for one value.

Device docs now use the firmware's names (schema v1.1.0, decision D2 in the
bellsystems-schema repo). The apps don't read these fields, so no app change.

- Manufacturing batch-create writes hw_family / hw_revision; the inventory
  API exposes hw_family / hw_revision (filters: ?hw_family= / ?hw_families=).
  Reads fall back to hw_type / hw_version so docs not yet migrated still work.
- devices/firestore_v1.py renames hw_type / hw_version on read and write and
  rejects a hw_family that isn't a code (e.g. "Bell Plus"): when the console
  generates NVS from it, the firmware builds its OTA URL from that value.
- Inventory, provisioning, onboarding and overview pages use the new names.

Unchanged on purpose: the firmware catalog and flash assets
(/api/firmware/{hw_type}/..., hw_type_override) — a separate store and the
URL devices call; same values, only the variable name differs. The public
cloudflash response keeps its hw_type field (public contract).

Data migration (rename + fix 3 display-label values) runs from the
bellsystems-schema repo AFTER this is deployed: the currently deployed
console still reads hw_type.

Verified: 118 backend tests pass; frontend builds; ESLint errors in
ProvisioningWizard.jsx (7) are pre-existing and unchanged.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-08 21:02:20 +02:00

1407 lines
61 KiB
React

// 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 Modal from '@/components/ui/Modal'
import { fmtDateMedium, fmtDateTimeMedium, fmtRelative, fmtLogTimestamp } 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'
import CopyableSerial from '@/components/shared/CopyableSerial'
// ─── 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`
}
// Latest Device Issue color: severity sets the base hue, age controls intensity.
// today = full opacity, fading out toward ~1 week, capped at a dim floor beyond that.
const ALERT_SEVERITY_HUE = {
CRITICAL: 'var(--color-danger)',
FAILED: 'var(--color-danger)',
WARNING: 'var(--color-warning)',
}
function alertEventStyle(occurredAtIso) {
const hue = ALERT_SEVERITY_HUE[occurredAtIso.state] || 'var(--color-warning)'
const ageMs = Date.now() - new Date(occurredAtIso.occurred_at).getTime()
const ageDays = ageMs / 86400000
// 1.0 opacity at "today", fading linearly to a 0.35 floor by 7 days out.
const opacity = Math.max(0.35, 1 - (ageDays / 7) * 0.65)
return { color: hue, opacity }
}
// ─── 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)' },
}
// Message text colour — INFO stays neutral/white, only WARN/ERROR get coloured
// so problem lines are the ones that visually stand out.
const MESSAGE_TEXT_COLOR = {
ERROR: 'var(--color-danger)',
WARN: 'var(--color-warning)',
INFO: 'var(--color-text-primary)',
}
// 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_family || ''
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)
// ── Latest device issue detail modal ─────────────────────────────────────
const [alertModalOpen, setAlertModalOpen] = useState(false)
const [alertLogs, setAlertLogs] = useState([])
const [alertLogsLoading, setAlertLogsLoading] = useState(false)
const openAlertModal = useCallback(() => {
setAlertModalOpen(true)
if (!sn) return
setAlertLogsLoading(true)
api.get(`/mqtt/logs/${sn}?limit=20&offset=0`)
.then(data => {
const rows = (data.logs || []).filter(l => l.level === 'ERROR' || l.level === 'WARN')
setAlertLogs(rows)
})
.catch(() => setAlertLogs([]))
.finally(() => setAlertLogsLoading(false))
}, [sn])
const handleNoteSaved = () => {
setNoteModal({ open: false })
loadNotes()
}
const handleIssueSaved = () => {
setIssueModal({ open: false, entry: null })
loadIssues()
}
// ── Live logs ─────────────────────────────────────────────────────────────
const [logs, setLogs] = useState([])
const [logsInitialLoading, setLogsInitialLoading] = useState(true)
const [levelStep, setLevelStep] = useState(0) // index into LEVEL_STEPS
const [searchText, setSearchText] = useState('')
const [autoScroll, setAutoScroll] = useState(true)
const [autoRefresh, setAutoRefresh] = useState(true)
const [liveLogs, setLiveLogs] = useState([])
const logsContainerRef = useRef(null)
const logsHasLoadedOnce = useRef(false)
const LIMIT = 50
const levelFilter = LEVEL_STEPS[levelStep].value
// Stepped severity order: a level also matches everything more severe than it
// (ALL < INFO < WARN < ERROR), so picking WARN also shows WARN and ERROR.
const LEVEL_RANK = { INFO: 0, WARN: 1, ERROR: 2 }
const meetsLevelFloor = lvl => !levelFilter || (LEVEL_RANK[lvl] ?? 0) >= LEVEL_RANK[levelFilter]
// `background` fetches (polling / manual refresh) never toggle a loading
// flag — only the very first load shows a spinner, so auto-sync and the
// REFRESH button stay seamless instead of flickering every few seconds.
const fetchLogs = useCallback(async (background = false) => {
if (!sn) return
if (!background && !logsHasLoadedOnce.current) setLogsInitialLoading(true)
try {
const params = new URLSearchParams({ limit: LIMIT, offset: 0 })
if (levelFilter) { params.set('level', levelFilter); params.set('min_level', 'true') }
if (searchText) params.set('search', searchText)
const data = await api.get(`/mqtt/logs/${sn}?${params}`)
setLogs(data.logs || [])
} catch {
// silent
} finally {
logsHasLoadedOnce.current = true
setLogsInitialLoading(false)
}
}, [sn, levelFilter, searchText])
useEffect(() => { if (sn) fetchLogs(false) }, [sn, fetchLogs])
useEffect(() => {
if (!autoRefresh || !sn) return
const t = setInterval(() => fetchLogs(true), 5000)
return () => clearInterval(t)
}, [autoRefresh, sn, fetchLogs])
const handleWsMessage = useCallback((data) => {
if (data.type === 'system/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 (!meetsLevelFloor(l.level)) return false
if (searchText && !l.message.toLowerCase().includes(searchText.toLowerCase())) return false
return true
}),
...logs,
]
// Only auto-scroll to top when a genuinely NEW live log arrives — not when
// the level filter / search changes the visible set (that should update
// the list in place, without yanking the scroll position).
const liveLogCount = liveLogs.length
const prevLiveLogCount = useRef(liveLogCount)
useEffect(() => {
if (liveLogCount > prevLiveLogCount.current && autoScroll && logsContainerRef.current) {
logsContainerRef.current.scrollTop = 0
}
prevLiveLogCount.current = liveLogCount
}, [liveLogCount, 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+D: Device info grid (Serial/HW/Uptime/Location/Rev/Issue) ── */}
<div style={{
flex: 2,
padding: 'var(--space-6)',
marginLeft: 'var(--space-4)',
display: 'flex',
alignItems: 'center',
minWidth: 0,
}} className="overview-hero-grid-wrap">
<div className="overview-hero-grid" style={{
display: 'grid',
gridTemplateColumns: 'repeat(3, minmax(0, 1fr))',
gridAutoRows: 'auto',
columnGap: 'var(--space-8)',
rowGap: 'var(--space-5)',
width: '100%',
}}>
<InfoField label="Serial Number">
<CopyableSerial
serial={sn}
textStyle={{ fontFamily: 'var(--font-family-mono)' }}
/>
</InfoField>
<InfoField label="Hardware Family">{hwVariant}</InfoField>
<InfoField label="Device Uptime">
{mqttStatus?.last_heartbeat?.uptime_ms != null
? <span style={{ fontFamily: 'var(--font-family-mono)', fontSize: 'var(--font-size-base)' }}>{formatUptime(Math.floor(mqttStatus.last_heartbeat.uptime_ms / 1000))}</span>
: <span style={{ color: 'var(--color-text-muted)', fontStyle: 'italic', fontWeight: 'var(--font-weight-normal)' }}>Unavailable</span>}
</InfoField>
<InfoField label="Firmware Version" mono>{mqttStatus?.last_heartbeat?.firmware_version || '—'}</InfoField>
<InfoField label="Hardware Revision">{hwRevision || device.device_attributes?.firmwareVersion || '—'}</InfoField>
<div style={{ display: 'flex', flexDirection: 'column', gap: 'var(--space-1)', minWidth: 0 }}>
<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_alert_event ? (
<div
onClick={openAlertModal}
role="button"
tabIndex={0}
onKeyDown={e => { if (e.key === 'Enter' || e.key === ' ') { e.preventDefault(); openAlertModal() } }}
style={{
display: 'flex',
flexDirection: 'column',
gap: 2,
cursor: 'pointer',
borderRadius: 'var(--radius-sm)',
marginInline: -4,
paddingInline: 4,
transition: 'background 0.15s',
}}
onMouseEnter={e => e.currentTarget.style.background = GLASS_INNER}
onMouseLeave={e => e.currentTarget.style.background = 'transparent'}
>
<span style={{
fontSize: 'var(--font-size-xs)',
fontWeight: 'var(--font-weight-semibold)',
letterSpacing: 'var(--tracking-wide)',
textTransform: 'uppercase',
whiteSpace: 'nowrap',
overflow: 'hidden',
textOverflow: 'ellipsis',
...alertEventStyle(mqttStatus.last_alert_event),
}}>
{mqttStatus.last_alert_event.state} · {mqttStatus.last_alert_event.subsystem} · {fmtRelative(mqttStatus.last_alert_event.occurred_at)}
</span>
<span style={{
fontSize: 'var(--font-size-sm)',
color: 'var(--color-text-secondary)',
lineHeight: 1.4,
overflow: 'hidden',
display: '-webkit-box',
WebkitLineClamp: 1,
WebkitBoxOrient: 'vertical',
textOverflow: 'ellipsis',
}}>
{mqttStatus.last_alert_event.message || 'No details provided.'}
</span>
</div>
) : (
<span style={{ fontSize: 'var(--font-size-sm)', color: 'var(--color-text-muted)', fontStyle: 'italic' }}>
No recent issues
</span>
)}
</div>
</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)}
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. No spinner/dim-out:
a background sync must stay seamless, not flicker every few seconds. */}
<button
onClick={() => fetchLogs(true)}
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: 'pointer',
letterSpacing: 'var(--tracking-wide)',
fontFamily: 'var(--font-family-base)',
flexShrink: 0,
}}
>
REFRESH
</button>
</div>
{/* Log rows */}
<div ref={logsContainerRef} style={{ maxHeight: 320, overflowY: 'auto', fontFamily: 'var(--font-family-mono)', fontSize: 'var(--font-size-sm)' }}>
{logsInitialLoading && 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' }}>
{fmtLogTimestamp(log.received_at)}
{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: MESSAGE_TEXT_COLOR[log.level] || '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; }
}
@media (max-width: 1100px) {
.overview-hero-grid { grid-template-columns: repeat(2, minmax(0, 1fr)) !important; }
}
@media (max-width: 640px) {
.overview-hero-grid { 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?.console_name || device?.device_name || sn, locked: true }]}
knownEntities={id ? { [id]: device?.console_name || 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>
)}
{/* ── Latest Device Issue detail modal ──────────────────────────────── */}
<Modal
open={alertModalOpen}
onClose={() => setAlertModalOpen(false)}
title="Latest Device Issue"
size="md"
>
{mqttStatus?.last_alert_event && (
<div style={{ display: 'flex', flexDirection: 'column', gap: 'var(--space-5)' }}>
<div style={{ display: 'flex', flexDirection: 'column', gap: 'var(--space-2)' }}>
<div style={{ display: 'flex', alignItems: 'center', gap: 'var(--space-2)' }}>
<span style={{
fontSize: 'var(--font-size-xs)',
fontWeight: 'var(--font-weight-semibold)',
letterSpacing: 'var(--tracking-wide)',
textTransform: 'uppercase',
...alertEventStyle(mqttStatus.last_alert_event),
opacity: 1,
}}>
{mqttStatus.last_alert_event.state} · {mqttStatus.last_alert_event.subsystem}
</span>
<span style={{ fontSize: 'var(--font-size-xs)', color: 'var(--color-text-muted)' }}>
{fmtDateTimeMedium(mqttStatus.last_alert_event.occurred_at)}
</span>
</div>
<p style={{ margin: 0, fontSize: 'var(--font-size-sm)', color: 'var(--color-text-primary)', lineHeight: 1.7, whiteSpace: 'pre-wrap' }}>
{mqttStatus.last_alert_event.message || 'No details provided.'}
</p>
</div>
<div style={{ display: 'flex', flexDirection: 'column', gap: 'var(--space-2)', borderTop: '1px solid var(--color-border)', paddingTop: 'var(--space-4)' }}>
<SectionLabel>Recent Error &amp; Warning Logs</SectionLabel>
{alertLogsLoading ? (
<div style={{ display: 'flex', justifyContent: 'center', padding: 'var(--space-4)' }}>
<Spinner size="sm" />
</div>
) : alertLogs.length === 0 ? (
<p style={{ fontSize: 'var(--font-size-sm)', color: 'var(--color-text-muted)', fontStyle: 'italic' }}>
No recent error or warning logs.
</p>
) : (
<div style={{ display: 'flex', flexDirection: 'column', gap: 'var(--space-2)', maxHeight: 280, overflowY: 'auto' }}>
{alertLogs.map((log, i) => {
const s = LOG_COLORS[log.level] || LOG_COLORS.INFO
return (
<div
key={log.id || i}
style={{
display: 'flex',
alignItems: 'flex-start',
gap: 'var(--space-3)',
padding: 'var(--space-2) var(--space-3)',
borderRadius: 'var(--radius-md)',
background: GLASS_INNER,
border: '1px solid var(--color-border)',
}}
>
<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)',
flexShrink: 0,
}}>
{log.level}
</span>
<span style={{ flex: 1, fontSize: 'var(--font-size-sm)', color: MESSAGE_TEXT_COLOR[log.level] || 'var(--color-text-primary)', fontFamily: 'var(--font-family-mono)' }}>
{log.message}
</span>
<span style={{ fontSize: 'var(--font-size-xs)', color: 'var(--color-text-muted)', whiteSpace: 'nowrap', flexShrink: 0 }}>
{fmtLogTimestamp(log.received_at)}
</span>
</div>
)
})}
</div>
)}
</div>
</div>
)}
</Modal>
</div>
)
}