// Compact PnL indicator for the top app header — shows real-time
// Current PnL (all open positions) and Day PnL (positions opened today).
import { useLivePnl } from "@/hooks/use-live-pnl";
import { fmtNum } from "@/lib/mock-data";
import { TrendingUp, TrendingDown } from "lucide-react";

function fmtSigned(n: number) {
  if (!Number.isFinite(n)) return "0.00";
  const sign = n >= 0 ? "+" : "";
  return `${sign}${fmtNum(n)}`;
}

export function HeaderPnl() {
  const { currentPnl, dayPnl, openCount } = useLivePnl();

  const chip = (
    label: string,
    value: number,
    title: string,
  ) => {
    const positive = value >= 0;
    const Icon = positive ? TrendingUp : TrendingDown;
    return (
      <div
        title={title}
        className={`hidden items-center gap-1.5 rounded-md border px-2 py-1 text-[11px] font-semibold tabular-nums md:flex ${
          positive
            ? "border-emerald-500/40 bg-emerald-500/10 text-emerald-300"
            : "border-rose-500/40 bg-rose-500/10 text-rose-300"
        }`}
        aria-label={`${label} ${fmtSigned(value)}`}
      >
        <Icon className="h-3 w-3" aria-hidden />
        <span className="uppercase tracking-widest text-[9px] opacity-80">{label}</span>
        <span>{fmtSigned(value)}</span>
      </div>
    );
  };

  return (
    <div className="flex items-center gap-2" aria-live="polite">
      {chip("Current PnL", currentPnl, `Unrealized PnL across ${openCount} open position${openCount === 1 ? "" : "s"}`)}
      {chip("Day PnL", dayPnl, "Unrealized PnL for positions opened today")}
      {/* Compact single-line variant for mobile */}
      <div
        className={`flex items-center gap-1 rounded-md border px-2 py-1 text-[11px] font-semibold tabular-nums md:hidden ${
          currentPnl >= 0
            ? "border-emerald-500/40 bg-emerald-500/10 text-emerald-300"
            : "border-rose-500/40 bg-rose-500/10 text-rose-300"
        }`}
        aria-label={`Current PnL ${fmtSigned(currentPnl)}, Day PnL ${fmtSigned(dayPnl)}`}
      >
        <span>{fmtSigned(currentPnl)}</span>
        <span className="text-muted-foreground">/</span>
        <span className={dayPnl >= 0 ? "text-emerald-300" : "text-rose-300"}>{fmtSigned(dayPnl)}</span>
      </div>
    </div>
  );
}
