import React from "react";
import { AllocationBar } from "../data/AllocationBar";
import { AllocationChip } from "../data/AllocationChip";

function ensureStyle(id, css) {
  if (typeof document === "undefined") return;
  if (document.getElementById(id)) return;
  const el = document.createElement("style");
  el.id = id; el.textContent = css;
  document.head.appendChild(el);
}

ensureStyle("at-allocsummary", `
  .at-allocsummary{display:grid;gap:var(--space-sm);font-family:var(--font-sans)}
  .at-allocsummary__id{display:flex;flex-direction:column;gap:1px}
  .at-allocsummary__name{font-size:13px;font-weight:600;color:var(--fg-1)}
  .at-allocsummary__role{font-size:11px;color:var(--fg-4)}
  .at-allocsummary__chips{display:flex;flex-wrap:wrap;gap:var(--space-xs)}
`);

/**
 * The allocation summary surface: an optional identity (name + role), the shared
 * AllocationBar, an optional balance badge, and an optional category chip row.
 * One configurable surface that covers both the directory person row (identity +
 * bar + balance) and the breakdown strip (bar + balance + chips). Composes
 * AllocationBar and AllocationChip.
 */
export function AllocationSummary({
  name,
  role,
  allocations = [],
  showChips = true,
  showBalance = true,
  height = 12,
}) {
  return (
    <div className="at-allocsummary">
      {(name || role) && (
        <div className="at-allocsummary__id">
          {name && <div className="at-allocsummary__name">{name}</div>}
          {role && <div className="at-allocsummary__role">{role}</div>}
        </div>
      )}
      <AllocationBar allocations={allocations} height={height} showLabels showTotal={showBalance} />
      {showChips && allocations.length > 0 && (
        <div className="at-allocsummary__chips">
          {allocations.map((a, i) => (
            <AllocationChip key={i} color={a.color} label={a.label} pct={a.pct != null ? a.pct + "%" : undefined} />
          ))}
        </div>
      )}
    </div>
  );
}
