import i,{Fragment as x,createContext as A,useContext as H,useMemo as E,useRef as F,useState as M,useEffect as _}from"react";import{forwardRefWithAs as U,render as P,compact as K}from'../../utils/render.js';import{useId as B}from'../../hooks/use-id.js';import{Keys as g}from'../keyboard.js';import{isDisabledReactIssue7711 as I}from'../../utils/bugs.js';import{Label as O,useLabels as W}from'../label/label.js';import{Description as N,useDescriptions as J}from'../description/description.js';import{useResolveButtonType as X}from'../../hooks/use-resolve-button-type.js';import{useSyncRefs as j}from'../../hooks/use-sync-refs.js';import{Hidden as $,Features as q}from'../../internal/hidden.js';import{attemptSubmit as z}from'../../utils/form.js';import{useEvent as m}from'../../hooks/use-event.js';import{useControllable as Q}from'../../hooks/use-controllable.js';import{useDisposables as V}from'../../hooks/use-disposables.js';let y=A(null);y.displayName="GroupContext";let Y=x;function Z(s){var d;let[n,p]=M(null),[c,f]=W(),[r,h]=J(),l=E(()=>({switch:n,setSwitch:p,labelledby:c,describedby:r}),[n,p,c,r]),T={},b=s;return i.createElement(h,{name:"Switch.Description"},i.createElement(f,{name:"Switch.Label",props:{htmlFor:(d=l.switch)==null?void 0:d.id,onClick(t){n&&(t.currentTarget.tagName==="LABEL"&&t.preventDefault(),n.click(),n.focus({preventScroll:!0}))}}},i.createElement(y.Provider,{value:l},P({ourProps:T,theirProps:b,defaultTag:Y,name:"Switch.Group"}))))}let ee="button";function te(s,n){let p=B(),{id:c=`headlessui-switch-${p}`,checked:f,defaultChecked:r=!1,onChange:h,name:l,value:T,form:b,...d}=s,t=H(y),u=F(null),D=j(u,n,t===null?null:t.setSwitch),[o,a]=Q(f,h,r),S=m(()=>a==null?void 0:a(!o)),C=m(e=>{if(I(e.currentTarget))return e.preventDefault();e.preventDefault(),S()}),L=m(e=>{e.key===g.Space?(e.preventDefault(),S()):e.key===g.Enter&&z(e.currentTarget)}),v=m(e=>e.preventDefault()),G=E(()=>({checked:o}),[o]),R={id:c,ref:D,role:"switch",type:X(s,u),tabIndex:0,"aria-checked":o,"aria-labelledby":t==null?void 0:t.labelledby,"aria-describedby":t==null?void 0:t.describedby,onClick:C,onKeyUp:L,onKeyPress:v},k=V();return _(()=>{var w;let e=(w=u.current)==null?void 0:w.closest("form");e&&r!==void 0&&k.addEventListener(e,"reset",()=>{a(r)})},[u,a]),i.createElement(i.Fragment,null,l!=null&&o&&i.createElement($,{features:q.Hidden,...K({as:"input",type:"checkbox",hidden:!0,readOnly:!0,form:b,checked:o,name:l,value:T})}),P({ourProps:R,theirProps:d,slot:G,defaultTag:ee,name:"Switch"}))}let ne=U(te),re=Z,Ge=Object.assign(ne,{Group:re,Label:O,Description:N});export{Ge as Switch};
