'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 && children.length > 5) {
        throw 'You must build segmented button with 2 or more buttons, but no more 5';
    }

    const extraClasses =
        `m3 m3-segmented-buttons m3-density-${density} m3-button-segments-amount-${children.length} ${props.className ?? ''}`.trimEnd();

    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={extraClasses} ref={ref}>
            {SegmentedButtons}
        </div>
    );
});
