import "../../styles/components/ToggleButtonGroup.css";

function joinClasses(parts) {
  return parts.filter(Boolean).join(" ");
}

export default function ToggleButtonGroup({
  value,
  options,
  onChange,
  ariaLabel,
  role = "group",
  className = "tbg-group",
  buttonBaseClassName = "tbg-button",
  buttonClassName,
  activeClassName = "is-active",
  inactiveClassName = "is-inactive",
  sizeClassName = "tbg-size-default"
}) {
  const optionCount = Math.max(options.length, 1);
  const activeIndex =
    value == null ? -1 : options.findIndex((option) => option.value === value);

  const groupStyle = {
    "--tbg-option-count": optionCount,
    "--tbg-active-index": activeIndex >= 0 ? activeIndex : 0
  };

  return (
    <div
      className={joinClasses([className, activeIndex >= 0 && "has-active"])}
      role={role}
      aria-label={ariaLabel}
      style={groupStyle}
    >
      <span className="tbg-indicator" aria-hidden="true" />
      {options.map((option) => {
        const isActive = value != null && option.value === value;
        const handleClick = option.onClick
          ? option.onClick
          : onChange
            ? () => onChange(option.value)
            : undefined;

        return (
          <button
            key={option.value}
            type="button"
            className={joinClasses([
              buttonBaseClassName,
              sizeClassName,
              buttonClassName,
              isActive ? (option.activeClassName || activeClassName) : (option.inactiveClassName || inactiveClassName),
              option.className
            ])}
            onClick={handleClick}
            disabled={option.disabled}
            aria-pressed={value != null ? isActive : undefined}
            aria-label={option.ariaLabel}
          >
            {option.label}
          </button>
        );
      })}
    </div>
  );
}
