"use client";

import Link from "next/link";
import useSWR from "swr";
import type { QuotaSummary } from "@/lib/subscription/service";
import { fetcher } from "@/lib/utils";

export function UsageBadge() {
  const { data } = useSWR<QuotaSummary>(
    `${process.env.NEXT_PUBLIC_BASE_PATH ?? ""}/api/usage`,
    fetcher,
    {
      refreshInterval: 15_000,
      revalidateOnFocus: true,
    }
  );

  if (!data) {
    return null;
  }

  const isPro = data.tier === "pro";
  const lowQuota =
    !isPro &&
    (data.messages.remaining <= 2 || data.toolCalls.remaining <= 1);

  return (
    <Link
      className={`flex items-center gap-2 rounded-lg border px-2.5 py-1 text-[11px] font-medium transition-colors ${
        lowQuota
          ? "border-amber-500/40 bg-amber-500/10 text-amber-600 hover:bg-amber-500/15"
          : "border-border/40 text-muted-foreground hover:text-foreground"
      }`}
      href="/pricing"
      title={`${data.tier} tier — ${data.toolCalls.used}/${data.toolCalls.limit} tool calls today`}
    >
      <span className="uppercase tracking-wider opacity-60">{data.tier}</span>
      <span>
        {data.messages.used}/{data.messages.limit} msgs
      </span>
      {isPro ? null : <span aria-hidden>→</span>}
    </Link>
  );
}
