import { type ReactNode } from 'react'
import styles from './ButtonGroup.module.css'

export interface ButtonGroupItem {
  value: string
  label: ReactNode
  /** Optional color for dot indicator and active tint */
  color?: string
}

interface ButtonGroupProps {
  items: ButtonGroupItem[]
  /** Currently selected values (multi-select) */
  value: Set<string>
  onChange: (value: Set<string>) => void
  className?: string
}

export function ButtonGroup({ items, value, onChange, className }: ButtonGroupProps) {
  function handleClick(itemValue: string) {
    const next = new Set(value)
    if (next.has(itemValue)) {
      next.delete(itemValue)
    } else {
      next.add(itemValue)
    }
    onChange(next)
  }

  return (
    <div className={`${styles.group} ${className ?? ''}`} role="group">
      {items.map((item) => {
        const active = value.has(item.value)

        return (
          <button
            key={item.value}
            type="button"
            className={`${styles.btn} ${active ? styles.active : ''}`}
            style={active && item.color ? {
              borderColor: item.color,
              color: item.color,
              background: `color-mix(in srgb, ${item.color} 10%, transparent)`,
            } : undefined}
            onClick={() => handleClick(item.value)}
            aria-pressed={active}
          >
            {item.color && (
              <span
                className={`${styles.dot} ${active ? '' : styles.dotMuted}`}
                style={{ background: item.color }}
              />
            )}
            {item.label}
          </button>
        )
      })}
    </div>
  )
}
