// ui/tags.jsx — the small inline markers: severity tag + CVSS bar, status pill,
// kind tag, CIA triad.
/* ------------------------------------------------------------ severity */
// Severity band order. Populated from the backend config (severity_band table) at
// startup via applyAppConfig(); the initial values are the fallback used before
// config arrives or if the fetch fails. Mutated IN PLACE so every module that
// captured this array reference sees the update.
const SEV_ORDER = ["Critical", "High", "Medium", "Low"];
function sevClass(s){ return "sev-" + String(s).toLowerCase().replace(/\s+/g, "-"); }
function SeverityTag({ s, cvss, size = "md" }) {
  return (
    <span className={"sevtag " + sevClass(s) + " sevtag-" + size}>
      <span className="sevtag-dot" />
      <span className="sevtag-label">{s}</span>
      {cvss != null && <span className="sevtag-cvss">{cvss.toFixed(1)}</span>}
    </span>
  );
}

/* CVSS bar (0–10) */
function CvssBar({ cvss, sev }) {
  return (
    <div className="cvssbar" title={"CVSS " + cvss.toFixed(1)}>
      <div className={"cvssbar-fill " + sevClass(sev)} style={{ width: (cvss / 10 * 100) + "%" }} />
    </div>
  );
}

function StatusPill({ status, onClick, interactive }) {
  const m = STATUS_META[status] || STATUS_META.new;
  const inner = (
    <>
      <span className="statuspill-dot" style={{ background: m.dot }} />
      {m.label}
      {interactive && <Icon name="chevD" size={12} className="statuspill-chev" />}
    </>
  );
  // Render a span when non-interactive so it can sit inside <button> rows
  // (triage queue, entity drill-down) without invalid <button>-in-<button> nesting.
  if (!interactive) return <span className="statuspill">{inner}</span>;
  return (
    <button className="statuspill statuspill-int" onClick={onClick} type="button">
      {inner}
    </button>
  );
}

/* --------------------------------------------------------------- kind */
function KindTag({ kind }) {
  const auto = kind === "automotive";
  return (
    <span className={"kindtag " + (auto ? "kindtag-auto" : "kindtag-iot")}>
      <Icon name={auto ? "car" : "chip"} size={12} />
      {auto ? "Automotive" : "IoT / Embedded"}
    </span>
  );
}

/* --------------------------------------------------------- CIA triad */
function CIA({ cia, compact }) {
  const items = [["C", "Confidentiality", cia.c], ["I", "Integrity", cia.i], ["A", "Availability", cia.a]];
  const lvl = (v) => ({ High: "cia-hi", Medium: "cia-md", Low: "cia-lo" }[v] || "cia-lo");
  return (
    <div className={"cia" + (compact ? " cia-compact" : "")}>
      {items.map(([k, full, v]) => (
        <div key={k} className={"cia-cell " + lvl(v)} title={full + ": " + v}>
          <span className="cia-k">{k}</span>
          {!compact && <span className="cia-v">{v}</span>}
        </div>
      ))}
    </div>
  );
}

Object.assign(window, { SeverityTag, CvssBar, StatusPill, KindTag, CIA, SEV_ORDER, sevClass });
