function clampPct(n: number): number {
  return Math.max(0, Math.min(100, n))
}

function parseSoc(v: string | number | null | undefined): number | null {
  if (v == null) return null
  if (typeof v === 'number' && !Number.isNaN(v)) return v
  const x = Number(v)
  return Number.isFinite(x) ? x : null
}

type Props = {
  socPercent: string | number | null | undefined
  loading?: boolean
}

const R = 52
const C = 2 * Math.PI * R
const STROKE = 8

export function SocGauge({ socPercent, loading }: Props) {
  if (loading) {
    return (
      <div className="flex flex-col items-center justify-center rounded-xl border border-slate-800 bg-slate-900/60 p-6">
        <div className="h-36 w-36 animate-pulse rounded-full bg-slate-800/80" />
        <div className="mt-4 h-4 w-24 animate-pulse rounded bg-slate-800/80" />
      </div>
    )
  }

  const raw = parseSoc(socPercent)
  if (raw == null) {
    return (
      <div className="flex flex-col items-center justify-center rounded-xl border border-slate-800 bg-slate-900/60 p-6">
        <div className="h-36 w-36 animate-pulse rounded-full bg-slate-800/80" />
        <div className="mt-4 h-3 w-20 animate-pulse rounded bg-slate-800/80" />
      </div>
    )
  }

  const pct = clampPct(raw)
  const offset = C - (pct / 100) * C

  return (
    <div className="flex flex-col items-center rounded-xl border border-slate-800 bg-slate-900/60 p-6">
      <div className="relative">
        <svg width="140" height="140" viewBox="0 0 120 120" className="-rotate-90" aria-hidden>
          <circle
            cx="60"
            cy="60"
            r={R}
            fill="none"
            stroke="currentColor"
            strokeWidth={STROKE}
            className="text-slate-800"
          />
          <circle
            cx="60"
            cy="60"
            r={R}
            fill="none"
            stroke="currentColor"
            strokeWidth={STROKE}
            strokeLinecap="round"
            strokeDasharray={C}
            strokeDashoffset={offset}
            className="text-emerald-500 transition-[stroke-dashoffset] duration-500"
          />
        </svg>
        <div className="absolute inset-0 flex flex-col items-center justify-center">
          <span className="text-2xl font-bold tabular-nums text-slate-50">{pct.toFixed(0)}</span>
          <span className="text-xs text-slate-500">% SoC</span>
        </div>
      </div>
    </div>
  )
}
