// ActuatorStatusBar.jsx — actuator state indicator for hive gate controls
// Renders the gate state badge by delegating to the GateStatusBadge component when it is
// available and recognises the given state; falls back to an inline colour-coded pill.
//
// Props:
//   state  {string} — one of: "open" | "closed" | "auto"
//                     Any unrecognised value is treated as "closed".
//   label  {string} — optional override label; defaults to the built-in display label
//   style  {object} — optional inline style passed through to the root <span>
//
// Delegation behaviour:
//   "open"   → GateStatusBadge state="open"   (green)  if GateStatusBadge available;
//              else inline status--ok pill     (#26972B green)
//   "closed" → GateStatusBadge state="closed" (grey)   if GateStatusBadge available;
//              else inline status--muted pill  (#9AA5B3 grey)
//   "auto"   → inline status--info pill       (#007BFB blue)   always (not a GateStatusBadge state)

// States that GateStatusBadge natively handles and can be delegated to it.
const GATE_BADGE_STATES = new Set(["open", "closed", "transitioning", "offline"]);

// Inline fallback configuration for each actuator state.
const ACTUATOR_FALLBACK_MAP = {
  open:   { cls: "ok",    label: "Open"   },
  closed: { cls: "muted", label: "Closed" },
  auto:   { cls: "info",  label: "Auto"   },
};

/**
 * Actuator gate state indicator for virtual device panels.
 * Delegates to GateStatusBadge for "open"/"closed" states when the component is loaded;
 * falls back to an inline colour-coded pill for "auto" or when GateStatusBadge is absent.
 * @param {{ state: string, label?: string, style?: object }} props
 */
function ActuatorStatusBar({ state, label, style }) {
  const normalised = state ? String(state).toLowerCase() : "closed";

  // Delegate to GateStatusBadge for states it recognises, if the component is loaded.
  const GateBadge = window.GateStatusBadge;
  if (GateBadge && GATE_BADGE_STATES.has(normalised)) {
    return <GateBadge state={normalised} label={label} style={style} />;
  }

  // Inline colour-coded pill fallback — used for "auto" or when GateStatusBadge is absent.
  const cfg = ACTUATOR_FALLBACK_MAP[normalised] || ACTUATOR_FALLBACK_MAP["closed"];
  const displayLabel = label !== undefined ? label : cfg.label;

  return (
    <span className={"status status--" + cfg.cls} style={style} data-actuator-state={normalised}>
      <span className="dot"></span>
      {displayLabel}
    </span>
  );
}

window.ActuatorStatusBar = ActuatorStatusBar;
