// src/components/ui/SegmentedControl.jsx
// A row of mutually-exclusive toggle buttons — styled like Button variants,
// grouped into a single visual unit with shared borders.
//
// Props:
//   options  — Array<{
//                value:      string
//                label:      ReactNode
//                icon?:      ReactNode
//                activeBg?:  string   — CSS value for active background (overrides variant)
//                activeText?:string   — CSS value for active text color (overrides variant)
//              }>
//   value    — currently selected value (string)
//   onChange — (value: string) => void
//   variant  — button variant for active item when no per-option color: 'primary' | 'secondary' | 'ghost'
//              (default: 'secondary')
//   size     — 'sm' | 'md' | 'lg'  (default: 'md')
//   disabled — boolean
//   className — extra class on wrapper

export default function SegmentedControl({
  options = [],
  value,
  onChange,
  variant = 'secondary',
  size = 'md',
  disabled = false,
  className = '',
}) {
  return (
    <div
      className={`seg-ctrl ${className}`}
      role="group"
      aria-label="Segmented control"
    >
      {options.map((opt, idx) => {
        const isActive = opt.value === value
        const isFirst  = idx === 0
        const isLast   = idx === options.length - 1

        // Per-option color override: inline style applied only when active
        const hasCustomColor = isActive && (opt.activeBg || opt.activeText)
        const customStyle = hasCustomColor
          ? {
              backgroundColor: opt.activeBg  || undefined,
              color:           opt.activeText || undefined,
              borderColor:     'transparent',
            }
          : undefined

        return (
          <button
            key={opt.value}
            type="button"
            disabled={disabled}
            aria-pressed={isActive}
            onClick={() => !disabled && onChange(opt.value)}
            style={customStyle}
            className={[
              'btn',
              isActive && !hasCustomColor ? `btn-${variant}` : isActive ? '' : 'btn-ghost',
              `btn-${size}`,
              'seg-ctrl__btn',
              isFirst  ? 'seg-ctrl__btn--first' : '',
              isLast   ? 'seg-ctrl__btn--last'  : '',
              !isFirst && !isLast ? 'seg-ctrl__btn--mid' : '',
            ].filter(Boolean).join(' ')}
          >
            {opt.icon && (
              <span className="shrink-0 flex items-center" aria-hidden="true">
                {opt.icon}
              </span>
            )}
            {opt.label != null && <span>{opt.label}</span>}
          </button>
        )
      })}
    </div>
  )
}
