"use client";

import Link from "next/link";
import { useMemory } from "@/lib/hooks";

function Bar({ label, usage }: { label: string; usage: string }) {
  const pctMatch = usage.match(/(\d+)%/);
  const pct = pctMatch ? parseInt(pctMatch[1]) : 0;

  return (
    <div className="flex items-center gap-3">
      <span className="text-[12px] w-12" style={{ color: "var(--text-2)" }}>{label}</span>
      <div className="flex-1 h-1.5 rounded-full" style={{ background: "var(--border)" }}>
        <div
          className="h-full rounded-full transition-all"
          style={{
            width: pct + "%",
            background: pct > 85 ? "#ff3b30" : "var(--accent)",
          }}
        />
      </div>
      <span className="text-[11px] font-mono w-10 text-right" style={{ color: "var(--text-3)" }}>
        {pct}%
      </span>
    </div>
  );
}

export function MemorySnapshotCard() {
  const { data } = useMemory();
  const mem = data?.targets?.find((t) => t.target === "memory");
  const usr = data?.targets?.find((t) => t.target === "user");

  return (
    <Link href="/memory">
      <div className="card card-hover p-4 space-y-2 transition-colors">
        <div className="flex items-center justify-between mb-1">
          <span className="text-[13px] font-medium" style={{ color: "var(--text-1)" }}>Memory</span>
          <span className="text-[11px]" style={{ color: "var(--text-3)" }}>
            {(mem?.entry_count || 0) + (usr?.entry_count || 0)} entries
          </span>
        </div>
        {mem && <Bar label="Agent" usage={mem.usage} />}
        {usr && <Bar label="User" usage={usr.usage} />}
      </div>
    </Link>
  );
}
