// frontend/src/pages/bellcloud/devices/tabs/shared.jsx
// Shared helpers, sub-components, and constants used across device tabs

import Button from '@/components/ui/Button'
import Card from '@/components/ui/Card'

// ─── Date / time helpers ──────────────────────────────────────────────────────

export function parseFirestoreDate(str) {
  if (!str) return null
  if (typeof str === 'object') {
    const secs = str._seconds ?? str.seconds
    if (typeof secs === 'number') return new Date(secs * 1000)
    return null
  }
  const cleaned = str.replace(' at ', ' ').replace('UTC+0000', 'UTC').replace(/UTC\+(\d{4})/, 'UTC')
  const d = new Date(cleaned)
  return isNaN(d.getTime()) ? null : d
}

export function formatDate(str) {
  const d = parseFirestoreDate(str)
  if (!d) return str || '—'
  const day = d.getUTCDate().toString().padStart(2, '0')
  const month = (d.getUTCMonth() + 1).toString().padStart(2, '0')
  return `${day}-${month}-${d.getUTCFullYear()}`
}

export function formatDateNice(d) {
  if (!d) return '—'
  const months = ['January', 'February', 'March', 'April', 'May', 'June', 'July', 'August', 'September', 'October', 'November', 'December']
  return `${d.getUTCDate()} ${months[d.getUTCMonth()]} ${d.getUTCFullYear()}`
}

export function daysUntil(targetDate) {
  return Math.ceil((targetDate.getTime() - Date.now()) / 86400000)
}

export function addDays(date, days) {
  return new Date(date.getTime() + days * 86400000)
}

export function daysToDisplay(days) {
  if (days >= 365 && days % 365 === 0) return `${days / 365} year${days / 365 > 1 ? 's' : ''} (${days} days)`
  if (days >= 30) {
    const months = Math.floor(days / 30)
    const rem = days % 30
    if (rem === 0) return `${months} month${months > 1 ? 's' : ''} (${days} days)`
    return `${days} days (~${months} month${months > 1 ? 's' : ''})`
  }
  return `${days} days`
}

export function formatTimestamp(str) {
  if (!str) return '—'
  const d = parseFirestoreDate(str)
  if (d) return `${d.getUTCHours().toString().padStart(2, '0')}:${d.getUTCMinutes().toString().padStart(2, '0')}`
  const match = str.match(/(\d{1,2}):(\d{2})/)
  return match ? `${match[1].padStart(2, '0')}:${match[2]}` : str
}

export function parseCoordinates(coordStr) {
  if (!coordStr) return null
  if (typeof coordStr === 'object') {
    const lat = parseFloat(coordStr.lat ?? coordStr.latitude)
    const lng = parseFloat(coordStr.lng ?? coordStr.longitude)
    if (!isNaN(lat) && !isNaN(lng)) return { lat, lng }
    return null
  }
  const numbers = coordStr.match(/-?\d+(?:\.\d+)?/g)
  if (numbers?.length >= 2) {
    let lat = parseFloat(numbers[0])
    let lng = parseFloat(numbers[1])
    if (!isNaN(lat) && !isNaN(lng)) {
      if (/\bS\b/.test(coordStr)) lat = -Math.abs(lat)
      if (/\bW\b/.test(coordStr)) lng = -Math.abs(lng)
      return { lat, lng }
    }
  }
  return null
}

export function formatCoordinates(coords) {
  if (!coords) return '—'
  const latDir = coords.lat >= 0 ? 'N' : 'S'
  const lngDir = coords.lng >= 0 ? 'E' : 'W'
  return `${Math.abs(coords.lat).toFixed(6)}° ${latDir}, ${Math.abs(coords.lng).toFixed(6)}° ${lngDir}`
}

export function formatLocale(v) {
  if (!v || v === 'all') return 'Global'
  if (v === 'orthodox') return 'Orthodox'
  if (v === 'catholic') return 'Catholic'
  return v
}

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

export const LOG_LEVEL_LABELS = { 0: 'Disabled', 1: 'Error', 2: 'Warning', 3: 'Info', 4: 'Debug', 5: 'Verbose' }
export const LOG_LEVEL_VARIANTS = { 0: 'neutral', 1: 'danger', 2: 'warning', 3: 'info', 4: 'neutral', 5: 'neutral' }

// ─── Shared sub-components ────────────────────────────────────────────────────

export function Field({ label, children, mono = false }) {
  const isEmpty = children == null || children === ''
  return (
    <div style={{ display: 'flex', flexDirection: 'column', gap: 'var(--space-1)' }}>
      <dt style={{ fontSize: 'var(--font-size-sm)', color: 'var(--color-text-muted)', fontWeight: 'var(--font-weight-medium)' }}>
        {label}
      </dt>
      <dd style={{
        fontSize: 'var(--font-size-base)',
        color: isEmpty ? 'var(--color-text-muted)' : 'var(--color-text-primary)',
        fontFamily: mono ? 'var(--font-family-mono)' : 'inherit',
      }}>
        {isEmpty ? '—' : children}
      </dd>
    </div>
  )
}

export function FieldGrid({ children, cols = 2 }) {
  return (
    <dl style={{ display: 'grid', gridTemplateColumns: `repeat(${cols}, minmax(0, 1fr))`, gap: 'var(--space-4)' }}>
      {children}
    </dl>
  )
}

export function SectionTitle({ title, onEdit, canEdit }) {
  return (
    <div style={{ display: 'flex', alignItems: 'center', justifyContent: 'space-between', marginBottom: 'var(--space-4)' }}>
      <h3 style={{ fontSize: 'var(--font-size-base)', fontWeight: 'var(--font-weight-semibold)', color: 'var(--color-text-primary)' }}>
        {title}
      </h3>
      {canEdit && onEdit && (
        <Button variant="ghost" size="sm" onClick={onEdit}>Edit</Button>
      )}
    </div>
  )
}

export function KpiCard({ label, value, variant }) {
  const valueColor = variant === 'success'
    ? 'var(--color-success)'
    : variant === 'danger'
    ? 'var(--color-danger)'
    : variant === 'warning'
    ? 'var(--color-warning)'
    : 'var(--color-text-primary)'
  return (
    <Card padding>
      <div style={{ display: 'flex', flexDirection: 'column', gap: 'var(--space-1)' }}>
        <span style={{ fontSize: 'var(--font-size-sm)', color: 'var(--color-text-muted)' }}>{label}</span>
        <span style={{ fontSize: 'var(--font-size-2xl)', fontWeight: 'var(--font-weight-bold)', letterSpacing: 'var(--tracking-display)', color: valueColor, lineHeight: 1, fontFamily: 'var(--font-family-display)' }}>
          {value}
        </span>
      </div>
    </Card>
  )
}

export function ProgressBar({ value, variant = 'primary' }) {
  const width = 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: '6px', borderRadius: 'var(--radius-full)', backgroundColor: 'var(--color-bg-elevated)', overflow: 'hidden' }}>
      <div style={{ height: '100%', width: `${width}%`, backgroundColor: color, borderRadius: 'var(--radius-full)', transition: 'width 0.3s' }} />
    </div>
  )
}
