'use client';

import { SegmentButton } from './segment-button';
import { SegmentedButtonsProps } from './segmented-buttons.types';
import React, { cloneElement, forwardRef, ReactElement } from 'react';

export const SegmentedButtons = forwardRef<
    HTMLDivElement,
    SegmentedButtonsProps
>(({ selectable = false, density = 0, children, ...props }, ref) => {
    if (children.length <= 1) {
        throw 'You must build segmented button with 2 or more button';
    }

    const SegmentedButtons: Array<ReactElement> = children.map(
        (Button: ReactElement, index: number) => {
            return cloneElement(<SegmentButton />, {
                ...Button.props,
                selectable: Button.props.selectable ?? selectable,
                key: index,
            });
        },
    );

    return (
        <div
            className={`m3 m3-segmented-buttons m3-density-${density} ${props.className ?? ''}`.trimEnd()}
            ref={ref}
        >
            {SegmentedButtons}
        </div>
    );
});
