import { Badge } from "@/components/ui";
import type { Severity, FindingState } from "@/lib/api";

/*
 * One place that knows how a severity looks, because the board, the server tab
 * and the digest counts all draw the same five words and must not drift.
 *
 * Colour is never the whole message: every pill carries its word, and the three
 * state variants add a dot, so the distinction survives a monochrome screen.
 */

export const SEVERITY_ORDER: Severity[] = ["critical", "high", "medium", "low", "unknown"];

const severityVariant: Record<Severity, "danger" | "warning" | "accent" | "neutral"> = {
    critical: "danger",
    high: "danger",
    medium: "warning",
    low: "accent",
    unknown: "neutral",
};

export function severityRank(s: Severity): number {
    switch (s) {
        case "critical":
            return 4;
        case "high":
            return 3;
        case "medium":
            return 2;
        case "low":
            return 1;
        default:
            return 0;
    }
}

export function SeverityBadge({ severity }: { severity: Severity }) {
    return <Badge variant={severityVariant[severity]}>{severity}</Badge>;
}

export function StateBadge({ state }: { state: FindingState }) {
    if (state === "fixed") return <Badge variant="success">fixed</Badge>;
    if (state === "accepted") return <Badge variant="warning">accepted</Badge>;
    return <Badge variant="danger">open</Badge>;
}

/** relativeTime renders an age in the coarsest honest unit. */
export function relativeTime(iso?: string): string {
    if (!iso) return "never";
    const then = new Date(iso).getTime();
    if (Number.isNaN(then)) return "unknown";

    const mins = Math.floor((Date.now() - then) / 60000);
    if (mins < 1) return "just now";
    if (mins < 60) return `${mins}m ago`;
    const hours = Math.floor(mins / 60);
    if (hours < 48) return `${hours}h ago`;
    return `${Math.floor(hours / 24)}d ago`;
}

/** ageHours is how the freshness banner decides whether to raise its voice. */
export function ageHours(iso?: string): number | null {
    if (!iso) return null;
    const then = new Date(iso).getTime();
    if (Number.isNaN(then)) return null;
    return (Date.now() - then) / 3600000;
}
