import { useState } from "react"
import { Moon, ChevronDown, ChevronRight } from "lucide-react"
import { useChronik } from "@/lib/queries"

// Morgenlage: das jüngste Verdikt des nächtlichen Chef-Gutachters (gpt-oss urteilt im
// Leerlauf über die autonome Arbeit; der Feed spiegelt es still in den Briefkasten).
// Keine Lage vorhanden → Karte verschwindet ganz (Ruhe statt leerer Fläche).
export function MorgenlageCard() {
  const { data: items = [] } = useChronik(150, 60_000)
  const [open, setOpen] = useState(false)
  const lage = items.find((i) => i.source === "chef-gutachter")
  if (!lage) return null

  const when = new Date(lage.ts * 1000).toLocaleString("de-DE", {
    weekday: "long", day: "2-digit", month: "2-digit", hour: "2-digit", minute: "2-digit",
  })
  // VERDIKT-Zeile als Kurzfassung herausziehen (Raster des Chef-Gutachters).
  const verdikt = lage.text.split("\n").find((l) => l.trim().startsWith("VERDIKT:"))?.replace(/^\s*VERDIKT:\s*/, "")

  return (
    <div className="rounded-2xl border border-violet-500/25 bg-violet-500/[0.05] p-4 shadow-lg shadow-black/15 backdrop-blur-md">
      <button onClick={() => setOpen((o) => !o)} className="flex w-full items-center gap-3 text-left cursor-pointer">
        <span className="flex h-9 w-9 shrink-0 items-center justify-center rounded-xl border border-violet-500/30 bg-background/30 text-violet-300">
          <Moon className="h-4.5 w-4.5" />
        </span>
        <span className="min-w-0 flex-1">
          <span className="block text-sm font-bold text-foreground">Morgenlage</span>
          <span className="block truncate text-xs text-muted-foreground">
            {verdikt || lage.subject || "Nächtliches Gutachten über die autonome Arbeit"}
          </span>
        </span>
        <span className="shrink-0 text-[10px] text-muted-foreground/60">{when}</span>
        {open ? <ChevronDown className="h-4 w-4 shrink-0 text-muted-foreground" /> : <ChevronRight className="h-4 w-4 shrink-0 text-muted-foreground" />}
      </button>
      {open && (
        <div className="mt-3 border-t border-violet-500/15 pt-3">
          {lage.subject && <p className="mb-1 text-[10px] font-semibold uppercase tracking-wider text-violet-300/80">{lage.subject}</p>}
          <p className="whitespace-pre-wrap text-xs leading-relaxed text-foreground/85">{lage.text}</p>
        </div>
      )}
    </div>
  )
}
