import React from "react";

function ensureStyleAB(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);
}

ensureStyleAB("at-allocbar", `
  .at-allocbar{width:100%;background:var(--at-plum-100);border-radius:var(--radius-sm);overflow:hidden;display:flex}
  .at-allocbar__seg{height:100%;display:flex;align-items:center;padding:0 6px;color:#fff;
    font-family:var(--font-sans);font-size:10px;font-weight:600;font-variant-numeric:tabular-nums;
    white-space:nowrap;overflow:hidden;border-right:1px solid rgba(255,255,255,.6)}
  .at-allocbar__seg:last-child{border-right:0}
  .at-allocbar__empty{background:repeating-linear-gradient(45deg,var(--at-plum-200) 0 6px,var(--at-plum-100) 6px 12px)}
`);

/* Category-aware palette so each allocation segment is distinguishable. */
const PALETTES = {
  1: ["#E03A63", "#C12B51", "#EF5277", "#F0738F", "#FFC8D4", "#981F3F", "#B07FE0", "#7A5AE0"],
  2: ["#3F73B5", "#2F5B92", "#6F9BD0", "#A8C2DE"],
  3: ["#C58A2C", "#8A5A12", "#E1B05A", "#1F8A5B"],
};
function segColor(a, i) {
  const cat = a.category || 1;
  const p = PALETTES[cat] || PALETTES[1];
  return a.color || p[i % p.length];
}

/**
 * Horizontal stacked bar showing how one person's capacity (%) splits across
 * work groups. Segments that don't reach 100% leave a hatched "unallocated" tail.
 */
export function AllocationBar({ allocations = [], height = 10, showLabels = false }) {
  const sum = allocations.reduce((s, a) => s + (a.pct || 0), 0);
  const denom = Math.max(sum, 100);
  return (
    <div className="at-allocbar" style={{ height }}>
      {allocations.map((a, i) => {
        const w = (a.pct / denom) * 100;
        return (
          <div key={i} className="at-allocbar__seg"
            style={{ width: `${w}%`, background: segColor(a, i) }}
            title={`${a.label || ""} · ${a.pct}%`}>
            {showLabels && w > 8 ? `${a.pct}%` : null}
          </div>
        );
      })}
      {sum < 100 && (
        <div className="at-allocbar__seg at-allocbar__empty" style={{ width: `${((100 - sum) / denom) * 100}%` }}
          title={`${100 - sum}% unallocated`} />
      )}
    </div>
  );
}
