'use strict';
// C4 CustomSelect's portal/outside-click/viewport positioning pattern, without its UI framework.
window.CustomSelect=function CustomSelect({id,label,value,options,onChange,disabled=false,minMenuWidth=0,triggerClassName}){
  const items=options.map(option=>typeof option==='object'?option:{value:option,label:String(option)});
  const trigger=React.useRef(null),menu=React.useRef(null),buttons=React.useRef([]);
  const [open,setOpen]=React.useState(false),[active,setActive]=React.useState(0),[position,setPosition]=React.useState({});
  const menuId=React.useId(),selected=items.findIndex(option=>option.value===value);
  const close=(restore=false)=>{setOpen(false);if(restore)trigger.current?.focus();};
  React.useLayoutEffect(()=>{
    if(!open)return;
    const place=()=>{
      const rect=trigger.current.getBoundingClientRect(),below=innerHeight-rect.bottom-12,above=rect.top-12,up=below<160&&above>below;
      const height=Math.min(224,Math.max(80,up?above:below));
      const width=Math.min(Math.max(rect.width,minMenuWidth),innerWidth-16);
      setPosition({left:Math.max(8,Math.min(rect.left,innerWidth-width-8)),top:up?Math.max(8,rect.top-height-4):rect.bottom+4,width,maxHeight:height});
    };
    const outside=event=>{if(!trigger.current?.contains(event.target)&&!menu.current?.contains(event.target))close();};
    place();document.addEventListener('pointerdown',outside,true);window.addEventListener('resize',place);window.addEventListener('scroll',place,true);
    return()=>{document.removeEventListener('pointerdown',outside,true);window.removeEventListener('resize',place);window.removeEventListener('scroll',place,true);};
  },[open,minMenuWidth]);
  React.useLayoutEffect(()=>{if(open)buttons.current[active]?.focus();},[open,active]);
  function show(index=selected){setActive(Math.max(0,index));setOpen(true);}
  function choose(option){onChange(option.value);close(true);}
  function key(event){
    if(event.key==='Escape'){event.preventDefault();event.stopPropagation();close(true);return;}
    if(event.key==='Tab'){close(true);return;}
    const directions=['ArrowDown','ArrowUp','Home','End'];
    if(directions.includes(event.key)){
      event.preventDefault();setActive(index=>event.key==='Home'?0:event.key==='End'?items.length-1:(index+(event.key==='ArrowDown'?1:-1)+items.length)%items.length);
    }else if(event.key.length===1&&event.key!==' '){const index=items.findIndex(option=>option.label.toLowerCase().startsWith(event.key.toLowerCase()));if(index>=0){event.preventDefault();setActive(index);}}
  }
  return (
    <div className="custom-select relative min-w-0">
      <button
        ref={trigger}
        id={id}
        type="button"
        role="combobox"
        aria-label={label}
        aria-expanded={open}
        aria-haspopup="listbox"
        aria-controls={open ? menuId : undefined}
        disabled={disabled || !items.length}
        className={
          'custom-select-trigger grid w-full min-w-0 items-center text-left [font-family:inherit] leading-[inherit] aria-expanded:border-accent ' +
          (triggerClassName ||
            'min-h-[38px] grid-cols-[minmax(0,1fr)_16px] gap-2 rounded-[10px] border border-solid border-edge bg-surface px-[11px] py-2 text-[13px] [font-weight:inherit] text-ink')
        }
        onClick={() => (open ? close() : show())}
        onKeyDown={(event) => {
          if (['ArrowDown', 'ArrowUp'].includes(event.key)) {
            event.preventDefault();
            show(event.key === 'ArrowUp' ? items.length - 1 : selected);
          }
        }}
      >
        <span className="min-w-0 truncate">{items[selected]?.label || 'Choose…'}</span>
        {HubIcons.render('chevron-down', {
          className: 'text-[16px] text-muted'
        })}
      </button>
      {open &&
        ReactDOM.createPortal(
          <div
            ref={menu}
            id={menuId}
            style={position}
            role="listbox"
            aria-label={label}
            onKeyDown={key}
            className="fixed z-[9999] grid gap-0.5 overflow-auto overscroll-contain rounded-[10px] border border-solid border-edge bg-canvas p-[5px] text-ink shadow-hub-popup"
          >
            {items.map((option, index) => (
              <button
                key={option.value}
                ref={(node) => (buttons.current[index] = node)}
                type="button"
                role="option"
                aria-selected={option.value === value}
                tabIndex={index === active ? 0 : -1}
                onFocus={() => setActive(index)}
                onClick={() => choose(option)}
                className={
                  'custom-select-option flex min-h-[34px] w-full min-w-0 items-center justify-between gap-3 rounded-md border-0 ' +
                  'bg-transparent px-[9px] py-[7px] text-left text-[13px] text-ink hover:bg-surface focus:bg-surface aria-selected:bg-surface aria-selected:text-accent'
                }
              >
                <span className="min-w-0 truncate">{option.label}</span>
                {option.value === value && HubIcons.render('check')}
              </button>
            ))}
          </div>,
          trigger.current.closest('dialog[open]') || document.body
        )}
    </div>
  );
};
