'use client'

import { useEffect, useState } from 'react'
import Link from 'next/link'
import { HeartPulse } from 'lucide-react'

// Header indicator: the count of infrastructure problems needing a look.
// Renders as a plain muted icon when everything is green, so a healthy system
// is visually silent and a number always means "go look".
//
// An unread digest shows a GREEN count. Green because nothing is wrong — it is
// a reading task, not a fault — and a number because the useful question is how
// many are waiting.
//
// A buyer waiting on the quail loop shows AMBER, and adds to the same number as
// a broken host. Those two are not the same kind of thing, and they are kept as
// separate counters all the way up from the API for exactly that reason — but
// out here on the dashboard the question is only "how many things want me", and
// splitting one small badge into two competing numbers answers a question
// nobody asked. The tooltip says which is which; red still wins the colour when
// something is actually critical.
//
// Without this an unread digest, and now a waiting buyer, were invisible from
// the dashboard: both markers lived on /health, which you only see once you
// have already gone there.
export function HealthBadge() {
  const [problems, setProblems] = useState(0)
  const [crit, setCrit] = useState(false)
  const [unread, setUnread] = useState(0)
  const [waiting, setWaiting] = useState(0)

  useEffect(() => {
    let alive = true
    const load = async () => {
      try {
        const res = await fetch('/api/monitor', { cache: 'no-store' })
        if (!res.ok || !alive) return
        const d = await res.json()
        setProblems(d.problems || 0)
        setWaiting(d.quailWaiting || 0)
        setCrit(d.status === 'CRIT' || d.status === 'STALE')
        // Unread AND notable. A digest that found only junk is filed and
        // readable but must not light this — see the Digest model's note.
        setUnread(((d.digests || []) as { read: boolean; notable: boolean }[])
          .filter(x => !x.read && x.notable).length)
      } catch { /* offline — keep the last known count */ }
    }
    load()
    const t = setInterval(load, 60000)
    return () => { alive = false; clearInterval(t) }
  }, [])

  // Amber's total. Kept apart in the data, added together here, and spelled
  // out in the tooltip so the number is never ambiguous when you hover it.
  const needsYou = problems + waiting
  const parts = [
    problems ? `${problems} ${problems === 1 ? 'issue' : 'issues'} need a look` : '',
    waiting ? `${waiting} buyer${waiting === 1 ? '' : 's'} waiting on your answer` : '',
  ].filter(Boolean)
  const label = parts.length ? parts.join(' · ')
    : unread ? `${unread} unread digest${unread === 1 ? '' : 's'}`
    : 'Infrastructure health'

  return (
    <Link
      href="/health"
      className="relative p-2 rounded-lg hover:bg-muted text-muted-foreground"
      aria-label={`Infrastructure health — ${label}`}
      title={label}
    >
      <HeartPulse className={`h-4 w-4 ${needsYou ? (crit ? 'text-destructive' : 'text-amber-500') : (unread ? 'text-emerald-600' : '')}`} />
      {needsYou === 0 && unread > 0 && (
        <span className="absolute -top-0.5 -right-0.5 min-w-[1rem] h-4 px-1 rounded-full text-[10px] font-semibold leading-4 text-center text-white tabular-nums bg-emerald-500">
          {unread > 9 ? '9+' : unread}
        </span>
      )}
      {needsYou > 0 && (
        <span
          className={`absolute -top-0.5 -right-0.5 min-w-[1rem] h-4 px-1 rounded-full text-[10px] font-semibold leading-4 text-center text-white tabular-nums ${crit ? 'bg-destructive' : 'bg-amber-500'}`}
        >
          {needsYou > 9 ? '9+' : needsYou}
        </span>
      )}
    </Link>
  )
}
