import React, { forwardRef, useLayoutEffect, useRef } from "react";
import { useForkRef } from "../../../../hooks";
import { createEvent } from "../../../../utils";
import { SelectHidden } from "./SelectNative.styles";
export const SelectNative = /*#__PURE__*/ forwardRef(({ name, multiple, items, value, handleChange, outerOnChange }, ref)=>{
    const values = Array.isArray(value) ? value : [
        value
    ].filter(Boolean);
    const selectRef = useRef(null);
    const forkRef = useForkRef(selectRef, ref);
    const options = Array.from(new Set([
        ...items.keys(),
        ...values
    ]));
    useLayoutEffect(()=>{
        if (selectRef.current && !multiple) {
            const valueInit = selectRef.current.value;
            if (valueInit) {
                handleChange(valueInit, null);
            }
        }
        if (selectRef.current && multiple) {
            const valuesInit = Array.from(selectRef.current.selectedOptions).map((v)=>v.value);
            if (valuesInit.length !== 0) {
                handleChange(valuesInit, null);
            }
        }
    }, []);
    useLayoutEffect(()=>{
        const event = createEvent(selectRef);
        if (event && outerOnChange) {
            outerOnChange(event);
        }
    }, [
        value
    ]);
    return /*#__PURE__*/ React.createElement(React.Fragment, null, /*#__PURE__*/ React.createElement(SelectHidden, {
        ref: forkRef,
        multiple: multiple,
        name: name,
        hidden: true,
        value: multiple ? values : values[0] ?? ''
    }, /*#__PURE__*/ React.createElement("option", {
        value: ""
    }, " "), options.map((option)=>/*#__PURE__*/ React.createElement("option", {
            key: option,
            value: option
        }, option))));
});
