@voxket-ai/voxket-live 1.0.101 โ 1.0.102
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/index.cjs +174 -3
- package/dist/index.js +173 -11
- package/package.json +1 -1
package/dist/index.cjs
CHANGED
|
@@ -79,7 +79,7 @@ theme.transitions = createTransitions(theme.transitions || {});
|
|
|
79
79
|
|
|
80
80
|
export default theme;`}function Io(e={},...t){const{breakpoints:n,mixins:r={},spacing:o,palette:s={},transitions:i={},typography:a={},shape:c,...d}=e;if(e.vars&&e.generateThemeVars===void 0)throw new Error(process.env.NODE_ENV!=="production"?"MUI: `vars` is a private field used for CSS variables support.\nPlease use another name or follow the [docs](https://mui.com/material-ui/customization/css-theme-variables/usage/) to enable the feature.":pt(20));const u=Ms(s),f=ed(e);let h=Le(f,{mixins:Qx(f.breakpoints,r),palette:u,shadows:s1.slice(),typography:t1(u,a),transitions:l1(i),zIndex:{...d1}});if(h=Le(h,d),h=t.reduce((x,y)=>Le(x,y),h),process.env.NODE_ENV!=="production"){const x=["active","checked","completed","disabled","error","expanded","focused","focusVisible","required","selected"],y=(m,b)=>{let C;for(C in m){const v=m[C];if(x.includes(C)&&Object.keys(v).length>0){if(process.env.NODE_ENV!=="production"){const T=Ts("",C);console.error([`MUI: The \`${b}\` component increases the CSS specificity of the \`${C}\` internal state.`,"You can not override it like this: ",JSON.stringify(m,null,2),"",`Instead, you need to use the '&.${T}' syntax:`,JSON.stringify({root:{[`&.${T}`]:v}},null,2),"","https://mui.com/r/state-classes-guide"].join(`
|
|
81
81
|
`))}m[C]={}}}};Object.keys(h.components).forEach(m=>{const b=h.components[m].styleOverrides;b&&m.startsWith("Mui")&&y(b,m)})}return h.unstable_sxConfig={...kr,...d==null?void 0:d.unstable_sxConfig},h.unstable_sx=function(y){return Jt({sx:y,theme:this})},h.toRuntimeSource=cd,h}function f1(e){let t;return e<1?t=5.11916*e**2:t=4.5*Math.log(e+1)+2,Math.round(t*10)/1e3}const h1=[...Array(25)].map((e,t)=>{if(t===0)return"none";const n=f1(t);return`linear-gradient(rgba(255 255 255 / ${n}), rgba(255 255 255 / ${n}))`});function ld(e){return{inputPlaceholder:e==="dark"?.5:.42,inputUnderline:e==="dark"?.7:.42,switchTrackDisabled:e==="dark"?.2:.12,switchTrack:e==="dark"?.3:.38}}function dd(e){return e==="dark"?h1:[]}function m1(e){const{palette:t={mode:"light"},opacity:n,overlays:r,...o}=e,s=Ms(t);return{palette:s,opacity:{...ld(s.mode),...n},overlays:r||dd(s.mode),...o}}function g1(e){var t;return!!e[0].match(/(cssVarPrefix|colorSchemeSelector|rootSelector|typography|mixins|breakpoints|direction|transitions)/)||!!e[0].match(/sxConfig$/)||e[0]==="palette"&&!!((t=e[1])!=null&&t.match(/(mode|contrastThreshold|tonalOffset)/))}const p1=e=>[...[...Array(25)].map((t,n)=>`--${e?`${e}-`:""}overlays-${n}`),`--${e?`${e}-`:""}palette-AppBar-darkBg`,`--${e?`${e}-`:""}palette-AppBar-darkColor`],x1=e=>(t,n)=>{const r=e.rootSelector||":root",o=e.colorSchemeSelector;let s=o;if(o==="class"&&(s=".%s"),o==="data"&&(s="[data-%s]"),o!=null&&o.startsWith("data-")&&!o.includes("%s")&&(s=`[${o}="%s"]`),e.defaultColorScheme===t){if(t==="dark"){const i={};return p1(e.cssVarPrefix).forEach(a=>{i[a]=n[a],delete n[a]}),s==="media"?{[r]:n,"@media (prefers-color-scheme: dark)":{[r]:i}}:s?{[s.replace("%s",t)]:i,[`${r}, ${s.replace("%s",t)}`]:n}:{[r]:{...n,...i}}}if(s&&s!=="media")return`${r}, ${s.replace("%s",String(t))}`}else if(t){if(s==="media")return{[`@media (prefers-color-scheme: ${String(t)})`]:{[r]:n}};if(s)return s.replace("%s",String(t))}return r};function y1(e,t){t.forEach(n=>{e[n]||(e[n]={})})}function N(e,t,n){!e[t]&&n&&(e[t]=n)}function hn(e){return typeof e!="string"||!e.startsWith("hsl")?e:sd(e)}function ot(e,t){`${t}Channel`in e||(e[`${t}Channel`]=fn(hn(e[t]),`MUI: Can't create \`palette.${t}Channel\` because \`palette.${t}\` is not one of these formats: #nnn, #nnnnnn, rgb(), rgba(), hsl(), hsla(), color().
|
|
82
|
-
To suppress this warning, you need to explicitly provide the \`palette.${t}Channel\` as a string (in rgb format, for example "12 12 12") or undefined if you want to remove the channel token.`))}function b1(e){return typeof e=="number"?`${e}px`:typeof e=="string"||typeof e=="function"||Array.isArray(e)?e:"8px"}const Xe=e=>{try{return e()}catch{}},v1=(e="mui")=>Lx(e);function ro(e,t,n,r){if(!t)return;t=t===!0?{}:t;const o=r==="dark"?"dark":"light";if(!n){e[r]=m1({...t,palette:{mode:o,...t==null?void 0:t.palette}});return}const{palette:s,...i}=Io({...n,palette:{mode:o,...t==null?void 0:t.palette}});return e[r]={...t,palette:s,opacity:{...ld(o),...t==null?void 0:t.opacity},overlays:(t==null?void 0:t.overlays)||dd(o)},i}function w1(e={},...t){const{colorSchemes:n={light:!0},defaultColorScheme:r,disableCssColorScheme:o=!1,cssVarPrefix:s="mui",shouldSkipGeneratingVar:i=g1,colorSchemeSelector:a=n.light&&n.dark?"media":void 0,rootSelector:c=":root",...d}=e,u=Object.keys(n)[0],f=r||(n.light&&u!=="light"?"light":u),h=v1(s),{[f]:x,light:y,dark:m,...b}=n,C={...b};let v=x;if((f==="dark"&&!("dark"in n)||f==="light"&&!("light"in n))&&(v=!0),!v)throw new Error(process.env.NODE_ENV!=="production"?`MUI: The \`colorSchemes.${f}\` option is either missing or invalid.`:pt(21,f));const T=ro(C,v,d,f);y&&!C.light&&ro(C,y,void 0,"light"),m&&!C.dark&&ro(C,m,void 0,"dark");let k={defaultColorScheme:f,...T,cssVarPrefix:s,colorSchemeSelector:a,rootSelector:c,getCssVar:h,colorSchemes:C,font:{...Jx(T.typography),...T.font},spacing:b1(d.spacing)};Object.keys(k.colorSchemes).forEach(_=>{const p=k.colorSchemes[_].palette,V=B=>{const G=B.split("-"),te=G[1],ne=G[2];return h(B,p[te][ne])};if(p.mode==="light"&&(N(p.common,"background","#fff"),N(p.common,"onBackground","#000")),p.mode==="dark"&&(N(p.common,"background","#000"),N(p.common,"onBackground","#fff")),y1(p,["Alert","AppBar","Avatar","Button","Chip","FilledInput","LinearProgress","Skeleton","Slider","SnackbarContent","SpeedDialAction","StepConnector","StepContent","Switch","TableCell","Tooltip"]),p.mode==="light"){N(p.Alert,"errorColor",me(p.error.light,.6)),N(p.Alert,"infoColor",me(p.info.light,.6)),N(p.Alert,"successColor",me(p.success.light,.6)),N(p.Alert,"warningColor",me(p.warning.light,.6)),N(p.Alert,"errorFilledBg",V("palette-error-main")),N(p.Alert,"infoFilledBg",V("palette-info-main")),N(p.Alert,"successFilledBg",V("palette-success-main")),N(p.Alert,"warningFilledBg",V("palette-warning-main")),N(p.Alert,"errorFilledColor",Xe(()=>p.getContrastText(p.error.main))),N(p.Alert,"infoFilledColor",Xe(()=>p.getContrastText(p.info.main))),N(p.Alert,"successFilledColor",Xe(()=>p.getContrastText(p.success.main))),N(p.Alert,"warningFilledColor",Xe(()=>p.getContrastText(p.warning.main))),N(p.Alert,"errorStandardBg",ge(p.error.light,.9)),N(p.Alert,"infoStandardBg",ge(p.info.light,.9)),N(p.Alert,"successStandardBg",ge(p.success.light,.9)),N(p.Alert,"warningStandardBg",ge(p.warning.light,.9)),N(p.Alert,"errorIconColor",V("palette-error-main")),N(p.Alert,"infoIconColor",V("palette-info-main")),N(p.Alert,"successIconColor",V("palette-success-main")),N(p.Alert,"warningIconColor",V("palette-warning-main")),N(p.AppBar,"defaultBg",V("palette-grey-100")),N(p.Avatar,"defaultBg",V("palette-grey-400")),N(p.Button,"inheritContainedBg",V("palette-grey-300")),N(p.Button,"inheritContainedHoverBg",V("palette-grey-A100")),N(p.Chip,"defaultBorder",V("palette-grey-400")),N(p.Chip,"defaultAvatarColor",V("palette-grey-700")),N(p.Chip,"defaultIconColor",V("palette-grey-700")),N(p.FilledInput,"bg","rgba(0, 0, 0, 0.06)"),N(p.FilledInput,"hoverBg","rgba(0, 0, 0, 0.09)"),N(p.FilledInput,"disabledBg","rgba(0, 0, 0, 0.12)"),N(p.LinearProgress,"primaryBg",ge(p.primary.main,.62)),N(p.LinearProgress,"secondaryBg",ge(p.secondary.main,.62)),N(p.LinearProgress,"errorBg",ge(p.error.main,.62)),N(p.LinearProgress,"infoBg",ge(p.info.main,.62)),N(p.LinearProgress,"successBg",ge(p.success.main,.62)),N(p.LinearProgress,"warningBg",ge(p.warning.main,.62)),N(p.Skeleton,"bg",`rgba(${V("palette-text-primaryChannel")} / 0.11)`),N(p.Slider,"primaryTrack",ge(p.primary.main,.62)),N(p.Slider,"secondaryTrack",ge(p.secondary.main,.62)),N(p.Slider,"errorTrack",ge(p.error.main,.62)),N(p.Slider,"infoTrack",ge(p.info.main,.62)),N(p.Slider,"successTrack",ge(p.success.main,.62)),N(p.Slider,"warningTrack",ge(p.warning.main,.62));const B=Wn(p.background.default,.8);N(p.SnackbarContent,"bg",B),N(p.SnackbarContent,"color",Xe(()=>p.getContrastText(B))),N(p.SpeedDialAction,"fabHoverBg",Wn(p.background.paper,.15)),N(p.StepConnector,"border",V("palette-grey-400")),N(p.StepContent,"border",V("palette-grey-400")),N(p.Switch,"defaultColor",V("palette-common-white")),N(p.Switch,"defaultDisabledColor",V("palette-grey-100")),N(p.Switch,"primaryDisabledColor",ge(p.primary.main,.62)),N(p.Switch,"secondaryDisabledColor",ge(p.secondary.main,.62)),N(p.Switch,"errorDisabledColor",ge(p.error.main,.62)),N(p.Switch,"infoDisabledColor",ge(p.info.main,.62)),N(p.Switch,"successDisabledColor",ge(p.success.main,.62)),N(p.Switch,"warningDisabledColor",ge(p.warning.main,.62)),N(p.TableCell,"border",ge(Zn(p.divider,1),.88)),N(p.Tooltip,"bg",Zn(p.grey[700],.92))}if(p.mode==="dark"){N(p.Alert,"errorColor",ge(p.error.light,.6)),N(p.Alert,"infoColor",ge(p.info.light,.6)),N(p.Alert,"successColor",ge(p.success.light,.6)),N(p.Alert,"warningColor",ge(p.warning.light,.6)),N(p.Alert,"errorFilledBg",V("palette-error-dark")),N(p.Alert,"infoFilledBg",V("palette-info-dark")),N(p.Alert,"successFilledBg",V("palette-success-dark")),N(p.Alert,"warningFilledBg",V("palette-warning-dark")),N(p.Alert,"errorFilledColor",Xe(()=>p.getContrastText(p.error.dark))),N(p.Alert,"infoFilledColor",Xe(()=>p.getContrastText(p.info.dark))),N(p.Alert,"successFilledColor",Xe(()=>p.getContrastText(p.success.dark))),N(p.Alert,"warningFilledColor",Xe(()=>p.getContrastText(p.warning.dark))),N(p.Alert,"errorStandardBg",me(p.error.light,.9)),N(p.Alert,"infoStandardBg",me(p.info.light,.9)),N(p.Alert,"successStandardBg",me(p.success.light,.9)),N(p.Alert,"warningStandardBg",me(p.warning.light,.9)),N(p.Alert,"errorIconColor",V("palette-error-main")),N(p.Alert,"infoIconColor",V("palette-info-main")),N(p.Alert,"successIconColor",V("palette-success-main")),N(p.Alert,"warningIconColor",V("palette-warning-main")),N(p.AppBar,"defaultBg",V("palette-grey-900")),N(p.AppBar,"darkBg",V("palette-background-paper")),N(p.AppBar,"darkColor",V("palette-text-primary")),N(p.Avatar,"defaultBg",V("palette-grey-600")),N(p.Button,"inheritContainedBg",V("palette-grey-800")),N(p.Button,"inheritContainedHoverBg",V("palette-grey-700")),N(p.Chip,"defaultBorder",V("palette-grey-700")),N(p.Chip,"defaultAvatarColor",V("palette-grey-300")),N(p.Chip,"defaultIconColor",V("palette-grey-300")),N(p.FilledInput,"bg","rgba(255, 255, 255, 0.09)"),N(p.FilledInput,"hoverBg","rgba(255, 255, 255, 0.13)"),N(p.FilledInput,"disabledBg","rgba(255, 255, 255, 0.12)"),N(p.LinearProgress,"primaryBg",me(p.primary.main,.5)),N(p.LinearProgress,"secondaryBg",me(p.secondary.main,.5)),N(p.LinearProgress,"errorBg",me(p.error.main,.5)),N(p.LinearProgress,"infoBg",me(p.info.main,.5)),N(p.LinearProgress,"successBg",me(p.success.main,.5)),N(p.LinearProgress,"warningBg",me(p.warning.main,.5)),N(p.Skeleton,"bg",`rgba(${V("palette-text-primaryChannel")} / 0.13)`),N(p.Slider,"primaryTrack",me(p.primary.main,.5)),N(p.Slider,"secondaryTrack",me(p.secondary.main,.5)),N(p.Slider,"errorTrack",me(p.error.main,.5)),N(p.Slider,"infoTrack",me(p.info.main,.5)),N(p.Slider,"successTrack",me(p.success.main,.5)),N(p.Slider,"warningTrack",me(p.warning.main,.5));const B=Wn(p.background.default,.98);N(p.SnackbarContent,"bg",B),N(p.SnackbarContent,"color",Xe(()=>p.getContrastText(B))),N(p.SpeedDialAction,"fabHoverBg",Wn(p.background.paper,.15)),N(p.StepConnector,"border",V("palette-grey-600")),N(p.StepContent,"border",V("palette-grey-600")),N(p.Switch,"defaultColor",V("palette-grey-300")),N(p.Switch,"defaultDisabledColor",V("palette-grey-600")),N(p.Switch,"primaryDisabledColor",me(p.primary.main,.55)),N(p.Switch,"secondaryDisabledColor",me(p.secondary.main,.55)),N(p.Switch,"errorDisabledColor",me(p.error.main,.55)),N(p.Switch,"infoDisabledColor",me(p.info.main,.55)),N(p.Switch,"successDisabledColor",me(p.success.main,.55)),N(p.Switch,"warningDisabledColor",me(p.warning.main,.55)),N(p.TableCell,"border",me(Zn(p.divider,1),.68)),N(p.Tooltip,"bg",Zn(p.grey[700],.92))}ot(p.background,"default"),ot(p.background,"paper"),ot(p.common,"background"),ot(p.common,"onBackground"),ot(p,"divider"),Object.keys(p).forEach(B=>{const G=p[B];B!=="tonalOffset"&&G&&typeof G=="object"&&(G.main&&N(p[B],"mainChannel",fn(hn(G.main))),G.light&&N(p[B],"lightChannel",fn(hn(G.light))),G.dark&&N(p[B],"darkChannel",fn(hn(G.dark))),G.contrastText&&N(p[B],"contrastTextChannel",fn(hn(G.contrastText))),B==="text"&&(ot(p[B],"primary"),ot(p[B],"secondary")),B==="action"&&(G.active&&ot(p[B],"active"),G.selected&&ot(p[B],"selected")))})}),k=t.reduce((_,p)=>Le(_,p),k);const S={prefix:s,disableCssColorScheme:o,shouldSkipGeneratingVar:i,getSelector:x1(k)},{vars:j,generateThemeVars:P,generateStyleSheets:A}=zx(k,S);return k.vars=j,Object.entries(k.colorSchemes[k.defaultColorScheme]).forEach(([_,p])=>{k[_]=p}),k.generateThemeVars=P,k.generateStyleSheets=A,k.generateSpacing=function(){return Ql(d.spacing,Cs(this))},k.getColorSchemeSelector=Hx(a),k.spacing=k.generateSpacing(),k.shouldSkipGeneratingVar=i,k.unstable_sxConfig={...kr,...d==null?void 0:d.unstable_sxConfig},k.unstable_sx=function(p){return Jt({sx:p,theme:this})},k.toRuntimeSource=cd,k}function Ua(e,t,n){e.colorSchemes&&n&&(e.colorSchemes[t]={...n!==!0&&n,palette:Ms({...n===!0?{}:n.palette,mode:t})})}function S1(e={},...t){const{palette:n,cssVariables:r=!1,colorSchemes:o=n?void 0:{light:!0},defaultColorScheme:s=n==null?void 0:n.mode,...i}=e,a=s||"light",c=o==null?void 0:o[a],d={...o,...n?{[a]:{...typeof c!="boolean"&&c,palette:n}}:void 0};if(r===!1){if(!("colorSchemes"in e))return Io(e,...t);let u=n;"palette"in e||d[a]&&(d[a]!==!0?u=d[a].palette:a==="dark"&&(u={mode:"dark"}));const f=Io({...e,palette:u},...t);return f.defaultColorScheme=a,f.colorSchemes=d,f.palette.mode==="light"&&(f.colorSchemes.light={...d.light!==!0&&d.light,palette:f.palette},Ua(f,"dark",d.dark)),f.palette.mode==="dark"&&(f.colorSchemes.dark={...d.dark!==!0&&d.dark,palette:f.palette},Ua(f,"light",d.light)),f}return!n&&!("light"in d)&&a==="light"&&(d.light=!0),w1({...i,colorSchemes:d,defaultColorScheme:a,...typeof r!="boolean"&&r},...t)}const k1=S1(),C1="$$material";function E1(e){return e!=="ownerState"&&e!=="theme"&&e!=="sx"&&e!=="as"}const T1=e=>E1(e)&&e!=="classes",A1=Ex({themeId:C1,defaultTheme:k1,rootShouldForwardProp:T1}),j1=Ox;process.env.NODE_ENV!=="production"&&(ae.node,ae.object.isRequired);function P1(e){return Fx(e)}function M1(e){return Ts("MuiSvgIcon",e)}vx("MuiSvgIcon",["root","colorPrimary","colorSecondary","colorAction","colorError","colorDisabled","fontSizeInherit","fontSizeSmall","fontSizeMedium","fontSizeLarge"]);const V1=e=>{const{color:t,fontSize:n,classes:r}=e,o={root:["root",t!=="inherit"&&`color${Mt(t)}`,`fontSize${Mt(n)}`]};return up(o,M1,r)},N1=A1("svg",{name:"MuiSvgIcon",slot:"Root",overridesResolver:(e,t)=>{const{ownerState:n}=e;return[t.root,n.color!=="inherit"&&t[`color${Mt(n.color)}`],t[`fontSize${Mt(n.fontSize)}`]]}})(j1(({theme:e})=>{var t,n,r,o,s,i,a,c,d,u,f,h,x,y;return{userSelect:"none",width:"1em",height:"1em",display:"inline-block",flexShrink:0,transition:(o=(t=e.transitions)==null?void 0:t.create)==null?void 0:o.call(t,"fill",{duration:(r=(n=(e.vars??e).transitions)==null?void 0:n.duration)==null?void 0:r.shorter}),variants:[{props:m=>!m.hasSvgAsChild,style:{fill:"currentColor"}},{props:{fontSize:"inherit"},style:{fontSize:"inherit"}},{props:{fontSize:"small"},style:{fontSize:((i=(s=e.typography)==null?void 0:s.pxToRem)==null?void 0:i.call(s,20))||"1.25rem"}},{props:{fontSize:"medium"},style:{fontSize:((c=(a=e.typography)==null?void 0:a.pxToRem)==null?void 0:c.call(a,24))||"1.5rem"}},{props:{fontSize:"large"},style:{fontSize:((u=(d=e.typography)==null?void 0:d.pxToRem)==null?void 0:u.call(d,35))||"2.1875rem"}},...Object.entries((e.vars??e).palette).filter(([,m])=>m&&m.main).map(([m])=>{var b,C;return{props:{color:m},style:{color:(C=(b=(e.vars??e).palette)==null?void 0:b[m])==null?void 0:C.main}}}),{props:{color:"action"},style:{color:(h=(f=(e.vars??e).palette)==null?void 0:f.action)==null?void 0:h.active}},{props:{color:"disabled"},style:{color:(y=(x=(e.vars??e).palette)==null?void 0:x.action)==null?void 0:y.disabled}},{props:{color:"inherit"},style:{color:void 0}}]}})),lr=g.forwardRef(function(t,n){const r=P1({props:t,name:"MuiSvgIcon"}),{children:o,className:s,color:i="inherit",component:a="svg",fontSize:c="medium",htmlColor:d,inheritViewBox:u=!1,titleAccess:f,viewBox:h="0 0 24 24",...x}=r,y=g.isValidElement(o)&&o.type==="svg",m={...r,color:i,component:a,fontSize:c,instanceFontSize:t.fontSize,inheritViewBox:u,viewBox:h,hasSvgAsChild:y},b={};u||(b.viewBox=h);const C=V1(m);return l.jsxs(N1,{as:a,className:Oo(C.root,s),focusable:"false",color:d,"aria-hidden":f?void 0:!0,role:f?"img":void 0,ref:n,...b,...x,...y&&o.props,ownerState:m,children:[y?o.props.children:o,f?l.jsx("title",{children:f}):null]})});process.env.NODE_ENV!=="production"&&(lr.propTypes={children:ae.node,classes:ae.object,className:ae.string,color:ae.oneOfType([ae.oneOf(["inherit","action","disabled","primary","secondary","error","info","success","warning"]),ae.string]),component:ae.elementType,fontSize:ae.oneOfType([ae.oneOf(["inherit","large","medium","small"]),ae.string]),htmlColor:ae.string,inheritViewBox:ae.bool,shapeRendering:ae.string,sx:ae.oneOfType([ae.arrayOf(ae.oneOfType([ae.func,ae.object,ae.bool])),ae.func,ae.object]),titleAccess:ae.string,viewBox:ae.string});lr.muiName="SvgIcon";function sn(e,t){function n(r,o){return l.jsx(lr,{"data-testid":process.env.NODE_ENV!=="production"?`${t}Icon`:void 0,ref:o,...r,children:e})}return process.env.NODE_ENV!=="production"&&(n.displayName=`${t}Icon`),n.muiName=lr.muiName,g.memo(g.forwardRef(n))}const R1=sn(l.jsx("path",{d:"M16.5 6v11.5c0 2.21-1.79 4-4 4s-4-1.79-4-4V5c0-1.38 1.12-2.5 2.5-2.5s2.5 1.12 2.5 2.5v10.5c0 .55-.45 1-1 1s-1-.45-1-1V6H10v9.5c0 1.38 1.12 2.5 2.5 2.5s2.5-1.12 2.5-2.5V5c0-2.21-1.79-4-4-4S7 2.79 7 5v12.5c0 3.04 2.46 5.5 5.5 5.5s5.5-2.46 5.5-5.5V6z"}),"AttachFile"),I1=sn(l.jsx("path",{d:"M12 9c-1.6 0-3.15.25-4.6.72v3.1c0 .39-.23.74-.56.9-.98.49-1.87 1.12-2.66 1.85-.18.18-.43.28-.7.28-.28 0-.53-.11-.71-.29L.29 13.08c-.18-.17-.29-.42-.29-.7s.11-.53.29-.71C3.34 8.78 7.46 7 12 7s8.66 1.78 11.71 4.67c.18.18.29.43.29.71s-.11.53-.29.71l-2.48 2.48c-.18.18-.43.29-.71.29-.27 0-.52-.11-.7-.28-.79-.74-1.69-1.36-2.67-1.85-.33-.16-.56-.5-.56-.9v-3.1C15.15 9.25 13.6 9 12 9"}),"CallEnd"),D1=sn([l.jsx("circle",{cx:"12",cy:"12",r:"3.2"},"0"),l.jsx("path",{d:"M9 2 7.17 4H4c-1.1 0-2 .9-2 2v12c0 1.1.9 2 2 2h16c1.1 0 2-.9 2-2V6c0-1.1-.9-2-2-2h-3.17L15 2zm3 15c-2.76 0-5-2.24-5-5s2.24-5 5-5 5 2.24 5 5-2.24 5-5 5"},"1")],"CameraAlt"),ud=sn(l.jsx("path",{d:"M20 2H4c-1.1 0-1.99.9-1.99 2L2 22l4-4h14c1.1 0 2-.9 2-2V4c0-1.1-.9-2-2-2M6 9h12v2H6zm8 5H6v-2h8zm4-6H6V6h12z"}),"Chat"),fd=sn(l.jsx("path",{d:"M12 14c1.66 0 2.99-1.34 2.99-3L15 5c0-1.66-1.34-3-3-3S9 3.34 9 5v6c0 1.66 1.34 3 3 3m5.3-3c0 3-2.54 5.1-5.3 5.1S6.7 14 6.7 11H5c0 3.41 2.72 6.23 6 6.72V21h2v-3.28c3.28-.48 6-3.3 6-6.72z"}),"Mic"),hd=sn(l.jsx("path",{d:"M17 10.5V7c0-.55-.45-1-1-1H4c-.55 0-1 .45-1 1v10c0 .55.45 1 1 1h12c.55 0 1-.45 1-1v-3.5l4 4v-11z"}),"Videocam"),$1=({disabled:e,capabilities:t,sessionStarted:n,ref:r,participantName:o="User",loadingText:s="Waiting for agent to connect...",theme:i="vox",client:a,displayType:c="widget",onBack:d})=>{var I,q,M,z,Q,W,U;const[u,f]=w.useState(!1),[h,x]=w.useState(!1),[y,m]=w.useState(!1),[b,C]=w.useState(()=>{var D;const E=(D=a==null?void 0:a.getCurrentInteraction)==null?void 0:D.call(a);return console.log("SessionView: Initializing with existing interaction:",(E==null?void 0:E.methodName)||"none"),E||null}),{messages:v,send:T}=J0(),k=w.useRef(null),S=w.useRef(null),{agent:{isActive:j=!1}={}}=a?Gl(a):{agent:{isActive:!1}},P=Ne(i),A=c==="popup",_=w.useMemo(()=>a&&typeof a.getCurrentSession=="function"?!!a.getCurrentSession():!1,[a]),p=w.useMemo(()=>a&&typeof a.getIsAgentConnected=="function"&&a.getIsAgentConnected()||y,[a,y]),V=j||p;w.useEffect(()=>{var E,D;console.log("๐ค SessionView agent state:",{isAgentActive:j,hasActiveSession:_,isAgentActuallyConnected:p,effectiveAgentActive:V,sessionStarted:n,clientSession:(D=(E=a==null?void 0:a.getCurrentSession)==null?void 0:E.call(a))==null?void 0:D.id})},[j,_,p,V,n,a]),w.useEffect(()=>{console.log("๐ค Agent active state changed:",j)},[j]),w.useEffect(()=>{console.log("๐ Session state changed:",{sessionStarted:n,disabled:e,participantName:o,effectiveAgentActive:V,chatOpen:u,currentInteraction:(b==null?void 0:b.methodName)||"none"})},[n,e,o,V,u,b]),w.useEffect(()=>{if(n&&!V){console.log("โฐ Starting agent timeout detection...");const E=setTimeout(()=>{_&&!V&&(console.log("โก Fallback: Assuming agent is connected after 5 seconds with active session"),m(!0),x(!1))},5e3),D=setTimeout(()=>{V||(console.log("โ ๏ธ Agent timeout: Agent did not become active within 30 seconds"),x(!0))},3e4);return()=>{clearTimeout(E),clearTimeout(D)}}else V&&(console.log("โ
Agent is active, clearing timeout"),x(!1))},[n,V,_]),w.useEffect(()=>{if(!a)return;const E=()=>{console.log("๐ Client connection state changed:",a.connected)},D=O=>{console.log("๐ด Client disconnected:",O),C(null),f(!1),x(!1)};return a.on("connection.connected",E),a.on("connection.disconnected",D),()=>{a.off("connection.connected",E),a.off("connection.disconnected",D)}},[a]),w.useEffect(()=>{if(!a)return;const E=F=>{console.log("๐ค SessionView: Agent connected!",F),m(!0),x(!1)},D=F=>{console.log("๐ฃ๏ธ SessionView: Agent speaking detected!",F),y||(m(!0),x(!1))},O=F=>{console.log("๐ค SessionView: Agent thinking detected!",F),y||(m(!0),x(!1))},$=()=>{console.log("๐ค SessionView: Agent disconnected"),m(!1)};return a.on("agent.connected",E),a.on("agent.speaking",D),a.on("agent.thinking",O),a.on("connection.disconnected",$),()=>{a.off("agent.connected",E),a.off("agent.speaking",D),a.off("agent.thinking",O),a.off("connection.disconnected",$)}},[a,y]),w.useEffect(()=>{if(!a)return;const E=F=>{console.log("๐ฏ SessionView: RPC Interaction started:",F);const L=a.getCurrentInteraction();L&&(console.log("๐ฑ SessionView: Setting current interaction:",L.methodName,"mode:",L.presentationMode),C(L))},D=F=>{console.log("โ
SessionView: RPC Interaction completed:",F),C(null)},O=async F=>{console.log("โฐ SessionView: RPC Interaction timeout:",F),C(null)},$=async F=>{console.log("โ SessionView: RPC Interaction dismissed:",F),C(null)};return a.on("rpc.interaction.started",E),a.on("rpc.interaction.completed",D),a.on("rpc.interaction.timeout",O),a.on("rpc.interaction.dismissed",$),()=>{a.off("rpc.interaction.started",E),a.off("rpc.interaction.completed",D),a.off("rpc.interaction.timeout",O),a.off("rpc.interaction.dismissed",$)}},[a]),w.useEffect(()=>{if(!a)return;const E=a.getCurrentInteraction();E?(console.log("๐ SessionView: Syncing with existing interaction:",E.methodName),C(E)):C(null)},[a]),w.useEffect(()=>{console.log("๐ญ SessionView: Current interaction changed:",(b==null?void 0:b.methodName)||"none","mode:",(b==null?void 0:b.presentationMode)||"none")},[b]),w.useEffect(()=>{var E,D,O;console.log("๐ฑ SessionView: Display type changed to:",c),console.log("๐ฑ SessionView: Current session state during display change:",{sessionStarted:n,effectiveAgentActive:V,hasSession:!!((E=a==null?void 0:a.getCurrentSession)!=null&&E.call(a)),sessionId:(O=(D=a==null?void 0:a.getCurrentSession)==null?void 0:D.call(a))==null?void 0:O.id})},[c,n,V,a]),w.useEffect(()=>{console.log("๐ฌ SessionView: Chat open state changed:",u)},[u]),w.useEffect(()=>{b&&u&&(console.log("๐ญ SessionView: Interactive UI appeared, closing chat"),f(!1))},[b,u]),Q0(),w.useEffect(()=>{k.current&&u&&v.length>0&&(console.log("๐ SessionView: Auto-scrolling to latest message, count:",v.length),setTimeout(()=>{if(k.current){let E=k.current.parentElement;for(;E&&E.scrollHeight<=E.clientHeight;)E=E.parentElement;E?(console.log("๐ SessionView: Scrolling container found, scrolling to bottom"),E.scrollTo({top:E.scrollHeight,behavior:"smooth"})):(console.log("๐ SessionView: Using fallback scroll method"),k.current.scrollIntoView({behavior:"smooth",block:"end",inline:"nearest"}))}},100))},[v.length,u]),w.useEffect(()=>{var O,$;console.log("๐ SessionView: Messages updated, count:",v.length),v.length>0&&console.log("๐ SessionView: Latest messages:",v.slice(-3).map(F=>{var L,J,R,ce,xe,pe,Re;return{id:F.id,message:F.message,timestamp:F.timestamp,from:((L=F.from)==null?void 0:L.name)||((J=F.from)==null?void 0:J.identity),fromType:F.from===void 0?"unknown":"participant",isLocal:((R=F.from)==null?void 0:R.identity)===((pe=(xe=(ce=a==null?void 0:a.getCurrentSession)==null?void 0:ce.call(a))==null?void 0:xe.localParticipant)==null?void 0:pe.identity),messageLength:((Re=F.message)==null?void 0:Re.length)||0}}));const E=((O=a==null?void 0:a.getTranscriptions)==null?void 0:O.call(a))||[],D=(($=a==null?void 0:a.getChatMessages)==null?void 0:$.call(a))||[];console.log("๐ SessionView: Raw transcriptions count:",E.length),console.log("๐ SessionView: Raw chat messages count:",D.length)},[v.length,v,a]),w.useEffect(()=>{console.log("๐ฌ SessionView: Chat state changed:",{chatOpen:u,messagesCount:v.length,displayType:c,hasMessages:v.length>0})},[u,v.length,c]);async function B(E){await T(E)}const G=w.useCallback(E=>{console.log("๐ SessionView: Adding local message for voice session context:",E)},[]),te=w.useCallback(async E=>{try{a&&typeof a.sendAttachments=="function"&&(await a.sendAttachments(E),console.log("๐ SessionView: Attachments sent successfully:",E.map(D=>D.name)))}catch(D){console.error("โ SessionView: Failed to send attachments:",D)}},[a]),ne=w.useCallback(()=>{try{console.log("๐ SessionView: Ending call..."),console.log("๐ SessionView: Current state before ending:",{sessionStarted:n,effectiveAgentActive:V,chatOpen:u,currentInteraction:b==null?void 0:b.methodName,hasOnBack:!!d}),b&&(console.log("๐ญ SessionView: Dismissing current interaction:",b.methodName),C(null),a&&typeof a.dismissCurrentInteraction=="function"&&a.dismissCurrentInteraction()),f(!1),x(!1),m(!1),console.log("โ
SessionView: Local state reset"),a&&typeof a.endSession=="function"&&(a.endSession(),console.log("โ
SessionView: Session ended via client.endSession()")),a&&typeof a.disconnect=="function"&&(a.disconnect(),console.log("โ
SessionView: Client disconnected")),d?(console.log("๐ SessionView: Calling onBack to return to welcome..."),d(),console.log("โ
SessionView: onBack called")):console.warn("โ ๏ธ SessionView: No onBack function provided - cannot return to welcome"),console.log("๐ SessionView: Call ended and cleanup completed")}catch(E){console.error("โ SessionView: Failed to end call:",E),C(null),f(!1),x(!1),m(!1),d&&(console.log("๐ SessionView: Error occurred, still calling onBack..."),d())}},[a,d,b,n,V,u]);w.useEffect(()=>(console.log("๐ SessionView: Component mounted/props changed:",{sessionStarted:n,disabled:e,participantName:o,displayType:c,hasOnBack:!!d,hasClient:!!a}),()=>{console.log("๐งน SessionView: Component unmounting or props changing")}),[n,e,o,c,d,a]),w.useEffect(()=>{console.log("๐ SessionView: onBack prop:",{hasOnBack:!!d,onBackType:typeof d})},[d]),w.useEffect(()=>{var D,O;const E=((O=(D=a==null?void 0:a.getCurrentSession)==null?void 0:D.call(a))==null?void 0:O.id)||null;S.current&&!E&&console.warn("โ ๏ธ SessionView: Session was lost unexpectedly!",{previousSession:S.current,currentSession:E,displayType:c,sessionStarted:n,effectiveAgentActive:V}),S.current=E},[a,c,n,V]);const oe=Z("w-full flex flex-col items-center justify-center",c==="fullscreen"?"w-full max-w-none mx-0 h-full":"w-full mx-auto",P.main,c==="fullscreen"?"max-w-none":"","overflow-hidden","h-full"),X=d&&(c==="popup"||c==="fullscreen");return l.jsxs("main",{ref:r,className:Z(oe,"relative session-view",e&&"pointer-events-none opacity-50"),style:{minHeight:0},children:[X&&l.jsx("div",{className:Z("flex items-center justify-between w-full border-b flex-shrink-0",A?"p-2":"p-4",((I=P.chatHeader)==null?void 0:I.container)||"border-gray-200"),children:l.jsx("div",{className:"flex items-center",children:l.jsxs("div",{children:[l.jsx("h3",{className:Z("font-semibold",A?"text-xs":"text-sm",P.text.primary),children:"Voice Session"}),l.jsx("p",{className:Z(A?"text-[10px]":"text-sm",P.text.muted),children:o})]})})}),l.jsxs("div",{className:"w-full flex-1 flex flex-col items-center px-0 min-h-0 overflow-hidden",children:[!V&&n&&l.jsxs("div",{className:"flex flex-col items-center justify-center w-full h-full min-h-[180px]",children:[l.jsx(ie.div,{animate:{rotate:360,scale:[1,1.1,1]},transition:{rotate:{duration:2,repeat:1/0,ease:"linear"},scale:{duration:1,repeat:1/0,ease:"easeInOut"}},className:"w-12 h-12 mb-4",children:l.jsx(ws,{className:P.spinner,weight:"bold"})}),l.jsx(ie.span,{initial:{opacity:0,y:10},animate:{opacity:1,y:0},className:`text-sm opacity-80 ${P.text.muted} text-center max-w-xs`,children:h?"Agent is taking longer than expected...":s}),l.jsx(ie.p,{initial:{opacity:0},animate:{opacity:1},transition:{delay:2},className:`text-xs ${P.text.muted} mt-2 text-center opacity-60`,children:h?"Please check your connection or try again.":"Agent is connecting... This may take a moment."}),h&&d&&l.jsx(ie.button,{initial:{opacity:0,scale:.9},animate:{opacity:1,scale:1},transition:{delay:.5},onClick:d,className:`mt-4 px-4 py-2 rounded-lg ${((q=P.chatHeader)==null?void 0:q.backButton)||"bg-gray-100 hover:bg-gray-200"} transition-colors`,children:"Go Back"})]}),V&&l.jsxs(l.Fragment,{children:[u&&l.jsxs("div",{className:Z("absolute inset-0 w-full h-full flex flex-col transition-[opacity,translate] duration-300 ease-out z-10",i==="light"?"bg-white":"bg-gray-900/95 backdrop-blur-sm",u?"translate-y-0 opacity-100 delay-200":"translate-y-10 opacity-0"),children:[l.jsxs("div",{className:Z("flex-shrink-0 px-4 py-3 border-b",c==="fullscreen"?"px-8":"px-5",((M=P.chatHeader)==null?void 0:M.container)||"border-gray-200 dark:border-gray-700"),children:[l.jsx("h3",{className:Z("font-semibold text-lg",((z=P.text)==null?void 0:z.primary)||"text-gray-900 dark:text-white"),children:"Transcription & Chat"}),l.jsxs("p",{className:Z("text-sm",((Q=P.text)==null?void 0:Q.muted)||"text-gray-600 dark:text-gray-400"),children:[v.length," messages"]})]}),l.jsx("div",{className:Z("flex-1 flex flex-col min-h-0",c==="fullscreen"?"px-8":"px-5"),children:l.jsx(H0,{className:"flex-1 flex flex-col min-h-0 h-full",children:l.jsxs("div",{className:`flex-1 flex flex-col h-full w-full ${Z("overflow-y-auto scrollbar-hide py-4")}`,style:{scrollbarWidth:"none",scrollBehavior:"smooth",paddingBottom:"120px"},children:[v.length===0&&l.jsx("div",{className:"flex-1 flex items-center justify-center",children:l.jsxs("div",{className:"text-center",children:[l.jsx("p",{className:Z("text-lg font-medium mb-2",((W=P.text)==null?void 0:W.primary)||"text-gray-900 dark:text-white"),children:"Start Speaking"}),l.jsx("p",{className:Z("text-sm",((U=P.text)==null?void 0:U.muted)||"text-gray-600 dark:text-gray-400"),children:"Your conversation will appear here"})]})}),v.length>0&&l.jsxs(l.Fragment,{children:[l.jsx("div",{className:"flex-1 min-h-4"}),l.jsx("div",{ref:k,className:"space-y-4 relative whitespace-pre-wrap z-0",children:l.jsx(Wt,{mode:"popLayout",children:v.map((E,D)=>l.jsx(ie.div,{initial:{opacity:0,y:20},animate:{opacity:1,y:0},exit:{opacity:0,y:-20},transition:{duration:.3,ease:"easeOut",delay:D*.02},layout:!0,children:l.jsx(B0,{participantName:o,entry:E})},E.id||`message-${D}`))})})]})]})})})]}),!u&&l.jsxs("div",{className:Z("flex-1 flex flex-col items-center w-full h-full min-h-0",(b==null?void 0:b.presentationMode)==="embedded"?"justify-end":"justify-center"),children:[l.jsx(ie.div,{className:"w-full flex justify-center",animate:{y:(b==null?void 0:b.presentationMode)==="embedded"?-8:0},transition:{duration:.3,ease:"easeOut"},children:l.jsx(X0,{chatOpen:u,client:a})}),l.jsx(Wt,{mode:"wait",children:b&&b.presentationMode==="embedded"&&l.jsx(ie.div,{initial:{opacity:0,y:20,height:0},animate:{opacity:1,y:0,height:"auto"},exit:{opacity:0,y:20,height:0},transition:{duration:.3,ease:"easeOut"},className:Z("w-full relative mt-4 flex justify-center z-50",c==="fullscreen"?"max-w-4xl":"max-w-md"),children:l.jsx("div",{className:"bg-white/10 backdrop-blur-sm rounded-xl border border-white/20 shadow-lg overflow-hidden z-50 relative",style:{zIndex:50},children:l.jsx(Xt,{interaction:b,theme:i,onDismiss:()=>{var E;return(E=a==null?void 0:a.dismissCurrentInteraction)==null?void 0:E.call(a)},client:a,addLocalMessage:G})})},`embedded-${b.methodName}`)})]})]})]}),l.jsx(Wt,{mode:"wait",children:b&&b.presentationMode!=="embedded"&&!u&&l.jsx("div",{className:Z("absolute inset-0 z-50 flex items-center justify-center backdrop-blur-sm",c==="fullscreen"?"bg-black/70":"bg-black/50"),children:l.jsx(ie.div,{initial:{opacity:0,scale:.9},animate:{opacity:1,scale:1},exit:{opacity:0,scale:.9},transition:{duration:.2,ease:"easeOut"},className:Z("relative w-full overflow-hidden",c==="fullscreen"?"max-w-2xl mx-8 max-h-[85vh]":"max-w-lg mx-4 max-h-[80vh]","bg-white dark:bg-gray-900 rounded-2xl shadow-2xl","border border-gray-200 dark:border-gray-700"),children:l.jsx(Xt,{interaction:b,theme:i,onDismiss:()=>{var E;return(E=a==null?void 0:a.dismissCurrentInteraction)==null?void 0:E.call(a)},client:a,addLocalMessage:G})},`modal-${b.methodName}`)})}),l.jsx(ie.div,{initial:{opacity:0,y:20},animate:{opacity:1,y:0},transition:{delay:.2},className:"absolute bottom-0 left-0 right-0 flex-shrink-0 w-full z-20",children:l.jsx(F1,{capabilities:t,onSendMessage:B,onSendAttachments:te,onEndCall:ne,onChatOpenChange:f,disabled:e,theme:i,client:a,sessionStarted:n,displayType:c})})]})};function F1({capabilities:e,onSendMessage:t,onSendAttachments:n,onEndCall:r,onChatOpenChange:o,disabled:s=!1,theme:i,client:a,sessionStarted:c=!1,displayType:d="widget"}){const[u,f]=w.useState(!1),h=w.useRef(null),x=w.useRef(null),y=d==="popup";w.useEffect(()=>{const k=()=>{const S=navigator.userAgent.toLowerCase(),P=["android","iphone","ipad","mobile","tablet"].some(p=>S.includes(p)),A="ontouchstart"in window||navigator.maxTouchPoints>0,_=window.innerWidth<=768;f(P||A&&_)};return k(),window.addEventListener("resize",k),()=>window.removeEventListener("resize",k)},[]);const m=k=>{const S=k.target.files;if(S&&S.length>0){const P=Array.from(S).filter(A=>A.type.startsWith("image/"));if(P.length===0){console.warn("No valid image files selected");return}n&&n(P),h.current&&(h.current.value="")}},b=k=>{const S=k.target.files;if(S&&S.length>0){const j=S[0];j.type.startsWith("image/")&&n&&n([j]),x.current&&(x.current.value="")}},C=()=>{!s&&h.current&&h.current.click()},v=()=>{!s&&u&&x.current&&x.current.click()},T=()=>{console.log("๐ด VoiceControlPanel: End call button clicked"),console.log("๐ด VoiceControlPanel: Current state:",{disabled:s,sessionStarted:c,hasOnEndCall:!!r}),r?r():console.warn("โ ๏ธ VoiceControlPanel: No onEndCall function provided")};return l.jsx("div",{className:Z("w-full backdrop-blur-xl border-0 shadow-lg flex-shrink-0",y?"px-2 py-1":"px-3 py-2",i==="light"?"bg-white/95 border-t border-gray-200":"bg-gray-900/95 border-t border-gray-700"),children:l.jsxs("div",{className:Z("flex items-center justify-between w-full mx-auto",y?"max-w-xs":"max-w-4xl"),children:[l.jsx("input",{ref:h,type:"file",multiple:!0,onChange:m,className:"hidden",accept:"image/*"}),l.jsx("input",{ref:x,type:"file",onChange:b,className:"hidden",accept:"image/*",capture:"environment"}),l.jsxs("div",{className:Z("flex items-center",y?"gap-0.5":"gap-1"),children:[l.jsx("button",{onClick:C,disabled:s,className:Z(y?"p-0.5 rounded-full transition-all duration-200 hover:scale-105 active:scale-95":"p-2 rounded-full transition-all duration-200 hover:scale-105 active:scale-95",s?"opacity-50 cursor-not-allowed":"hover:shadow-md",i==="light"?"bg-gray-100 hover:bg-gray-200 text-gray-600":"bg-gray-700/50 hover:bg-gray-600/50 text-gray-300"),title:"Attach files",children:l.jsx(R1,{className:y?"w-3 h-3":"w-4 h-4"})}),u&&l.jsx("button",{onClick:v,disabled:s,className:Z(y?"p-0.5 rounded-full transition-all duration-200 hover:scale-105 active:scale-95":"p-2 rounded-full transition-all duration-200 hover:scale-105 active:scale-95",s?"opacity-50 cursor-not-allowed":"hover:shadow-md",i==="light"?"bg-gray-100 hover:bg-gray-200 text-gray-600":"bg-gray-700/50 hover:bg-gray-600/50 text-gray-300"),title:"Take photo",children:l.jsx(D1,{className:y?"w-3 h-3":"w-4 h-4"})})]}),l.jsx("div",{className:Z("flex-1 flex justify-center",y?"px-1":"px-3"),children:l.jsx(L0,{capabilities:e,onChatOpenChange:o,onSendMessage:t,theme:i,client:a,className:Z("border-none py-0 rounded-xl w-full",y?"max-w-xs":"max-w-md")})}),l.jsx("div",{className:"flex items-center",children:l.jsx("button",{onClick:T,disabled:s||!c,className:Z(y?"p-0.5 rounded-full transition-all duration-200 hover:scale-105 active:scale-95":"p-2 rounded-full transition-all duration-200 hover:scale-105 active:scale-95",s||!c?"opacity-50 cursor-not-allowed":"hover:shadow-md","bg-red-500 hover:bg-red-600 text-white"),title:"End call",children:l.jsx(I1,{className:y?"w-3 h-3":"w-4 h-4"})})})]})})}function O1({onSendMessage:e,onSendAttachments:t,disabled:n,theme:r,onEndChat:o,displayType:s}){const[i,a]=g.useState(""),[c,d]=g.useState(!1),u=g.useRef(null),f=g.useRef(null),[h,x]=g.useState(!1),y=Ne(r),m=s==="popup";g.useEffect(()=>{const j=()=>{const P=navigator.userAgent.toLowerCase(),_=["android","iphone","ipad","mobile","tablet"].some(B=>P.includes(B)),p="ontouchstart"in window||navigator.maxTouchPoints>0,V=window.innerWidth<=768;x(_||p&&V)};return j(),window.addEventListener("resize",j),()=>window.removeEventListener("resize",j)},[]);const b=j=>{j.preventDefault(),i.trim()&&!n&&(e(i.trim()),a(""))},C=j=>{j.key==="Enter"&&!j.shiftKey&&(j.preventDefault(),b(j))},v=j=>{const P=j.target.files;if(P&&P.length>0){const A=Array.from(P),_=A.filter(p=>p.type.startsWith("image/"));if(_.length===0){console.warn("No valid image files selected");return}_.length!==A.length&&console.warn("Some non-image files were filtered out"),console.log("Selected image files:",_),t(_),u.current&&(u.current.value="")}},T=()=>{!n&&u.current&&u.current.click()},k=()=>{!n&&h&&f.current&&f.current.click()},S=j=>{const P=j.target.files;if(P&&P.length>0){const A=P[0];A.type.startsWith("image/")?t([A]):console.warn("Selected file is not an image"),f.current&&(f.current.value="")}};return l.jsx("div",{className:`${m?"px-2 py-1":"px-4 py-3"} !w-full backdrop-blur-xl border-0 shadow-lg `,children:l.jsx("form",{onSubmit:b,className:`flex items-center !w-full mx-auto ${m?"max-w-xs":"max-w-4xl"}`,children:l.jsxs("div",{className:`flex items-center ${m?"gap-1":"gap-2"} !w-full backdrop-blur-md rounded-full ${m?"px-2 py-1":"px-3 py-2"} shadow-sm hover:shadow-md focus-within:shadow-lg focus-within:ring-2 focus-within:ring-blue-500/30 focus-within:border-blue-500/50 transition-all duration-200 border ${r==="light"?"bg-white/90":y.chatInput.container}`,children:[l.jsx(ie.button,{type:"button",onClick:T,whileHover:{scale:1.05},whileTap:{scale:.95},className:`${m?"p-0.5":"p-1"} rounded-full transition-all duration-200 border-0 ${y.chatInput.attachButton}`,disabled:n,"aria-label":"Attach file",children:l.jsx(Pe.Paperclip,{className:m?"w-3 h-3":"w-4 h-4"})}),h&&l.jsx(ie.button,{type:"button",onClick:k,whileHover:{scale:1.05},whileTap:{scale:.95},className:`${m?"p-0.5":"p-1"} rounded-full transition-all duration-200 border-0 ${y.chatInput.attachButton}`,disabled:n,"aria-label":"Take photo",children:l.jsx(Pe.Camera,{className:m?"w-3 h-3":"w-4 h-4"})}),l.jsx("input",{ref:u,type:"file",multiple:!0,onChange:v,className:"hidden",accept:"image/*"}),l.jsx("input",{ref:f,type:"file",onChange:S,className:"hidden",accept:"image/*",capture:"environment"}),l.jsx("textarea",{value:i,onChange:j=>a(j.target.value),onKeyDown:C,onFocus:()=>d(!0),onBlur:()=>d(!1),placeholder:"Type your message...",disabled:n,className:`flex-1 ${m?"px-1 py-0.5 text-xs min-h-[20px]":"px-2 py-1 text-sm min-h-[32px]"} bg-transparent resize-none max-h-20 focus:outline-none border-0 ${y.chatInput.textarea}`,rows:1,style:{height:"auto",minHeight:m?"20px":"32px"},onInput:j=>{const P=j.target;P.style.height="auto",P.style.height=`${Math.min(P.scrollHeight,m?60:80)}px`}}),l.jsx(ie.button,{type:"submit",disabled:n||!i.trim(),whileHover:{scale:1.05},whileTap:{scale:.95},className:`${m?"p-0.5":"p-1"} rounded-full transition-all duration-200 border-0 flex-shrink-0 ${i.trim()&&!n?y.chatInput.sendButton:r==="light"?"bg-gray-200 text-gray-400 cursor-not-allowed opacity-70":"bg-gray-600/50 text-gray-500 cursor-not-allowed opacity-50"}`,"aria-label":"Send message",children:l.jsx(Pe.SendHorizontal,{className:m?"w-3 h-3":"w-4 h-4"})}),o&&l.jsx(ie.button,{type:"button",onClick:o,whileHover:{scale:1.05},whileTap:{scale:.95},className:`${m?"p-0.5":"p-1"} rounded-full transition-all duration-200 border-0 flex-shrink-0 ${y.chatInput.endButton}`,"aria-label":"End chat",children:l.jsx(Pe.PhoneOff,{className:m?"w-3 h-3":"w-4 h-4"})})]})})})}function L1({text:e,isComplete:t,isRealTimeStream:n=!1,speed:r=50}){const[o,s]=g.useState(""),[i,a]=g.useState(0);return g.useEffect(()=>{if(n){s(e);return}if(t){s(e);return}if(i<e.length){const c=setTimeout(()=>{s(e.slice(0,i+1)),a(i+1)},r);return()=>clearTimeout(c)}},[e,i,t,r,n]),g.useEffect(()=>{n||(a(0),s(""))},[e,n]),l.jsxs("span",{className:"relative",children:[l.jsx("span",{className:"inline-block",children:o}),!t&&l.jsx("span",{className:"inline-flex items-center ml-1",children:[0,1,2].map(c=>l.jsx(ie.span,{className:"w-1.5 h-1.5 bg-current rounded-full mx-0.5",animate:{y:[0,-4,0],opacity:[.4,1,.4],scale:[.8,1,.8]},transition:{duration:.8,repeat:1/0,repeatType:"mirror",delay:c*.2,ease:"easeInOut"}},c))})]})}function _1({message:e,theme:t,isOwn:n,isStreaming:r=!1,displayType:o}){var c,d;const s=Ne(t),i=o==="popup",a=e.sender.name?e.sender.name.split(" ").map(u=>u[0]).join("").toUpperCase().slice(0,2):"U";return l.jsx("div",{className:`flex w-full ${n?"justify-end":"justify-start"} mb-4 px-1`,children:l.jsxs("div",{className:`relative group ${n?"flex-row-reverse":"flex-row"} flex items-end gap-3 max-w-[85%]`,children:[l.jsx("div",{className:`w-6 h-6 rounded-full flex items-center justify-center text-white text-xs font-semibold flex-shrink-0 shadow-lg ${n?t==="light"?"bg-gradient-to-br from-blue-500 to-purple-600":"bg-gradient-to-br from-gray-600 to-gray-700":t==="light"?"bg-gradient-to-br from-blue-500 to-purple-600":"bg-gradient-to-br from-gray-600 to_gray-700"}`,children:a}),l.jsxs("div",{className:`
|
|
82
|
+
To suppress this warning, you need to explicitly provide the \`palette.${t}Channel\` as a string (in rgb format, for example "12 12 12") or undefined if you want to remove the channel token.`))}function b1(e){return typeof e=="number"?`${e}px`:typeof e=="string"||typeof e=="function"||Array.isArray(e)?e:"8px"}const Xe=e=>{try{return e()}catch{}},v1=(e="mui")=>Lx(e);function ro(e,t,n,r){if(!t)return;t=t===!0?{}:t;const o=r==="dark"?"dark":"light";if(!n){e[r]=m1({...t,palette:{mode:o,...t==null?void 0:t.palette}});return}const{palette:s,...i}=Io({...n,palette:{mode:o,...t==null?void 0:t.palette}});return e[r]={...t,palette:s,opacity:{...ld(o),...t==null?void 0:t.opacity},overlays:(t==null?void 0:t.overlays)||dd(o)},i}function w1(e={},...t){const{colorSchemes:n={light:!0},defaultColorScheme:r,disableCssColorScheme:o=!1,cssVarPrefix:s="mui",shouldSkipGeneratingVar:i=g1,colorSchemeSelector:a=n.light&&n.dark?"media":void 0,rootSelector:c=":root",...d}=e,u=Object.keys(n)[0],f=r||(n.light&&u!=="light"?"light":u),h=v1(s),{[f]:x,light:y,dark:m,...b}=n,C={...b};let v=x;if((f==="dark"&&!("dark"in n)||f==="light"&&!("light"in n))&&(v=!0),!v)throw new Error(process.env.NODE_ENV!=="production"?`MUI: The \`colorSchemes.${f}\` option is either missing or invalid.`:pt(21,f));const T=ro(C,v,d,f);y&&!C.light&&ro(C,y,void 0,"light"),m&&!C.dark&&ro(C,m,void 0,"dark");let k={defaultColorScheme:f,...T,cssVarPrefix:s,colorSchemeSelector:a,rootSelector:c,getCssVar:h,colorSchemes:C,font:{...Jx(T.typography),...T.font},spacing:b1(d.spacing)};Object.keys(k.colorSchemes).forEach(_=>{const p=k.colorSchemes[_].palette,V=B=>{const G=B.split("-"),te=G[1],ne=G[2];return h(B,p[te][ne])};if(p.mode==="light"&&(N(p.common,"background","#fff"),N(p.common,"onBackground","#000")),p.mode==="dark"&&(N(p.common,"background","#000"),N(p.common,"onBackground","#fff")),y1(p,["Alert","AppBar","Avatar","Button","Chip","FilledInput","LinearProgress","Skeleton","Slider","SnackbarContent","SpeedDialAction","StepConnector","StepContent","Switch","TableCell","Tooltip"]),p.mode==="light"){N(p.Alert,"errorColor",me(p.error.light,.6)),N(p.Alert,"infoColor",me(p.info.light,.6)),N(p.Alert,"successColor",me(p.success.light,.6)),N(p.Alert,"warningColor",me(p.warning.light,.6)),N(p.Alert,"errorFilledBg",V("palette-error-main")),N(p.Alert,"infoFilledBg",V("palette-info-main")),N(p.Alert,"successFilledBg",V("palette-success-main")),N(p.Alert,"warningFilledBg",V("palette-warning-main")),N(p.Alert,"errorFilledColor",Xe(()=>p.getContrastText(p.error.main))),N(p.Alert,"infoFilledColor",Xe(()=>p.getContrastText(p.info.main))),N(p.Alert,"successFilledColor",Xe(()=>p.getContrastText(p.success.main))),N(p.Alert,"warningFilledColor",Xe(()=>p.getContrastText(p.warning.main))),N(p.Alert,"errorStandardBg",ge(p.error.light,.9)),N(p.Alert,"infoStandardBg",ge(p.info.light,.9)),N(p.Alert,"successStandardBg",ge(p.success.light,.9)),N(p.Alert,"warningStandardBg",ge(p.warning.light,.9)),N(p.Alert,"errorIconColor",V("palette-error-main")),N(p.Alert,"infoIconColor",V("palette-info-main")),N(p.Alert,"successIconColor",V("palette-success-main")),N(p.Alert,"warningIconColor",V("palette-warning-main")),N(p.AppBar,"defaultBg",V("palette-grey-100")),N(p.Avatar,"defaultBg",V("palette-grey-400")),N(p.Button,"inheritContainedBg",V("palette-grey-300")),N(p.Button,"inheritContainedHoverBg",V("palette-grey-A100")),N(p.Chip,"defaultBorder",V("palette-grey-400")),N(p.Chip,"defaultAvatarColor",V("palette-grey-700")),N(p.Chip,"defaultIconColor",V("palette-grey-700")),N(p.FilledInput,"bg","rgba(0, 0, 0, 0.06)"),N(p.FilledInput,"hoverBg","rgba(0, 0, 0, 0.09)"),N(p.FilledInput,"disabledBg","rgba(0, 0, 0, 0.12)"),N(p.LinearProgress,"primaryBg",ge(p.primary.main,.62)),N(p.LinearProgress,"secondaryBg",ge(p.secondary.main,.62)),N(p.LinearProgress,"errorBg",ge(p.error.main,.62)),N(p.LinearProgress,"infoBg",ge(p.info.main,.62)),N(p.LinearProgress,"successBg",ge(p.success.main,.62)),N(p.LinearProgress,"warningBg",ge(p.warning.main,.62)),N(p.Skeleton,"bg",`rgba(${V("palette-text-primaryChannel")} / 0.11)`),N(p.Slider,"primaryTrack",ge(p.primary.main,.62)),N(p.Slider,"secondaryTrack",ge(p.secondary.main,.62)),N(p.Slider,"errorTrack",ge(p.error.main,.62)),N(p.Slider,"infoTrack",ge(p.info.main,.62)),N(p.Slider,"successTrack",ge(p.success.main,.62)),N(p.Slider,"warningTrack",ge(p.warning.main,.62));const B=Wn(p.background.default,.8);N(p.SnackbarContent,"bg",B),N(p.SnackbarContent,"color",Xe(()=>p.getContrastText(B))),N(p.SpeedDialAction,"fabHoverBg",Wn(p.background.paper,.15)),N(p.StepConnector,"border",V("palette-grey-400")),N(p.StepContent,"border",V("palette-grey-400")),N(p.Switch,"defaultColor",V("palette-common-white")),N(p.Switch,"defaultDisabledColor",V("palette-grey-100")),N(p.Switch,"primaryDisabledColor",ge(p.primary.main,.62)),N(p.Switch,"secondaryDisabledColor",ge(p.secondary.main,.62)),N(p.Switch,"errorDisabledColor",ge(p.error.main,.62)),N(p.Switch,"infoDisabledColor",ge(p.info.main,.62)),N(p.Switch,"successDisabledColor",ge(p.success.main,.62)),N(p.Switch,"warningDisabledColor",ge(p.warning.main,.62)),N(p.TableCell,"border",ge(Zn(p.divider,1),.88)),N(p.Tooltip,"bg",Zn(p.grey[700],.92))}if(p.mode==="dark"){N(p.Alert,"errorColor",ge(p.error.light,.6)),N(p.Alert,"infoColor",ge(p.info.light,.6)),N(p.Alert,"successColor",ge(p.success.light,.6)),N(p.Alert,"warningColor",ge(p.warning.light,.6)),N(p.Alert,"errorFilledBg",V("palette-error-dark")),N(p.Alert,"infoFilledBg",V("palette-info-dark")),N(p.Alert,"successFilledBg",V("palette-success-dark")),N(p.Alert,"warningFilledBg",V("palette-warning-dark")),N(p.Alert,"errorFilledColor",Xe(()=>p.getContrastText(p.error.dark))),N(p.Alert,"infoFilledColor",Xe(()=>p.getContrastText(p.info.dark))),N(p.Alert,"successFilledColor",Xe(()=>p.getContrastText(p.success.dark))),N(p.Alert,"warningFilledColor",Xe(()=>p.getContrastText(p.warning.dark))),N(p.Alert,"errorStandardBg",me(p.error.light,.9)),N(p.Alert,"infoStandardBg",me(p.info.light,.9)),N(p.Alert,"successStandardBg",me(p.success.light,.9)),N(p.Alert,"warningStandardBg",me(p.warning.light,.9)),N(p.Alert,"errorIconColor",V("palette-error-main")),N(p.Alert,"infoIconColor",V("palette-info-main")),N(p.Alert,"successIconColor",V("palette-success-main")),N(p.Alert,"warningIconColor",V("palette-warning-main")),N(p.AppBar,"defaultBg",V("palette-grey-900")),N(p.AppBar,"darkBg",V("palette-background-paper")),N(p.AppBar,"darkColor",V("palette-text-primary")),N(p.Avatar,"defaultBg",V("palette-grey-600")),N(p.Button,"inheritContainedBg",V("palette-grey-800")),N(p.Button,"inheritContainedHoverBg",V("palette-grey-700")),N(p.Chip,"defaultBorder",V("palette-grey-700")),N(p.Chip,"defaultAvatarColor",V("palette-grey-300")),N(p.Chip,"defaultIconColor",V("palette-grey-300")),N(p.FilledInput,"bg","rgba(255, 255, 255, 0.09)"),N(p.FilledInput,"hoverBg","rgba(255, 255, 255, 0.13)"),N(p.FilledInput,"disabledBg","rgba(255, 255, 255, 0.12)"),N(p.LinearProgress,"primaryBg",me(p.primary.main,.5)),N(p.LinearProgress,"secondaryBg",me(p.secondary.main,.5)),N(p.LinearProgress,"errorBg",me(p.error.main,.5)),N(p.LinearProgress,"infoBg",me(p.info.main,.5)),N(p.LinearProgress,"successBg",me(p.success.main,.5)),N(p.LinearProgress,"warningBg",me(p.warning.main,.5)),N(p.Skeleton,"bg",`rgba(${V("palette-text-primaryChannel")} / 0.13)`),N(p.Slider,"primaryTrack",me(p.primary.main,.5)),N(p.Slider,"secondaryTrack",me(p.secondary.main,.5)),N(p.Slider,"errorTrack",me(p.error.main,.5)),N(p.Slider,"infoTrack",me(p.info.main,.5)),N(p.Slider,"successTrack",me(p.success.main,.5)),N(p.Slider,"warningTrack",me(p.warning.main,.5));const B=Wn(p.background.default,.98);N(p.SnackbarContent,"bg",B),N(p.SnackbarContent,"color",Xe(()=>p.getContrastText(B))),N(p.SpeedDialAction,"fabHoverBg",Wn(p.background.paper,.15)),N(p.StepConnector,"border",V("palette-grey-600")),N(p.StepContent,"border",V("palette-grey-600")),N(p.Switch,"defaultColor",V("palette-grey-300")),N(p.Switch,"defaultDisabledColor",V("palette-grey-600")),N(p.Switch,"primaryDisabledColor",me(p.primary.main,.55)),N(p.Switch,"secondaryDisabledColor",me(p.secondary.main,.55)),N(p.Switch,"errorDisabledColor",me(p.error.main,.55)),N(p.Switch,"infoDisabledColor",me(p.info.main,.55)),N(p.Switch,"successDisabledColor",me(p.success.main,.55)),N(p.Switch,"warningDisabledColor",me(p.warning.main,.55)),N(p.TableCell,"border",me(Zn(p.divider,1),.68)),N(p.Tooltip,"bg",Zn(p.grey[700],.92))}ot(p.background,"default"),ot(p.background,"paper"),ot(p.common,"background"),ot(p.common,"onBackground"),ot(p,"divider"),Object.keys(p).forEach(B=>{const G=p[B];B!=="tonalOffset"&&G&&typeof G=="object"&&(G.main&&N(p[B],"mainChannel",fn(hn(G.main))),G.light&&N(p[B],"lightChannel",fn(hn(G.light))),G.dark&&N(p[B],"darkChannel",fn(hn(G.dark))),G.contrastText&&N(p[B],"contrastTextChannel",fn(hn(G.contrastText))),B==="text"&&(ot(p[B],"primary"),ot(p[B],"secondary")),B==="action"&&(G.active&&ot(p[B],"active"),G.selected&&ot(p[B],"selected")))})}),k=t.reduce((_,p)=>Le(_,p),k);const S={prefix:s,disableCssColorScheme:o,shouldSkipGeneratingVar:i,getSelector:x1(k)},{vars:j,generateThemeVars:P,generateStyleSheets:A}=zx(k,S);return k.vars=j,Object.entries(k.colorSchemes[k.defaultColorScheme]).forEach(([_,p])=>{k[_]=p}),k.generateThemeVars=P,k.generateStyleSheets=A,k.generateSpacing=function(){return Ql(d.spacing,Cs(this))},k.getColorSchemeSelector=Hx(a),k.spacing=k.generateSpacing(),k.shouldSkipGeneratingVar=i,k.unstable_sxConfig={...kr,...d==null?void 0:d.unstable_sxConfig},k.unstable_sx=function(p){return Jt({sx:p,theme:this})},k.toRuntimeSource=cd,k}function Ua(e,t,n){e.colorSchemes&&n&&(e.colorSchemes[t]={...n!==!0&&n,palette:Ms({...n===!0?{}:n.palette,mode:t})})}function S1(e={},...t){const{palette:n,cssVariables:r=!1,colorSchemes:o=n?void 0:{light:!0},defaultColorScheme:s=n==null?void 0:n.mode,...i}=e,a=s||"light",c=o==null?void 0:o[a],d={...o,...n?{[a]:{...typeof c!="boolean"&&c,palette:n}}:void 0};if(r===!1){if(!("colorSchemes"in e))return Io(e,...t);let u=n;"palette"in e||d[a]&&(d[a]!==!0?u=d[a].palette:a==="dark"&&(u={mode:"dark"}));const f=Io({...e,palette:u},...t);return f.defaultColorScheme=a,f.colorSchemes=d,f.palette.mode==="light"&&(f.colorSchemes.light={...d.light!==!0&&d.light,palette:f.palette},Ua(f,"dark",d.dark)),f.palette.mode==="dark"&&(f.colorSchemes.dark={...d.dark!==!0&&d.dark,palette:f.palette},Ua(f,"light",d.light)),f}return!n&&!("light"in d)&&a==="light"&&(d.light=!0),w1({...i,colorSchemes:d,defaultColorScheme:a,...typeof r!="boolean"&&r},...t)}const k1=S1(),C1="$$material";function E1(e){return e!=="ownerState"&&e!=="theme"&&e!=="sx"&&e!=="as"}const T1=e=>E1(e)&&e!=="classes",A1=Ex({themeId:C1,defaultTheme:k1,rootShouldForwardProp:T1}),j1=Ox;process.env.NODE_ENV!=="production"&&(ae.node,ae.object.isRequired);function P1(e){return Fx(e)}function M1(e){return Ts("MuiSvgIcon",e)}vx("MuiSvgIcon",["root","colorPrimary","colorSecondary","colorAction","colorError","colorDisabled","fontSizeInherit","fontSizeSmall","fontSizeMedium","fontSizeLarge"]);const V1=e=>{const{color:t,fontSize:n,classes:r}=e,o={root:["root",t!=="inherit"&&`color${Mt(t)}`,`fontSize${Mt(n)}`]};return up(o,M1,r)},N1=A1("svg",{name:"MuiSvgIcon",slot:"Root",overridesResolver:(e,t)=>{const{ownerState:n}=e;return[t.root,n.color!=="inherit"&&t[`color${Mt(n.color)}`],t[`fontSize${Mt(n.fontSize)}`]]}})(j1(({theme:e})=>{var t,n,r,o,s,i,a,c,d,u,f,h,x,y;return{userSelect:"none",width:"1em",height:"1em",display:"inline-block",flexShrink:0,transition:(o=(t=e.transitions)==null?void 0:t.create)==null?void 0:o.call(t,"fill",{duration:(r=(n=(e.vars??e).transitions)==null?void 0:n.duration)==null?void 0:r.shorter}),variants:[{props:m=>!m.hasSvgAsChild,style:{fill:"currentColor"}},{props:{fontSize:"inherit"},style:{fontSize:"inherit"}},{props:{fontSize:"small"},style:{fontSize:((i=(s=e.typography)==null?void 0:s.pxToRem)==null?void 0:i.call(s,20))||"1.25rem"}},{props:{fontSize:"medium"},style:{fontSize:((c=(a=e.typography)==null?void 0:a.pxToRem)==null?void 0:c.call(a,24))||"1.5rem"}},{props:{fontSize:"large"},style:{fontSize:((u=(d=e.typography)==null?void 0:d.pxToRem)==null?void 0:u.call(d,35))||"2.1875rem"}},...Object.entries((e.vars??e).palette).filter(([,m])=>m&&m.main).map(([m])=>{var b,C;return{props:{color:m},style:{color:(C=(b=(e.vars??e).palette)==null?void 0:b[m])==null?void 0:C.main}}}),{props:{color:"action"},style:{color:(h=(f=(e.vars??e).palette)==null?void 0:f.action)==null?void 0:h.active}},{props:{color:"disabled"},style:{color:(y=(x=(e.vars??e).palette)==null?void 0:x.action)==null?void 0:y.disabled}},{props:{color:"inherit"},style:{color:void 0}}]}})),lr=g.forwardRef(function(t,n){const r=P1({props:t,name:"MuiSvgIcon"}),{children:o,className:s,color:i="inherit",component:a="svg",fontSize:c="medium",htmlColor:d,inheritViewBox:u=!1,titleAccess:f,viewBox:h="0 0 24 24",...x}=r,y=g.isValidElement(o)&&o.type==="svg",m={...r,color:i,component:a,fontSize:c,instanceFontSize:t.fontSize,inheritViewBox:u,viewBox:h,hasSvgAsChild:y},b={};u||(b.viewBox=h);const C=V1(m);return l.jsxs(N1,{as:a,className:Oo(C.root,s),focusable:"false",color:d,"aria-hidden":f?void 0:!0,role:f?"img":void 0,ref:n,...b,...x,...y&&o.props,ownerState:m,children:[y?o.props.children:o,f?l.jsx("title",{children:f}):null]})});process.env.NODE_ENV!=="production"&&(lr.propTypes={children:ae.node,classes:ae.object,className:ae.string,color:ae.oneOfType([ae.oneOf(["inherit","action","disabled","primary","secondary","error","info","success","warning"]),ae.string]),component:ae.elementType,fontSize:ae.oneOfType([ae.oneOf(["inherit","large","medium","small"]),ae.string]),htmlColor:ae.string,inheritViewBox:ae.bool,shapeRendering:ae.string,sx:ae.oneOfType([ae.arrayOf(ae.oneOfType([ae.func,ae.object,ae.bool])),ae.func,ae.object]),titleAccess:ae.string,viewBox:ae.string});lr.muiName="SvgIcon";function sn(e,t){function n(r,o){return l.jsx(lr,{"data-testid":process.env.NODE_ENV!=="production"?`${t}Icon`:void 0,ref:o,...r,children:e})}return process.env.NODE_ENV!=="production"&&(n.displayName=`${t}Icon`),n.muiName=lr.muiName,g.memo(g.forwardRef(n))}const R1=sn(l.jsx("path",{d:"M16.5 6v11.5c0 2.21-1.79 4-4 4s-4-1.79-4-4V5c0-1.38 1.12-2.5 2.5-2.5s2.5 1.12 2.5 2.5v10.5c0 .55-.45 1-1 1s-1-.45-1-1V6H10v9.5c0 1.38 1.12 2.5 2.5 2.5s2.5-1.12 2.5-2.5V5c0-2.21-1.79-4-4-4S7 2.79 7 5v12.5c0 3.04 2.46 5.5 5.5 5.5s5.5-2.46 5.5-5.5V6z"}),"AttachFile"),I1=sn(l.jsx("path",{d:"M12 9c-1.6 0-3.15.25-4.6.72v3.1c0 .39-.23.74-.56.9-.98.49-1.87 1.12-2.66 1.85-.18.18-.43.28-.7.28-.28 0-.53-.11-.71-.29L.29 13.08c-.18-.17-.29-.42-.29-.7s.11-.53.29-.71C3.34 8.78 7.46 7 12 7s8.66 1.78 11.71 4.67c.18.18.29.43.29.71s-.11.53-.29.71l-2.48 2.48c-.18.18-.43.29-.71.29-.27 0-.52-.11-.7-.28-.79-.74-1.69-1.36-2.67-1.85-.33-.16-.56-.5-.56-.9v-3.1C15.15 9.25 13.6 9 12 9"}),"CallEnd"),D1=sn([l.jsx("circle",{cx:"12",cy:"12",r:"3.2"},"0"),l.jsx("path",{d:"M9 2 7.17 4H4c-1.1 0-2 .9-2 2v12c0 1.1.9 2 2 2h16c1.1 0 2-.9 2-2V6c0-1.1-.9-2-2-2h-3.17L15 2zm3 15c-2.76 0-5-2.24-5-5s2.24-5 5-5 5 2.24 5 5-2.24 5-5 5"},"1")],"CameraAlt"),ud=sn(l.jsx("path",{d:"M20 2H4c-1.1 0-1.99.9-1.99 2L2 22l4-4h14c1.1 0 2-.9 2-2V4c0-1.1-.9-2-2-2M6 9h12v2H6zm8 5H6v-2h8zm4-6H6V6h12z"}),"Chat"),fd=sn(l.jsx("path",{d:"M12 14c1.66 0 2.99-1.34 2.99-3L15 5c0-1.66-1.34-3-3-3S9 3.34 9 5v6c0 1.66 1.34 3 3 3m5.3-3c0 3-2.54 5.1-5.3 5.1S6.7 14 6.7 11H5c0 3.41 2.72 6.23 6 6.72V21h2v-3.28c3.28-.48 6-3.3 6-6.72z"}),"Mic"),hd=sn(l.jsx("path",{d:"M17 10.5V7c0-.55-.45-1-1-1H4c-.55 0-1 .45-1 1v10c0 .55.45 1 1 1h12c.55 0 1-.45 1-1v-3.5l4 4v-11z"}),"Videocam"),$1=({disabled:e,capabilities:t,sessionStarted:n,ref:r,participantName:o="User",loadingText:s="Waiting for agent to connect...",theme:i="vox",client:a,displayType:c="widget",onBack:d})=>{var I,q,M,z,Q,W,U;const[u,f]=w.useState(!1),[h,x]=w.useState(!1),[y,m]=w.useState(!1),[b,C]=w.useState(()=>{var D;const E=(D=a==null?void 0:a.getCurrentInteraction)==null?void 0:D.call(a);return console.log("SessionView: Initializing with existing interaction:",(E==null?void 0:E.methodName)||"none"),E||null}),{messages:v,send:T}=J0(),k=w.useRef(null),S=w.useRef(null),{agent:{isActive:j=!1}={}}=a?Gl(a):{agent:{isActive:!1}},P=Ne(i),A=c==="popup",_=w.useMemo(()=>a&&typeof a.getCurrentSession=="function"?!!a.getCurrentSession():!1,[a]),p=w.useMemo(()=>a&&typeof a.getIsAgentConnected=="function"&&a.getIsAgentConnected()||y,[a,y]),V=j||p;w.useEffect(()=>{var E,D;console.log("๐ค SessionView agent state:",{isAgentActive:j,hasActiveSession:_,isAgentActuallyConnected:p,effectiveAgentActive:V,sessionStarted:n,clientSession:(D=(E=a==null?void 0:a.getCurrentSession)==null?void 0:E.call(a))==null?void 0:D.id})},[j,_,p,V,n,a]),w.useEffect(()=>{console.log("๐ค Agent active state changed:",j)},[j]),w.useEffect(()=>{console.log("๐ Session state changed:",{sessionStarted:n,disabled:e,participantName:o,effectiveAgentActive:V,chatOpen:u,currentInteraction:(b==null?void 0:b.methodName)||"none"})},[n,e,o,V,u,b]),w.useEffect(()=>{if(n&&!V){console.log("โฐ Starting agent timeout detection...");const E=setTimeout(()=>{_&&!V&&(console.log("โก Fallback: Assuming agent is connected after 5 seconds with active session"),m(!0),x(!1))},5e3),D=setTimeout(()=>{V||(console.log("โ ๏ธ Agent timeout: Agent did not become active within 30 seconds"),x(!0))},3e4);return()=>{clearTimeout(E),clearTimeout(D)}}else V&&(console.log("โ
Agent is active, clearing timeout"),x(!1))},[n,V,_]),w.useEffect(()=>{if(!a)return;const E=()=>{console.log("๐ Client connection state changed:",a.connected)},D=O=>{console.log("๐ด Client disconnected:",O),C(null),f(!1),x(!1)};return a.on("connection.connected",E),a.on("connection.disconnected",D),()=>{a.off("connection.connected",E),a.off("connection.disconnected",D)}},[a]),w.useEffect(()=>{if(!a)return;const E=F=>{console.log("๐ค SessionView: Agent connected!",F),m(!0),x(!1)},D=F=>{console.log("๐ฃ๏ธ SessionView: Agent speaking detected!",F),y||(m(!0),x(!1))},O=F=>{console.log("๐ค SessionView: Agent thinking detected!",F),y||(m(!0),x(!1))},$=()=>{console.log("๐ค SessionView: Agent disconnected"),m(!1)};return a.on("agent.connected",E),a.on("agent.speaking",D),a.on("agent.thinking",O),a.on("connection.disconnected",$),()=>{a.off("agent.connected",E),a.off("agent.speaking",D),a.off("agent.thinking",O),a.off("connection.disconnected",$)}},[a,y]),w.useEffect(()=>{if(!a)return;const E=F=>{console.log("๐ฏ SessionView: RPC Interaction started:",F);const L=a.getCurrentInteraction();L&&(console.log("๐ฑ SessionView: Setting current interaction:",L.methodName,"mode:",L.presentationMode),C(L))},D=F=>{console.log("โ
SessionView: RPC Interaction completed:",F),C(null)},O=async F=>{console.log("โฐ SessionView: RPC Interaction timeout:",F),C(null)},$=async F=>{console.log("โ SessionView: RPC Interaction dismissed:",F),C(null)};return a.on("rpc.interaction.started",E),a.on("rpc.interaction.completed",D),a.on("rpc.interaction.timeout",O),a.on("rpc.interaction.dismissed",$),()=>{a.off("rpc.interaction.started",E),a.off("rpc.interaction.completed",D),a.off("rpc.interaction.timeout",O),a.off("rpc.interaction.dismissed",$)}},[a]),w.useEffect(()=>{if(!a)return;const E=a.getCurrentInteraction();E?(console.log("๐ SessionView: Syncing with existing interaction:",E.methodName),C(E)):C(null)},[a]),w.useEffect(()=>{console.log("๐ญ SessionView: Current interaction changed:",(b==null?void 0:b.methodName)||"none","mode:",(b==null?void 0:b.presentationMode)||"none")},[b]),w.useEffect(()=>{var E,D,O;console.log("๐ฑ SessionView: Display type changed to:",c),console.log("๐ฑ SessionView: Current session state during display change:",{sessionStarted:n,effectiveAgentActive:V,hasSession:!!((E=a==null?void 0:a.getCurrentSession)!=null&&E.call(a)),sessionId:(O=(D=a==null?void 0:a.getCurrentSession)==null?void 0:D.call(a))==null?void 0:O.id})},[c,n,V,a]),w.useEffect(()=>{console.log("๐ฌ SessionView: Chat open state changed:",u)},[u]),w.useEffect(()=>{b&&u&&(console.log("๐ญ SessionView: Interactive UI appeared, closing chat"),f(!1))},[b,u]),Q0(),w.useEffect(()=>{k.current&&u&&v.length>0&&(console.log("๐ SessionView: Auto-scrolling to latest message, count:",v.length),setTimeout(()=>{if(k.current){let E=k.current.parentElement;for(;E&&E.scrollHeight<=E.clientHeight;)E=E.parentElement;E?(console.log("๐ SessionView: Scrolling container found, scrolling to bottom"),E.scrollTo({top:E.scrollHeight,behavior:"smooth"})):(console.log("๐ SessionView: Using fallback scroll method"),k.current.scrollIntoView({behavior:"smooth",block:"end",inline:"nearest"}))}},100))},[v.length,u]),w.useEffect(()=>{var O,$;console.log("๐ SessionView: Messages updated, count:",v.length),v.length>0&&console.log("๐ SessionView: Latest messages:",v.slice(-3).map(F=>{var L,J,R,ce,xe,pe,Re;return{id:F.id,message:F.message,timestamp:F.timestamp,from:((L=F.from)==null?void 0:L.name)||((J=F.from)==null?void 0:J.identity),fromType:F.from===void 0?"unknown":"participant",isLocal:((R=F.from)==null?void 0:R.identity)===((pe=(xe=(ce=a==null?void 0:a.getCurrentSession)==null?void 0:ce.call(a))==null?void 0:xe.localParticipant)==null?void 0:pe.identity),messageLength:((Re=F.message)==null?void 0:Re.length)||0}}));const E=((O=a==null?void 0:a.getTranscriptions)==null?void 0:O.call(a))||[],D=(($=a==null?void 0:a.getChatMessages)==null?void 0:$.call(a))||[];console.log("๐ SessionView: Raw transcriptions count:",E.length),console.log("๐ SessionView: Raw chat messages count:",D.length)},[v.length,v,a]),w.useEffect(()=>{console.log("๐ฌ SessionView: Chat state changed:",{chatOpen:u,messagesCount:v.length,displayType:c,hasMessages:v.length>0})},[u,v.length,c]);async function B(E){await T(E)}const G=w.useCallback(E=>{console.log("๐ SessionView: Adding local message for voice session context:",E)},[]),te=w.useCallback(async E=>{try{a&&typeof a.sendAttachments=="function"&&(await a.sendAttachments(E),console.log("๐ SessionView: Attachments sent successfully:",E.map(D=>D.name)))}catch(D){console.error("โ SessionView: Failed to send attachments:",D)}},[a]),ne=w.useCallback(()=>{try{console.log("๐ SessionView: Ending call..."),console.log("๐ SessionView: Current state before ending:",{sessionStarted:n,effectiveAgentActive:V,chatOpen:u,currentInteraction:b==null?void 0:b.methodName,hasOnBack:!!d}),b&&(console.log("๐ญ SessionView: Dismissing current interaction:",b.methodName),C(null),a&&typeof a.dismissCurrentInteraction=="function"&&a.dismissCurrentInteraction()),f(!1),x(!1),m(!1),console.log("โ
SessionView: Local state reset"),a&&typeof a.endSession=="function"&&(a.endSession(),console.log("โ
SessionView: Session ended via client.endSession()")),a&&typeof a.disconnect=="function"&&(a.disconnect(),console.log("โ
SessionView: Client disconnected")),d?(console.log("๐ SessionView: Calling onBack to return to welcome..."),d(),console.log("โ
SessionView: onBack called")):console.warn("โ ๏ธ SessionView: No onBack function provided - cannot return to welcome"),console.log("๐ SessionView: Call ended and cleanup completed")}catch(E){console.error("โ SessionView: Failed to end call:",E),C(null),f(!1),x(!1),m(!1),d&&(console.log("๐ SessionView: Error occurred, still calling onBack..."),d())}},[a,d,b,n,V,u]);w.useEffect(()=>(console.log("๐ SessionView: Component mounted/props changed:",{sessionStarted:n,disabled:e,participantName:o,displayType:c,hasOnBack:!!d,hasClient:!!a}),()=>{console.log("๐งน SessionView: Component unmounting or props changing")}),[n,e,o,c,d,a]),w.useEffect(()=>{console.log("๐ SessionView: onBack prop:",{hasOnBack:!!d,onBackType:typeof d})},[d]),w.useEffect(()=>{var D,O;const E=((O=(D=a==null?void 0:a.getCurrentSession)==null?void 0:D.call(a))==null?void 0:O.id)||null;S.current&&!E&&console.warn("โ ๏ธ SessionView: Session was lost unexpectedly!",{previousSession:S.current,currentSession:E,displayType:c,sessionStarted:n,effectiveAgentActive:V}),S.current=E},[a,c,n,V]);const oe=Z("w-full flex flex-col items-center justify-center",c==="fullscreen"?"w-full max-w-none mx-0 h-full":"w-full mx-auto",P.main,c==="fullscreen"?"max-w-none":"","overflow-hidden","h-full"),X=d&&(c==="popup"||c==="fullscreen");return l.jsxs("main",{ref:r,className:Z(oe,"relative session-view",e&&"pointer-events-none opacity-50"),style:{minHeight:0},children:[X&&l.jsx("div",{className:Z("flex items-center justify-between w-full border-b flex-shrink-0",A?"p-2":"p-4",((I=P.chatHeader)==null?void 0:I.container)||"border-gray-200"),children:l.jsx("div",{className:"flex items-center",children:l.jsxs("div",{children:[l.jsx("h3",{className:Z("font-semibold",A?"text-xs":"text-sm",P.text.primary),children:"Voice Session"}),l.jsx("p",{className:Z(A?"text-[10px]":"text-sm",P.text.muted),children:o})]})})}),l.jsxs("div",{className:"w-full flex-1 flex flex-col items-center px-0 min-h-0 overflow-hidden",children:[!V&&n&&l.jsxs("div",{className:"flex flex-col items-center justify-center w-full h-full min-h-[180px]",children:[l.jsx(ie.div,{animate:{rotate:360,scale:[1,1.1,1]},transition:{rotate:{duration:2,repeat:1/0,ease:"linear"},scale:{duration:1,repeat:1/0,ease:"easeInOut"}},className:"w-12 h-12 mb-4",children:l.jsx(ws,{className:P.spinner,weight:"bold"})}),l.jsx(ie.span,{initial:{opacity:0,y:10},animate:{opacity:1,y:0},className:`text-sm opacity-80 ${P.text.muted} text-center max-w-xs`,children:h?"Agent is taking longer than expected...":s}),l.jsx(ie.p,{initial:{opacity:0},animate:{opacity:1},transition:{delay:2},className:`text-xs ${P.text.muted} mt-2 text-center opacity-60`,children:h?"Please check your connection or try again.":"Agent is connecting... This may take a moment."}),h&&d&&l.jsx(ie.button,{initial:{opacity:0,scale:.9},animate:{opacity:1,scale:1},transition:{delay:.5},onClick:d,className:`mt-4 px-4 py-2 rounded-lg ${((q=P.chatHeader)==null?void 0:q.backButton)||"bg-gray-100 hover:bg-gray-200"} transition-colors`,children:"Go Back"})]}),V&&l.jsxs(l.Fragment,{children:[u&&l.jsxs("div",{className:Z("absolute inset-0 w-full h-full flex flex-col transition-[opacity,translate] duration-300 ease-out z-10",i==="light"?"bg-white":"bg-gray-900/95 backdrop-blur-sm",u?"translate-y-0 opacity-100 delay-200":"translate-y-10 opacity-0"),children:[l.jsxs("div",{className:Z("flex-shrink-0 px-4 py-3 border-b",c==="fullscreen"?"px-8":"px-5",((M=P.chatHeader)==null?void 0:M.container)||"border-gray-200 dark:border-gray-700"),children:[l.jsx("h3",{className:Z("font-semibold text-lg",((z=P.text)==null?void 0:z.primary)||"text-gray-900 dark:text-white"),children:"Transcription & Chat"}),l.jsxs("p",{className:Z("text-sm",((Q=P.text)==null?void 0:Q.muted)||"text-gray-600 dark:text-gray-400"),children:[v.length," messages"]})]}),l.jsx("div",{className:Z("flex-1 flex flex-col min-h-0",c==="fullscreen"?"px-8":"px-5"),children:l.jsx(H0,{className:"flex-1 flex flex-col min-h-0 h-full",children:l.jsxs("div",{className:`flex-1 flex flex-col h-full w-full ${Z("overflow-y-auto scrollbar-hide py-4")}`,style:{scrollbarWidth:"none",scrollBehavior:"smooth",paddingBottom:"120px"},children:[v.length===0&&l.jsx("div",{className:"flex-1 flex items-center justify-center",children:l.jsxs("div",{className:"text-center",children:[l.jsx("p",{className:Z("text-lg font-medium mb-2",((W=P.text)==null?void 0:W.primary)||"text-gray-900 dark:text-white"),children:"Start Speaking"}),l.jsx("p",{className:Z("text-sm",((U=P.text)==null?void 0:U.muted)||"text-gray-600 dark:text-gray-400"),children:"Your conversation will appear here"})]})}),v.length>0&&l.jsxs(l.Fragment,{children:[l.jsx("div",{className:"flex-1 min-h-4"}),l.jsx("div",{ref:k,className:"space-y-4 relative whitespace-pre-wrap z-0",children:l.jsx(Wt,{mode:"popLayout",children:v.map((E,D)=>l.jsx(ie.div,{initial:{opacity:0,y:20},animate:{opacity:1,y:0},exit:{opacity:0,y:-20},transition:{duration:.3,ease:"easeOut",delay:D*.02},layout:!0,children:l.jsx(B0,{participantName:o,entry:E})},E.id||`message-${D}`))})})]})]})})})]}),!u&&l.jsxs("div",{className:Z("flex-1 flex flex-col items-center w-full h-full min-h-0",(b==null?void 0:b.presentationMode)==="embedded"?"justify-end":"justify-center"),children:[l.jsx(ie.div,{className:"w-full flex justify-center",animate:{y:(b==null?void 0:b.presentationMode)==="embedded"?-8:0},transition:{duration:.3,ease:"easeOut"},children:l.jsx(X0,{chatOpen:u,client:a})}),l.jsx(Wt,{mode:"wait",children:b&&b.presentationMode==="embedded"&&l.jsx(ie.div,{initial:{opacity:0,y:20,height:0},animate:{opacity:1,y:0,height:"auto"},exit:{opacity:0,y:20,height:0},transition:{duration:.3,ease:"easeOut"},className:Z("w-full relative mt-4 flex justify-center z-50",c==="fullscreen"?"max-w-4xl":"max-w-md"),children:l.jsx("div",{className:"bg-white/10 backdrop-blur-sm rounded-xl border border-white/20 shadow-lg overflow-hidden z-50 relative",style:{zIndex:50},children:l.jsx(Xt,{interaction:b,theme:i,onDismiss:()=>{var E;return(E=a==null?void 0:a.dismissCurrentInteraction)==null?void 0:E.call(a)},client:a,addLocalMessage:G})})},`embedded-${b.methodName}`)})]})]})]}),l.jsx(Wt,{mode:"wait",children:b&&b.presentationMode!=="embedded"&&!u&&l.jsx("div",{className:Z("absolute inset-0 z-50 flex items-center justify-center backdrop-blur-sm",c==="fullscreen"?"bg-black/70":"bg-black/50"),children:l.jsx(ie.div,{initial:{opacity:0,scale:.9},animate:{opacity:1,scale:1},exit:{opacity:0,scale:.9},transition:{duration:.2,ease:"easeOut"},className:Z("relative w-full overflow-hidden",c==="fullscreen"?"max-w-2xl mx-8 max-h-[85vh]":"max-w-lg mx-4 max-h-[80vh]","bg-white dark:bg-gray-900 rounded-2xl shadow-2xl","border border-gray-200 dark:border-gray-700"),children:l.jsx(Xt,{interaction:b,theme:i,onDismiss:()=>{var E;return(E=a==null?void 0:a.dismissCurrentInteraction)==null?void 0:E.call(a)},client:a,addLocalMessage:G})},`modal-${b.methodName}`)})}),l.jsx(ie.div,{initial:{opacity:0,y:20},animate:{opacity:1,y:0},transition:{delay:.2},className:"absolute bottom-0 left-0 right-0 flex-shrink-0 w-full z-20",children:l.jsx(F1,{capabilities:t,onSendMessage:B,onSendAttachments:te,onEndCall:ne,onChatOpenChange:f,disabled:e,theme:i,client:a,sessionStarted:n,displayType:c})})]})};function F1({capabilities:e,onSendMessage:t,onSendAttachments:n,onEndCall:r,onChatOpenChange:o,disabled:s=!1,theme:i,client:a,sessionStarted:c=!1,displayType:d="widget"}){const[u,f]=w.useState(!1),h=w.useRef(null),x=w.useRef(null),y=d==="popup";w.useEffect(()=>{const k=()=>{const S=navigator.userAgent.toLowerCase(),P=["android","iphone","ipad","mobile","tablet"].some(p=>S.includes(p)),A="ontouchstart"in window||navigator.maxTouchPoints>0,_=window.innerWidth<=768;f(P||A&&_)};return k(),window.addEventListener("resize",k),()=>window.removeEventListener("resize",k)},[]);const m=k=>{const S=k.target.files;if(S&&S.length>0){const P=Array.from(S).filter(A=>A.type.startsWith("image/"));if(P.length===0){console.warn("No valid image files selected");return}n&&n(P),h.current&&(h.current.value="")}},b=k=>{const S=k.target.files;if(S&&S.length>0){const j=S[0];j.type.startsWith("image/")&&n&&n([j]),x.current&&(x.current.value="")}},C=()=>{!s&&h.current&&h.current.click()},v=()=>{!s&&u&&x.current&&x.current.click()},T=()=>{console.log("๐ด VoiceControlPanel: End call button clicked"),console.log("๐ด VoiceControlPanel: Current state:",{disabled:s,sessionStarted:c,hasOnEndCall:!!r}),r?r():console.warn("โ ๏ธ VoiceControlPanel: No onEndCall function provided")};return l.jsx("div",{className:Z("w-full backdrop-blur-xl border-0 shadow-lg flex-shrink-0",y?"px-2 py-1":"px-3 py-2",i==="light"?"bg-white/95 border-t border-gray-200":"bg-gray-900/95 border-t border-gray-700"),children:l.jsxs("div",{className:Z("flex items-center justify-between w-full mx-auto",y?"max-w-xs":"max-w-4xl"),children:[l.jsx("input",{ref:h,type:"file",multiple:!0,onChange:m,className:"hidden",accept:"image/*"}),l.jsx("input",{ref:x,type:"file",onChange:b,className:"hidden",accept:"image/*",capture:"environment"}),l.jsxs("div",{className:Z("flex items-center",y?"gap-0.5":"gap-1"),children:[l.jsx("button",{onClick:C,disabled:s,className:Z(y?"p-0.5 rounded-full transition-all duration-200 hover:scale-105 active:scale-95":"p-2 rounded-full transition-all duration-200 hover:scale-105 active:scale-95",s?"opacity-50 cursor-not-allowed":"hover:shadow-md",i==="light"?"bg-gray-100 hover:bg-gray-200 text-gray-600":"bg-gray-700/50 hover:bg-gray-600/50 text-gray-300"),title:"Attach files",children:l.jsx(R1,{className:y?"w-3 h-3":"w-4 h-4"})}),u&&l.jsx("button",{onClick:v,disabled:s,className:Z(y?"p-0.5 rounded-full transition-all duration-200 hover:scale-105 active:scale-95":"p-2 rounded-full transition-all duration-200 hover:scale-105 active:scale-95",s?"opacity-50 cursor-not-allowed":"hover:shadow-md",i==="light"?"bg-gray-100 hover:bg-gray-200 text-gray-600":"bg-gray-700/50 hover:bg-gray-600/50 text-gray-300"),title:"Take photo",children:l.jsx(D1,{className:y?"w-3 h-3":"w-4 h-4"})})]}),l.jsx("div",{className:Z("flex-1 flex justify-center",y?"px-1":"px-3"),children:l.jsx(L0,{capabilities:e,onChatOpenChange:o,onSendMessage:t,theme:i,client:a,className:Z("border-none py-0 rounded-xl w-full",y?"max-w-xs":"max-w-md")})}),l.jsx("div",{className:"flex items-center",children:l.jsx("button",{onClick:T,disabled:s||!c,className:Z(y?"p-0.5 rounded-full transition-all duration-200 hover:scale-105 active:scale-95":"p-2 rounded-full transition-all duration-200 hover:scale-105 active:scale-95",s||!c?"opacity-50 cursor-not-allowed":"hover:shadow-md","bg-red-500 hover:bg-red-600 text-white"),title:"End call",children:l.jsx(I1,{className:y?"w-3 h-3":"w-4 h-4"})})})]})})}function O1({onSendMessage:e,onSendAttachments:t,disabled:n,theme:r,onEndChat:o,displayType:s}){const[i,a]=g.useState(""),[c,d]=g.useState(!1),u=g.useRef(null),f=g.useRef(null),[h,x]=g.useState(!1),y=Ne(r),m=s==="popup";g.useEffect(()=>{const j=()=>{const P=navigator.userAgent.toLowerCase(),_=["android","iphone","ipad","mobile","tablet"].some(B=>P.includes(B)),p="ontouchstart"in window||navigator.maxTouchPoints>0,V=window.innerWidth<=768;x(_||p&&V)};return j(),window.addEventListener("resize",j),()=>window.removeEventListener("resize",j)},[]);const b=j=>{j.preventDefault(),i.trim()&&!n&&(e(i.trim()),a(""))},C=j=>{j.key==="Enter"&&!j.shiftKey&&(j.preventDefault(),b(j))},v=j=>{const P=j.target.files;if(P&&P.length>0){const A=Array.from(P),_=A.filter(p=>p.type.startsWith("image/"));if(_.length===0){console.warn("No valid image files selected");return}_.length!==A.length&&console.warn("Some non-image files were filtered out"),console.log("Selected image files:",_),t(_),u.current&&(u.current.value="")}},T=()=>{!n&&u.current&&u.current.click()},k=()=>{!n&&h&&f.current&&f.current.click()},S=j=>{const P=j.target.files;if(P&&P.length>0){const A=P[0];A.type.startsWith("image/")?t([A]):console.warn("Selected file is not an image"),f.current&&(f.current.value="")}};return l.jsx("div",{className:`${m?"px-2 py-1":"px-4 py-3"} !w-full backdrop-blur-xl border-0 shadow-lg `,children:l.jsx("form",{onSubmit:b,className:`w-full mx-auto ${m?"max-w-xs":""}`,children:l.jsxs("div",{className:`flex items-center ${m?"gap-1":"gap-2"} !w-full backdrop-blur-md rounded-full ${m?"px-2 py-1":"px-3 py-2"} shadow-sm hover:shadow-md focus-within:shadow-lg focus-within:ring-2 focus-within:ring-blue-500/30 focus-within:border-blue-500/50 transition-all duration-200 border ${r==="light"?"bg-white/90":y.chatInput.container}`,children:[l.jsx(ie.button,{type:"button",onClick:T,whileHover:{scale:1.05},whileTap:{scale:.95},className:`${m?"p-0.5":"p-1"} rounded-full transition-all duration-200 border-0 ${y.chatInput.attachButton}`,disabled:n,"aria-label":"Attach file",children:l.jsx(Pe.Paperclip,{className:m?"w-3 h-3":"w-4 h-4"})}),h&&l.jsx(ie.button,{type:"button",onClick:k,whileHover:{scale:1.05},whileTap:{scale:.95},className:`${m?"p-0.5":"p-1"} rounded-full transition-all duration-200 border-0 ${y.chatInput.attachButton}`,disabled:n,"aria-label":"Take photo",children:l.jsx(Pe.Camera,{className:m?"w-3 h-3":"w-4 h-4"})}),l.jsx("input",{ref:u,type:"file",multiple:!0,onChange:v,className:"hidden",accept:"image/*"}),l.jsx("input",{ref:f,type:"file",onChange:S,className:"hidden",accept:"image/*",capture:"environment"}),l.jsx("textarea",{value:i,onChange:j=>a(j.target.value),onKeyDown:C,onFocus:()=>d(!0),onBlur:()=>d(!1),placeholder:"Type your message...",disabled:n,className:`flex-1 ${m?"px-1 py-0.5 text-xs min-h-[20px]":"px-2 py-1 text-sm min-h-[32px]"} bg-transparent resize-none max-h-20 focus:outline-none border-0 ${y.chatInput.textarea}`,rows:1,style:{height:"auto",minHeight:m?"20px":"32px"},onInput:j=>{const P=j.target;P.style.height="auto",P.style.height=`${Math.min(P.scrollHeight,m?60:80)}px`}}),l.jsx(ie.button,{type:"submit",disabled:n||!i.trim(),whileHover:{scale:1.05},whileTap:{scale:.95},className:`${m?"p-0.5":"p-1"} rounded-full transition-all duration-200 border-0 flex-shrink-0 ${i.trim()&&!n?y.chatInput.sendButton:r==="light"?"bg-gray-200 text-gray-400 cursor-not-allowed opacity-70":"bg-gray-600/50 text-gray-500 cursor-not-allowed opacity-50"}`,"aria-label":"Send message",children:l.jsx(Pe.SendHorizontal,{className:m?"w-3 h-3":"w-4 h-4"})}),o&&l.jsx(ie.button,{type:"button",onClick:o,whileHover:{scale:1.05},whileTap:{scale:.95},className:`${m?"p-0.5":"p-1"} rounded-full transition-all duration-200 border-0 flex-shrink-0 ${y.chatInput.endButton}`,"aria-label":"End chat",children:l.jsx(Pe.PhoneOff,{className:m?"w-3 h-3":"w-4 h-4"})})]})})})}function L1({text:e,isComplete:t,isRealTimeStream:n=!1,speed:r=50}){const[o,s]=g.useState(""),[i,a]=g.useState(0);return g.useEffect(()=>{if(n){s(e);return}if(t){s(e);return}if(i<e.length){const c=setTimeout(()=>{s(e.slice(0,i+1)),a(i+1)},r);return()=>clearTimeout(c)}},[e,i,t,r,n]),g.useEffect(()=>{n||(a(0),s(""))},[e,n]),l.jsxs("span",{className:"relative",children:[l.jsx("span",{className:"inline-block",children:o}),!t&&l.jsx("span",{className:"inline-flex items-center ml-1",children:[0,1,2].map(c=>l.jsx(ie.span,{className:"w-1.5 h-1.5 bg-current rounded-full mx-0.5",animate:{y:[0,-4,0],opacity:[.4,1,.4],scale:[.8,1,.8]},transition:{duration:.8,repeat:1/0,repeatType:"mirror",delay:c*.2,ease:"easeInOut"}},c))})]})}function _1({message:e,theme:t,isOwn:n,isStreaming:r=!1,displayType:o}){var c,d;const s=Ne(t),i=o==="popup",a=e.sender.name?e.sender.name.split(" ").map(u=>u[0]).join("").toUpperCase().slice(0,2):"U";return l.jsx("div",{className:`flex w-full ${n?"justify-end":"justify-start"} mb-4 px-1`,children:l.jsxs("div",{className:`relative group ${n?"flex-row-reverse":"flex-row"} flex items-end gap-3 max-w-[85%]`,children:[l.jsx("div",{className:`w-6 h-6 rounded-full flex items-center justify-center text-white text-xs font-semibold flex-shrink-0 shadow-lg ${n?t==="light"?"bg-gradient-to-br from-blue-500 to-purple-600":"bg-gradient-to-br from-gray-600 to-gray-700":t==="light"?"bg-gradient-to-br from-blue-500 to-purple-600":"bg-gradient-to-br from-gray-600 to_gray-700"}`,children:a}),l.jsxs("div",{className:`
|
|
83
83
|
relative ${i?"px-2 py-1":"px-3 py-2"} rounded-2xl break-words shadow-lg backdrop-blur-sm message-bubble message-hover
|
|
84
84
|
${n?`${s.chatMessage.own} rounded-br-md`:`${s.chatMessage.other} rounded-bl-md`}
|
|
85
85
|
${r?"shimmer":""}
|
|
@@ -96,7 +96,7 @@ To suppress this warning, you need to explicitly provide the \`palette.${t}Chann
|
|
|
96
96
|
`,children:l.jsx(ie.div,{className:`h-full ${t==="light"?"bg-blue-500":"bg-blue-400"}`,initial:{width:0},animate:{width:`${b*100}%`},transition:{duration:.3}})})]}),h&&!m&&l.jsx(ie.button,{onClick:k,whileHover:{scale:1.05},whileTap:{scale:.95},className:`
|
|
97
97
|
p-2 rounded-lg transition-colors duration-200
|
|
98
98
|
${t==="light"?"hover:bg-gray-200 text-gray-600 hover:text-gray-800":"hover:bg-gray-600 text-gray-400 hover:text-gray-200"}
|
|
99
|
-
`,"aria-label":"Download file",children:l.jsx(Pe.Download,{className:"w-4 h-4"})})]})]})}function U1(){return l.jsxs("div",{className:"max-w-xs mx-auto bg-green-50 border border-green-200 rounded-lg shadow p-3 flex flex-col items-center",children:[l.jsx("div",{className:"text-2xl mb-2",children:"โ
"}),l.jsx("div",{className:"text-green-700 font-semibold text-sm mb-1",children:"Success!"}),l.jsx("div",{className:"text-xs text-gray-600 text-center mb-1",children:"Your action was completed successfully."})]})}function Z1(){return l.jsxs("div",{className:"max-w-xs mx-auto bg-yellow-50 border border-yellow-200 rounded-lg shadow p-3 flex flex-col items-center",children:[l.jsx("div",{className:"text-2xl mb-2",children:"โฐ"}),l.jsx("div",{className:"text-yellow-700 font-semibold text-sm mb-1",children:"Interaction timed out"}),l.jsx("div",{className:"text-xs text-gray-600 text-center mb-1",children:"No response was provided in time."})]})}function W1({client:e,theme:t="vox",onBack:n,disabled:r=!1,displayType:o="widget",onEndChat:s}){const[i,a]=g.useState(()=>{if(e&&typeof e.getChatMessages=="function"){const E=e.getChatMessages();return console.log("๐ ChatView: Initializing with existing messages:",E.length),E}return[]}),[c,d]=g.useState(!0),[u,f]=g.useState(()=>{const E=e&&typeof e.getCurrentSession=="function"&&!!e.getCurrentSession(),D=e&&typeof e.getChatMessages=="function"&&e.getChatMessages().length>0;return!E&&!D}),[h,x]=g.useState(new Set),[y,m]=g.useState([]),[b,C]=g.useState(!1),[v,T]=g.useState(!1),[k,S]=g.useState(()=>{const E=e.getCurrentInteraction();return console.log("ChatView: Initializing with existing interaction:",(E==null?void 0:E.methodName)||"none"),E}),j=g.useRef(null),P=g.useRef(null),A=Ne(t);g.useEffect(()=>{const E=()=>{const D=navigator.userAgent.toLowerCase(),$=["android","iphone","ipad","mobile","tablet"].some(R=>D.includes(R)),F="ontouchstart"in window||navigator.maxTouchPoints>0,L=window.innerWidth<=768,J=$||F&&L;C(J),J&&o==="widget"&&T(!0)};return E(),window.addEventListener("resize",E),()=>window.removeEventListener("resize",E)},[o]),g.useEffect(()=>(v&&b&&(document.body.style.overflow="hidden",document.body.style.position="fixed",document.body.style.width="100%",document.body.style.height="100%",document.documentElement.requestFullscreen&&document.documentElement.requestFullscreen().catch(console.log)),()=>{v&&b&&(document.body.style.overflow="unset",document.body.style.position="unset",document.body.style.width="unset",document.body.style.height="unset",document.fullscreenElement&&document.exitFullscreen().catch(console.log))}),[v,b]);const _=e.getCurrentAgentInfo(),p=(_==null?void 0:_.name)||"AI Assistant",V=p.split(" ").map(E=>E[0]).join("").toUpperCase().slice(0,2),B=g.useCallback(E=>{const D={id:`local_${Date.now()}_${Math.random().toString(36).substr(2,9)}`,content:E,timestamp:new Date,sender:{id:"participant",name:"You",type:"participant"},metadata:{isLocal:!0}};a(O=>(console.log("ChatView: Adding local message:",D.id),[...O,D]))},[]);g.useEffect(()=>{var E,D,O,$,F;console.log("๐ฌ ChatView loading state:",{isLoading:u,hasActiveSession:!!((E=e==null?void 0:e.getCurrentSession)!=null&&E.call(e)),messagesCount:i.length,sessionId:(O=(D=e==null?void 0:e.getCurrentSession)==null?void 0:D.call(e))==null?void 0:O.id,hasStoredMessages:!!((F=($=e==null?void 0:e.getChatMessages)==null?void 0:$.call(e))!=null&&F.length),isMobile:b,isFullscreen:v})},[u,i.length,e,b,v]);const G=g.useCallback((E=!1)=>{const D=P.current;D&&(E?D.scrollTop=D.scrollHeight:D.scrollTo({top:D.scrollHeight,behavior:"smooth"}))},[]);g.useEffect(()=>{G(!0);const E=setTimeout(()=>{G(!1)},10);return()=>clearTimeout(E)},[i.length,G]),g.useEffect(()=>{if(k){G(!0);const E=setTimeout(()=>{G(!1)},50);return()=>clearTimeout(E)}},[k,G]),g.useEffect(()=>{const E=$=>{if(console.log("ChatView: Received message:",$),f(!1),k&&$.sender.type==="agent"){console.log("ChatView: Queuing agent message due to active interaction:",k.methodName),m(F=>[...F,$]);return}$.sender.type==="agent"&&d(!1),a(F=>{var J;if(F.some(R=>R.id===$.id))return console.log("ChatView: Message already exists, skipping:",$.id),F;if(console.log("ChatView: Adding new message:",$.id),$.sender.type==="agent"&&(x(R=>new Set(R).add($.id)),!((J=$.metadata)!=null&&J.streaming))){const R=$.content.length*35+1e3;setTimeout(()=>{x(ce=>{const xe=new Set(ce);return xe.delete($.id),xe})},R)}return[...F,$]}),setTimeout(()=>G(!0),0)},D=$=>{var F;if(console.log("ChatView: Updated message:",$),k&&$.sender.type==="agent"){console.log("ChatView: Queuing agent message update due to active interaction:",k.methodName),m(L=>{const J=L.findIndex(R=>R.id===$.id);if(J>=0){const R=[...L];return R[J]=$,R}else return[...L,$]});return}a(L=>L.map(J=>J.id===$.id?{...$}:J)),setTimeout(()=>G(!0),0),(F=$.metadata)!=null&&F.streaming||x(L=>{const J=new Set(L);return J.delete($.id),J})},O=$=>{console.log("ChatView: Sent message:",$),f(!1),a(F=>F.some(J=>J.id===$.id)?(console.log("ChatView: Sent message already exists, skipping:",$.id),F):(console.log("ChatView: Adding sent message:",$.id),[...F,$])),setTimeout(()=>G(!0),0)};return e.on("chat.message.received",E),e.on("chat.message.updated",D),e.on("chat.message.sent",O),()=>{e.off("chat.message.received",E),e.off("chat.message.updated",D),e.off("chat.message.sent",O)}},[e,k]),g.useEffect(()=>{const E=F=>{console.log("ChatView: RPC interaction started:",F);const L=e.getCurrentInteraction();console.log("ChatView: Got interaction from client:",L==null?void 0:L.methodName),S(L),d(!1),G(!0),setTimeout(()=>{G(!1)},100)},D=F=>{if(console.log("ChatView: RPC interaction completed:",F),S(null),y.length>0&&(console.log("ChatView: Processing",y.length,"queued messages"),a(L=>{const J=[...L];return y.forEach(R=>{var xe;if(!J.some(pe=>pe.id===R.id)&&(console.log("ChatView: Adding queued message:",R.id),J.push(R),R.sender.type==="agent"&&(x(pe=>new Set(pe).add(R.id)),!((xe=R.metadata)!=null&&xe.streaming)))){const pe=R.content.length*35+1e3;setTimeout(()=>{x(Re=>{const tt=new Set(Re);return tt.delete(R.id),tt})},pe)}}),J}),m([]),setTimeout(()=>G(!0),0)),F&&F.response&&F.response.success){let L=null;F.response.successView?L=F.response.successView:F.successView&&(L=F.successView),a(J=>{const R=[...J].reverse().findIndex(Re=>Re.sender.type==="participant");let ce=J.length;R!==-1&&(ce=J.length-R);const xe={id:`success_${Date.now()}_${Math.random().toString(36).substr(2,9)}`,content:"",timestamp:new Date,sender:{id:"participant",name:"You",type:"participant"},metadata:{type:"successView",view:L||l.jsx(U1,{})}};e&&typeof e.addChatMessage=="function"&&e.addChatMessage(xe);const pe=[...J];return pe.splice(ce,0,xe),pe})}},O=async F=>{k&&(console.log("ChatView: Dismissing active interaction due to timeout"),e.dismissCurrentInteraction()),S(null),y.length>0&&(console.log("ChatView: Processing",y.length,"queued messages after timeout"),a(J=>{const R=[...J];return y.forEach(ce=>{var pe;if(!R.some(Re=>Re.id===ce.id)&&(R.push(ce),ce.sender.type==="agent"&&(x(Re=>new Set(Re).add(ce.id)),!((pe=ce.metadata)!=null&&pe.streaming)))){const Re=ce.content.length*35+1e3;setTimeout(()=>{x(tt=>{const dt=new Set(tt);return dt.delete(ce.id),dt})},Re)}}),R}),m([]),setTimeout(()=>G(!0),0));let L=null;F&&F.response&&F.response.timeoutView?L=F.response.timeoutView:F&&F.timeoutView&&(L=F.timeoutView),a(J=>{const R={id:`timeout_${Date.now()}_${Math.random().toString(36).substr(2,9)}`,content:"",timestamp:new Date,sender:{id:"agent",name:p,type:"agent"},metadata:{type:"timeoutView",view:L||l.jsx(Z1,{})}};return e&&typeof e.addChatMessage=="function"&&e.addChatMessage(R),[...J,R]}),setTimeout(()=>{e.getCurrentInteraction()||S(null)},100)},$=async F=>{console.log("ChatView: RPC interaction dismissed:",F),console.log("ChatView: Current interaction before dismiss:",k==null?void 0:k.methodName),S(null),y.length>0&&(console.log("ChatView: Processing",y.length,"queued messages after dismissal"),a(L=>{const J=[...L];return y.forEach(R=>{var xe;if(!J.some(pe=>pe.id===R.id)&&(J.push(R),R.sender.type==="agent"&&(x(pe=>new Set(pe).add(R.id)),!((xe=R.metadata)!=null&&xe.streaming)))){const pe=R.content.length*35+1e3;setTimeout(()=>{x(Re=>{const tt=new Set(Re);return tt.delete(R.id),tt})},pe)}}),J}),m([]),setTimeout(()=>G(!0),0)),setTimeout(()=>{const L=e.getCurrentInteraction();console.log("ChatView: Latest interaction from client after dismiss:",(L==null?void 0:L.methodName)||"null"),L===null&&S(null)},50),console.log("ChatView: Set currentInteraction to null after dismiss")};return e.on("rpc.interaction.started",E),e.on("rpc.interaction.completed",D),e.on("rpc.interaction.timeout",O),e.on("rpc.interaction.dismissed",$),()=>{e.off("rpc.interaction.started",E),e.off("rpc.interaction.completed",D),e.off("rpc.interaction.timeout",O),e.off("rpc.interaction.dismissed",$)}},[e]),g.useEffect(()=>{const E=()=>{if(console.log("ChatView: Agent is thinking"),k){console.log("ChatView: Suppressing thinking indicator due to active interaction:",k.methodName);return}d(!0)},D=()=>{console.log("ChatView: Agent is speaking"),d(!1)};return e.on("agent.thinking",E),e.on("agent.speaking",D),()=>{e.off("agent.thinking",E),e.off("agent.speaking",D)}},[e,k]),g.useEffect(()=>{const E=e.getCurrentInteraction();E?(console.log("ChatView: Restoring interaction state on mount/client change:",E.methodName),S(E)):S(null)},[e]),g.useEffect(()=>{console.log("ChatView: Display type changed to:",o,"Current interaction:",(k==null?void 0:k.methodName)||"none")},[o,k]);const te=async E=>{try{k&&(console.log("ChatView: Dismissing active interaction due to user message send"),e.dismissCurrentInteraction(),S(null)),await e.sendChatMessage(E)}catch(D){console.error("Failed to send message:",D)}},ne=async E=>{try{k&&(console.log("ChatView: Dismissing active interaction due to user attachment send"),e.dismissCurrentInteraction(),S(null)),await e.sendAttachments(E),console.log("Attachments sent successfully:",E.map(D=>D.name))}catch(D){console.error("Failed to send attachments:",D)}},[oe,X]=g.useState([]);if(g.useEffect(()=>{const E=D=>{X(Array.isArray(D)?D:["tes","hello how are you","algebra make me learn that ","what is the meaning of life"])};return e.on("suggested.response",E),()=>{e.off("suggested.response",E)}},[e]),u){const E=v&&b?"fixed inset-0 z-[9999] flex flex-col items-center justify-center h-screen w-screen bg-black":"flex w-full flex-col items-center justify-center h-full p-8";return l.jsxs("div",{className:E,children:[l.jsx("div",{className:`${A.spinner} w-12 h-12 mb-6`}),l.jsxs("p",{className:`text-sm text-center ${v&&b?"text-white":""}`,children:["Connecting to ",p,"..."]})]})}const I=v&&b?"fullscreen":o,q=o==="popup",M=I==="fullscreen"?v&&b?"fixed inset-0 z-[9999] flex flex-col h-screen w-screen bg-black":"flex flex-col h-full w-full max-w-none":"flex flex-col h-full w-full backdrop-blur-sm max-h-full overflow-hidden",z=I==="fullscreen"?v&&b?"flex items-center w-full justify-between px-4 pt-3 pb-3 bg-black/80 text-white border-b border-gray-700":`flex items-center w-full justify-between px-6 pt-5 pb-4 border-b ${A.chatHeader.container}`:`flex items-center w-full justify-between ${q?"px-3 pt-3 pb-3 text-xs":"px-5 pt-6 pb-5"} border-b ${A.chatHeader.container}`,Q=I==="fullscreen"?v&&b?"flex-1 overflow-y-auto scrollbar-hide p-4 w-full max-w-none chat-scrollable min-h-0":"flex-1 overflow-y-auto scrollbar-hide p-6 w-full max-w-none chat-scrollable min-h-0":`flex-1 overflow-y-auto scrollbar-hide w-full ${q?"p-2 text-xs":"p-4"} chat-scrollable min-h-0`,W="flex-shrink-0 !w-full",U=()=>{T(!1),n&&n()};return l.jsxs("div",{className:`${M} chat-view`,children:[l.jsx("div",{className:z,children:l.jsxs("div",{className:"flex items-center gap-2",children:[v&&b&&l.jsx(ie.button,{onClick:U,whileHover:{scale:1.05},whileTap:{scale:.95},className:`${q?"p-1 text-sm":"p-2"} rounded-full bg-white/20 hover:bg-white/30 text-white transition-colors mr-2`,"aria-label":"Exit fullscreen",children:"โ"}),l.jsxs("div",{children:[l.jsx("h3",{className:`font-semibold ${q?"text-xs":"text-base"} leading-tight ${v&&b?"text-white":A.text.primary}`,children:p}),l.jsxs("p",{className:`${q?"text-[10px]":"text-xs"} flex items-center ${q?"gap-1":"gap-1.5"} mt-0.5 ${v&&b?"text-gray-300":A.text.muted}`,children:[l.jsx("span",{className:`${q?"w-1 h-1":"w-1.5 h-1.5"} bg-green-500 rounded-full animate-pulse`}),"Online"]})]})]})}),l.jsxs("div",{ref:P,className:`${Q} flex flex-col`,style:{scrollBehavior:"smooth",scrollbarWidth:"none"},children:[" ",i.length===0?l.jsxs("div",{className:"flex flex-col items-center justify-center flex-1 text-center py-12",children:[l.jsx(ie.div,{transition:{duration:2,repeat:1/0,ease:"easeInOut"},className:"w-16 h-16 rounded-full bg-gradient-to-br from-blue-500 to-purple-600 flex items-center justify-center text-white font-bold text-xl mb-6 shadow-xl",children:V}),l.jsxs("p",{className:`text-base mb-2 ${v&&b?"text-white":A.text.secondary}`,children:[p," is joining..."]}),l.jsx("p",{className:`text-xs ${v&&b?"text-gray-300":A.text.muted}`,children:"Your conversation will begin shortly"})]}):l.jsx("div",{className:"w-full max-w-5xl mx-auto space-y-3 py-4 flex-1 flex flex-col justify-end",children:l.jsxs("div",{className:"space-y-3",children:[i.map((E,D)=>{var O,$;return l.jsx("div",{children:((O=E.metadata)==null?void 0:O.type)==="successView"?l.jsx("div",{className:"flex w-full justify-end mb-4 px-1",children:l.jsxs("div",{className:"relative group flex-row-reverse flex items-end gap-3 max-w-[85%]",children:[l.jsx(ie.div,{initial:{scale:0},animate:{scale:1},transition:{delay:.1},className:`w-6 h-6 rounded-full flex items-center justify-center text-white text-xs font-semibold flex-shrink-0 shadow-lg ${t==="light"?"bg-gradient-to-br from-blue-500 to-purple-600":"bg-gradient-to-br from-gray-600 to-gray-700"}`,children:"Y"}),l.jsxs("div",{className:`flex h-full flex-col justify-between border ${q?"px-2 py-1":"px-3 py-2"} rounded-2xl shadow-lg backdrop-bl-sm message-bubble rounded-br-md message-hover dark:border-gray-700 ${A.chatMessage.own}`,children:[E.metadata.view,l.jsx("div",{className:`text-xs ${A.text.muted} mt-1 opacity-0 group-hover:opacity-100 transition-opacity duration-200 `,children:E.timestamp.toLocaleTimeString([],{hour:"2-digit",minute:"2-digit"})})]})]})}):(($=E.metadata)==null?void 0:$.type)==="timeoutView"?l.jsx("div",{className:"flex w-full justify-start mb-4 px-1",children:l.jsxs("div",{className:"relative group flex-row flex items-end gap-3 max-w-[85%]",children:[l.jsx("div",{className:`w-6 h-6 rounded-full flex items-center justify-center text-white text-xs font-semibold flex-shrink-0 shadow-lg ${t==="light"?"bg-gradient-to-br from-blue-500 to-purple-600":"bg-gradient-to-br from-gray-600 to_gray-700"}`,children:V}),l.jsxs("div",{className:`flex h-full flex-col justify-between border ${q?"px-2 py-1":"px-3 py-2"} rounded-2xl shadow-lg backdrop-bl-sm message-bubble rounded-bl-md message-hover border-gray-200 dark:border-gray-700 ${A.chatMessage.other}`,children:[E.metadata.view,l.jsx("div",{className:`text-xs ${A.text.muted} mt-1 opacity-0 group-hover:opacity-100 transition-opacity duration-200 `,children:E.timestamp.toLocaleTimeString([],{hour:"2-digit",minute:"2-digit"})})]})]})}):l.jsx(_1,{message:E,theme:t,isOwn:E.sender.type==="participant",isStreaming:h.has(E.id),displayType:o})},E.id)}),c&&!k&&l.jsx(ie.div,{initial:{opacity:0,y:20},animate:{opacity:1,y:0},transition:{delay:i.length*.1},className:"flex w-full justify-start mb-4 px-1",children:l.jsxs("div",{className:"relative group flex-row flex items-end gap-3 max-w-[85%]",children:[l.jsx("div",{className:`w-6 h-6 rounded-full flex items-center justify-center text-white text-xs font-semibold flex-shrink-0 shadow-lg ${t==="light"?"bg-gradient-to-br from-blue-500 to-purple-600":"bg-gradient-to-br from-gray-600 to-gray-700"}`,children:V}),l.jsx("div",{className:`relative ${q?"px-2 py-1":"px-3 py-2"} rounded-2xl break-words shadow-lg backdrop-blur-sm message-bubble message-hover ${A.chatMessage.other} rounded-bl-md transition-all duration-200 group-hover:scale-[1.02]`,style:{wordWrap:"break-word",overflowWrap:"break-word",minWidth:48},children:l.jsx("span",{className:"inline-flex items-center",children:[0,1,2].map(E=>l.jsx(ie.span,{className:"w-1.5 h-1.5 bg-current rounded-full mx-0.5",animate:{y:[0,-4,0],opacity:[.4,1,.4],scale:[.8,1,.8]},transition:{duration:.8,repeat:1/0,repeatType:"mirror",delay:E*.2,ease:"easeInOut"}},E))})})]})}),k&&k.presentationMode==="embedded"&&l.jsxs("div",{className:"relative group flex-row flex items-end gap-3 max-w-[85%]",children:[l.jsx(ie.div,{initial:{scale:0},animate:{scale:1},transition:{delay:.1},className:`w-6 h-6 rounded-full flex items-center justify-center text-white text-xs font-semibold flex-shrink-0 shadow-lg ${t==="light"?"bg-gradient-to-br from-blue-500 to-purple-600":"bg-gradient-to-br from-gray-600 to_gray-700"}`,children:V}),l.jsxs("div",{className:`flex h-full flex-col justify-between border ${q?"px-2 py-1":"px-3 py-2"} rounded-2xl shadow-lg backdrop-bl-sm message-bubble rounded-bl-md message-hover border-gray-200 dark:border-gray-700 ${A.chatMessage.other}`,children:[l.jsx(Xt,{interaction:k,theme:t,onDismiss:()=>e.dismissCurrentInteraction(),client:e,addLocalMessage:B},k.methodName),l.jsx(ie.div,{initial:{opacity:0},animate:{opacity:1},transition:{delay:.2},className:`text-xs ${A.text.muted} mt-1 opacity-0 group-hover:opacity-100 transition-opacity duration-200 `,children:new Date().toLocaleTimeString([],{hour:"2-digit",minute:"2-digit"})})]})]}),l.jsx("div",{ref:j})]})})]}),oe.length>0&&l.jsx("div",{className:"w-full flex overflow-x-auto gap-2 px-4 py-2 mb-1 scrollbar-hide",children:oe.map((E,D)=>{var O;return l.jsx("button",{className:`whitespace-nowrap px-3 py-1 rounded-full border shadow-sm flex-shrink-0 transition-all duration-150 font-medium text-sm focus:outline-none focus:ring-2 focus:ring-blue-400/40
|
|
99
|
+
`,"aria-label":"Download file",children:l.jsx(Pe.Download,{className:"w-4 h-4"})})]})]})}function U1(){return l.jsxs("div",{className:"max-w-xs mx-auto bg-green-50 border border-green-200 rounded-lg shadow p-3 flex flex-col items-center",children:[l.jsx("div",{className:"text-2xl mb-2",children:"โ
"}),l.jsx("div",{className:"text-green-700 font-semibold text-sm mb-1",children:"Success!"}),l.jsx("div",{className:"text-xs text-gray-600 text-center mb-1",children:"Your action was completed successfully."})]})}function Z1(){return l.jsxs("div",{className:"max-w-xs mx-auto bg-yellow-50 border border-yellow-200 rounded-lg shadow p-3 flex flex-col items-center",children:[l.jsx("div",{className:"text-2xl mb-2",children:"โฐ"}),l.jsx("div",{className:"text-yellow-700 font-semibold text-sm mb-1",children:"Interaction timed out"}),l.jsx("div",{className:"text-xs text-gray-600 text-center mb-1",children:"No response was provided in time."})]})}function W1({client:e,theme:t="vox",onBack:n,disabled:r=!1,displayType:o="widget",onEndChat:s}){const[i,a]=g.useState(()=>{if(e&&typeof e.getChatMessages=="function"){const E=e.getChatMessages();return console.log("๐ ChatView: Initializing with existing messages:",E.length),E}return[]}),[c,d]=g.useState(!0),[u,f]=g.useState(()=>{const E=e&&typeof e.getCurrentSession=="function"&&!!e.getCurrentSession(),D=e&&typeof e.getChatMessages=="function"&&e.getChatMessages().length>0;return!E&&!D}),[h,x]=g.useState(new Set),[y,m]=g.useState([]),[b,C]=g.useState(!1),[v,T]=g.useState(!1),[k,S]=g.useState(()=>{const E=e.getCurrentInteraction();return console.log("ChatView: Initializing with existing interaction:",(E==null?void 0:E.methodName)||"none"),E}),j=g.useRef(null),P=g.useRef(null),A=Ne(t);g.useEffect(()=>{const E=()=>{const D=navigator.userAgent.toLowerCase(),$=["android","iphone","ipad","mobile","tablet"].some(R=>D.includes(R)),F="ontouchstart"in window||navigator.maxTouchPoints>0,L=window.innerWidth<=768,J=$||F&&L;C(J),J&&o==="widget"&&T(!0)};return E(),window.addEventListener("resize",E),()=>window.removeEventListener("resize",E)},[o]),g.useEffect(()=>(v&&b&&(document.body.style.overflow="hidden",document.body.style.position="fixed",document.body.style.width="100%",document.body.style.height="100%",document.documentElement.requestFullscreen&&document.documentElement.requestFullscreen().catch(console.log)),()=>{v&&b&&(document.body.style.overflow="unset",document.body.style.position="unset",document.body.style.width="unset",document.body.style.height="unset",document.fullscreenElement&&document.exitFullscreen().catch(console.log))}),[v,b]);const _=e.getCurrentAgentInfo(),p=(_==null?void 0:_.name)||"AI Assistant",V=p.split(" ").map(E=>E[0]).join("").toUpperCase().slice(0,2),B=g.useCallback(E=>{const D={id:`local_${Date.now()}_${Math.random().toString(36).substr(2,9)}`,content:E,timestamp:new Date,sender:{id:"participant",name:"You",type:"participant"},metadata:{isLocal:!0}};a(O=>(console.log("ChatView: Adding local message:",D.id),[...O,D]))},[]);g.useEffect(()=>{var E,D,O,$,F;console.log("๐ฌ ChatView loading state:",{isLoading:u,hasActiveSession:!!((E=e==null?void 0:e.getCurrentSession)!=null&&E.call(e)),messagesCount:i.length,sessionId:(O=(D=e==null?void 0:e.getCurrentSession)==null?void 0:D.call(e))==null?void 0:O.id,hasStoredMessages:!!((F=($=e==null?void 0:e.getChatMessages)==null?void 0:$.call(e))!=null&&F.length),isMobile:b,isFullscreen:v})},[u,i.length,e,b,v]);const G=g.useCallback((E=!1)=>{const D=P.current;D&&(E?D.scrollTop=D.scrollHeight:D.scrollTo({top:D.scrollHeight,behavior:"smooth"}))},[]);g.useEffect(()=>{G(!0);const E=setTimeout(()=>{G(!1)},10);return()=>clearTimeout(E)},[i.length,G]),g.useEffect(()=>{if(k){G(!0);const E=setTimeout(()=>{G(!1)},50);return()=>clearTimeout(E)}},[k,G]),g.useEffect(()=>{const E=$=>{if(console.log("ChatView: Received message:",$),f(!1),k&&$.sender.type==="agent"){console.log("ChatView: Queuing agent message due to active interaction:",k.methodName),m(F=>[...F,$]);return}$.sender.type==="agent"&&d(!1),a(F=>{var J;if(F.some(R=>R.id===$.id))return console.log("ChatView: Message already exists, skipping:",$.id),F;if(console.log("ChatView: Adding new message:",$.id),$.sender.type==="agent"&&(x(R=>new Set(R).add($.id)),!((J=$.metadata)!=null&&J.streaming))){const R=$.content.length*35+1e3;setTimeout(()=>{x(ce=>{const xe=new Set(ce);return xe.delete($.id),xe})},R)}return[...F,$]}),setTimeout(()=>G(!0),0)},D=$=>{var F;if(console.log("ChatView: Updated message:",$),k&&$.sender.type==="agent"){console.log("ChatView: Queuing agent message update due to active interaction:",k.methodName),m(L=>{const J=L.findIndex(R=>R.id===$.id);if(J>=0){const R=[...L];return R[J]=$,R}else return[...L,$]});return}a(L=>L.map(J=>J.id===$.id?{...$}:J)),setTimeout(()=>G(!0),0),(F=$.metadata)!=null&&F.streaming||x(L=>{const J=new Set(L);return J.delete($.id),J})},O=$=>{console.log("ChatView: Sent message:",$),f(!1),a(F=>F.some(J=>J.id===$.id)?(console.log("ChatView: Sent message already exists, skipping:",$.id),F):(console.log("ChatView: Adding sent message:",$.id),[...F,$])),setTimeout(()=>G(!0),0)};return e.on("chat.message.received",E),e.on("chat.message.updated",D),e.on("chat.message.sent",O),()=>{e.off("chat.message.received",E),e.off("chat.message.updated",D),e.off("chat.message.sent",O)}},[e,k]),g.useEffect(()=>{const E=F=>{console.log("ChatView: RPC interaction started:",F);const L=e.getCurrentInteraction();console.log("ChatView: Got interaction from client:",L==null?void 0:L.methodName),S(L),d(!1),G(!0),setTimeout(()=>{G(!1)},100)},D=F=>{if(console.log("ChatView: RPC interaction completed:",F),S(null),y.length>0&&(console.log("ChatView: Processing",y.length,"queued messages"),a(L=>{const J=[...L];return y.forEach(R=>{var xe;if(!J.some(pe=>pe.id===R.id)&&(console.log("ChatView: Adding queued message:",R.id),J.push(R),R.sender.type==="agent"&&(x(pe=>new Set(pe).add(R.id)),!((xe=R.metadata)!=null&&xe.streaming)))){const pe=R.content.length*35+1e3;setTimeout(()=>{x(Re=>{const tt=new Set(Re);return tt.delete(R.id),tt})},pe)}}),J}),m([]),setTimeout(()=>G(!0),0)),F&&F.response&&F.response.success){let L=null;F.response.successView?L=F.response.successView:F.successView&&(L=F.successView),a(J=>{const R=[...J].reverse().findIndex(Re=>Re.sender.type==="participant");let ce=J.length;R!==-1&&(ce=J.length-R);const xe={id:`success_${Date.now()}_${Math.random().toString(36).substr(2,9)}`,content:"",timestamp:new Date,sender:{id:"participant",name:"You",type:"participant"},metadata:{type:"successView",view:L||l.jsx(U1,{})}};e&&typeof e.addChatMessage=="function"&&e.addChatMessage(xe);const pe=[...J];return pe.splice(ce,0,xe),pe})}},O=async F=>{k&&(console.log("ChatView: Dismissing active interaction due to timeout"),e.dismissCurrentInteraction()),S(null),y.length>0&&(console.log("ChatView: Processing",y.length,"queued messages after timeout"),a(J=>{const R=[...J];return y.forEach(ce=>{var pe;if(!R.some(Re=>Re.id===ce.id)&&(R.push(ce),ce.sender.type==="agent"&&(x(Re=>new Set(Re).add(ce.id)),!((pe=ce.metadata)!=null&&pe.streaming)))){const Re=ce.content.length*35+1e3;setTimeout(()=>{x(tt=>{const dt=new Set(tt);return dt.delete(ce.id),dt})},Re)}}),R}),m([]),setTimeout(()=>G(!0),0));let L=null;F&&F.response&&F.response.timeoutView?L=F.response.timeoutView:F&&F.timeoutView&&(L=F.timeoutView),a(J=>{const R={id:`timeout_${Date.now()}_${Math.random().toString(36).substr(2,9)}`,content:"",timestamp:new Date,sender:{id:"agent",name:p,type:"agent"},metadata:{type:"timeoutView",view:L||l.jsx(Z1,{})}};return e&&typeof e.addChatMessage=="function"&&e.addChatMessage(R),[...J,R]}),setTimeout(()=>{e.getCurrentInteraction()||S(null)},100)},$=async F=>{console.log("ChatView: RPC interaction dismissed:",F),console.log("ChatView: Current interaction before dismiss:",k==null?void 0:k.methodName),S(null),y.length>0&&(console.log("ChatView: Processing",y.length,"queued messages after dismissal"),a(L=>{const J=[...L];return y.forEach(R=>{var xe;if(!J.some(pe=>pe.id===R.id)&&(J.push(R),R.sender.type==="agent"&&(x(pe=>new Set(pe).add(R.id)),!((xe=R.metadata)!=null&&xe.streaming)))){const pe=R.content.length*35+1e3;setTimeout(()=>{x(Re=>{const tt=new Set(Re);return tt.delete(R.id),tt})},pe)}}),J}),m([]),setTimeout(()=>G(!0),0)),setTimeout(()=>{const L=e.getCurrentInteraction();console.log("ChatView: Latest interaction from client after dismiss:",(L==null?void 0:L.methodName)||"null"),L===null&&S(null)},50),console.log("ChatView: Set currentInteraction to null after dismiss")};return e.on("rpc.interaction.started",E),e.on("rpc.interaction.completed",D),e.on("rpc.interaction.timeout",O),e.on("rpc.interaction.dismissed",$),()=>{e.off("rpc.interaction.started",E),e.off("rpc.interaction.completed",D),e.off("rpc.interaction.timeout",O),e.off("rpc.interaction.dismissed",$)}},[e]),g.useEffect(()=>{const E=()=>{if(console.log("ChatView: Agent is thinking"),k){console.log("ChatView: Suppressing thinking indicator due to active interaction:",k.methodName);return}d(!0)},D=()=>{console.log("ChatView: Agent is speaking"),d(!1)};return e.on("agent.thinking",E),e.on("agent.speaking",D),()=>{e.off("agent.thinking",E),e.off("agent.speaking",D)}},[e,k]),g.useEffect(()=>{const E=e.getCurrentInteraction();E?(console.log("ChatView: Restoring interaction state on mount/client change:",E.methodName),S(E)):S(null)},[e]),g.useEffect(()=>{console.log("ChatView: Display type changed to:",o,"Current interaction:",(k==null?void 0:k.methodName)||"none")},[o,k]);const te=async E=>{try{k&&(console.log("ChatView: Dismissing active interaction due to user message send"),e.dismissCurrentInteraction(),S(null)),await e.sendChatMessage(E)}catch(D){console.error("Failed to send message:",D)}},ne=async E=>{try{k&&(console.log("ChatView: Dismissing active interaction due to user attachment send"),e.dismissCurrentInteraction(),S(null)),await e.sendAttachments(E),console.log("Attachments sent successfully:",E.map(D=>D.name))}catch(D){console.error("Failed to send attachments:",D)}},[oe,X]=g.useState([]);if(g.useEffect(()=>{const E=D=>{X(Array.isArray(D)?D:["tes","hello how are you","algebra make me learn that ","what is the meaning of life"])};return e.on("suggested.response",E),()=>{e.off("suggested.response",E)}},[e]),u){const E=v&&b?"fixed inset-0 z-[9999] flex flex-col items-center justify-center h-screen w-screen bg-black":"flex w-full flex-col items-center justify-center h-full p-8";return l.jsxs("div",{className:E,children:[l.jsx("div",{className:`${A.spinner} w-12 h-12 mb-6`}),l.jsxs("p",{className:`text-sm text-center ${v&&b?"text-white":""}`,children:["Connecting to ",p,"..."]})]})}const I=v&&b?"fullscreen":o,q=o==="popup",M=I==="fullscreen"?v&&b?"fixed inset-0 z-[9999] flex flex-col h-screen w-screen bg-black":"flex flex-col h-full w-full max-w-none":"flex flex-col h-full w-full backdrop-blur-sm max-h-full overflow-hidden",z=I==="fullscreen"?v&&b?"flex items-center w-full justify-between px-4 pt-3 pb-3 bg-black/80 text-white border-b border-gray-700":`flex items-center w-full justify-between px-6 pt-3 pb-4 border-b ${A.chatHeader.container}`:`flex items-center w-full justify-between ${q?"px-3 pt-3 pb-3 text-xs":"px-5 pt-3 pb-5"} border-b ${A.chatHeader.container}`,Q=I==="fullscreen"?v&&b?"flex-1 overflow-y-auto scrollbar-hide p-4 w-full max-w-none chat-scrollable min-h-0":"flex-1 overflow-y-auto scrollbar-hide p-6 w-full max-w-none chat-scrollable min-h-0":`flex-1 overflow-y-auto scrollbar-hide w-full ${q?"p-2 text-xs":"p-4"} chat-scrollable min-h-0`,W="flex-shrink-0 !w-full",U=()=>{T(!1),n&&n()};return l.jsxs("div",{className:`${M} chat-view`,children:[l.jsx("div",{className:z,children:l.jsxs("div",{className:"flex items-center gap-2",children:[v&&b&&l.jsx(ie.button,{onClick:U,whileHover:{scale:1.05},whileTap:{scale:.95},className:`${q?"p-1 text-sm":"p-2"} rounded-full bg-white/20 hover:bg-white/30 text-white transition-colors mr-2`,"aria-label":"Exit fullscreen",children:"โ"}),l.jsxs("div",{children:[l.jsx("h3",{className:`font-semibold ${q?"text-xs":"text-base"} leading-tight ${v&&b?"text-white":A.text.primary}`,children:p}),l.jsxs("p",{className:`${q?"text-[10px]":"text-xs"} flex items-center ${q?"gap-1":"gap-1.5"} mt-0.5 ${v&&b?"text-gray-300":A.text.muted}`,children:[l.jsx("span",{className:`${q?"w-1 h-1":"w-1.5 h-1.5"} bg-green-500 rounded-full animate-pulse`}),"Online"]})]})]})}),l.jsxs("div",{ref:P,className:`${Q} flex flex-col`,style:{scrollBehavior:"smooth",scrollbarWidth:"none"},children:[" ",i.length===0?l.jsxs("div",{className:"flex flex-col items-center justify-center flex-1 text-center py-12",children:[l.jsx(ie.div,{transition:{duration:2,repeat:1/0,ease:"easeInOut"},className:"w-16 h-16 rounded-full bg-gradient-to-br from-blue-500 to-purple-600 flex items-center justify-center text-white font-bold text-xl mb-6 shadow-xl",children:V}),l.jsxs("p",{className:`text-base mb-2 ${v&&b?"text-white":A.text.secondary}`,children:[p," is joining..."]}),l.jsx("p",{className:`text-xs ${v&&b?"text-gray-300":A.text.muted}`,children:"Your conversation will begin shortly"})]}):l.jsx("div",{className:"w-full max-w-5xl mx-auto space-y-3 py-4 flex-1 flex flex-col justify-end",children:l.jsxs("div",{className:"space-y-3",children:[i.map((E,D)=>{var O,$;return l.jsx("div",{children:((O=E.metadata)==null?void 0:O.type)==="successView"?l.jsx("div",{className:"flex w-full justify-end mb-4 px-1",children:l.jsxs("div",{className:"relative group flex-row-reverse flex items-end gap-3 max-w-[85%]",children:[l.jsx(ie.div,{initial:{scale:0},animate:{scale:1},transition:{delay:.1},className:`w-6 h-6 rounded-full flex items-center justify-center text-white text-xs font-semibold flex-shrink-0 shadow-lg ${t==="light"?"bg-gradient-to-br from-blue-500 to-purple-600":"bg-gradient-to-br from-gray-600 to-gray-700"}`,children:"Y"}),l.jsxs("div",{className:`flex h-full flex-col justify-between border ${q?"px-2 py-1":"px-3 py-2"} rounded-2xl shadow-lg backdrop-bl-sm message-bubble rounded-br-md message-hover dark:border-gray-700 ${A.chatMessage.own}`,children:[E.metadata.view,l.jsx("div",{className:`text-xs ${A.text.muted} mt-1 opacity-0 group-hover:opacity-100 transition-opacity duration-200 `,children:E.timestamp.toLocaleTimeString([],{hour:"2-digit",minute:"2-digit"})})]})]})}):(($=E.metadata)==null?void 0:$.type)==="timeoutView"?l.jsx("div",{className:"flex w-full justify-start mb-4 px-1",children:l.jsxs("div",{className:"relative group flex-row flex items-end gap-3 max-w-[85%]",children:[l.jsx("div",{className:`w-6 h-6 rounded-full flex items-center justify-center text-white text-xs font-semibold flex-shrink-0 shadow-lg ${t==="light"?"bg-gradient-to-br from-blue-500 to-purple-600":"bg-gradient-to-br from-gray-600 to_gray-700"}`,children:V}),l.jsxs("div",{className:`flex h-full flex-col justify-between border ${q?"px-2 py-1":"px-3 py-2"} rounded-2xl shadow-lg backdrop-bl-sm message-bubble rounded-bl-md message-hover border-gray-200 dark:border-gray-700 ${A.chatMessage.other}`,children:[E.metadata.view,l.jsx("div",{className:`text-xs ${A.text.muted} mt-1 opacity-0 group-hover:opacity-100 transition-opacity duration-200 `,children:E.timestamp.toLocaleTimeString([],{hour:"2-digit",minute:"2-digit"})})]})]})}):l.jsx(_1,{message:E,theme:t,isOwn:E.sender.type==="participant",isStreaming:h.has(E.id),displayType:o})},E.id)}),c&&!k&&l.jsx(ie.div,{initial:{opacity:0,y:20},animate:{opacity:1,y:0},transition:{delay:i.length*.1},className:"flex w-full justify-start mb-4 px-1",children:l.jsxs("div",{className:"relative group flex-row flex items-end gap-3 max-w-[85%]",children:[l.jsx("div",{className:`w-6 h-6 rounded-full flex items-center justify-center text-white text-xs font-semibold flex-shrink-0 shadow-lg ${t==="light"?"bg-gradient-to-br from-blue-500 to-purple-600":"bg-gradient-to-br from-gray-600 to-gray-700"}`,children:V}),l.jsx("div",{className:`relative ${q?"px-2 py-1":"px-3 py-2"} rounded-2xl break-words shadow-lg backdrop-blur-sm message-bubble message-hover ${A.chatMessage.other} rounded-bl-md transition-all duration-200 group-hover:scale-[1.02]`,style:{wordWrap:"break-word",overflowWrap:"break-word",minWidth:48},children:l.jsx("span",{className:"inline-flex items-center",children:[0,1,2].map(E=>l.jsx(ie.span,{className:"w-1.5 h-1.5 bg-current rounded-full mx-0.5",animate:{y:[0,-4,0],opacity:[.4,1,.4],scale:[.8,1,.8]},transition:{duration:.8,repeat:1/0,repeatType:"mirror",delay:E*.2,ease:"easeInOut"}},E))})})]})}),k&&k.presentationMode==="embedded"&&l.jsxs("div",{className:"relative group flex-row flex items-end gap-3 max-w-[85%]",children:[l.jsx(ie.div,{initial:{scale:0},animate:{scale:1},transition:{delay:.1},className:`w-6 h-6 rounded-full flex items-center justify-center text-white text-xs font-semibold flex-shrink-0 shadow-lg ${t==="light"?"bg-gradient-to-br from-blue-500 to-purple-600":"bg-gradient-to-br from-gray-600 to_gray-700"}`,children:V}),l.jsxs("div",{className:`flex h-full flex-col justify-between border ${q?"px-2 py-1":"px-3 py-2"} rounded-2xl shadow-lg backdrop-bl-sm message-bubble rounded-bl-md message-hover border-gray-200 dark:border-gray-700 ${A.chatMessage.other}`,children:[l.jsx(Xt,{interaction:k,theme:t,onDismiss:()=>e.dismissCurrentInteraction(),client:e,addLocalMessage:B},k.methodName),l.jsx(ie.div,{initial:{opacity:0},animate:{opacity:1},transition:{delay:.2},className:`text-xs ${A.text.muted} mt-1 opacity-0 group-hover:opacity-100 transition-opacity duration-200 `,children:new Date().toLocaleTimeString([],{hour:"2-digit",minute:"2-digit"})})]})]}),l.jsx("div",{ref:j})]})})]}),oe.length>0&&l.jsx("div",{className:"w-full flex overflow-x-auto gap-2 px-4 py-2 mb-1 scrollbar-hide",children:oe.map((E,D)=>{var O;return l.jsx("button",{className:`whitespace-nowrap px-3 py-1 rounded-full border shadow-sm flex-shrink-0 transition-all duration-150 font-medium text-sm focus:outline-none focus:ring-2 focus:ring-blue-400/40
|
|
100
100
|
${t==="light"?"bg-white text-blue-700 border-blue-200 hover:bg-blue-50 hover:text-blue-900":t==="dark"?"bg-gray-800 text-blue-300 border-gray-700 hover:bg-gray-700 hover:text-white":((O=A.suggestedResponse)==null?void 0:O.container)||"bg-gradient-to-br from-blue-500 to-purple-600 text-white border-blue-400 hover:from-blue-600 hover:to-purple-700"}
|
|
101
101
|
`,style:{boxShadow:t==="vox"?"0 2px 8px 0 rgba(80,60,200,0.10)":void 0,borderWidth:1},onClick:()=>{te(E),X([])},children:E},E+D)})}),k&&k.presentationMode!=="embedded"&&l.jsx(Xt,{interaction:k,theme:t,onDismiss:()=>e.dismissCurrentInteraction(),client:e,addLocalMessage:B},k.methodName),l.jsx(ie.div,{initial:{opacity:0,y:20},animate:{opacity:1,y:0},transition:{delay:.2},className:W,children:l.jsx(O1,{onSendMessage:te,onSendAttachments:ne,disabled:r,theme:t,onEndChat:s,displayType:o})})]})}function G1({onToggleCamera:e,onToggleScreenShare:t,onEndCall:n,onBack:r,theme:o,cameraEnabled:s,screenShareEnabled:i,isCameraLoading:a,isScreenShareLoading:c,disabled:d,displayType:u}){const f=Ne(o),h=u==="popup";return l.jsxs("div",{className:`flex items-center justify-center ${h?"gap-1 p-2":"gap-3 p-4"} ${f.video.controlsBackground}`,children:[l.jsx("button",{onClick:e,disabled:d||a,className:`${h?"p-1.5":"p-3"} rounded-full transition-all duration-200 ${s?f.video.controlEnabled:f.video.controlDisabled} ${d?"opacity-50 cursor-not-allowed":"hover:scale-105"}`,title:s?"Turn off camera":"Turn on camera",children:s?l.jsx(Pe.Camera,{className:h?"w-4 h-4":"w-5 h-5"}):l.jsx(Pe.CameraOff,{className:h?"w-4 h-4":"w-5 h-5"})}),l.jsx("button",{onClick:t,disabled:d||c,className:`${h?"p-1.5":"p-3"} rounded-full transition-all duration-200 ${i?f.video.controlEnabled:f.video.controlDisabled} ${d?"opacity-50 cursor-not-allowed":"hover:scale-105"}`,title:i?"Stop screen share":"Share screen",children:c?l.jsx("div",{className:`${h?"w-4 h-4":"w-5 h-5"} animate-spin rounded-full border-2 border-current border-t-transparent`}):i?l.jsx(Pe.MonitorOff,{className:h?"w-4 h-4":"w-5 h-5"}):l.jsx(Pe.Monitor,{className:h?"w-4 h-4":"w-5 h-5"})}),n&&l.jsx("button",{onClick:n,disabled:d,className:`${h?"p-1.5":"p-3"} rounded-full transition-all duration-200 ${f.video.endCall} ${d?"opacity-50 cursor-not-allowed":"hover:scale-105"}`,title:"End call",children:l.jsx(Pe.PhoneOff,{className:h?"w-4 h-4":"w-5 h-5"})}),r&&l.jsx("button",{onClick:r,disabled:d,className:`p-3 rounded-full transition-all duration-200 ${f.video.controlDisabled} ${d?"opacity-50 cursor-not-allowed":"hover:scale-105"}`,title:"Back",children:l.jsx("svg",{className:"w-5 h-5",fill:"none",stroke:"currentColor",viewBox:"0 0 24 24",children:l.jsx("path",{strokeLinecap:"round",strokeLinejoin:"round",strokeWidth:2,d:"M10 19l-7-7m0 0l7-7m-7 7h18"})})})]})}function Za({trackRef:e,participant:t,isLocal:n=!1,className:r="",theme:o}){var c;const s=Ne(o),i=(t==null?void 0:t.name)||(t==null?void 0:t.identity)||(n?"You":"Participant"),a=(e==null?void 0:e.publication)&&!e.publication.isMuted;return l.jsxs("div",{className:`relative rounded-lg overflow-hidden ${s.video.tile} ${r}`,children:[a?l.jsx(Ie.VideoTrack,{trackRef:e,className:"w-full h-full object-cover"}):l.jsx("div",{className:`w-full h-full flex items-center justify-center ${s.video.placeholder}`,children:l.jsxs("div",{className:"text-center",children:[l.jsx("div",{className:`w-16 h-16 mx-auto mb-2 rounded-full flex items-center justify-center ${s.video.avatar}`,children:l.jsx(Pe.User,{className:"w-8 h-8"})}),l.jsx("p",{className:"text-sm opacity-80",children:i}),l.jsx("p",{className:"text-xs opacity-60",children:"Camera off"})]})}),l.jsx("div",{className:`absolute bottom-2 left-2 px-2 py-1 rounded text-xs ${s.video.nameOverlay}`,children:i}),((c=e==null?void 0:e.publication)==null?void 0:c.isMuted)&&l.jsx("div",{className:`absolute top-2 right-2 p-1 rounded ${s.video.mutedIndicator}`,children:l.jsx(Pe.CameraOff,{className:"w-4 h-4"})})]})}function K1({trackRefs:e,participants:t,theme:n,localParticipant:r}){const o=e.find(u=>u.source===H.Track.Source.Camera&&u.participant===r),s=e.filter(u=>u.participant!==r),i=e.length,a=i<=1?1:i<=4?2:3,c="grid gap-2 h-full",d={gridTemplateColumns:`repeat(${a}, 1fr)`,gridAutoRows:"minmax(0, 1fr)"};return l.jsxs("div",{className:c,style:d,children:[o&&r&&l.jsx(Za,{trackRef:o,participant:r,isLocal:!0,theme:n,className:"min-h-0"}),s.map((u,f)=>{var h;return l.jsx(Za,{trackRef:u,participant:u.participant,isLocal:!1,theme:n,className:"min-h-0"},((h=u.publication)==null?void 0:h.trackSid)||f)}),i===0&&l.jsx("div",{className:"flex items-center justify-center h-full",children:l.jsxs("div",{className:"text-center",children:[l.jsx(Pe.Users,{className:"w-12 h-12 mx-auto mb-4 opacity-50"}),l.jsx("p",{className:"text-lg opacity-70",children:"Waiting for participants..."}),l.jsx("p",{className:"text-sm opacity-50",children:"Turn on your camera to start the video call"})]})})]})}function Y1({client:e,theme:t="vox",onBack:n,disabled:r=!1,displayType:o,onEndCall:s}){const i=Ne(t),a=Wl(e),{videoTrackRefs:c}=M0(e),d=g.useMemo(()=>e.getRemoteParticipants(),[e,a]),u=yn(e,"camera"),f=yn(e,"screenShare"),[h,x]=g.useState(null),y=g.useCallback(async()=>{u.pending||await u.toggle()},[u]),m=g.useCallback(async()=>{f.pending||await f.toggle()},[f]),b=g.useCallback(()=>{s?s():n&&n()},[s,n]);return g.useEffect(()=>{if(!e)return;const C=v=>{console.log("๐บ Video: Interactive UI state updated:",v),x(v)};return e.on("interactive.ui.update",C),e.on("interactive.ui.show",C),()=>{e.off("interactive.ui.update",C),e.off("interactive.ui.show",C)}},[e]),l.jsxs("div",{className:`flex flex-col h-full ${i.video.container}`,children:[l.jsxs("div",{className:`flex items-center justify-between p-4 border-b ${i.video.header}`,children:[l.jsxs("div",{className:"flex items-center gap-3",children:[l.jsx("div",{className:`w-3 h-3 rounded-full ${i.video.statusDot}`}),l.jsx("span",{className:"font-medium",children:"Video Call"}),l.jsxs("span",{className:"text-sm opacity-70",children:[d.length+1," participant",d.length!==0?"s":""]})]}),l.jsx("div",{className:"flex items-center gap-2",children:l.jsx("button",{className:`p-2 rounded-lg transition-colors ${i.video.headerButton}`,title:"Layout options",children:l.jsx(Pe.LayoutGrid,{className:"w-4 h-4"})})})]}),l.jsx("div",{className:"flex-1 p-4 min-h-0",children:l.jsx(K1,{trackRefs:c,participants:d,localParticipant:a==null?void 0:a.localParticipant,theme:t})}),h&&l.jsx(ie.div,{initial:{opacity:0,y:20},animate:{opacity:1,y:0},exit:{opacity:0,y:20},className:"absolute inset-4 z-10",children:l.jsx(Xt,{interaction:h,onDismiss:()=>x(null),theme:t})}),l.jsx(G1,{onToggleCamera:y,onToggleScreenShare:m,onEndCall:b,onBack:n,theme:t,cameraEnabled:u.enabled,screenShareEnabled:f.enabled,isCameraLoading:u.pending,isScreenShareLoading:f.pending,disabled:r,displayType:o})]})}function Gn({onClick:e,disabled:t,theme:n,displayType:r}){var c;const o=Ne(n),s=r==="popup",i=s?(c=o.popup)==null?void 0:c.buttonSizes.large:"w-20 h-20",a=s?"w-5 h-5":"w-6 h-6";return l.jsx("button",{className:`${o.micButton.replace("w-20 h-20",i||"w-20 h-20")} ${n==="vox"||n==="dark"?"text-white":""}`,onClick:e,disabled:t,"aria-label":"Start Voice Session",type:"button",children:l.jsx(fd,{className:`${a} ${n==="vox"||n==="dark"?"text-white":"text-current"}`})})}function oo({onClick:e,disabled:t,theme:n,displayType:r}){var c;const o=Ne(n),s=r==="popup",i=s?(c=o.popup)==null?void 0:c.buttonSizes.large:"w-20 h-20",a=s?"w-5 h-5":"w-6 h-6";return l.jsx("button",{className:`${o.chatButton.replace("w-20 h-20",i||"w-20 h-20")} ${n==="vox"||n==="dark"?"text-white":""}`,onClick:e,disabled:t,children:l.jsx(ud,{className:`${a} ${n==="vox"||n==="dark"?"text-white":"text-current"}`})})}function so({onClick:e,disabled:t,theme:n,displayType:r}){var c;const o=Ne(n),s=r==="popup",i=s?(c=o.popup)==null?void 0:c.buttonSizes.large:"w-20 h-20",a=s?"w-5 h-5":"w-6 h-6";return l.jsx("button",{className:`${o.videoButton.replace("w-20 h-20",i||"w-20 h-20")} ${n==="vox"||n==="dark"?"text-white":""}`,onClick:e,disabled:t,children:l.jsx(hd,{className:`${a} ${n==="vox"||n==="dark"?"text-white":"text-current"}`})})}function q1({prompts:e,theme:t,displayType:n}){const r=Ne(t),[o,s]=w.useState(0),i=n==="popup";return w.useEffect(()=>{const a=setInterval(()=>{s(c=>(c+1)%e.length)},3e3);return()=>clearInterval(a)},[e.length]),l.jsx("div",{className:`${i?"w-64 min-h-[2rem] h-8":"w-96 min-h-[3rem] h-12"} relative overflow-hidden flex items-center justify-center`,children:e.map((a,c)=>l.jsx("div",{className:`
|
|
102
102
|
${r.promptSlider} ${i?"py-1 px-1 text-xs":""}
|
|
@@ -1204,7 +1204,178 @@ To suppress this warning, you need to explicitly provide the \`palette.${t}Chann
|
|
|
1204
1204
|
.voxket-widget-root .text-blue-600 {
|
|
1205
1205
|
color: #2563eb !important;
|
|
1206
1206
|
}
|
|
1207
|
-
`,t=document.createElement("style");t.type="text/css",t.setAttribute("data-voxket-styles","true"),t.textContent=e,document.head.appendChild(t),Wa=!0}class he extends Error{constructor(t,n,r){super(t),this.code=n,this.details=r,this.name="VoxketError"}}class Rn extends Vs{constructor(n){super();ke(this,"config");ke(this,"room",null);ke(this,"pluginManager");ke(this,"rpcManager");ke(this,"isConnected",!1);ke(this,"currentSession",null);ke(this,"connectionState",H.ConnectionState.Disconnected);ke(this,"renderedComponents",new Map);ke(this,"textStreamHandlersRegistered",!1);ke(this,"currentAgentInfo",null);ke(this,"chatMessages",[]);ke(this,"isAgentConnected",!1);ke(this,"agentState","idle");yd(),this.config=n,this.pluginManager=new gd(this),this.rpcManager=new ry,this.setupEventListeners(),this.initializeClient()}setupEventListeners(){this.on("connection.connected",()=>{var n,r;this.isConnected=!0,(r=(n=this.config).onConnected)==null||r.call(n)}),this.on("connection.disconnected",n=>{var r,o;this.isConnected=!1,(o=(r=this.config).onDisconnected)==null||o.call(r,n)}),this.on("connection.error",n=>{var r,o;(o=(r=this.config).onError)==null||o.call(r,n)}),this.on("chat.message.received",n=>{var r,o;this.addChatMessage(n),(o=(r=this.config).onMessageReceived)==null||o.call(r,n)}),this.on("chat.message.updated",n=>{this.updateChatMessage(n)}),this.on("chat.message.sent",n=>{this.addChatMessage(n)}),this.on("transcription.received",n=>{var r,o;(o=(r=this.config).onTranscriptionReceived)==null||o.call(r,n)}),this.on("session.state.changed",n=>{var r,o;(o=(r=this.config).onSessionStateChanged)==null||o.call(r,n)}),this.on("session.created",n=>{var r,o;(o=(r=this.config).onSessionStart)==null||o.call(r,n.id)}),this.on("session.ended",(n,r)=>{var o,s;(s=(o=this.config).onSessionEnd)==null||s.call(o,r)}),this.on("participant.joined",n=>{var r,o;(o=(r=this.config).onUserJoined)==null||o.call(r,n.id)}),this.on("participant.left",n=>{var r,o;(o=(r=this.config).onUserLeft)==null||o.call(r,n.id)}),this.setupRpcEventForwarding()}setupRpcEventForwarding(){if(!this.rpcManager){console.warn("RpcManager not initialized, skipping event forwarding setup");return}this.rpcManager.on("rpc.method.registered",n=>this.emit("rpc.method.registered",n)),this.rpcManager.on("rpc.method.called",n=>this.emit("rpc.method.called",n)),this.rpcManager.on("rpc.interaction.started",n=>this.emit("rpc.interaction.started",n)),this.rpcManager.on("rpc.interaction.completed",n=>this.emit("rpc.interaction.completed",n)),this.rpcManager.on("rpc.interaction.timeout",n=>this.emit("rpc.interaction.timeout",n)),this.rpcManager.on("rpc.interaction.dismissed",n=>this.emit("rpc.interaction.dismissed",n))}initializeClient(){this.room=new H.Room,this.setupRoomEventListeners()}setupRoomEventListeners(){this.room&&(this.room.on(H.RoomEvent.Connected,()=>{var n,r;this.connectionState=H.ConnectionState.Connected,this.emit("connection.connected"),this.rpcManager.setRoom(this.room),(r=(n=this.currentSession)==null?void 0:n.activeModalities)!=null&&r.includes("voice")&&setTimeout(async()=>{var o;try{(o=this.room)!=null&&o.localParticipant&&(this.room.localParticipant.isMicrophoneEnabled?this.emit("track.unmuted",{source:"microphone",enabled:!0}):(await this.room.localParticipant.setMicrophoneEnabled(!0),this.emit("track.unmuted",{source:"microphone",enabled:!0})))}catch(s){console.warn("VoxketClient: Failed to enable microphone after room connection:",s)}},1e3),this.textStreamHandlersRegistered||this.setupTextStreamHandlers()}),this.room.on(H.RoomEvent.Disconnected,n=>{var r;console.log("๐ด VoxketClient: Room disconnected, reason:",n),this.connectionState=H.ConnectionState.Disconnected,this.textStreamHandlersRegistered=!1,this.isAgentConnected=!1,console.log("๐ค VoxketClient: Agent marked as disconnected"),n&&console.log("๐ VoxketClient: Disconnect reason details:",{reason:n.toString(),currentSession:(r=this.currentSession)==null?void 0:r.id,agentConnected:this.isAgentConnected,connectionState:this.connectionState}),this.emit("connection.disconnected",n==null?void 0:n.toString())}),this.room.on(H.RoomEvent.ConnectionStateChanged,n=>{this.connectionState=n,n===H.ConnectionState.Connecting&&this.emit("connection.connecting")}),this.room.on(H.RoomEvent.ParticipantConnected,n=>{const r={id:n.identity,name:n.name||n.identity,isLocal:!1};this.emit("participant.joined",r)}),this.room.on(H.RoomEvent.ParticipantDisconnected,n=>{const r={id:n.identity,name:n.name||n.identity,isLocal:!1};this.emit("participant.left",r)}))}setupTextStreamHandlers(){if(!this.room)return;try{this.room.registerTextStreamHandler("lk.chat",async(r,o)=>{try{const s=await r.readAll(),i={id:`msg_${Date.now()}_${o.identity||"user"}_${Math.random().toString(36).substr(2,9)}`,content:s,timestamp:new Date,sender:{id:o.identity||"user",name:o.identity||"User",type:"participant"},metadata:{topic:"lk.chat"}};this.emit("chat.message.received",i)}catch(s){console.error("VoxketClient: Failed to process lk.chat message:",s)}})}catch(r){console.warn("VoxketClient: lk.chat handler already registered, skipping:",r)}try{this.room.registerTextStreamHandler("lk.transcription",async(r,o)=>{var s,i;try{const a=`msg_${Date.now()}_agent_transcription_${Math.random().toString(36).substr(2,9)}`;let c="";const d=((s=this.currentAgentInfo)==null?void 0:s.name)||o.identity||"AI Assistant",u={id:a,content:"",timestamp:new Date,sender:{id:o.identity||"agent",name:d,type:"agent"},metadata:{topic:"lk.transcription",streaming:!0}};this.emit("chat.message.received",u);for await(const x of r){c+=x;const y=this.convertMarkdownToText(c),m={...u,content:y,metadata:{...u.metadata,streaming:!0}};this.emit("chat.message.updated",m)}const f=this.convertMarkdownToText(c),h={...u,content:f,metadata:{...u.metadata,streaming:!1}};this.emit("chat.message.updated",h)}catch(a){console.error("VoxketClient: Failed to process lk.transcription message:",a);try{const c=await r.readAll(),d=((i=this.currentAgentInfo)==null?void 0:i.name)||o.identity||"AI Assistant",u={id:`msg_${Date.now()}_agent_transcription_${Math.random().toString(36).substr(2,9)}`,content:c,timestamp:new Date,sender:{id:o.identity||"agent",name:d,type:"agent"},metadata:{topic:"lk.transcription"}};this.emit("chat.message.received",u)}catch(c){console.error("VoxketClient: Fallback failed for lk.transcription:",c)}}})}catch(r){console.warn("VoxketClient: lk.transcription handler already registered, skipping:",r)}try{this.room.registerTextStreamHandler("suggested_response",async r=>{const o=await r.readAll();let s=[];try{s=["tes","hello how are you","algebra make me learn that ","what is the meaning of life"]}catch(i){console.warn("VoxketClient: Failed to parse suggested_response:",i,o)}this.emit("suggested.response",s)})}catch(r){console.warn("VoxketClient: suggested_response handler already registered, skipping:",r)}try{this.room.registerTextStreamHandler("agent_state_changed",async(r,o)=>{const s=await r.readAll();console.log("๐ค VoxketClient: agent_state_changed stream received:",s);let i={};try{i=typeof s=="string"?JSON.parse(s.replace(/'/g,'"')):s}catch(a){console.warn("VoxketClient: Failed to parse agent_state_changed:",a,s)}this.isAgentConnected||(this.isAgentConnected=!0,console.log("๐ค VoxketClient: Agent marked as connected (first state change received)"),this.emit("agent.connected",i)),i.new_state==="speaking"?(this.setAgentState("speaking"),this.emit("agent.speaking",i)):i.new_state==="thinking"?(this.setAgentState("thinking"),this.emit("agent.thinking",i)):(i.new_state==="idle"||i.new_state==="listening")&&this.setAgentState("idle")})}catch(r){console.warn("VoxketClient: conversation_item_added handler already registered, skipping:",r)}try{this.room.registerTextStreamHandler("images",async(r,o)=>{try{const s=await r.readAll()}catch(s){console.error("VoxketClient: Error processing images stream:",s)}})}catch(r){console.warn("VoxketClient: images handler already registered, skipping:",r)}try{this.room.registerByteStreamHandler("images",async(r,o)=>{var s,i;try{const a=r.info,c={id:`img_${Date.now()}_${o.identity||"agent"}_${Math.random().toString(36).substr(2,9)}`,content:`๏ฟฝ๏ธ ${a.name||"Image"}`,sender:{id:o.identity||"agent",name:o.identity||"Agent",type:o.identity===((i=(s=this.room)==null?void 0:s.localParticipant)==null?void 0:i.identity)?"participant":"agent"},timestamp:new Date,metadata:{type:"attachment",fileName:a.name,fileSize:a.size,mimeType:a.mimeType,streamId:a.id,downloading:!0}};this.emit("chat.message.received",c),r.onProgress&&(r.onProgress=x=>{const y={...c,metadata:{...c.metadata,downloadProgress:x||0}};this.emit("chat.message.updated",y)});const d=[];for await(const x of r)d.push(x);const u=new Blob(d,{type:a.mimeType||"application/octet-stream"}),f=URL.createObjectURL(u),h={...c,metadata:{...c.metadata,downloading:!1,downloadProgress:1,downloadUrl:f,blob:u}};this.emit("chat.message.updated",h)}catch(a){console.error("VoxketClient: Error processing image attachment:",a)}})}catch(r){console.warn("VoxketClient: image handler already registered, skipping:",r)}["error","warning","status","system","debug","info"].forEach(r=>{try{this.room.registerTextStreamHandler(r,async(o,s)=>{try{const i=await o.readAll();if(console.log(`๐ VoxketClient: Received '${r}' stream:`,i),r==="error"){let a={};try{a=typeof i=="string"?JSON.parse(i):i}catch{a={message:i}}console.warn("๏ฟฝ VoxketClient: Agent error:",a),this.emit("agent.error",a)}else this.emit("text.stream.received",{topic:r,data:i,participantInfo:s})}catch(i){console.error(`VoxketClient: Failed to process '${r}' stream:`,i)}})}catch(o){console.warn(`VoxketClient: Handler for '${r}' already registered, skipping:`,o)}});try{this.room.registerTextStreamHandler("*",async(r,o)=>{var s;try{const i=await r.readAll(),a=((s=r.info)==null?void 0:s.topic)||"unknown";console.log(`๐ VoxketClient: Received unhandled text stream for topic '${a}':`,i),this.emit("text.stream.unhandled",{topic:a,data:i,participantInfo:o})}catch(i){console.error("VoxketClient: Failed to process unhandled text stream:",i)}})}catch(r){console.warn("VoxketClient: Generic text stream handler already registered, skipping:",r)}this.textStreamHandlersRegistered=!0}async fetchConnectionDetails(n,r,o){const s=n||this.config.agentId||"default-agent",i=r||this.config.participantName||"User",a=o||this.config.modalities||["voice"];try{const c={agent_id:s,participant_name:i,participant_metadata:{user_id:""},modality:a[0],modalities:a};console.log("๐ VoxketClient: Creating session with modalities:",a);const d=await fetch(`${this.config.baseUrl}/api/live/agent/session`,{method:"POST",headers:{accept:"application/json","X-APP-ID":this.config.appId,"X-APP-SECRET":this.config.appSecret,"Content-Type":"application/json"},body:JSON.stringify(c)});if(!d.ok){let h=`HTTP ${d.status}: Failed to fetch connection details`;try{const x=await d.json();x&&(x.error?h=`API Error: ${x.error}`:x.detail?h=`API Error: ${x.detail}`:x.message&&(h=`API Error: ${x.message}`))}catch{try{const y=await d.text();y&&(h=`API Error: ${y}`)}catch{}}throw new Error(h)}const u=await d.json();let f;return u.agent_info&&(f={id:u.agent_info.id||s,name:u.agent_info.name||"AI Assistant",avatar:u.agent_info.avatar,capabilities:u.agent_info.capabilities||["voice_interaction","text_chat"],metadata:u.agent_info.metadata||{}},this.currentAgentInfo=f),{serverUrl:u.wss_url,participantToken:u.token,voxketSessionId:u.session_id,agentInfo:f}}catch(c){console.error("VoxketClient: fetchConnectionDetails failed:",c);const d=new he(`Failed to fetch connection details: ${c instanceof Error?c.message:"Unknown error"}`,"CONNECTION_FAILED",c);throw this.emit("connection.error",d),d}}async connect(n,r,o){var s;try{this.emit("connection.connecting");const i=await this.fetchConnectionDetails(n,r,o);return await((s=this.room)==null?void 0:s.connect(i.serverUrl,i.participantToken)),this.isConnected=!0,i}catch(i){console.error("VoxketClient: Connection failed:",i);const a=new he(`Failed to connect to Voxket services: ${i instanceof Error?i.message:"Unknown error"}`,"CONNECTION_FAILED",i);throw this.emit("connection.error",a),a}}async disconnect(){var n;try{await((n=this.room)==null?void 0:n.disconnect()),this.isConnected=!1,this.currentSession=null,this.currentAgentInfo=null,this.textStreamHandlersRegistered=!1,this.clearChatMessages(),this.room=new H.Room,this.setupRoomEventListeners()}catch(r){const o=new he("Failed to disconnect properly","NETWORK_ERROR",r);throw this.emit("connection.error",o),o}}async createSession(n){var r,o,s,i;try{const a=await this.connect(n.agentId,n.participantName,n.modalities),c={id:a.voxketSessionId,agentId:n.agentId,state:"connecting",startedAt:new Date,metadata:n.metadata||{},activeModalities:n.modalities||["voice"],agentInfo:a.agentInfo||this.currentAgentInfo};if(this.currentSession=c,this.emit("session.created",c),(r=n.modalities)!=null&&r.includes("voice"))try{await new Promise(d=>setTimeout(d,500)),(o=this.room)!=null&&o.localParticipant?(await this.room.localParticipant.setMicrophoneEnabled(!0,void 0,{preConnectBuffer:!0}),this.emit("track.unmuted",{source:"microphone",enabled:!0})):console.warn("VoxketClient: No local participant found, microphone not enabled")}catch(d){console.warn("VoxketClient: Failed to enable microphone, but continuing with session:",d)}if((s=n.modalities)!=null&&s.includes("video"))try{await new Promise(d=>setTimeout(d,200)),(i=this.room)!=null&&i.localParticipant&&(console.log("๐ฅ VoxketClient: Attempting to enable camera for video session"),await this.room.localParticipant.setCameraEnabled(!0),this.emit("track.unmuted",{source:"camera",enabled:!0}),console.log("๐ฅ VoxketClient: Camera enabled successfully"))}catch(d){console.warn("VoxketClient: Failed to enable camera, but continuing with session:",d)}return setTimeout(()=>{var d;this.currentSession&&(this.currentSession.state="active",this.emit("session.state.changed","active",this.currentSession.state),this.forceAgentConnected(),console.log("๐ค VoxketClient: Session marked as active:",{sessionId:this.currentSession.id,modalities:this.currentSession.activeModalities,agentConnected:this.isAgentConnected,hasRoom:!!this.room,remoteParticipants:((d=this.room)==null?void 0:d.remoteParticipants.size)||0}))},1e3),c}catch(a){throw console.error("VoxketClient: Failed to create session:",a),a instanceof he?a:a instanceof TypeError&&a.message.includes("fetch")?new he("Network connection failed","CONNECTION_FAILED",a):a instanceof Error&&a.message.includes("Failed to fetch connection details")?new he(`API connection failed: ${a.message}`,"CONNECTION_FAILED",a):new he(`Failed to create session: ${a instanceof Error?a.message:"Unknown error"}`,"SESSION_NOT_FOUND",a)}}async startSession(n,r){const o={agentId:n||this.config.agentId||"default-agent",participantName:(r==null?void 0:r.participantName)||this.config.participantName||"User",modalities:(r==null?void 0:r.modalities)||this.config.modalities||["voice","chat"],metadata:r==null?void 0:r.metadata};return this.createSession(o)}async endSession(){var n,r;if(!this.currentSession)return null;try{const o={sessionId:this.currentSession.id,duration:Date.now()-(((n=this.currentSession.startedAt)==null?void 0:n.getTime())||0),messageCount:0,participantCount:((r=this.room)==null?void 0:r.remoteParticipants.size)||0,audioQuality:{avgBitrate:64e3,avgLatency:150,packetLoss:.01,jitter:.05},videoQuality:{avgBitrate:5e5,avgLatency:150,packetLoss:.01,jitter:.05},networkStats:{totalBytesReceived:0,totalBytesSent:0,connectionType:"webrtc",avgRoundTripTime:150},events:[]};return this.currentSession.endedAt=new Date,this.currentSession.state="disconnected",this.emit("session.ended",this.currentSession,o),await this.disconnect(),o}catch(o){throw new he("Failed to end session","SESSION_NOT_FOUND",o)}}getCurrentSession(){return this.currentSession}getCurrentAgentInfo(){return this.currentAgentInfo}getIsAgentConnected(){return this.isAgentConnected}forceAgentConnected(){this.isAgentConnected||(this.isAgentConnected=!0,console.log("๐ค VoxketClient: Agent manually marked as connected"),this.emit("agent.connected",{forced:!0}))}getAgentState(){return this.agentState}setAgentState(n){this.agentState!==n&&(this.agentState=n,this.emit("agent.state.changed",{state:n}))}getAgentAudioTrack(){const n=this.getRemoteParticipants();for(const r of n){const o=r.getTrackPublication(H.Track.Source.Microphone);if(o!=null&&o.track)return{source:H.Track.Source.Microphone,participant:r,publication:o}}return null}getAgentVideoTrack(){const n=this.getRemoteParticipants();for(const r of n){const o=r.getTrackPublication(H.Track.Source.Camera);if(o!=null&&o.track)return{source:H.Track.Source.Camera,participant:r,publication:o}}return null}getVideoTrackRefs(){const n=[],r=this.getLocalParticipant();if(r){const s=r.getTrackPublication(H.Track.Source.Camera);s!=null&&s.track&&n.push({source:H.Track.Source.Camera,participant:r,publication:s});const i=r.getTrackPublication(H.Track.Source.ScreenShare);i!=null&&i.track&&n.push({source:H.Track.Source.ScreenShare,participant:r,publication:i})}const o=this.getRemoteParticipants();for(const s of o){const i=s.getTrackPublication(H.Track.Source.Camera);i!=null&&i.track&&n.push({source:H.Track.Source.Camera,participant:s,publication:i});const a=s.getTrackPublication(H.Track.Source.ScreenShare);a!=null&&a.track&&n.push({source:H.Track.Source.ScreenShare,participant:s,publication:a})}return n}getCameraTrackRefs(){return this.getVideoTrackRefs().filter(n=>n.source===H.Track.Source.Camera)}getScreenShareTrackRefs(){return this.getVideoTrackRefs().filter(n=>n.source===H.Track.Source.ScreenShare)}getChatMessages(){return[...this.chatMessages]}addChatMessage(n){this.chatMessages.some(o=>o.id===n.id)||this.chatMessages.push(n)}updateChatMessage(n){const r=this.chatMessages.findIndex(o=>o.id===n.id);r!==-1&&(this.chatMessages[r]=n)}clearChatMessages(){this.chatMessages=[],this.dismissCurrentInteraction(),this.renderedComponents.clear(),this.forceCleanupFullscreenOverlays(),this.emit("chat.history.cleared")}renderUI(n={}){var c,d,u;const r=this.resolveTarget(n.target||"body"),o=this.getTargetKey(r),s=this.renderedComponents.get(o);s&&s.target===r||this.removeUI(r);const i=(s==null?void 0:s.root)||Hd.createRoot(r),a={agentId:n.agentId||this.config.agentId||"default-agent",participantName:n.participantName||this.config.participantName||"User",baseUrl:this.config.baseUrl,appSecret:this.config.appSecret,appId:this.config.appId,className:n.className,theme:typeof n.theme=="string"?n.theme:void 0,modalities:n.modality||this.config.modalities||["voice"],suportsChatInput:((c=n.modality)==null?void 0:c.includes("chat"))!==!1,suportsVideoInput:((d=n.modality)==null?void 0:d.includes("video"))===!0,suportsScreenShare:((u=n.modality)==null?void 0:u.includes("screen_share"))===!0,autoStart:n.autoStart,displayType:n.displayType||"widget",popupPosition:n.popupPosition||"bottom-right",popupTriggerText:n.popupTriggerText||"Open Chat",width:n.width,height:n.height,onDisplayTypeChange:n.onDisplayTypeChange,prompts:n.prompts,statusMessage:n.statusMessage,welcomeTitle:n.welcomeTitle,welcomeSubTitle:n.welcomeSubTitle,loadingText:n.loadingText,voxketClient:this};if(!i||typeof i.render!="function")throw new Error("Invalid React root. Make sure React 18+ is properly installed and configured.");try{i.render(w.createElement(xd,{config:this.config,autoConnect:n.autoStart||!1,children:w.createElement(bd,a)}))}catch(f){throw console.error("Error rendering Voxket widget:",f),new Error(`Failed to render Voxket widget: ${f instanceof Error?f.message:"Unknown error"}`)}this.renderedComponents.set(o,{root:i,target:r})}removeUI(n){const r=n?this.resolveTarget(n):null;if(r){const o=this.getTargetKey(r),s=this.renderedComponents.get(o);s&&(s.root.unmount(),this.renderedComponents.delete(o),r.querySelectorAll('[id*="voxket"], [class*="voxket"], .fixed.inset-0.z-50').forEach(a=>{try{a.remove()}catch(c){console.warn("Failed to remove element:",c)}}),r===document.body&&r.querySelectorAll(".fixed.z-50, .fixed.inset-0").forEach(c=>{if(c.classList.contains("bg-black")&&c.classList.contains("backdrop-blur-sm"))try{c.remove()}catch(d){console.warn("Failed to remove fixed element:",d)}}))}}removeAllUI(){for(const[n,r]of this.renderedComponents)r.root.unmount();this.renderedComponents.clear(),this.forceCleanupFullscreenOverlays()}forceCleanupFullscreenOverlays(){document.body.querySelectorAll(".fixed.inset-0.z-50").forEach(r=>{if(r.classList.contains("bg-black")&&(r.classList.contains("backdrop-blur-sm")||r.classList.contains("bg-opacity-30")))try{r.remove()}catch(o){console.warn("Failed to remove overlay:",o)}})}resolveTarget(n){if(typeof n=="string"){const r=document.querySelector(n);if(!r)throw new Error(`Target element not found: ${n}`);return r}return n}getTargetKey(n){return n.id?n.id:n.className?n.tagName+"_"+n.className.replace(/\s+/g,"_"):n.tagName+"_"+n.outerHTML.length%1e3}async sendMessage(n,r){var o;if(!this.currentSession)throw console.error("VoxketClient: No active session found"),new he("No active session","SESSION_NOT_FOUND");if(!this.room)throw console.error("VoxketClient: No room instance found"),new he("No room connection","CONNECTION_FAILED");if(!this.room.localParticipant)throw console.error("VoxketClient: No local participant found"),new he("No local participant","CONNECTION_FAILED");this.dismissCurrentInteraction();try{const s={id:`msg_${Date.now()}`,content:n,sender:{id:"user",name:this.config.participantName||"User",type:"participant"},timestamp:new Date,metadata:r||{}},i=await((o=this.room)==null?void 0:o.localParticipant.sendText(n,{topic:"lk.chat",destinationIdentities:[]}));this.emit("chat.message.sent",s)}catch(s){throw console.error("VoxketClient: Failed to send chat message:",s),new he("Failed to send message","NETWORK_ERROR",s)}}async sendChatMessage(n,r){return this.sendMessage(n,r)}async sendAttachments(n,r){if(!this.currentSession)throw console.error("VoxketClient: No active session found"),new he("No active session","SESSION_NOT_FOUND");if(!this.room)throw console.error("VoxketClient: No room instance found"),new he("No room connection","CONNECTION_FAILED");if(!this.room.localParticipant)throw console.error("VoxketClient: No local participant found"),new he("No local participant","CONNECTION_FAILED");if(!n||n.length===0)throw new he("No files provided","INVALID_PARAMETER");this.dismissCurrentInteraction();const o=n.filter(s=>s.type.startsWith("image/"));if(o.length===0)throw new he("Only image files are allowed","INVALID_PARAMETER");o.length!==n.length&&console.warn("VoxketClient: Some non-image files were filtered out");try{const s=o.map(async(i,a)=>{const d={id:`att_${Date.now()}_${a}`,content:`๐ ${i.name}`,sender:{id:"user",name:this.config.participantName||"User",type:"participant"},timestamp:new Date,metadata:{...r,type:"attachment",fileName:i.name,fileSize:i.size,mimeType:i.type,uploading:!0}};this.emit("chat.message.sent",d);const u=await this.room.localParticipant.sendFile(i,{mimeType:i.type,topic:"images",onProgress:h=>{const x={...d,metadata:{...d.metadata,uploadProgress:h}};this.emit("chat.message.updated",x)}});try{const h=new FileReader,x=new Promise((b,C)=>{h.onload=()=>{typeof h.result=="string"?b(h.result):C(new Error("Failed to convert to base64"))},h.onerror=C});h.readAsDataURL(i);const m={type:"image",data:await x,filename:i.name,mimeType:i.type,size:i.size};await this.room.localParticipant.sendText(JSON.stringify(m),{topic:"images",destinationIdentities:[]})}catch(h){console.warn("VoxketClient: Failed to send image data to agent:",h);try{const x=`I've shared an image: ${i.name}`;await this.room.localParticipant.sendText(x,{topic:"lk.chat",destinationIdentities:[]})}catch(x){console.warn("VoxketClient: Failed to send image notification to agent:",x)}}const f={...d,metadata:{...d.metadata,uploading:!1,uploadProgress:1,streamId:u.id}};return this.emit("chat.message.updated",f),u});await Promise.all(s)}catch(s){throw console.error("VoxketClient: Failed to send attachments:",s),new he("Failed to send attachments","NETWORK_ERROR",s)}}async sendAttachment(n,r){return this.sendAttachments([n],r)}toggleMicrophone(n){return this.setMicrophoneEnabled(n!==!1)}async setMicrophoneEnabled(n){var r,o;try{const s=(r=this.room)==null?void 0:r.localParticipant.isMicrophoneEnabled,i=n??!s;await((o=this.room)==null?void 0:o.localParticipant.setMicrophoneEnabled(i)),i?this.emit("track.unmuted",{source:"microphone",enabled:!0}):this.emit("track.muted",{source:"microphone",enabled:!1})}catch(s){throw console.error("VoxketClient: Failed to toggle microphone:",s),new he("Failed to toggle microphone","PERMISSION_DENIED",s)}}toggleCamera(n){return this.setCameraEnabled(n!==!1)}async setCameraEnabled(n){var r,o;try{const s=(r=this.room)==null?void 0:r.localParticipant.isCameraEnabled,i=n??!s;await((o=this.room)==null?void 0:o.localParticipant.setCameraEnabled(i)),i?this.emit("track.unmuted",{source:"camera",enabled:!0}):this.emit("track.muted",{source:"camera",enabled:!1})}catch(s){throw console.error("VoxketClient: Failed to toggle camera:",s),new he("Failed to toggle camera","PERMISSION_DENIED",s)}}async enableCamera(){return this.setCameraEnabled(!0)}async disableCamera(){return this.setCameraEnabled(!1)}async startScreenShare(){var n;try{await((n=this.room)==null?void 0:n.localParticipant.setScreenShareEnabled(!0))}catch(r){throw new he("Failed to start screen share","PERMISSION_DENIED",r)}}async stopScreenShare(){var n;try{await((n=this.room)==null?void 0:n.localParticipant.setScreenShareEnabled(!1))}catch(r){throw new he("Failed to stop screen share","PERMISSION_DENIED",r)}}async getAudioInputDevices(){try{return(await navigator.mediaDevices.enumerateDevices()).filter(r=>r.kind==="audioinput")}catch(n){throw new he("Failed to get audio input devices","DEVICE_ERROR",n)}}async getVideoInputDevices(){try{return(await navigator.mediaDevices.enumerateDevices()).filter(r=>r.kind==="videoinput")}catch(n){throw new he("Failed to get video input devices","DEVICE_ERROR",n)}}async setAudioInputDevice(n){var r;try{if(!((r=this.room)!=null&&r.localParticipant))throw new Error("Not connected to room")}catch(o){throw new he("Failed to set audio input device","DEVICE_ERROR",o)}}async setVideoInputDevice(n){var r;try{if(!((r=this.room)!=null&&r.localParticipant))throw new Error("Not connected to room")}catch(o){throw new he("Failed to set video input device","DEVICE_ERROR",o)}}getLocalParticipant(){var n;return((n=this.room)==null?void 0:n.localParticipant)??null}getRemoteParticipants(){var n;return Array.from(((n=this.room)==null?void 0:n.remoteParticipants.values())??[])}getPublishPermissions(){const n=this.getLocalParticipant();if(!n)return{camera:!1,microphone:!1,screenShare:!1,data:!1};const r=n.permissions;if(!r)return{camera:!0,microphone:!0,screenShare:!0,data:!0};const o=s=>!!r.canPublish&&(r.canPublishSources.length===0||r.canPublishSources.includes(s));return{camera:o(1),microphone:o(2),screenShare:o(3),data:r.canPublishData??!1}}canPublishSource(n){return this.getPublishPermissions()[n]}getRoom(){return this.room}getConnectionState(){return this.connectionState}get connected(){return this.isConnected&&this.connectionState===H.ConnectionState.Connected}getMicrophoneTrack(){const n=this.getLocalParticipant();if(!n)return null;for(const[,r]of n.trackPublications)if(r.source===H.Track.Source.Microphone)return r.track;return null}getCameraTrack(){const n=this.getLocalParticipant();if(!n)return null;for(const[,r]of n.trackPublications)if(r.source===H.Track.Source.Camera)return r.track;return null}getScreenShareTrack(){const n=this.getLocalParticipant();if(!n)return null;for(const[,r]of n.trackPublications)if(r.source===H.Track.Source.ScreenShare)return r.track;return null}get isMicrophoneEnabled(){const n=this.getMicrophoneTrack();return n?!n.isMuted:!1}get isCameraEnabled(){const n=this.getCameraTrack();return n?!n.isMuted:!1}get isScreenShareEnabled(){const n=this.getScreenShareTrack();return n?!n.isMuted:!1}registerPlugin(n){this.pluginManager.register(n)}getPluginManager(){return this.pluginManager}getParticipants(){if(!this.room)return[];const n=[];return this.room.localParticipant&&n.push({id:this.room.localParticipant.identity,name:this.room.localParticipant.name||this.room.localParticipant.identity,isLocal:!0}),this.room.remoteParticipants.forEach(r=>{n.push({id:r.identity,name:r.name||r.identity,isLocal:!1})}),n}getSessionMetrics(){var n,r;return this.currentSession?{sessionId:this.currentSession.id,duration:Date.now()-(((n=this.currentSession.startedAt)==null?void 0:n.getTime())||0),messageCount:0,participantCount:((r=this.room)==null?void 0:r.remoteParticipants.size)||0,audioQuality:{avgBitrate:64e3,avgLatency:150,packetLoss:.01,jitter:.05},videoQuality:{avgBitrate:5e5,avgLatency:150,packetLoss:.01,jitter:.05},networkStats:{totalBytesReceived:0,totalBytesSent:0,connectionType:"webrtc",avgRoundTripTime:150},events:[]}:null}updateConfig(n){this.config={...this.config,...n}}async startRecording(){var n;try{this.emit("recording.started",{sessionId:(n=this.currentSession)==null?void 0:n.id,timestamp:new Date})}catch(r){throw new he("Failed to start recording","RECORDING_ERROR",r)}}async stopRecording(){var n;try{this.emit("recording.stopped",{sessionId:(n=this.currentSession)==null?void 0:n.id,timestamp:new Date})}catch(r){throw new he("Failed to stop recording","RECORDING_ERROR",r)}}async registerFrontendRPC(n,r,o="embedded"){return this.rpcManager.registerFrontendRPC(n,r,o)}getCurrentInteraction(){return this.rpcManager.getCurrentInteraction()}dismissCurrentInteraction(){this.rpcManager.dismissCurrentInteraction()}getRegisteredRpcMethods(){return this.rpcManager.getRegisteredMethods()}unregisterRpcMethod(n){this.rpcManager.unregisterMethod(n)}registerEventListener(n,r){return this.on(n,r)}registerEventEmitter(n,r){if(!this.room)throw new Error("Room not available");try{this.room.registerTextStreamHandler(n,async o=>{try{const s=await o.readAll();r(s)}catch(s){console.error(`Error processing event for topic '${n}':`,s)}})}catch(o){console.warn(`VoxketClient: Handler for topic '${n}' may already be registered:`,o)}}convertMarkdownToText(n){if(!n)return"";let r=n;return r=r.replace(/\*\*(.*?)\*\*/g,"$1"),r=r.replace(/__(.*?)__/g,"$1"),r=r.replace(/\*(.*?)\*/g,"$1"),r=r.replace(/_(.*?)_/g,"$1"),r=r.replace(/~~(.*?)~~/g,"$1"),r=r.replace(/`([^`]+)`/g,"$1"),r=r.replace(/```[\s\S]*?```/g,""),r=r.replace(/^#{1,6}\s+/gm,""),r=r.replace(/\[([^\]]+)\]\([^)]+\)/g,"$1"),r.trim()}}function Lt({title:e,description:t}){console.error(`${e}: ${t}`)}const oy=ie.create($1),sy=ie.create(W1),iy=ie.create(Y1),ay=ie.create(J1);function cy({onClick:e,text:t="Open Chat",position:n="bottom-right",theme:r}){const o={"top-left":"top-4 left-4","top-right":"top-4 right-4","bottom-left":"bottom-4 left-4","bottom-right":"bottom-4 right-4"},s=Ne(r);return l.jsx(ie.button,{onClick:e,className:`fixed ${o[n]} z-50 px-4 py-2 rounded-full shadow-lg ${s.popupTrigger} transition-all duration-200 hover:scale-105`,initial:{scale:0,opacity:0},animate:{scale:1,opacity:1},exit:{scale:0,opacity:0},whileHover:{scale:1.05},whileTap:{scale:.95},children:t})}function Ga({children:e,theme:t,displayType:n="widget",onClose:r,popupPosition:o="bottom-right",onExpand:s}){const i=Ne(t);if(n==="fullscreen")return l.jsx("div",{className:"fixed inset-0 z-[9999] bg-black/40 bg-opacity-30 backdrop-blur-sm flex items-center justify-center p-8",onClick:a=>{a.target===a.currentTarget&&r&&r()},children:l.jsxs("div",{className:"w-full h-full max-w-6xl max-h-[90vh] rounded-2xl relative bg-transparent",onClick:a=>{a.stopPropagation()},children:[r&&l.jsx("button",{onClick:a=>{a.preventDefault(),a.stopPropagation(),r()},className:"absolute top-4 cursor-pointer right-4 z-[10000] w-12 h-12 rounded-full bg-gray-900 bg-opacity-90 text-white flex items-center justify-center hover:bg-gray-800 transition-all duration-200 shadow-lg border border-gray-700 backdrop-blur-sm",title:"Exit Fullscreen",type:"button",children:l.jsx("svg",{width:"20",height:"20",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",children:l.jsx("path",{d:"M8 3H5a2 2 0 0 0-2 2v3m18 0V5a2 2 0 0 0-2-2h-3m0 18h3a2 2 0 0 0 2-2v-3M3 16v3a2 2 0 0 0 2 2h3"})})}),l.jsxs("div",{id:"voice-card",className:`theme-${t} ${i.card} w-full h-full flex flex-col rounded-xl shadow-2xl`,style:{minHeight:"600px"},children:[l.jsx("div",{className:i.cardTopGradient}),l.jsx("div",{className:i.cardPurpleBlur}),l.jsx("div",{className:i.cardPinkBlur}),l.jsx("div",{className:" flex flex-col h-full w-full",children:e}),l.jsx("div",{className:i.cardPulse1}),l.jsx("div",{className:i.cardPulse2,style:{animationDelay:"1s"}})]})]})});if(n==="popup"){const a={"top-left":"top-4 left-4","top-right":"top-4 right-4","bottom-left":"bottom-4 left-4","bottom-right":"bottom-4 right-4"};return l.jsx("div",{className:"fixed rounded-2xl inset-0 z-[9999] pointer-events-none",children:l.jsxs("div",{className:`fixed rounded-2xl ${a[o]} pointer-events-auto`,children:[r&&l.jsx("button",{onClick:r,className:"absolute -top-2 -right-2 z-10 w-8 h-8 rounded-full bg-gray-900 bg-opacity-90 text-white flex items-center justify-center hover:bg-gray-800 transition-all duration-200 text-sm shadow-lg border border-gray-700",children:"ร"}),l.jsxs("div",{id:"voice-card",className:`theme-${t} ${i.card} rounded-2xl flex flex-col`,style:{width:"300px",height:"450px"},children:[l.jsx("div",{className:i.cardPurpleBlur}),l.jsx("div",{className:i.cardPinkBlur}),l.jsx("div",{className:" flex flex-col h-full w-full",children:e}),l.jsx("div",{className:i.cardPulse1}),l.jsx("div",{className:i.cardPulse2,style:{animationDelay:"1s"}})]})]})})}return l.jsxs("div",{id:"voice-card",className:`theme-${t} ${i.card}`,style:{height:"100%",maxHeight:"100%"},children:[s&&l.jsx("button",{onClick:s,className:"absolute top-4 right-4 z-20 w-10 h-10 rounded-full bg-gray-900 bg-opacity-90 text-white flex items-center justify-center hover:bg-gray-800 transition-all duration-200 shadow-lg border border-gray-700 backdrop-blur-sm",title:"Enter Fullscreen",children:l.jsx("svg",{width:"16",height:"16",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",children:l.jsx("path",{d:"M15 3h6v6M9 21H3v-6M21 3l-7 7M3 21l7-7"})})}),l.jsx("div",{className:i.cardTopGradient}),l.jsx("div",{className:i.cardPurpleBlur}),l.jsx("div",{className:i.cardPinkBlur}),e,l.jsx("div",{className:i.cardPulse1}),l.jsx("div",{className:i.cardPulse2,style:{animationDelay:"1s"}})]})}function bd(e){if(typeof window>"u")return null;console.log("๐ฏ Widget component rendering with props:",{displayType:e.displayType,popupPosition:e.popupPosition,theme:e.theme});const{agentId:t,participantName:n,baseUrl:r,appSecret:o,appId:s,prompts:i,statusMessage:a,welcomeTitle:c,welcomeSubTitle:d,className:u,width:f,height:h,loadingText:x,suportsChatInput:y=!0,suportsVideoInput:m=!0,suportsScreenShare:b=!0,theme:C="vox",onSessionStart:v,onSessionEnd:T,enableSessionLogging:k=!0,onSessionLogsUpdate:S,onSessionMetricsUpdate:j,modalities:P=["voice"],displayType:A="widget",popupPosition:_="bottom-right",popupTriggerText:p="Open Chat",onPopupToggle:V,voxketClient:B,onDisplayTypeChange:G}=e,[te,ne]=g.useState(()=>B?!!B.getCurrentSession():!1),[oe,X]=g.useState(!1),[I,q]=g.useState(t||""),[M,z]=g.useState(n||"User"),[Q,W]=g.useState(()=>B?B.getCurrentSession():null),[U,E]=g.useState(()=>{var re,qe,We;if(B){const Se=B.getCurrentSession();if((re=Se==null?void 0:Se.activeModalities)!=null&&re.includes("chat"))return"chat";if((qe=Se==null?void 0:Se.activeModalities)!=null&&qe.includes("voice"))return"voice";if((We=Se==null?void 0:Se.activeModalities)!=null&&We.includes("video"))return"video"}return"welcome"}),[D,O]=g.useState(!1);g.useEffect(()=>{console.log("๐ฏ Widget displayType prop changed to:",A)},[A]),g.useEffect(()=>{console.log("๐ Session state changed:",{currentMode:U,sessionStarted:te,loading:oe,currentSession:Q==null?void 0:Q.id,isPopupOpen:D})},[U,te,oe,Q,D]);const $=g.useMemo(()=>{if(B)return console.log("๐ Using passed VoxketClient to preserve session state"),B;console.log("๐ Creating new VoxketClient instance");const re={appId:s,appSecret:o,baseUrl:r,agentId:I,participantName:M||"User",modalities:P};return new Rn(re)},[B,s,o,r,I,M,P]),F=P,L=g.useMemo(()=>$.getRoom()||new H.Room,[$]),J={suportsChatInput:y,suportsVideoInput:m,suportsScreenShare:b},{sessionMetrics:R,sessionLogs:ce,logEvent:xe}=md({room:L,onSessionStart:v,onSessionEnd:T,enableConsoleLogging:k,enableLocalStorage:k,voxketSessionId:Q==null?void 0:Q.id});g.useEffect(()=>{S&&S(ce)},[ce,S]),g.useEffect(()=>{j&&R&&j(R)},[R,j]),g.useEffect(()=>{const re=We=>{console.log("๐ด Room disconnected:",We),X(!1),ne(!1),W(null),E("welcome")},qe=We=>{console.log("๐น Media devices error:",We),Lt({title:"Allow access to your microphone/camera",description:`${We.name}: ${We.message}`})};return L.on(H.RoomEvent.MediaDevicesError,qe),L.on(H.RoomEvent.Disconnected,re),()=>{L.off(H.RoomEvent.Disconnected,re),L.off(H.RoomEvent.MediaDevicesError,qe)}},[L]);const pe=async()=>{try{console.log("๐ค Starting voice session...",{agentId:I,participantName:M}),console.log("๐ค Pre-start state:",{currentMode:U,sessionStarted:te,loading:oe}),X(!0),ne(!0),E("voice"),console.log("๐ค State after mode change:",{currentMode:"voice",sessionStarted:!0,loading:!0}),xe("USER_STARTED_VOICE_SESSION",{agentId:I,participantName:M});const re=await $.startSession(I,{participantName:M||"User",modalities:["voice",...m?["video"]:[]]});console.log("โ
Voice session started successfully:",re.id),W(re),X(!1),v&&v(re.id)}catch(re){console.error("โ Failed to start voice session:",re),Lt({title:"Failed to start voice session",description:re instanceof Error?re.message:"Unknown error occurred"}),X(!1),ne(!1),E("welcome")}},Re=async()=>{try{X(!0),ne(!0),E("chat"),xe("USER_STARTED_CHAT_SESSION",{agentId:I,participantName:M});const re=await $.startSession(I,{participantName:M||"User",modalities:["chat"]});W(re),X(!1),v&&v(re.id)}catch(re){console.error("Failed to start chat session:",re),Lt({title:"Failed to start chat session",description:re instanceof Error?re.message:"Unknown error occurred"}),X(!1),ne(!1),E("welcome")}},tt=async()=>{try{console.log("๐บ Starting video session...",{agentId:I,participantName:M}),console.log("๐บ Pre-start state:",{currentMode:U,sessionStarted:te,loading:oe}),X(!0),ne(!0),E("video"),console.log("๐บ State after mode change:",{currentMode:"video",sessionStarted:!0,loading:!0}),xe("USER_STARTED_VIDEO_SESSION",{agentId:I,participantName:M});const re=await $.startSession(I,{participantName:M||"User",modalities:["video","voice"]});console.log("โ
Video session started successfully:",re.id),W(re),X(!1),v&&v(re.id)}catch(re){console.error("โ Failed to start video session:",re),Lt({title:"Failed to start video session",description:re instanceof Error?re.message:"Unknown error occurred"}),X(!1),ne(!1),E("welcome")}},dt=()=>{E("welcome"),G&&G(e.displayType||"widget"),Q&&te&&(ne(!1),W(null),$.disconnect()),A==="popup"&&!D&&O(!0)},an=()=>{const re=!D;O(re),V&&V(re),!re&&!(Q&&te)&&(E("welcome"),ne(!1),W(null))},Dd=()=>{console.log("๐ Closing fullscreen, switching to widget display type"),e.onDisplayTypeChange?e.onDisplayTypeChange("widget"):console.warn("โ ๏ธ No onDisplayTypeChange callback provided")},$d=()=>{if(console.log("๐ Expand to fullscreen requested"),e.onDisplayTypeChange)e.onDisplayTypeChange("fullscreen");else{console.warn("โ ๏ธ No onDisplayTypeChange callback provided for expand functionality");const re=document.getElementById("voice-card")||document.querySelector(".voxket-widget-container");re&&re.requestFullscreen?re.requestFullscreen().catch(qe=>{console.warn("โ ๏ธ Fullscreen API not supported or failed:",qe),Lt({title:"Expand functionality unavailable",description:"Please implement onDisplayTypeChange callback for expand functionality"})}):Lt({title:"Expand functionality unavailable",description:"Please implement onDisplayTypeChange callback for expand functionality"})}};g.useEffect(()=>{var re,qe,We;if(B&&$){console.log("๐ Syncing widget state with existing client session state");const Se=$.getCurrentSession(),Fd=$.connected;console.log("๐ Existing session state:",{hasSession:!!Se,sessionId:Se==null?void 0:Se.id,isConnected:Fd,activeModalities:Se==null?void 0:Se.activeModalities}),Se&&(console.log("โ
Restoring session state from existing client"),W(Se),ne(!0),X(!1),(re=Se.activeModalities)!=null&&re.includes("chat")?E("chat"):(qe=Se.activeModalities)!=null&&qe.includes("voice")?E("voice"):(We=Se.activeModalities)!=null&&We.includes("video")&&E("video"))}},[B,$]),g.useEffect(()=>()=>{console.log("๐งน Cleaning up widget component"),B?console.log("๐ Widget cleanup: preserving passed client instance"):(console.log("๐งน Widget cleanup: disconnecting self-created client"),$.disconnect())},[$,B]);let Tr="w-96",Ar="h-[25rem]",jr={};if(f&&(f.startsWith("w-")?Tr=f:(jr.width=f,Tr="")),h&&(h.startsWith("h-")?Ar=h:(jr.height=h,Ar="")),A==="popup"&&!D)return console.log("๐ก Showing popup trigger button"),l.jsx(cy,{onClick:an,text:p,position:_,theme:C});console.log("๐ข Rendering widget content, displayType:",A,"isPopupOpen:",D,"currentMode:",U,"sessionStarted:",te,"loading:",oe);let Pr=`voxket-widget-root theme-${C}`,Dn={scrollMargin:0,scrollPadding:0,contain:"layout style paint"};A==="widget"?(Pr+=` flex items-center justify-center min-h-fit ${Tr} ${Ar} ${u}`,Dn={...Dn,...jr}):(Pr+=` ${u||""}`,Dn={});const Fs=l.jsx("div",{className:"h-full w-full flex flex-col overflow-hidden",children:l.jsxs(Wt,{mode:"wait",children:[U==="welcome"&&!oe&&l.jsx(ay,{agentId:I,participantName:M||"",onAgentIdChange:q,onParticipantNameChange:z,onStartCall:pe,onStartChat:Re,onStartVideo:tt,disabled:te||oe,prompts:i,statusMessage:a,title:c,subTitle:d,theme:C,modalities:F,displayType:A,initial:{opacity:0,y:0},animate:{opacity:1,y:0},exit:{opacity:0,y:40},transition:{duration:.3,ease:"easeInOut"}},"welcome"),U==="voice"&&l.jsxs(Ie.RoomContext.Provider,{value:L,children:[l.jsx(Ie.RoomAudioRenderer,{}),l.jsx(Ie.StartAudio,{label:"Start Audio"}),l.jsx(oy,{loadingText:x,participantName:M||"User",capabilities:J,sessionStarted:te,disabled:!te,theme:C,client:$,displayType:A,onBack:A==="popup"?an:dt,initial:{opacity:0,y:40},animate:{opacity:1,y:0},exit:{opacity:0,y:-40},transition:{duration:.3,ease:"easeInOut"}},"session-view")]}),U==="chat"&&l.jsx(sy,{client:$,theme:C,displayType:A,onBack:A==="popup"?an:dt,onEndChat:dt,disabled:!te,initial:{opacity:0,y:40},animate:{opacity:1,y:0},exit:{opacity:0,y:-40},transition:{duration:.3,ease:"easeInOut"}},"chat-view"),U==="video"&&l.jsxs(Ie.RoomContext.Provider,{value:L,children:[l.jsx(Ie.RoomAudioRenderer,{}),l.jsx(Ie.StartAudio,{label:"Start Audio"}),l.jsx(iy,{client:$,theme:C,displayType:A,onBack:A==="popup"?an:dt,onEndCall:dt,disabled:!te,initial:{opacity:0,y:40},animate:{opacity:1,y:0},exit:{opacity:0,y:-40},transition:{duration:.3,ease:"easeInOut"}},"video-view")]})]})});return A==="fullscreen"||A==="popup"?(console.log("๐ฑ Rendering fullscreen/popup mode, displayType:",A),l.jsx(Ga,{theme:C,displayType:A,popupPosition:_,onClose:A==="fullscreen"?Dd:an,children:Fs})):(console.log("๐ฆ Rendering widget mode"),l.jsx("div",{className:Pr,style:Dn,children:l.jsx(Ga,{theme:C,displayType:A,popupPosition:_,onExpand:$d,children:Fs})}))}class vd extends g.Component{constructor(t){super(t),this.state={hasError:!1}}static getDerivedStateFromError(t){return{hasError:!0,error:t}}componentDidCatch(t,n){console.error("VoxketWidget Error:",t,n)}render(){if(this.state.hasError){if(this.props.fallback){const t=this.props.fallback;return g.createElement(t,{error:this.state.error})}return g.createElement("div",{style:{padding:"20px",border:"1px solid #ff4444",borderRadius:"8px",background:"#fff5f5",color:"#cc0000"}},"VoxketWidget encountered an error. Please check the console for details.")}return this.props.children}}function ly({logs:e,onClear:t,onExport:n}){const[r,o]=w.useState(!1),[s,i]=w.useState(""),a=e.filter(c=>!s||c.event.toLowerCase().includes(s.toLowerCase()));return r?l.jsx("div",{className:"fixed inset-0 bg-black bg-opacity-50 flex items-center justify-center z-50",children:l.jsxs("div",{className:"bg-white rounded-lg shadow-xl max-w-4xl w-full max-h-[80vh] flex flex-col m-4",children:[l.jsxs("div",{className:"flex items-center justify-between p-4 border-b",children:[l.jsxs("h2",{className:"text-lg font-semibold",children:["Session Logs (",e.length,")"]}),l.jsxs("div",{className:"flex items-center gap-2",children:[l.jsx("input",{type:"text",placeholder:"Filter events...",value:s,onChange:c=>i(c.target.value),className:"px-3 py-1 border rounded text-sm"}),l.jsx("button",{onClick:t,className:"px-3 py-1 bg-red-600 text-white rounded text-sm hover:bg-red-700",children:"Clear"}),l.jsx("button",{onClick:n,className:"px-3 py-1 bg-green-600 text-white rounded text-sm hover:bg-green-700",children:"Export"}),l.jsx("button",{onClick:()=>o(!1),className:"px-3 py-1 bg-gray-600 text-white rounded text-sm hover:bg-gray-700",children:"Close"})]})]}),l.jsx("div",{className:"flex-1 overflow-auto p-4",children:a.length===0?l.jsx("p",{className:"text-gray-500 text-center py-8",children:"No logs found"}):l.jsx("div",{className:"space-y-2",children:a.map((c,d)=>l.jsxs("div",{className:"border rounded p-3 text-sm",children:[l.jsxs("div",{className:"flex items-center justify-between mb-1",children:[l.jsx("span",{className:"font-semibold text-blue-600",children:c.event}),l.jsx("span",{className:"text-gray-500 text-xs",children:new Date(c.timestamp).toLocaleTimeString()})]}),c.sessionId&&l.jsxs("div",{className:"text-xs text-gray-600 mb-1",children:["Session: ",c.sessionId]}),c.data&&l.jsx("div",{className:"bg-gray-50 p-2 rounded text-xs",children:l.jsx("pre",{className:"whitespace-pre-wrap overflow-auto",children:JSON.stringify(c.data,null,2)})})]},d))})})]})}):l.jsxs("button",{onClick:()=>o(!0),className:"fixed bottom-4 right-4 bg-blue-600 text-white px-4 py-2 rounded-lg shadow-lg hover:bg-blue-700 transition-colors text-sm z-50",children:["Session Logs (",e.length,")"]})}function dy({metrics:e}){return e?l.jsxs("div",{className:"bg-gray-100 p-4 rounded-lg",children:[l.jsx("h3",{className:"font-semibold mb-2",children:"Current Session"}),l.jsxs("div",{className:"grid grid-cols-2 gap-4 text-sm",children:[l.jsxs("div",{children:[l.jsx("span",{className:"text-gray-600",children:"Session ID:"}),l.jsx("div",{className:"font-mono text-xs",children:e.sessionId})]}),l.jsxs("div",{children:[l.jsx("span",{className:"text-gray-600",children:"Start Time:"}),l.jsx("div",{children:new Date(e.startTime).toLocaleString()})]}),l.jsxs("div",{children:[l.jsx("span",{className:"text-gray-600",children:"Messages:"}),l.jsx("div",{children:e.totalMessages})]}),l.jsxs("div",{children:[l.jsx("span",{className:"text-gray-600",children:"Participants:"}),l.jsx("div",{children:e.participantCount})]}),l.jsxs("div",{children:[l.jsx("span",{className:"text-gray-600",children:"Connection Issues:"}),l.jsx("div",{children:e.connectionIssues})]}),l.jsxs("div",{children:[l.jsx("span",{className:"text-gray-600",children:"Duration:"}),l.jsxs("div",{children:[Math.round((Date.now()-new Date(e.startTime).getTime())/1e3),"s"]})]})]})]}):null}function Vt(){const{currentSession:e,sessionState:t,sessionMetrics:n,createSession:r,endSession:o}=et(),s=w.useCallback(async(a,c)=>await r(a,c),[r]),i=w.useCallback(async()=>await o(),[o]);return{session:e,state:t,metrics:n,isActive:e!==null&&t!=="disconnected",isConnecting:t==="connecting",isConnected:t==="connected"||t==="active",start:s,stop:i}}function wd(){const{sessionMetrics:e,currentSession:t}=et();return{metrics:e,sessionId:t==null?void 0:t.id,duration:e==null?void 0:e.duration,participantCount:e==null?void 0:e.participantCount,messageCount:e==null?void 0:e.messageCount,audioQuality:e==null?void 0:e.audioQuality,networkStats:e==null?void 0:e.networkStats}}function Sd(){const{setMicrophoneEnabled:e,client:t}=et(),[n,r]=w.useState(!1),[o,s]=w.useState(!1),i=w.useCallback(async()=>{if(!o){s(!0);try{const d=!n;await e(d),r(d)}catch(d){console.error("Failed to toggle microphone:",d)}finally{s(!1)}}},[n,o,e]),a=w.useCallback(async()=>{if(!(n||o)){s(!0);try{await e(!0),r(!0)}catch(d){console.error("Failed to enable microphone:",d)}finally{s(!1)}}},[n,o,e]),c=w.useCallback(async()=>{if(!(!n||o)){s(!0);try{await e(!1),r(!1)}catch(d){console.error("Failed to disable microphone:",d)}finally{s(!1)}}},[n,o,e]);return{isEnabled:n,isLoading:o,toggle:i,enable:a,disable:c}}function kd(){const{setCameraEnabled:e}=et(),[t,n]=w.useState(!1),[r,o]=w.useState(!1),s=w.useCallback(async()=>{if(!r){o(!0);try{const c=!t;await e(c),n(c)}catch(c){console.error("Failed to toggle camera:",c)}finally{o(!1)}}},[t,r,e]),i=w.useCallback(async()=>{if(!(t||r)){o(!0);try{await e(!0),n(!0)}catch(c){console.error("Failed to enable camera:",c)}finally{o(!1)}}},[t,r,e]),a=w.useCallback(async()=>{if(!(!t||r)){o(!0);try{await e(!1),n(!1)}catch(c){console.error("Failed to disable camera:",c)}finally{o(!1)}}},[t,r,e]);return{isEnabled:t,isLoading:r,toggle:s,enable:i,disable:a}}function Cd(){const{startScreenShare:e,stopScreenShare:t}=et(),[n,r]=w.useState(!1),[o,s]=w.useState(!1),i=w.useCallback(async()=>{if(!(n||o)){s(!0);try{await e(),r(!0)}catch(d){console.error("Failed to start screen share:",d)}finally{s(!1)}}},[n,o,e]),a=w.useCallback(async()=>{if(!(!n||o)){s(!0);try{await t(),r(!1)}catch(d){console.error("Failed to stop screen share:",d)}finally{s(!1)}}},[n,o,t]),c=w.useCallback(async()=>{n?await a():await i()},[n,i,a]);return{isSharing:n,isLoading:o,start:i,stop:a,toggle:c}}function uy(){const{client:e}=et(),[t,n]=w.useState({tracks:[],layout:{type:"grid",showLocalVideo:!0,aspectRatio:"16:9"},isRecording:!1}),r=w.useMemo(()=>t.tracks.find(m=>m.isLocal),[t.tracks]),o=w.useMemo(()=>t.tracks.filter(m=>!m.isLocal),[t.tracks]),s=w.useCallback(async()=>{try{r!=null&&r.isEnabled?await(e==null?void 0:e.disableCamera()):await(e==null?void 0:e.enableCamera())}catch(m){throw console.error("Failed to toggle camera:",m),m}},[e,r]),i=w.useCallback(async()=>{try{t.tracks.find(b=>b.isScreenShare)?await(e==null?void 0:e.stopScreenShare()):await(e==null?void 0:e.startScreenShare())}catch(m){throw console.error("Failed to toggle screen share:",m),m}},[e,t.tracks]),a=w.useCallback(m=>{n(b=>({...b,layout:m}))},[]),c=w.useCallback(m=>{n(b=>({...b,pinnedTrack:m}))},[]),d=w.useCallback(()=>{n(m=>({...m,pinnedTrack:void 0}))},[]),u=w.useCallback(async()=>{try{await(e==null?void 0:e.startRecording()),n(m=>({...m,isRecording:!0}))}catch(m){throw console.error("Failed to start recording:",m),m}},[e]),f=w.useCallback(async()=>{try{await(e==null?void 0:e.stopRecording()),n(m=>({...m,isRecording:!1}))}catch(m){throw console.error("Failed to stop recording:",m),m}},[e]),h=w.useCallback(m=>t.tracks.find(b=>b.id===m),[t.tracks]),x=w.useCallback(m=>t.tracks.filter(b=>b.participantId===m),[t.tracks]),y=w.useCallback(m=>m.isEnabled&&t.tracks.includes(m),[t.tracks]);return w.useEffect(()=>{if(!e)return;const m=v=>{n(T=>({...T,tracks:[...T.tracks.filter(k=>k.id!==v.id),v]}))},b=v=>{n(T=>{var k;return{...T,tracks:T.tracks.filter(S=>S.id!==v),pinnedTrack:((k=T.pinnedTrack)==null?void 0:k.id)===v?void 0:T.pinnedTrack}})},C=v=>{n(T=>({...T,tracks:T.tracks.map(k=>k.id===v.id?v:k)}))};return e.on("videoTrackAdded",m),e.on("videoTrackRemoved",b),e.on("videoTrackUpdated",C),()=>{e.off("videoTrackAdded",m),e.off("videoTrackRemoved",b),e.off("videoTrackUpdated",C)}},[e]),{tracks:t.tracks,localTrack:r,remoteTraracks:o,pinnedTrack:t.pinnedTrack,layout:t.layout,isRecording:t.isRecording,toggleCamera:s,toggleScreenShare:i,setLayout:a,pinTrack:c,unpinTrack:d,startRecording:u,stopRecording:f,getTrackById:h,getTracksByParticipant:x,isTrackActive:y}}function Er(){const{chatMessages:e,sendChatMessage:t,currentSession:n}=et(),[r,o]=w.useState(!1),s=w.useCallback(async d=>{if(!(!d.trim()||r||!n)){o(!0);try{await t(d.trim())}catch(u){throw console.error("Failed to send chat message:",u),u}finally{o(!1)}}},[t,r,n]),{userMessages:i,agentMessages:a,allMessages:c}=w.useMemo(()=>{const d=e.filter(f=>f.sender.type==="participant"),u=e.filter(f=>f.sender.type==="agent");return{userMessages:d,agentMessages:u,allMessages:e}},[e]);return{messages:c,userMessages:i,agentMessages:a,messageCount:c.length,isSending:r,canSend:!!n&&!r,send:s}}function fy(){const{send:e,isSending:t,canSend:n}=Er(),[r,o]=w.useState(""),s=w.useCallback(async()=>{if(!(!r.trim()||!n))try{await e(r),o("")}catch(a){throw a}},[r,e,n]),i=w.useCallback(a=>{a.key==="Enter"&&!a.shiftKey&&(a.preventDefault(),s())},[s]);return{value:r,setValue:o,send:s,handleKeyPress:i,isSending:t,canSend:n&&r.trim().length>0}}function Rs(){const{isConnected:e,isConnecting:t,connectionError:n,connect:r,disconnect:o}=et(),s=w.useCallback(async()=>{if(!(e||t))try{await r()}catch(a){throw console.error("Failed to connect:",a),a}},[r,e,t]),i=w.useCallback(async()=>{if(e)try{await o()}catch(a){throw console.error("Failed to disconnect:",a),a}},[o,e]);return{isConnected:e,isConnecting:t,isDisconnected:!e&&!t,error:n,hasError:!!n,connect:s,disconnect:i}}function Ed(){const{participants:e}=et();return{participants:e,count:e.length,localParticipant:e.find(t=>t.isLocal),remoteParticipants:e.filter(t=>!t.isLocal)}}const Td=w.createContext({}),In=()=>w.useContext(Td);function Ad({children:e,...t}){return l.jsx(Td.Provider,{value:t,children:e})}function Qn({name:e,children:t,fallback:n,className:r}){return l.jsx("div",{className:`voxket-slot voxket-slot--${e} ${r||""}`,children:t||n})}function jd(e,t={}){return Object.assign(e,t)}function Pd({showMicrophoneControl:e=!0,showCameraControl:t=!0,showScreenShareControl:n=!0,showSessionActions:r=!0,customControls:o,className:s=""}){const i=Vt(),a=Sd(),c=kd(),d=Cd(),u=In(),f=["voxket-session-controls",`voxket-session-controls--${u.variant||"default"}`,`voxket-session-controls--${u.size||"md"}`,i.isActive?"voxket-session-controls--active":"voxket-session-controls--inactive",s].filter(Boolean).join(" ");return!i.isActive&&!r?l.jsx("div",{className:f,children:l.jsx("div",{className:"voxket-controls-inactive",children:l.jsx("p",{children:"Controls available during active session"})})}):l.jsxs("div",{className:f,children:[r&&l.jsx("div",{className:"voxket-session-actions",children:i.isActive?l.jsx("button",{onClick:i.stop,className:"voxket-button voxket-button--danger",children:"End Session"}):l.jsx(hy,{})}),i.isActive&&l.jsxs("div",{className:"voxket-media-controls",children:[e&&l.jsxs("button",{onClick:a.toggle,disabled:a.isLoading,className:`voxket-button voxket-button--media ${a.isEnabled?"voxket-button--active":""}`,title:a.isEnabled?"Mute microphone":"Unmute microphone",children:[l.jsx("span",{className:"voxket-icon",children:"๐ค"}),a.isLoading?"Loading...":a.isEnabled?"Mute":"Unmute"]}),t&&l.jsxs("button",{onClick:c.toggle,disabled:c.isLoading,className:`voxket-button voxket-button--media ${c.isEnabled?"voxket-button--active":""}`,title:c.isEnabled?"Stop camera":"Start camera",children:[l.jsx("span",{className:"voxket-icon",children:"๐น"}),c.isLoading?"Loading...":c.isEnabled?"Stop Video":"Start Video"]}),n&&l.jsxs("button",{onClick:d.toggle,disabled:d.isLoading,className:`voxket-button voxket-button--media ${d.isSharing?"voxket-button--active":""}`,title:d.isSharing?"Stop screen share":"Start screen share",children:[l.jsx("span",{className:"voxket-icon",children:"๐ฅ๏ธ"}),d.isLoading?"Loading...":d.isSharing?"Stop Share":"Share Screen"]})]}),o&&l.jsx("div",{className:"voxket-custom-controls",children:o})]})}function hy(){Vt();const[e,t]=w.useState(!1),n=async()=>{t(!0);try{console.log("Start session - agentId needed")}catch(r){console.error("Failed to start session:",r)}finally{t(!1)}};return l.jsx("button",{onClick:n,disabled:e,className:"voxket-button voxket-button--primary",children:e?"Starting...":"Start Session"})}function Is({showConnectionStatus:e=!0,showSessionInfo:t=!0,showAgentInfo:n=!0,className:r=""}){const o=Vt(),s=Rs(),i=In(),a=["voxket-session-header",`voxket-session-header--${i.variant||"default"}`,`voxket-session-header--${i.size||"md"}`,r].filter(Boolean).join(" ");return l.jsxs("div",{className:a,children:[e&&l.jsxs("div",{className:"voxket-connection-status",children:[l.jsx("div",{className:`voxket-status-indicator ${s.isConnected?"connected":"disconnected"}`}),l.jsx("span",{className:"voxket-status-text",children:s.isConnecting?"Connecting...":s.isConnected?"Connected":"Disconnected"})]}),t&&o.session&&l.jsxs("div",{className:"voxket-session-info",children:[l.jsxs("div",{className:"voxket-session-id",children:["Session: ",o.session.id.slice(-8)]}),l.jsxs("div",{className:"voxket-session-state",children:["State: ",o.state]})]}),n&&o.session&&l.jsxs("div",{className:"voxket-agent-info",children:[l.jsxs("div",{className:"voxket-agent-id",children:["Agent: ",o.session.agentId]}),l.jsxs("div",{className:"voxket-modalities",children:["Modalities: ",o.session.activeModalities.join(", ")]})]}),s.error&&l.jsxs("div",{className:"voxket-error-message",children:["Error: ",s.error.message]})]})}function Ds({showChat:e=!0,showTranscriptions:t=!1,customContent:n,className:r=""}){const o=Vt(),s=Er(),i=In(),a=["voxket-session-content",`voxket-session-content--${i.variant||"default"}`,`voxket-session-content--${i.size||"md"}`,r].filter(Boolean).join(" ");return o.isActive?l.jsx("div",{className:a,children:n||l.jsxs(l.Fragment,{children:[e&&l.jsxs("div",{className:"voxket-chat-container",children:[l.jsxs("div",{className:"voxket-chat-messages",children:[s.messages.map(c=>l.jsxs("div",{className:`voxket-message voxket-message--${c.sender.type}`,children:[l.jsxs("div",{className:"voxket-message-header",children:[l.jsx("span",{className:"voxket-message-sender",children:c.sender.name}),l.jsx("span",{className:"voxket-message-time",children:c.timestamp.toLocaleTimeString()})]}),l.jsx("div",{className:"voxket-message-content",children:c.content})]},c.id)),s.messages.length===0&&l.jsx("div",{className:"voxket-empty-messages",children:l.jsx("p",{children:"No messages yet. Start the conversation!"})})]}),l.jsx(my,{})]}),t&&l.jsx("div",{className:"voxket-transcriptions",children:l.jsx("div",{className:"voxket-transcription-placeholder",children:l.jsx("p",{children:"Voice transcriptions will appear here"})})})]})}):l.jsx("div",{className:a,children:l.jsx("div",{className:"voxket-inactive-state",children:l.jsxs("div",{className:"voxket-inactive-message",children:[l.jsx("h3",{children:"Start a conversation"}),l.jsx("p",{children:"Begin a session to start chatting with the AI agent"})]})})})}function my(){const e=Er(),[t,n]=w.useState(""),r=async()=>{if(!(!t.trim()||!e.canSend))try{await e.send(t),n("")}catch(s){console.error("Failed to send message:",s)}},o=s=>{s.key==="Enter"&&!s.shiftKey&&(s.preventDefault(),r())};return l.jsxs("div",{className:"voxket-chat-input",children:[l.jsx("input",{type:"text",value:t,onChange:s=>n(s.target.value),onKeyPress:o,placeholder:"Type your message...",disabled:!e.canSend,className:"voxket-input"}),l.jsx("button",{onClick:r,disabled:!e.canSend||!t.trim(),className:"voxket-send-button",children:e.isSending?"Sending...":"Send"})]})}function $s({showMetrics:e=!0,showParticipants:t=!0,showStatus:n=!0,customFooter:r,className:o=""}){const s=Vt(),i=wd(),a=Ed(),c=In(),d=["voxket-session-footer",`voxket-session-footer--${c.variant||"default"}`,`voxket-session-footer--${c.size||"md"}`,o].filter(Boolean).join(" ");return s.isActive?l.jsx("div",{className:d,children:r||l.jsxs(l.Fragment,{children:[n&&l.jsxs("div",{className:"voxket-session-status",children:[l.jsx("div",{className:"voxket-status-indicator voxket-status-indicator--active"}),l.jsx("span",{className:"voxket-status-text",children:"Session Active"})]}),e&&i.metrics&&l.jsxs("div",{className:"voxket-session-metrics",children:[l.jsxs("div",{className:"voxket-metric",children:[l.jsx("span",{className:"voxket-metric-label",children:"Duration:"}),l.jsx("span",{className:"voxket-metric-value",children:gy(i.duration||0)})]}),l.jsxs("div",{className:"voxket-metric",children:[l.jsx("span",{className:"voxket-metric-label",children:"Messages:"}),l.jsx("span",{className:"voxket-metric-value",children:i.metrics.messageCount})]})]}),t&&l.jsxs("div",{className:"voxket-participants-info",children:[l.jsxs("span",{className:"voxket-participants-count",children:[a.count," participant",a.count!==1?"s":""]}),a.remoteParticipants.length>0&&l.jsx("div",{className:"voxket-participant-list",children:a.remoteParticipants.map(u=>l.jsx("span",{className:"voxket-participant-name",children:u.name},u.id))})]})]})}):l.jsx("div",{className:d,children:l.jsx("div",{className:"voxket-footer-inactive",children:l.jsx("span",{className:"voxket-status-text",children:"Ready to start session"})})})}function gy(e){const t=Math.floor(e/1e3),n=Math.floor(t/60),r=Math.floor(n/60);return r>0?`${r}:${(n%60).toString().padStart(2,"0")}:${(t%60).toString().padStart(2,"0")}`:`${n}:${(t%60).toString().padStart(2,"0")}`}function py({agentId:e,sessionConfig:t,autoStart:n=!1,onSessionStart:r,onSessionEnd:o,variant:s="default",size:i="md",theme:a,className:c="",children:d}){var x;const u=Vt(),f=Rs();w.useEffect(()=>{n&&e&&f.isConnected&&!u.isActive&&u.start(e,t).catch(console.error)},[n,e,f.isConnected,u.isActive]),w.useEffect(()=>{var y;(y=u.session)!=null&&y.id&&r&&r(u.session.id)},[(x=u.session)==null?void 0:x.id,r]),w.useEffect(()=>()=>{u.isActive&&o&&u.stop().then(o).catch(console.error)},[]);const h=["voxket-session",`voxket-session--${s}`,`voxket-session--${i}`,u.isActive?"voxket-session--active":"voxket-session--inactive",c].filter(Boolean).join(" ");return l.jsx(Ad,{variant:s,size:i,theme:a,className:c,children:l.jsx("div",{className:h,children:d||l.jsxs(l.Fragment,{children:[l.jsx(Qn,{name:"header",fallback:l.jsx(Is,{})}),l.jsx(Qn,{name:"content",fallback:l.jsx(Ds,{})}),l.jsx(Qn,{name:"footer",fallback:l.jsx($s,{})})]})})})}const Md=jd(py,{Header:Is,Content:Ds,Footer:$s,Controls:Pd}),Pt={name:"default",colors:{primary:"#3B82F6",secondary:"#6B7280",accent:"#8B5CF6",background:"#FFFFFF",surface:"#F9FAFB",text:{primary:"#111827",secondary:"#6B7280",muted:"#9CA3AF",inverse:"#FFFFFF"},status:{success:"#10B981",warning:"#F59E0B",error:"#EF4444",info:"#3B82F6"},border:"#E5E7EB",shadow:"0 1px 3px 0 rgba(0, 0, 0, 0.1)"},typography:{fontFamily:"system-ui, -apple-system, sans-serif",fontSize:{xs:"0.75rem",sm:"0.875rem",md:"1rem",lg:"1.125rem",xl:"1.25rem"},fontWeight:{normal:400,medium:500,semibold:600,bold:700},lineHeight:{tight:1.25,normal:1.5,relaxed:1.75}},spacing:{xs:"0.25rem",sm:"0.5rem",md:"1rem",lg:"1.5rem",xl:"2rem"},borderRadius:{none:"0",sm:"0.25rem",md:"0.5rem",lg:"0.75rem",full:"9999px"},shadows:{sm:"0 1px 2px 0 rgba(0, 0, 0, 0.05)",md:"0 4px 6px -1px rgba(0, 0, 0, 0.1)",lg:"0 10px 15px -3px rgba(0, 0, 0, 0.1)"}},Do={...Pt,name:"dark",colors:{primary:"#60A5FA",secondary:"#9CA3AF",accent:"#A78BFA",background:"#111827",surface:"#1F2937",text:{primary:"#F9FAFB",secondary:"#D1D5DB",muted:"#9CA3AF",inverse:"#111827"},status:{success:"#34D399",warning:"#FBBF24",error:"#F87171",info:"#60A5FA"},border:"#374151",shadow:"0 1px 3px 0 rgba(0, 0, 0, 0.3)"}},$o={...Pt,name:"enterprise",colors:{primary:"#1E40AF",secondary:"#64748B",accent:"#7C3AED",background:"#FFFFFF",surface:"#F8FAFC",text:{primary:"#0F172A",secondary:"#475569",muted:"#94A3B8",inverse:"#FFFFFF"},status:{success:"#059669",warning:"#D97706",error:"#DC2626",info:"#1E40AF"},border:"#CBD5E1",shadow:"0 1px 3px 0 rgba(0, 0, 0, 0.1)"},borderRadius:{none:"0",sm:"0.125rem",md:"0.25rem",lg:"0.375rem",full:"9999px"}},Vd=w.createContext(null),Nd=()=>{const e=w.useContext(Vd);if(!e)throw new Error("useTheme must be used within a ThemeProvider");return e};function xy({theme:e="default",themes:t={},children:n,cssVariables:r=!0,className:o=""}){const[s,i]=w.useState(()=>{const h={default:Pt,dark:Do,enterprise:$o,...t};return typeof e=="string"?h[e]||Pt:e}),[a,c]=w.useState(()=>({default:Pt,dark:Do,enterprise:$o,...t})),d=h=>{if(typeof h=="string"){const x=a[h];x&&i(x)}else i(h)},u=h=>{c(x=>({...x,[h.name]:h}))};w.useEffect(()=>{if(r&&typeof document<"u"){const h=document.documentElement;Object.entries(Rd(s)).forEach(([x,y])=>{h.style.setProperty(`--voxket-${x}`,y)})}},[s,r]);const f={theme:s,setTheme:d,themes:a,registerTheme:u};return l.jsx(Vd.Provider,{value:f,children:l.jsx("div",{className:`voxket-theme voxket-theme--${s.name} ${o}`,children:n})})}function Rd(e){const t={},n=(r,o="")=>{for(const[s,i]of Object.entries(r)){const a=o?`${o}-${s}`:s;typeof i=="object"&&i!==null&&!Array.isArray(i)?n(i,a):t[a]=String(i)}};return n(e),t}function yy(e=Pt,t){return{...e,...t,colors:{...e.colors,...t.colors},typography:{...e.typography,...t.typography},spacing:{...e.spacing,...t.spacing},borderRadius:{...e.borderRadius,...t.borderRadius},shadows:{...e.shadows,...t.shadows}}}function by(e){var n;const{theme:t}=Nd();return((n=t.components)==null?void 0:n[e])||{}}const vy=Ns("voice-modality","voice",{onActivate:async e=>{const t=e.config;t.enableTranscription&&wy(e),t.enableVoiceActivation&&Sy(e,t),console.log("Voice modality activated",t)},onDeactivate:async e=>{console.log("Voice modality deactivated")},onMessage:async(e,t)=>{t.type==="audio"&&ky(e,t)}});function wy(e,t){e.on("participant.speaking.started",n=>{console.log("Transcription: Started for",n.name)}),e.on("participant.speaking.stopped",n=>{console.log("Transcription: Stopped for",n.name)})}function Sy(e,t){const n=t.silenceThreshold||-50;console.log("Voice activation setup with threshold:",n)}function ky(e,t){console.log("Playing audio response:",t.content)}const Cy=Ns("chat-modality","chat",{onActivate:async e=>{const t=e.config;t.enableRichText&&Ey(),t.enableFileUpload&&Ty(e),t.enableCustomComponents&&Ay(),console.log("Chat modality activated",t)},onDeactivate:async e=>{console.log("Chat modality deactivated")},onMessage:async(e,t)=>{const n=e.config;t.type==="ui_component"?jy(e,t):t.type==="text"&&n.enableRichText&&Py(e,t)}});function Ey(e){console.log("Rich text support enabled")}function Ty(e){console.log("File upload enabled"),e.on("chat.file.uploaded",t=>{console.log("File uploaded:",t.name)})}function Ay(e){console.log("Custom components enabled");const t=new Map;t.set("quick-actions",My),t.set("form",Vy),t.set("card",Ny),t.set("chart",Ry)}function jy(e,t){const{componentType:n,props:r}=t.metadata;console.log("Rendering custom component:",n,r),e.emit("chat.component.render",{type:n,props:r,timestamp:new Date})}function Py(e,t){console.log("Processing rich text message:",t.content)}function My(e){return{type:"quick-actions",actions:e.actions||[],layout:e.layout||"horizontal"}}function Vy(e){return{type:"form",fields:e.fields||[],submitAction:e.submitAction,validation:e.validation}}function Ny(e){return{type:"card",title:e.title,content:e.content,actions:e.actions,variant:e.variant||"default"}}function Ry(e){return{type:"chart",chartType:e.chartType||"line",data:e.data,options:e.options}}function er({track:e,participantName:t,showControls:n=!0,showName:r=!0,showMuteIndicator:o=!0,isPinned:s=!1,className:i="",onClick:a,onPin:c,onUnpin:d}){const u=w.useRef(null),[f,h]=w.useState(!1);w.useEffect(()=>{if(!u.current||!e.isEnabled)return;const b=u.current;return b.srcObject=null,()=>{b.srcObject&&(b.srcObject=null)}},[e]);const x=()=>{a==null||a(e)},y=b=>{b.stopPropagation(),s?d==null||d(e):c==null||c(e)},m=["voxket-video-tile",e.isLocal?"voxket-video-tile--local":"voxket-video-tile--remote",e.isScreenShare?"voxket-video-tile--screen-share":"voxket-video-tile--camera",s?"voxket-video-tile--pinned":"",e.isEnabled?"":"voxket-video-tile--disabled",f?"voxket-video-tile--hovered":"",i].filter(Boolean).join(" ");return l.jsxs("div",{className:m,onClick:x,onMouseEnter:()=>h(!0),onMouseLeave:()=>h(!1),style:{aspectRatio:e.dimensions?`${e.dimensions.width} / ${e.dimensions.height}`:"16 / 9"},children:[l.jsx("video",{ref:u,className:"voxket-video-element",autoPlay:!0,playsInline:!0,muted:e.isLocal}),!e.isEnabled&&l.jsxs("div",{className:"voxket-video-placeholder",children:[l.jsx("div",{className:"voxket-video-placeholder-icon",children:e.isScreenShare?"๐ฅ๏ธ":"๐น"}),l.jsx("p",{className:"voxket-video-placeholder-text",children:e.isScreenShare?"Screen sharing paused":"Camera off"})]}),l.jsxs("div",{className:"voxket-video-overlay",children:[r&&t&&l.jsxs("div",{className:"voxket-video-name",children:[t,e.isLocal&&" (You)"]}),o&&!e.isEnabled&&l.jsx("div",{className:"voxket-video-mute-indicator",children:"๐"}),n&&(f||s)&&l.jsxs("div",{className:"voxket-video-controls",children:[l.jsx("button",{className:`voxket-video-control-btn ${s?"voxket-video-control-btn--active":""}`,onClick:y,title:s?"Unpin video":"Pin video",children:"๐"}),e.isScreenShare&&l.jsx("div",{className:"voxket-video-indicator",children:"๐ฅ๏ธ"}),e.source&&l.jsx("div",{className:"voxket-video-source",children:e.source})]})]}),!e.isEnabled&&l.jsx("div",{className:"voxket-video-loading",children:l.jsx("div",{className:"voxket-spinner"})})]})}function Iy({tracks:e,layout:t,className:n="",onLayoutChange:r,onTrackClick:o,maxVisibleTracks:s=9,showPagination:i=!0}){const[a,c]=w.useState(0),[d,u]=w.useState(null),f=w.useMemo(()=>{let v=[...e];t.type==="speaker"&&d&&(v=[d,...e.filter(S=>S.id!==d.id)]);const T=a*s,k=T+s;return v.slice(T,k)},[e,t,d,a,s]),h=Math.ceil(e.length/s),x=w.useMemo(()=>{const v=f.length;switch(t.type){case"grid":const T=Math.ceil(Math.sqrt(v)),k=Math.ceil(v/T);return{display:"grid",gridTemplateColumns:`repeat(${T}, 1fr)`,gridTemplateRows:`repeat(${k}, 1fr)`,gap:"8px"};case"speaker":return{display:"flex",flexDirection:"column",gap:"8px"};case"sidebar":return{display:"flex",gap:"8px"};case"gallery":return{display:"flex",flexWrap:"wrap",gap:"8px",justifyContent:"center"};default:return{}}},[t.type,f.length]),y=v=>{u(v)},m=()=>{u(null)},b=v=>{r==null||r({...t,type:v})},C=["voxket-video-grid",`voxket-video-grid--${t.type}`,`voxket-video-grid--${f.length}-tracks`,n].filter(Boolean).join(" ");return e.length===0?l.jsx("div",{className:"voxket-video-grid-empty",children:l.jsxs("div",{className:"voxket-video-grid-empty-content",children:[l.jsx("div",{className:"voxket-video-grid-empty-icon",children:"๐น"}),l.jsx("p",{children:"No video tracks available"})]})}):l.jsxs("div",{className:C,children:[l.jsxs("div",{className:"voxket-video-grid-controls",children:[l.jsx("div",{className:"voxket-video-layout-controls",children:["grid","speaker","sidebar","gallery"].map(v=>l.jsx("button",{className:`voxket-layout-btn ${t.type===v?"voxket-layout-btn--active":""}`,onClick:()=>b(v),title:`Switch to ${v} layout`,children:Dy(v)},v))}),l.jsxs("div",{className:"voxket-video-count",children:[e.length," participant",e.length!==1?"s":""]})]}),l.jsx("div",{className:"voxket-video-grid-content",style:x,children:t.type==="speaker"&&d?l.jsxs(l.Fragment,{children:[l.jsx("div",{className:"voxket-video-speaker-main",children:l.jsx(er,{track:d,participantName:`Participant ${d.participantId}`,isPinned:!0,onClick:o,onUnpin:m})}),l.jsx("div",{className:"voxket-video-speaker-sidebar",children:f.filter(v=>v.id!==d.id).map(v=>l.jsx(er,{track:v,participantName:`Participant ${v.participantId}`,showControls:!1,onClick:o,onPin:y},v.id))})]}):f.map(v=>l.jsx(er,{track:v,participantName:`Participant ${v.participantId}`,isPinned:(d==null?void 0:d.id)===v.id,onClick:o,onPin:y,onUnpin:m},v.id))}),i&&h>1&&l.jsxs("div",{className:"voxket-video-pagination",children:[l.jsx("button",{className:"voxket-pagination-btn",onClick:()=>c(Math.max(0,a-1)),disabled:a===0,children:"โ"}),l.jsxs("span",{className:"voxket-pagination-info",children:["Page ",a+1," of ",h]}),l.jsx("button",{className:"voxket-pagination-btn",onClick:()=>c(Math.min(h-1,a+1)),disabled:a===h-1,children:"โ"})]})]})}function Dy(e){switch(e){case"grid":return"โ";case"speaker":return"๐ค";case"sidebar":return"โซธ";case"gallery":return"โก";case"picture-in-picture":return"โง";default:return"โ"}}function $y({localTrack:e,onToggleCamera:t,onToggleScreenShare:n,onLayoutChange:r,showLayoutControls:o=!0,showCameraControls:s=!0,showScreenShareControls:i=!0,className:a=""}){const c=["voxket-video-controls",a].filter(Boolean).join(" "),d=u=>{r==null||r({type:u,showLocalVideo:!0,aspectRatio:"16:9"})};return l.jsxs("div",{className:c,children:[s&&l.jsxs("div",{className:"voxket-video-controls-section",children:[l.jsx("h4",{className:"voxket-video-controls-title",children:"Camera"}),l.jsxs("button",{className:`voxket-control-btn ${e!=null&&e.isEnabled?"voxket-control-btn--active":""}`,onClick:t,title:e!=null&&e.isEnabled?"Turn off camera":"Turn on camera",children:[l.jsx("span",{className:"voxket-control-icon",children:e!=null&&e.isEnabled?"๐น":"๐ท"}),l.jsx("span",{className:"voxket-control-label",children:e!=null&&e.isEnabled?"Camera On":"Camera Off"})]}),(e==null?void 0:e.dimensions)&&l.jsxs("div",{className:"voxket-video-info",children:[e.dimensions.width," ร ",e.dimensions.height]})]}),i&&l.jsxs("div",{className:"voxket-video-controls-section",children:[l.jsx("h4",{className:"voxket-video-controls-title",children:"Screen Share"}),l.jsxs("button",{className:`voxket-control-btn ${e!=null&&e.isScreenShare?"voxket-control-btn--active":""}`,onClick:n,title:e!=null&&e.isScreenShare?"Stop screen sharing":"Start screen sharing",children:[l.jsx("span",{className:"voxket-control-icon",children:e!=null&&e.isScreenShare?"๐":"๐ฅ๏ธ"}),l.jsx("span",{className:"voxket-control-label",children:e!=null&&e.isScreenShare?"Stop Sharing":"Share Screen"})]})]}),o&&l.jsxs("div",{className:"voxket-video-controls-section",children:[l.jsx("h4",{className:"voxket-video-controls-title",children:"Layout"}),l.jsx("div",{className:"voxket-layout-buttons",children:[{type:"grid",icon:"โ",label:"Grid"},{type:"speaker",icon:"๐ค",label:"Speaker"},{type:"sidebar",icon:"โซธ",label:"Sidebar"},{type:"gallery",icon:"โก",label:"Gallery"}].map(({type:u,icon:f,label:h})=>l.jsxs("button",{className:"voxket-layout-control-btn",onClick:()=>d(u),title:`Switch to ${h} layout`,children:[l.jsx("span",{className:"voxket-control-icon",children:f}),l.jsx("span",{className:"voxket-control-label",children:h})]},u))})]}),l.jsxs("div",{className:"voxket-video-controls-section",children:[l.jsx("h4",{className:"voxket-video-controls-title",children:"Video Settings"}),l.jsxs("div",{className:"voxket-video-settings",children:[l.jsxs("div",{className:"voxket-setting-group",children:[l.jsx("label",{className:"voxket-setting-label",children:"Quality"}),l.jsxs("select",{className:"voxket-setting-select",children:[l.jsx("option",{value:"high",children:"High (720p)"}),l.jsx("option",{value:"medium",children:"Medium (480p)"}),l.jsx("option",{value:"low",children:"Low (240p)"})]})]}),l.jsxs("div",{className:"voxket-setting-group",children:[l.jsx("label",{className:"voxket-setting-label",children:"Frame Rate"}),l.jsxs("select",{className:"voxket-setting-select",children:[l.jsx("option",{value:"30",children:"30 fps"}),l.jsx("option",{value:"15",children:"15 fps"}),l.jsx("option",{value:"10",children:"10 fps"})]})]}),l.jsxs("div",{className:"voxket-setting-group",children:[l.jsx("label",{className:"voxket-setting-label",children:"Bandwidth"}),l.jsxs("select",{className:"voxket-setting-select",children:[l.jsx("option",{value:"unlimited",children:"Unlimited"}),l.jsx("option",{value:"1000",children:"1 Mbps"}),l.jsx("option",{value:"500",children:"500 Kbps"}),l.jsx("option",{value:"250",children:"250 Kbps"})]})]})]})]}),l.jsxs("div",{className:"voxket-video-controls-section",children:[l.jsx("h4",{className:"voxket-video-controls-title",children:"Statistics"}),l.jsxs("div",{className:"voxket-video-stats",children:[l.jsxs("div",{className:"voxket-stat-item",children:[l.jsx("span",{className:"voxket-stat-label",children:"Resolution:"}),l.jsx("span",{className:"voxket-stat-value",children:e!=null&&e.dimensions?`${e.dimensions.width}ร${e.dimensions.height}`:"N/A"})]}),l.jsxs("div",{className:"voxket-stat-item",children:[l.jsx("span",{className:"voxket-stat-label",children:"Source:"}),l.jsx("span",{className:"voxket-stat-value",children:(e==null?void 0:e.source)||"None"})]}),l.jsxs("div",{className:"voxket-stat-item",children:[l.jsx("span",{className:"voxket-stat-label",children:"Status:"}),l.jsx("span",{className:`voxket-stat-value ${e!=null&&e.isEnabled?"voxket-stat-value--active":"voxket-stat-value--inactive"}`,children:e!=null&&e.isEnabled?"Active":"Inactive"})]})]})]})]})}const Id=({handler:e,loadData:t,data:n,client:r,addLocalMessage:o})=>{const[s,i]=g.useState(null),[a,c]=g.useState(!0),[d,u]=g.useState(!1),[f]=g.useState(Date.now());g.useEffect(()=>{(async()=>{try{if(c(!0),console.log("๐ AssignmentView: Loading assignment data..."),console.log("๐ AssignmentView: Received data from RPC:",n),n&&typeof n=="object"){const b={title:n.title||"Untitled Assignment",description:n.description||"No description provided",estimated_time_of_completion:n.estimated_time_of_completion||"Unknown"};i(b),console.log("๐ AssignmentView: Assignment loaded from RPC data:",b)}}catch(b){console.error("๐ AssignmentView: Error loading assignment:",b),i({title:"Assignment Loading Error",description:"There was an error loading the assignment details. Please try again.",estimated_time_of_completion:"Unknown"})}finally{c(!1)}})()},[n,t]);const h=({message:m,assignment:b})=>{const C=m.toLowerCase().includes("declined"),v=C?"bg-red-50 border-red-200":"bg-green-50 border-green-200",T=C?"text-red-700":"text-green-700",k=C?"โ":"๐";return l.jsxs("div",{className:`max-w-sm mx-auto ${v} border rounded-lg shadow p-3 flex flex-col items-center`,children:[l.jsx("div",{className:"text-2xl mb-2",children:k}),l.jsx("div",{className:`${T} font-semibold text-sm mb-1`,children:m}),l.jsx("div",{className:"text-xs text-gray-600 text-center mb-1",children:b.title}),l.jsx("div",{className:"text-xs text-gray-500",children:"Thank you for your response!"})]})},x=async()=>{if(!(!s||!e)){u(!0);try{const m={message:"accepted"};console.log("๐ AssignmentView: Assignment accepted:",m),e.didSuccess(m,l.jsx(h,{message:"Assignment accepted!",assignment:s}))}catch(m){console.error("๐ AssignmentView: Error accepting assignment:",m),e.didFail({error:"Failed to accept assignment"})}finally{u(!1)}}},y=async()=>{if(!(!s||!e)){u(!0);try{const m={message:"declined"};console.log("๐ AssignmentView: Assignment declined:",m),e.didSuccess(m,l.jsx(h,{message:"Assignment declined",assignment:s}))}catch(m){console.error("๐ AssignmentView: Error declining assignment:",m),e.didFail({error:"Failed to decline assignment"})}finally{u(!1)}}};return a?l.jsx("div",{className:"max-w-sm mx-auto bg-white rounded-lg shadow-lg p-3",children:l.jsxs("div",{className:"flex items-center justify-center py-4",children:[l.jsx("div",{className:"animate-spin rounded-full h-4 w-4 border-b-2 border-blue-600"}),l.jsx("span",{className:"ml-2 text-xs text-gray-600",children:"Loading assignment..."})]})}):s?l.jsxs("div",{className:"max-w-sm mx-auto bg-white rounded-lg shadow-lg overflow-hidden",children:[l.jsx("div",{className:"bg-gradient-to-r from-blue-600 to-purple-600 text-white p-3",children:l.jsx("div",{className:"flex items-center justify-between",children:l.jsx("h3",{className:"text-xs font-semibold text-white truncate",children:s.title})})}),l.jsxs("div",{className:"p-3 text-black",children:[l.jsx("div",{className:"bg-gray-50 rounded p-2 mb-3",children:l.jsx("p",{className:"text-xs text-black leading-snug",children:s.description})}),l.jsx("div",{className:"mb-3 text-black",children:l.jsxs("div",{className:"flex items-center text-xs text-gray-600",children:[l.jsx("span",{className:"text-xs mr-1",children:"๐
"}),l.jsxs("span",{children:["Est: ",s.estimated_time_of_completion]})]})}),l.jsxs("div",{className:"flex gap-2",children:[l.jsx("button",{onClick:x,disabled:d,className:"flex-1 bg-green-600 text-white py-2 px-3 rounded text-xs font-medium hover:bg-green-700 transition-colors disabled:opacity-50 disabled:cursor-not-allowed",children:d?l.jsxs("span",{className:"flex items-center justify-center",children:[l.jsx("div",{className:"animate-spin rounded-full h-2 w-2 border-b-2 border-white mr-1"}),l.jsx("span",{className:"text-xs",children:"Processing..."})]}):"Accept"}),l.jsx("button",{onClick:y,disabled:d,className:"flex-1 bg-red-600 text-white py-2 px-3 rounded text-xs font-medium hover:bg-red-700 transition-colors disabled:opacity-50 disabled:cursor-not-allowed",children:"Decline"})]})]})]}):l.jsx("div",{className:"max-w-sm mx-auto bg-white rounded-lg shadow-lg p-3",children:l.jsxs("div",{className:"text-center py-4",children:[l.jsx("div",{className:"text-red-600 text-sm font-semibold mb-2",children:"โ ๏ธ Assignment Error"}),l.jsx("p",{className:"text-xs text-gray-600 mb-3",children:"Failed to load assignment details."})]})})};function Fy(){const[e,t]=g.useState(null),[n,r]=g.useState([]);g.useEffect(()=>{const a=new Rn({appId:"your-app-id",appSecret:"your-app-secret",baseUrl:"https://your-voxket-api.com",agentId:"your-agent-id",participantName:"User",modalities:["chat"]});return t(a),a.on("rpc.method.called",c=>{console.log("RPC Method Called:",c)}),a.on("rpc.interaction.completed",c=>{console.log("RPC Interaction Completed:",c)}),()=>{a.disconnect()}},[]);const o=async()=>{if(e)try{await e.registerFrontendRPC("give_assignment",Id,"embedded");const a=e.getRegisteredRpcMethods();r(a),console.log("โ
Assignment RPC registered successfully")}catch(a){console.error("โ Failed to register assignment RPC:",a)}},s=async()=>{if(!e)return;const a=({handler:c,timeout:d})=>{const[u,f]=g.useState(""),h=[{id:"pro",name:"Pro Plan",price:"$29/month"},{id:"enterprise",name:"Enterprise Plan",price:"$99/month"},{id:"basic",name:"Basic Plan",price:"$9/month"}],x=m=>{f(m)},y=()=>{const m=h.find(b=>b.id===u);c==null||c.didSuccess({selectedProduct:u,productName:m==null?void 0:m.name,price:m==null?void 0:m.price,timestamp:new Date().toISOString()})};return l.jsxs("div",{className:"p-6 bg-white rounded-lg",children:[l.jsx("h3",{className:"text-xl font-bold mb-4",children:"Choose Your Plan"}),l.jsx("p",{className:"text-gray-600 mb-4",children:"Select the plan that best fits your needs:"}),l.jsx("div",{className:"space-y-3 mb-6",children:h.map(m=>l.jsx("div",{onClick:()=>x(m.id),className:`p-4 border rounded-lg cursor-pointer transition-all ${u===m.id?"border-blue-500 bg-blue-50":"border-gray-200 hover:border-gray-300"}`,children:l.jsxs("div",{className:"flex justify-between items-center",children:[l.jsxs("div",{children:[l.jsx("h4",{className:"font-medium",children:m.name}),l.jsx("p",{className:"text-gray-600 text-sm",children:m.price})]}),l.jsx("div",{className:`w-4 h-4 rounded-full ${u===m.id?"bg-blue-500":"border-2 border-gray-300"}`})]})},m.id))}),l.jsxs("div",{className:"flex justify-end space-x-3",children:[l.jsx("button",{onClick:()=>c==null?void 0:c.dismissView(),className:"px-4 py-2 border border-gray-300 text-gray-700 rounded hover:bg-gray-50",children:"Cancel"}),l.jsx("button",{onClick:y,disabled:!u,className:"px-4 py-2 bg-blue-500 text-white rounded hover:bg-blue-600 disabled:opacity-50",children:"Select Plan"})]}),d&&l.jsxs("p",{className:"text-xs text-gray-500 mt-2",children:["Time remaining: ",d," seconds"]})]})};try{await e.registerFrontendRPC("recommend_product",a,"modal");const c=e.getRegisteredRpcMethods();r(c),console.log("โ
Product Recommendation RPC registered successfully")}catch(c){console.error("โ Failed to register product recommendation RPC:",c)}},i=async()=>{if(!e)return;const a=({handler:c})=>{const[d,u]=g.useState(0),[f,h]=g.useState(""),x=()=>{c==null||c.didSuccess({rating:d,comment:f,timestamp:new Date().toISOString()})};return l.jsxs("div",{className:"p-4 bg-white rounded-lg",children:[l.jsx("h3",{className:"text-lg font-semibold mb-3",children:"How was your experience?"}),l.jsxs("div",{className:"mb-4",children:[l.jsx("p",{className:"text-sm text-gray-600 mb-2",children:"Rate your experience:"}),l.jsx("div",{className:"flex space-x-1",children:[1,2,3,4,5].map(y=>l.jsx("button",{onClick:()=>u(y),className:`text-2xl ${y<=d?"text-yellow-400":"text-gray-300"}`,children:"โญ"},y))})]}),l.jsxs("div",{className:"mb-4",children:[l.jsx("p",{className:"text-sm text-gray-600 mb-2",children:"Additional comments:"}),l.jsx("textarea",{value:f,onChange:y=>h(y.target.value),className:"w-full p-2 border border-gray-300 rounded text-sm",rows:3,placeholder:"Tell us more about your experience..."})]}),l.jsxs("div",{className:"flex justify-end space-x-2",children:[l.jsx("button",{onClick:()=>c==null?void 0:c.dismissView(),className:"px-3 py-1 text-sm border border-gray-300 text-gray-700 rounded hover:bg-gray-50",children:"Skip"}),l.jsx("button",{onClick:x,disabled:d===0,className:"px-3 py-1 text-sm bg-blue-500 text-white rounded hover:bg-blue-600 disabled:opacity-50",children:"Submit"})]})]})};try{await e.registerFrontendRPC("collect_feedback",a,"embedded");const c=e.getRegisteredRpcMethods();r(c),console.log("โ
Feedback RPC registered successfully")}catch(c){console.error("โ Failed to register feedback RPC:",c)}};return l.jsxs("div",{className:"p-6",children:[l.jsx("h2",{className:"text-2xl font-bold mb-6",children:"Frontend RPC Examples"}),l.jsxs("div",{className:"space-y-4 mb-6",children:[l.jsxs("div",{children:[l.jsx("h3",{className:"text-lg font-semibold mb-2",children:"Register RPC Methods"}),l.jsxs("div",{className:"space-x-2",children:[l.jsx("button",{onClick:o,className:"px-4 py-2 bg-blue-500 text-white rounded hover:bg-blue-600",children:"Register Assignment RPC"}),l.jsx("button",{onClick:s,className:"px-4 py-2 bg-green-500 text-white rounded hover:bg-green-600",children:"Register Product Recommendation RPC"}),l.jsx("button",{onClick:i,className:"px-4 py-2 bg-purple-500 text-white rounded hover:bg-purple-600",children:"Register Feedback RPC"})]})]}),l.jsxs("div",{children:[l.jsx("h3",{className:"text-lg font-semibold mb-2",children:"Registered Methods"}),n.length>0?l.jsx("ul",{className:"list-disc list-inside space-y-1",children:n.map(a=>l.jsx("li",{className:"text-gray-700",children:l.jsx("code",{className:"bg-gray-100 px-2 py-1 rounded",children:a})},a))}):l.jsx("p",{className:"text-gray-500",children:"No methods registered yet"})]})]}),l.jsxs("div",{className:"bg-gray-50 p-4 rounded-lg",children:[l.jsx("h3",{className:"text-lg font-semibold mb-2",children:"How it works"}),l.jsxs("ol",{className:"list-decimal list-inside space-y-2 text-sm text-gray-700",children:[l.jsxs("li",{children:["Register RPC methods with React components using ",l.jsx("code",{children:"client.registerFrontendRPC()"})]}),l.jsx("li",{children:"When the agent calls an RPC method, the corresponding component will be displayed"}),l.jsx("li",{children:"Users interact with the component, and the response is sent back to the agent"}),l.jsx("li",{children:"Components can be displayed in different modes: embedded, modal, or fullscreen"}),l.jsx("li",{children:"Each component has a timeout and can handle success/failure scenarios"})]})]}),l.jsxs("div",{className:"mt-6 bg-blue-50 p-4 rounded-lg",children:[l.jsx("h3",{className:"text-lg font-semibold mb-2 text-blue-800",children:"Agent Side"}),l.jsx("p",{className:"text-sm text-blue-700 mb-2",children:"On the agent side, you can call these RPC methods like this:"}),l.jsx("pre",{className:"bg-white p-3 rounded text-xs text-gray-800 overflow-x-auto",children:`// Agent calls RPC method
|
|
1207
|
+
|
|
1208
|
+
/* GLOBAL STYLES FOR POPUP AND FULLSCREEN MODES */
|
|
1209
|
+
/* These styles apply globally when popup/fullscreen elements are rendered outside normal widget scope */
|
|
1210
|
+
|
|
1211
|
+
/* Popup and fullscreen containers */
|
|
1212
|
+
.fixed.z-\\[9999\\],
|
|
1213
|
+
div[class*="fixed"][class*="z-[9999]"] {
|
|
1214
|
+
/* Ensure fixed positioned elements get theme context */
|
|
1215
|
+
}
|
|
1216
|
+
|
|
1217
|
+
/* Global theme classes for popup/fullscreen */
|
|
1218
|
+
.theme-vox {
|
|
1219
|
+
color: #ffffff;
|
|
1220
|
+
}
|
|
1221
|
+
|
|
1222
|
+
.theme-dark {
|
|
1223
|
+
color: #ffffff;
|
|
1224
|
+
}
|
|
1225
|
+
|
|
1226
|
+
.theme-light {
|
|
1227
|
+
color: #1f2937;
|
|
1228
|
+
}
|
|
1229
|
+
|
|
1230
|
+
/* Global background utilities for popup/fullscreen */
|
|
1231
|
+
.bg-gradient-to-br {
|
|
1232
|
+
background-image: linear-gradient(to bottom right, var(--tw-gradient-stops));
|
|
1233
|
+
}
|
|
1234
|
+
|
|
1235
|
+
.bg-gradient-to-b {
|
|
1236
|
+
background-image: linear-gradient(to bottom, var(--tw-gradient-stops));
|
|
1237
|
+
}
|
|
1238
|
+
|
|
1239
|
+
.bg-gradient-to-r {
|
|
1240
|
+
background-image: linear-gradient(to right, var(--tw-gradient-stops));
|
|
1241
|
+
}
|
|
1242
|
+
|
|
1243
|
+
/* Global gradient stops */
|
|
1244
|
+
.from-black {
|
|
1245
|
+
--tw-gradient-from: #000000;
|
|
1246
|
+
--tw-gradient-stops: var(--tw-gradient-from), var(--tw-gradient-to, rgba(0, 0, 0, 0));
|
|
1247
|
+
}
|
|
1248
|
+
|
|
1249
|
+
.to-gray-900 {
|
|
1250
|
+
--tw-gradient-to: #111827;
|
|
1251
|
+
}
|
|
1252
|
+
|
|
1253
|
+
.from-\\[\\#171727\\] {
|
|
1254
|
+
--tw-gradient-from: #171727;
|
|
1255
|
+
--tw-gradient-stops: var(--tw-gradient-from), var(--tw-gradient-to, rgba(23, 23, 39, 0));
|
|
1256
|
+
}
|
|
1257
|
+
|
|
1258
|
+
.to-\\[\\#12121F\\] {
|
|
1259
|
+
--tw-gradient-to: #12121F;
|
|
1260
|
+
}
|
|
1261
|
+
|
|
1262
|
+
.from-slate-950 {
|
|
1263
|
+
--tw-gradient-from: #020617;
|
|
1264
|
+
--tw-gradient-stops: var(--tw-gradient-from), var(--tw-gradient-to, rgba(2, 6, 23, 0));
|
|
1265
|
+
}
|
|
1266
|
+
|
|
1267
|
+
.via-slate-900 {
|
|
1268
|
+
--tw-gradient-to: rgba(15, 23, 42, 0);
|
|
1269
|
+
--tw-gradient-stops: var(--tw-gradient-from), #0f172a, var(--tw-gradient-to, rgba(15, 23, 42, 0));
|
|
1270
|
+
}
|
|
1271
|
+
|
|
1272
|
+
.to-gray-950 {
|
|
1273
|
+
--tw-gradient-to: #030712;
|
|
1274
|
+
}
|
|
1275
|
+
|
|
1276
|
+
.from-sky-50 {
|
|
1277
|
+
--tw-gradient-from: #f0f9ff;
|
|
1278
|
+
--tw-gradient-stops: var(--tw-gradient-from), var(--tw-gradient-to, rgba(240, 249, 255, 0));
|
|
1279
|
+
}
|
|
1280
|
+
|
|
1281
|
+
.via-white {
|
|
1282
|
+
--tw-gradient-to: rgba(255, 255, 255, 0);
|
|
1283
|
+
--tw-gradient-stops: var(--tw-gradient-from), #ffffff, var(--tw-gradient-to, rgba(255, 255, 255, 0));
|
|
1284
|
+
}
|
|
1285
|
+
|
|
1286
|
+
.to-indigo-50 {
|
|
1287
|
+
--tw-gradient-to: #eef2ff;
|
|
1288
|
+
}
|
|
1289
|
+
|
|
1290
|
+
.from-\\[\\#0a0a1a\\] {
|
|
1291
|
+
--tw-gradient-from: #0a0a1a;
|
|
1292
|
+
--tw-gradient-stops: var(--tw-gradient-from), var(--tw-gradient-to, rgba(10, 10, 26, 0));
|
|
1293
|
+
}
|
|
1294
|
+
|
|
1295
|
+
.to-\\[\\#0f0f23\\] {
|
|
1296
|
+
--tw-gradient-to: #0f0f23;
|
|
1297
|
+
}
|
|
1298
|
+
|
|
1299
|
+
/* Global background colors */
|
|
1300
|
+
.bg-black\\/40 {
|
|
1301
|
+
background-color: rgba(0, 0, 0, 0.4);
|
|
1302
|
+
}
|
|
1303
|
+
|
|
1304
|
+
.bg-\\[\\#171727\\]\\/90 {
|
|
1305
|
+
background-color: rgba(23, 23, 39, 0.9);
|
|
1306
|
+
}
|
|
1307
|
+
|
|
1308
|
+
.bg-\\[\\#1E1E2E\\] {
|
|
1309
|
+
background-color: #1E1E2E;
|
|
1310
|
+
}
|
|
1311
|
+
|
|
1312
|
+
.bg-\\[\\#0a0a1a\\] {
|
|
1313
|
+
background-color: #0a0a1a;
|
|
1314
|
+
}
|
|
1315
|
+
|
|
1316
|
+
.bg-\\[\\#0f0f23\\] {
|
|
1317
|
+
background-color: #0f0f23;
|
|
1318
|
+
}
|
|
1319
|
+
|
|
1320
|
+
.bg-slate-950 {
|
|
1321
|
+
background-color: #020617;
|
|
1322
|
+
}
|
|
1323
|
+
|
|
1324
|
+
.bg-slate-900 {
|
|
1325
|
+
background-color: #0f172a;
|
|
1326
|
+
}
|
|
1327
|
+
|
|
1328
|
+
.bg-sky-50 {
|
|
1329
|
+
background-color: #f0f9ff;
|
|
1330
|
+
}
|
|
1331
|
+
|
|
1332
|
+
.bg-indigo-50 {
|
|
1333
|
+
background-color: #eef2ff;
|
|
1334
|
+
}
|
|
1335
|
+
|
|
1336
|
+
/* Global backdrop blur */
|
|
1337
|
+
.backdrop-blur-sm {
|
|
1338
|
+
backdrop-filter: blur(8px);
|
|
1339
|
+
-webkit-backdrop-filter: blur(8px);
|
|
1340
|
+
}
|
|
1341
|
+
|
|
1342
|
+
/* Global layout utilities */
|
|
1343
|
+
.fixed {
|
|
1344
|
+
position: fixed;
|
|
1345
|
+
}
|
|
1346
|
+
|
|
1347
|
+
.inset-0 {
|
|
1348
|
+
inset: 0px;
|
|
1349
|
+
}
|
|
1350
|
+
|
|
1351
|
+
.flex {
|
|
1352
|
+
display: flex;
|
|
1353
|
+
}
|
|
1354
|
+
|
|
1355
|
+
.items-center {
|
|
1356
|
+
align-items: center;
|
|
1357
|
+
}
|
|
1358
|
+
|
|
1359
|
+
.justify-center {
|
|
1360
|
+
justify-content: center;
|
|
1361
|
+
}
|
|
1362
|
+
|
|
1363
|
+
.w-full {
|
|
1364
|
+
width: 100%;
|
|
1365
|
+
}
|
|
1366
|
+
|
|
1367
|
+
.h-full {
|
|
1368
|
+
height: 100%;
|
|
1369
|
+
}
|
|
1370
|
+
|
|
1371
|
+
.rounded-2xl {
|
|
1372
|
+
border-radius: 1rem;
|
|
1373
|
+
}
|
|
1374
|
+
|
|
1375
|
+
.shadow-2xl {
|
|
1376
|
+
box-shadow: 0 25px 50px -12px rgba(0, 0, 0, 0.25);
|
|
1377
|
+
}
|
|
1378
|
+
`,t=document.createElement("style");t.type="text/css",t.setAttribute("data-voxket-styles","true"),t.textContent=e,document.head.appendChild(t),Wa=!0}class he extends Error{constructor(t,n,r){super(t),this.code=n,this.details=r,this.name="VoxketError"}}class Rn extends Vs{constructor(n){super();ke(this,"config");ke(this,"room",null);ke(this,"pluginManager");ke(this,"rpcManager");ke(this,"isConnected",!1);ke(this,"currentSession",null);ke(this,"connectionState",H.ConnectionState.Disconnected);ke(this,"renderedComponents",new Map);ke(this,"textStreamHandlersRegistered",!1);ke(this,"currentAgentInfo",null);ke(this,"chatMessages",[]);ke(this,"isAgentConnected",!1);ke(this,"agentState","idle");yd(),this.config=n,this.pluginManager=new gd(this),this.rpcManager=new ry,this.setupEventListeners(),this.initializeClient()}setupEventListeners(){this.on("connection.connected",()=>{var n,r;this.isConnected=!0,(r=(n=this.config).onConnected)==null||r.call(n)}),this.on("connection.disconnected",n=>{var r,o;this.isConnected=!1,(o=(r=this.config).onDisconnected)==null||o.call(r,n)}),this.on("connection.error",n=>{var r,o;(o=(r=this.config).onError)==null||o.call(r,n)}),this.on("chat.message.received",n=>{var r,o;this.addChatMessage(n),(o=(r=this.config).onMessageReceived)==null||o.call(r,n)}),this.on("chat.message.updated",n=>{this.updateChatMessage(n)}),this.on("chat.message.sent",n=>{this.addChatMessage(n)}),this.on("transcription.received",n=>{var r,o;(o=(r=this.config).onTranscriptionReceived)==null||o.call(r,n)}),this.on("session.state.changed",n=>{var r,o;(o=(r=this.config).onSessionStateChanged)==null||o.call(r,n)}),this.on("session.created",n=>{var r,o;(o=(r=this.config).onSessionStart)==null||o.call(r,n.id)}),this.on("session.ended",(n,r)=>{var o,s;(s=(o=this.config).onSessionEnd)==null||s.call(o,r)}),this.on("participant.joined",n=>{var r,o;(o=(r=this.config).onUserJoined)==null||o.call(r,n.id)}),this.on("participant.left",n=>{var r,o;(o=(r=this.config).onUserLeft)==null||o.call(r,n.id)}),this.setupRpcEventForwarding()}setupRpcEventForwarding(){if(!this.rpcManager){console.warn("RpcManager not initialized, skipping event forwarding setup");return}this.rpcManager.on("rpc.method.registered",n=>this.emit("rpc.method.registered",n)),this.rpcManager.on("rpc.method.called",n=>this.emit("rpc.method.called",n)),this.rpcManager.on("rpc.interaction.started",n=>this.emit("rpc.interaction.started",n)),this.rpcManager.on("rpc.interaction.completed",n=>this.emit("rpc.interaction.completed",n)),this.rpcManager.on("rpc.interaction.timeout",n=>this.emit("rpc.interaction.timeout",n)),this.rpcManager.on("rpc.interaction.dismissed",n=>this.emit("rpc.interaction.dismissed",n))}initializeClient(){this.room=new H.Room,this.setupRoomEventListeners()}setupRoomEventListeners(){this.room&&(this.room.on(H.RoomEvent.Connected,()=>{var n,r;this.connectionState=H.ConnectionState.Connected,this.emit("connection.connected"),this.rpcManager.setRoom(this.room),(r=(n=this.currentSession)==null?void 0:n.activeModalities)!=null&&r.includes("voice")&&setTimeout(async()=>{var o;try{(o=this.room)!=null&&o.localParticipant&&(this.room.localParticipant.isMicrophoneEnabled?this.emit("track.unmuted",{source:"microphone",enabled:!0}):(await this.room.localParticipant.setMicrophoneEnabled(!0),this.emit("track.unmuted",{source:"microphone",enabled:!0})))}catch(s){console.warn("VoxketClient: Failed to enable microphone after room connection:",s)}},1e3),this.textStreamHandlersRegistered||this.setupTextStreamHandlers()}),this.room.on(H.RoomEvent.Disconnected,n=>{var r;console.log("๐ด VoxketClient: Room disconnected, reason:",n),this.connectionState=H.ConnectionState.Disconnected,this.textStreamHandlersRegistered=!1,this.isAgentConnected=!1,console.log("๐ค VoxketClient: Agent marked as disconnected"),n&&console.log("๐ VoxketClient: Disconnect reason details:",{reason:n.toString(),currentSession:(r=this.currentSession)==null?void 0:r.id,agentConnected:this.isAgentConnected,connectionState:this.connectionState}),this.emit("connection.disconnected",n==null?void 0:n.toString())}),this.room.on(H.RoomEvent.ConnectionStateChanged,n=>{this.connectionState=n,n===H.ConnectionState.Connecting&&this.emit("connection.connecting")}),this.room.on(H.RoomEvent.ParticipantConnected,n=>{const r={id:n.identity,name:n.name||n.identity,isLocal:!1};this.emit("participant.joined",r)}),this.room.on(H.RoomEvent.ParticipantDisconnected,n=>{const r={id:n.identity,name:n.name||n.identity,isLocal:!1};this.emit("participant.left",r)}))}setupTextStreamHandlers(){if(!this.room)return;try{this.room.registerTextStreamHandler("lk.chat",async(r,o)=>{try{const s=await r.readAll(),i={id:`msg_${Date.now()}_${o.identity||"user"}_${Math.random().toString(36).substr(2,9)}`,content:s,timestamp:new Date,sender:{id:o.identity||"user",name:o.identity||"User",type:"participant"},metadata:{topic:"lk.chat"}};this.emit("chat.message.received",i)}catch(s){console.error("VoxketClient: Failed to process lk.chat message:",s)}})}catch(r){console.warn("VoxketClient: lk.chat handler already registered, skipping:",r)}try{this.room.registerTextStreamHandler("lk.transcription",async(r,o)=>{var s,i;try{const a=`msg_${Date.now()}_agent_transcription_${Math.random().toString(36).substr(2,9)}`;let c="";const d=((s=this.currentAgentInfo)==null?void 0:s.name)||o.identity||"AI Assistant",u={id:a,content:"",timestamp:new Date,sender:{id:o.identity||"agent",name:d,type:"agent"},metadata:{topic:"lk.transcription",streaming:!0}};this.emit("chat.message.received",u);for await(const x of r){c+=x;const y=this.convertMarkdownToText(c),m={...u,content:y,metadata:{...u.metadata,streaming:!0}};this.emit("chat.message.updated",m)}const f=this.convertMarkdownToText(c),h={...u,content:f,metadata:{...u.metadata,streaming:!1}};this.emit("chat.message.updated",h)}catch(a){console.error("VoxketClient: Failed to process lk.transcription message:",a);try{const c=await r.readAll(),d=((i=this.currentAgentInfo)==null?void 0:i.name)||o.identity||"AI Assistant",u={id:`msg_${Date.now()}_agent_transcription_${Math.random().toString(36).substr(2,9)}`,content:c,timestamp:new Date,sender:{id:o.identity||"agent",name:d,type:"agent"},metadata:{topic:"lk.transcription"}};this.emit("chat.message.received",u)}catch(c){console.error("VoxketClient: Fallback failed for lk.transcription:",c)}}})}catch(r){console.warn("VoxketClient: lk.transcription handler already registered, skipping:",r)}try{this.room.registerTextStreamHandler("suggested_response",async r=>{const o=await r.readAll();let s=[];try{s=["tes","hello how are you","algebra make me learn that ","what is the meaning of life"]}catch(i){console.warn("VoxketClient: Failed to parse suggested_response:",i,o)}this.emit("suggested.response",s)})}catch(r){console.warn("VoxketClient: suggested_response handler already registered, skipping:",r)}try{this.room.registerTextStreamHandler("agent_state_changed",async(r,o)=>{const s=await r.readAll();console.log("๐ค VoxketClient: agent_state_changed stream received:",s);let i={};try{i=typeof s=="string"?JSON.parse(s.replace(/'/g,'"')):s}catch(a){console.warn("VoxketClient: Failed to parse agent_state_changed:",a,s)}this.isAgentConnected||(this.isAgentConnected=!0,console.log("๐ค VoxketClient: Agent marked as connected (first state change received)"),this.emit("agent.connected",i)),i.new_state==="speaking"?(this.setAgentState("speaking"),this.emit("agent.speaking",i)):i.new_state==="thinking"?(this.setAgentState("thinking"),this.emit("agent.thinking",i)):(i.new_state==="idle"||i.new_state==="listening")&&this.setAgentState("idle")})}catch(r){console.warn("VoxketClient: conversation_item_added handler already registered, skipping:",r)}try{this.room.registerTextStreamHandler("images",async(r,o)=>{try{const s=await r.readAll()}catch(s){console.error("VoxketClient: Error processing images stream:",s)}})}catch(r){console.warn("VoxketClient: images handler already registered, skipping:",r)}try{this.room.registerByteStreamHandler("images",async(r,o)=>{var s,i;try{const a=r.info,c={id:`img_${Date.now()}_${o.identity||"agent"}_${Math.random().toString(36).substr(2,9)}`,content:`๏ฟฝ๏ธ ${a.name||"Image"}`,sender:{id:o.identity||"agent",name:o.identity||"Agent",type:o.identity===((i=(s=this.room)==null?void 0:s.localParticipant)==null?void 0:i.identity)?"participant":"agent"},timestamp:new Date,metadata:{type:"attachment",fileName:a.name,fileSize:a.size,mimeType:a.mimeType,streamId:a.id,downloading:!0}};this.emit("chat.message.received",c),r.onProgress&&(r.onProgress=x=>{const y={...c,metadata:{...c.metadata,downloadProgress:x||0}};this.emit("chat.message.updated",y)});const d=[];for await(const x of r)d.push(x);const u=new Blob(d,{type:a.mimeType||"application/octet-stream"}),f=URL.createObjectURL(u),h={...c,metadata:{...c.metadata,downloading:!1,downloadProgress:1,downloadUrl:f,blob:u}};this.emit("chat.message.updated",h)}catch(a){console.error("VoxketClient: Error processing image attachment:",a)}})}catch(r){console.warn("VoxketClient: image handler already registered, skipping:",r)}["error","warning","status","system","debug","info"].forEach(r=>{try{this.room.registerTextStreamHandler(r,async(o,s)=>{try{const i=await o.readAll();if(console.log(`๐ VoxketClient: Received '${r}' stream:`,i),r==="error"){let a={};try{a=typeof i=="string"?JSON.parse(i):i}catch{a={message:i}}console.warn("๏ฟฝ VoxketClient: Agent error:",a),this.emit("agent.error",a)}else this.emit("text.stream.received",{topic:r,data:i,participantInfo:s})}catch(i){console.error(`VoxketClient: Failed to process '${r}' stream:`,i)}})}catch(o){console.warn(`VoxketClient: Handler for '${r}' already registered, skipping:`,o)}});try{this.room.registerTextStreamHandler("*",async(r,o)=>{var s;try{const i=await r.readAll(),a=((s=r.info)==null?void 0:s.topic)||"unknown";console.log(`๐ VoxketClient: Received unhandled text stream for topic '${a}':`,i),this.emit("text.stream.unhandled",{topic:a,data:i,participantInfo:o})}catch(i){console.error("VoxketClient: Failed to process unhandled text stream:",i)}})}catch(r){console.warn("VoxketClient: Generic text stream handler already registered, skipping:",r)}this.textStreamHandlersRegistered=!0}async fetchConnectionDetails(n,r,o){const s=n||this.config.agentId||"default-agent",i=r||this.config.participantName||"User",a=o||this.config.modalities||["voice"];try{const c={agent_id:s,participant_name:i,participant_metadata:{user_id:""},modality:a[0],modalities:a};console.log("๐ VoxketClient: Creating session with modalities:",a);const d=await fetch(`${this.config.baseUrl}/api/live/agent/session`,{method:"POST",headers:{accept:"application/json","X-APP-ID":this.config.appId,"X-APP-SECRET":this.config.appSecret,"Content-Type":"application/json"},body:JSON.stringify(c)});if(!d.ok){let h=`HTTP ${d.status}: Failed to fetch connection details`;try{const x=await d.json();x&&(x.error?h=`API Error: ${x.error}`:x.detail?h=`API Error: ${x.detail}`:x.message&&(h=`API Error: ${x.message}`))}catch{try{const y=await d.text();y&&(h=`API Error: ${y}`)}catch{}}throw new Error(h)}const u=await d.json();let f;return u.agent_info&&(f={id:u.agent_info.id||s,name:u.agent_info.name||"AI Assistant",avatar:u.agent_info.avatar,capabilities:u.agent_info.capabilities||["voice_interaction","text_chat"],metadata:u.agent_info.metadata||{}},this.currentAgentInfo=f),{serverUrl:u.wss_url,participantToken:u.token,voxketSessionId:u.session_id,agentInfo:f}}catch(c){console.error("VoxketClient: fetchConnectionDetails failed:",c);const d=new he(`Failed to fetch connection details: ${c instanceof Error?c.message:"Unknown error"}`,"CONNECTION_FAILED",c);throw this.emit("connection.error",d),d}}async connect(n,r,o){var s;try{this.emit("connection.connecting");const i=await this.fetchConnectionDetails(n,r,o);return await((s=this.room)==null?void 0:s.connect(i.serverUrl,i.participantToken)),this.isConnected=!0,i}catch(i){console.error("VoxketClient: Connection failed:",i);const a=new he(`Failed to connect to Voxket services: ${i instanceof Error?i.message:"Unknown error"}`,"CONNECTION_FAILED",i);throw this.emit("connection.error",a),a}}async disconnect(){var n;try{await((n=this.room)==null?void 0:n.disconnect()),this.isConnected=!1,this.currentSession=null,this.currentAgentInfo=null,this.textStreamHandlersRegistered=!1,this.clearChatMessages(),this.room=new H.Room,this.setupRoomEventListeners()}catch(r){const o=new he("Failed to disconnect properly","NETWORK_ERROR",r);throw this.emit("connection.error",o),o}}async createSession(n){var r,o,s,i;try{const a=await this.connect(n.agentId,n.participantName,n.modalities),c={id:a.voxketSessionId,agentId:n.agentId,state:"connecting",startedAt:new Date,metadata:n.metadata||{},activeModalities:n.modalities||["voice"],agentInfo:a.agentInfo||this.currentAgentInfo};if(this.currentSession=c,this.emit("session.created",c),(r=n.modalities)!=null&&r.includes("voice"))try{await new Promise(d=>setTimeout(d,500)),(o=this.room)!=null&&o.localParticipant?(await this.room.localParticipant.setMicrophoneEnabled(!0,void 0,{preConnectBuffer:!0}),this.emit("track.unmuted",{source:"microphone",enabled:!0})):console.warn("VoxketClient: No local participant found, microphone not enabled")}catch(d){console.warn("VoxketClient: Failed to enable microphone, but continuing with session:",d)}if((s=n.modalities)!=null&&s.includes("video"))try{await new Promise(d=>setTimeout(d,200)),(i=this.room)!=null&&i.localParticipant&&(console.log("๐ฅ VoxketClient: Attempting to enable camera for video session"),await this.room.localParticipant.setCameraEnabled(!0),this.emit("track.unmuted",{source:"camera",enabled:!0}),console.log("๐ฅ VoxketClient: Camera enabled successfully"))}catch(d){console.warn("VoxketClient: Failed to enable camera, but continuing with session:",d)}return setTimeout(()=>{var d;this.currentSession&&(this.currentSession.state="active",this.emit("session.state.changed","active",this.currentSession.state),this.forceAgentConnected(),console.log("๐ค VoxketClient: Session marked as active:",{sessionId:this.currentSession.id,modalities:this.currentSession.activeModalities,agentConnected:this.isAgentConnected,hasRoom:!!this.room,remoteParticipants:((d=this.room)==null?void 0:d.remoteParticipants.size)||0}))},1e3),c}catch(a){throw console.error("VoxketClient: Failed to create session:",a),a instanceof he?a:a instanceof TypeError&&a.message.includes("fetch")?new he("Network connection failed","CONNECTION_FAILED",a):a instanceof Error&&a.message.includes("Failed to fetch connection details")?new he(`API connection failed: ${a.message}`,"CONNECTION_FAILED",a):new he(`Failed to create session: ${a instanceof Error?a.message:"Unknown error"}`,"SESSION_NOT_FOUND",a)}}async startSession(n,r){const o={agentId:n||this.config.agentId||"default-agent",participantName:(r==null?void 0:r.participantName)||this.config.participantName||"User",modalities:(r==null?void 0:r.modalities)||this.config.modalities||["voice","chat"],metadata:r==null?void 0:r.metadata};return this.createSession(o)}async endSession(){var n,r;if(!this.currentSession)return null;try{const o={sessionId:this.currentSession.id,duration:Date.now()-(((n=this.currentSession.startedAt)==null?void 0:n.getTime())||0),messageCount:0,participantCount:((r=this.room)==null?void 0:r.remoteParticipants.size)||0,audioQuality:{avgBitrate:64e3,avgLatency:150,packetLoss:.01,jitter:.05},videoQuality:{avgBitrate:5e5,avgLatency:150,packetLoss:.01,jitter:.05},networkStats:{totalBytesReceived:0,totalBytesSent:0,connectionType:"webrtc",avgRoundTripTime:150},events:[]};return this.currentSession.endedAt=new Date,this.currentSession.state="disconnected",this.emit("session.ended",this.currentSession,o),await this.disconnect(),o}catch(o){throw new he("Failed to end session","SESSION_NOT_FOUND",o)}}getCurrentSession(){return this.currentSession}getCurrentAgentInfo(){return this.currentAgentInfo}getIsAgentConnected(){return this.isAgentConnected}forceAgentConnected(){this.isAgentConnected||(this.isAgentConnected=!0,console.log("๐ค VoxketClient: Agent manually marked as connected"),this.emit("agent.connected",{forced:!0}))}getAgentState(){return this.agentState}setAgentState(n){this.agentState!==n&&(this.agentState=n,this.emit("agent.state.changed",{state:n}))}getAgentAudioTrack(){const n=this.getRemoteParticipants();for(const r of n){const o=r.getTrackPublication(H.Track.Source.Microphone);if(o!=null&&o.track)return{source:H.Track.Source.Microphone,participant:r,publication:o}}return null}getAgentVideoTrack(){const n=this.getRemoteParticipants();for(const r of n){const o=r.getTrackPublication(H.Track.Source.Camera);if(o!=null&&o.track)return{source:H.Track.Source.Camera,participant:r,publication:o}}return null}getVideoTrackRefs(){const n=[],r=this.getLocalParticipant();if(r){const s=r.getTrackPublication(H.Track.Source.Camera);s!=null&&s.track&&n.push({source:H.Track.Source.Camera,participant:r,publication:s});const i=r.getTrackPublication(H.Track.Source.ScreenShare);i!=null&&i.track&&n.push({source:H.Track.Source.ScreenShare,participant:r,publication:i})}const o=this.getRemoteParticipants();for(const s of o){const i=s.getTrackPublication(H.Track.Source.Camera);i!=null&&i.track&&n.push({source:H.Track.Source.Camera,participant:s,publication:i});const a=s.getTrackPublication(H.Track.Source.ScreenShare);a!=null&&a.track&&n.push({source:H.Track.Source.ScreenShare,participant:s,publication:a})}return n}getCameraTrackRefs(){return this.getVideoTrackRefs().filter(n=>n.source===H.Track.Source.Camera)}getScreenShareTrackRefs(){return this.getVideoTrackRefs().filter(n=>n.source===H.Track.Source.ScreenShare)}getChatMessages(){return[...this.chatMessages]}addChatMessage(n){this.chatMessages.some(o=>o.id===n.id)||this.chatMessages.push(n)}updateChatMessage(n){const r=this.chatMessages.findIndex(o=>o.id===n.id);r!==-1&&(this.chatMessages[r]=n)}clearChatMessages(){this.chatMessages=[],this.dismissCurrentInteraction(),this.renderedComponents.clear(),this.forceCleanupFullscreenOverlays(),this.emit("chat.history.cleared")}renderUI(n={}){var c,d,u;const r=this.resolveTarget(n.target||"body"),o=this.getTargetKey(r),s=this.renderedComponents.get(o);s&&s.target===r||this.removeUI(r);const i=(s==null?void 0:s.root)||Hd.createRoot(r),a={agentId:n.agentId||this.config.agentId||"default-agent",participantName:n.participantName||this.config.participantName||"User",baseUrl:this.config.baseUrl,appSecret:this.config.appSecret,appId:this.config.appId,className:n.className,theme:typeof n.theme=="string"?n.theme:void 0,modalities:n.modality||this.config.modalities||["voice"],suportsChatInput:((c=n.modality)==null?void 0:c.includes("chat"))!==!1,suportsVideoInput:((d=n.modality)==null?void 0:d.includes("video"))===!0,suportsScreenShare:((u=n.modality)==null?void 0:u.includes("screen_share"))===!0,autoStart:n.autoStart,displayType:n.displayType||"widget",popupPosition:n.popupPosition||"bottom-right",popupTriggerText:n.popupTriggerText||"Open Chat",width:n.width,height:n.height,onDisplayTypeChange:n.onDisplayTypeChange,prompts:n.prompts,statusMessage:n.statusMessage,welcomeTitle:n.welcomeTitle,welcomeSubTitle:n.welcomeSubTitle,loadingText:n.loadingText,voxketClient:this};if(!i||typeof i.render!="function")throw new Error("Invalid React root. Make sure React 18+ is properly installed and configured.");try{i.render(w.createElement(xd,{config:this.config,autoConnect:n.autoStart||!1,children:w.createElement(bd,a)}))}catch(f){throw console.error("Error rendering Voxket widget:",f),new Error(`Failed to render Voxket widget: ${f instanceof Error?f.message:"Unknown error"}`)}this.renderedComponents.set(o,{root:i,target:r})}removeUI(n){const r=n?this.resolveTarget(n):null;if(r){const o=this.getTargetKey(r),s=this.renderedComponents.get(o);s&&(s.root.unmount(),this.renderedComponents.delete(o),r.querySelectorAll('[id*="voxket"], [class*="voxket"], .fixed.inset-0.z-50').forEach(a=>{try{a.remove()}catch(c){console.warn("Failed to remove element:",c)}}),r===document.body&&r.querySelectorAll(".fixed.z-50, .fixed.inset-0").forEach(c=>{if(c.classList.contains("bg-black")&&c.classList.contains("backdrop-blur-sm"))try{c.remove()}catch(d){console.warn("Failed to remove fixed element:",d)}}))}}removeAllUI(){for(const[n,r]of this.renderedComponents)r.root.unmount();this.renderedComponents.clear(),this.forceCleanupFullscreenOverlays()}forceCleanupFullscreenOverlays(){document.body.querySelectorAll(".fixed.inset-0.z-50").forEach(r=>{if(r.classList.contains("bg-black")&&(r.classList.contains("backdrop-blur-sm")||r.classList.contains("bg-opacity-30")))try{r.remove()}catch(o){console.warn("Failed to remove overlay:",o)}})}resolveTarget(n){if(typeof n=="string"){const r=document.querySelector(n);if(!r)throw new Error(`Target element not found: ${n}`);return r}return n}getTargetKey(n){return n.id?n.id:n.className?n.tagName+"_"+n.className.replace(/\s+/g,"_"):n.tagName+"_"+n.outerHTML.length%1e3}async sendMessage(n,r){var o;if(!this.currentSession)throw console.error("VoxketClient: No active session found"),new he("No active session","SESSION_NOT_FOUND");if(!this.room)throw console.error("VoxketClient: No room instance found"),new he("No room connection","CONNECTION_FAILED");if(!this.room.localParticipant)throw console.error("VoxketClient: No local participant found"),new he("No local participant","CONNECTION_FAILED");this.dismissCurrentInteraction();try{const s={id:`msg_${Date.now()}`,content:n,sender:{id:"user",name:this.config.participantName||"User",type:"participant"},timestamp:new Date,metadata:r||{}},i=await((o=this.room)==null?void 0:o.localParticipant.sendText(n,{topic:"lk.chat",destinationIdentities:[]}));this.emit("chat.message.sent",s)}catch(s){throw console.error("VoxketClient: Failed to send chat message:",s),new he("Failed to send message","NETWORK_ERROR",s)}}async sendChatMessage(n,r){return this.sendMessage(n,r)}async sendAttachments(n,r){if(!this.currentSession)throw console.error("VoxketClient: No active session found"),new he("No active session","SESSION_NOT_FOUND");if(!this.room)throw console.error("VoxketClient: No room instance found"),new he("No room connection","CONNECTION_FAILED");if(!this.room.localParticipant)throw console.error("VoxketClient: No local participant found"),new he("No local participant","CONNECTION_FAILED");if(!n||n.length===0)throw new he("No files provided","INVALID_PARAMETER");this.dismissCurrentInteraction();const o=n.filter(s=>s.type.startsWith("image/"));if(o.length===0)throw new he("Only image files are allowed","INVALID_PARAMETER");o.length!==n.length&&console.warn("VoxketClient: Some non-image files were filtered out");try{const s=o.map(async(i,a)=>{const d={id:`att_${Date.now()}_${a}`,content:`๐ ${i.name}`,sender:{id:"user",name:this.config.participantName||"User",type:"participant"},timestamp:new Date,metadata:{...r,type:"attachment",fileName:i.name,fileSize:i.size,mimeType:i.type,uploading:!0}};this.emit("chat.message.sent",d);const u=await this.room.localParticipant.sendFile(i,{mimeType:i.type,topic:"images",onProgress:h=>{const x={...d,metadata:{...d.metadata,uploadProgress:h}};this.emit("chat.message.updated",x)}});try{const h=new FileReader,x=new Promise((b,C)=>{h.onload=()=>{typeof h.result=="string"?b(h.result):C(new Error("Failed to convert to base64"))},h.onerror=C});h.readAsDataURL(i);const m={type:"image",data:await x,filename:i.name,mimeType:i.type,size:i.size};await this.room.localParticipant.sendText(JSON.stringify(m),{topic:"images",destinationIdentities:[]})}catch(h){console.warn("VoxketClient: Failed to send image data to agent:",h);try{const x=`I've shared an image: ${i.name}`;await this.room.localParticipant.sendText(x,{topic:"lk.chat",destinationIdentities:[]})}catch(x){console.warn("VoxketClient: Failed to send image notification to agent:",x)}}const f={...d,metadata:{...d.metadata,uploading:!1,uploadProgress:1,streamId:u.id}};return this.emit("chat.message.updated",f),u});await Promise.all(s)}catch(s){throw console.error("VoxketClient: Failed to send attachments:",s),new he("Failed to send attachments","NETWORK_ERROR",s)}}async sendAttachment(n,r){return this.sendAttachments([n],r)}toggleMicrophone(n){return this.setMicrophoneEnabled(n!==!1)}async setMicrophoneEnabled(n){var r,o;try{const s=(r=this.room)==null?void 0:r.localParticipant.isMicrophoneEnabled,i=n??!s;await((o=this.room)==null?void 0:o.localParticipant.setMicrophoneEnabled(i)),i?this.emit("track.unmuted",{source:"microphone",enabled:!0}):this.emit("track.muted",{source:"microphone",enabled:!1})}catch(s){throw console.error("VoxketClient: Failed to toggle microphone:",s),new he("Failed to toggle microphone","PERMISSION_DENIED",s)}}toggleCamera(n){return this.setCameraEnabled(n!==!1)}async setCameraEnabled(n){var r,o;try{const s=(r=this.room)==null?void 0:r.localParticipant.isCameraEnabled,i=n??!s;await((o=this.room)==null?void 0:o.localParticipant.setCameraEnabled(i)),i?this.emit("track.unmuted",{source:"camera",enabled:!0}):this.emit("track.muted",{source:"camera",enabled:!1})}catch(s){throw console.error("VoxketClient: Failed to toggle camera:",s),new he("Failed to toggle camera","PERMISSION_DENIED",s)}}async enableCamera(){return this.setCameraEnabled(!0)}async disableCamera(){return this.setCameraEnabled(!1)}async startScreenShare(){var n;try{await((n=this.room)==null?void 0:n.localParticipant.setScreenShareEnabled(!0))}catch(r){throw new he("Failed to start screen share","PERMISSION_DENIED",r)}}async stopScreenShare(){var n;try{await((n=this.room)==null?void 0:n.localParticipant.setScreenShareEnabled(!1))}catch(r){throw new he("Failed to stop screen share","PERMISSION_DENIED",r)}}async getAudioInputDevices(){try{return(await navigator.mediaDevices.enumerateDevices()).filter(r=>r.kind==="audioinput")}catch(n){throw new he("Failed to get audio input devices","DEVICE_ERROR",n)}}async getVideoInputDevices(){try{return(await navigator.mediaDevices.enumerateDevices()).filter(r=>r.kind==="videoinput")}catch(n){throw new he("Failed to get video input devices","DEVICE_ERROR",n)}}async setAudioInputDevice(n){var r;try{if(!((r=this.room)!=null&&r.localParticipant))throw new Error("Not connected to room")}catch(o){throw new he("Failed to set audio input device","DEVICE_ERROR",o)}}async setVideoInputDevice(n){var r;try{if(!((r=this.room)!=null&&r.localParticipant))throw new Error("Not connected to room")}catch(o){throw new he("Failed to set video input device","DEVICE_ERROR",o)}}getLocalParticipant(){var n;return((n=this.room)==null?void 0:n.localParticipant)??null}getRemoteParticipants(){var n;return Array.from(((n=this.room)==null?void 0:n.remoteParticipants.values())??[])}getPublishPermissions(){const n=this.getLocalParticipant();if(!n)return{camera:!1,microphone:!1,screenShare:!1,data:!1};const r=n.permissions;if(!r)return{camera:!0,microphone:!0,screenShare:!0,data:!0};const o=s=>!!r.canPublish&&(r.canPublishSources.length===0||r.canPublishSources.includes(s));return{camera:o(1),microphone:o(2),screenShare:o(3),data:r.canPublishData??!1}}canPublishSource(n){return this.getPublishPermissions()[n]}getRoom(){return this.room}getConnectionState(){return this.connectionState}get connected(){return this.isConnected&&this.connectionState===H.ConnectionState.Connected}getMicrophoneTrack(){const n=this.getLocalParticipant();if(!n)return null;for(const[,r]of n.trackPublications)if(r.source===H.Track.Source.Microphone)return r.track;return null}getCameraTrack(){const n=this.getLocalParticipant();if(!n)return null;for(const[,r]of n.trackPublications)if(r.source===H.Track.Source.Camera)return r.track;return null}getScreenShareTrack(){const n=this.getLocalParticipant();if(!n)return null;for(const[,r]of n.trackPublications)if(r.source===H.Track.Source.ScreenShare)return r.track;return null}get isMicrophoneEnabled(){const n=this.getMicrophoneTrack();return n?!n.isMuted:!1}get isCameraEnabled(){const n=this.getCameraTrack();return n?!n.isMuted:!1}get isScreenShareEnabled(){const n=this.getScreenShareTrack();return n?!n.isMuted:!1}registerPlugin(n){this.pluginManager.register(n)}getPluginManager(){return this.pluginManager}getParticipants(){if(!this.room)return[];const n=[];return this.room.localParticipant&&n.push({id:this.room.localParticipant.identity,name:this.room.localParticipant.name||this.room.localParticipant.identity,isLocal:!0}),this.room.remoteParticipants.forEach(r=>{n.push({id:r.identity,name:r.name||r.identity,isLocal:!1})}),n}getSessionMetrics(){var n,r;return this.currentSession?{sessionId:this.currentSession.id,duration:Date.now()-(((n=this.currentSession.startedAt)==null?void 0:n.getTime())||0),messageCount:0,participantCount:((r=this.room)==null?void 0:r.remoteParticipants.size)||0,audioQuality:{avgBitrate:64e3,avgLatency:150,packetLoss:.01,jitter:.05},videoQuality:{avgBitrate:5e5,avgLatency:150,packetLoss:.01,jitter:.05},networkStats:{totalBytesReceived:0,totalBytesSent:0,connectionType:"webrtc",avgRoundTripTime:150},events:[]}:null}updateConfig(n){this.config={...this.config,...n}}async startRecording(){var n;try{this.emit("recording.started",{sessionId:(n=this.currentSession)==null?void 0:n.id,timestamp:new Date})}catch(r){throw new he("Failed to start recording","RECORDING_ERROR",r)}}async stopRecording(){var n;try{this.emit("recording.stopped",{sessionId:(n=this.currentSession)==null?void 0:n.id,timestamp:new Date})}catch(r){throw new he("Failed to stop recording","RECORDING_ERROR",r)}}async registerFrontendRPC(n,r,o="embedded"){return this.rpcManager.registerFrontendRPC(n,r,o)}getCurrentInteraction(){return this.rpcManager.getCurrentInteraction()}dismissCurrentInteraction(){this.rpcManager.dismissCurrentInteraction()}getRegisteredRpcMethods(){return this.rpcManager.getRegisteredMethods()}unregisterRpcMethod(n){this.rpcManager.unregisterMethod(n)}registerEventListener(n,r){return this.on(n,r)}registerEventEmitter(n,r){if(!this.room)throw new Error("Room not available");try{this.room.registerTextStreamHandler(n,async o=>{try{const s=await o.readAll();r(s)}catch(s){console.error(`Error processing event for topic '${n}':`,s)}})}catch(o){console.warn(`VoxketClient: Handler for topic '${n}' may already be registered:`,o)}}convertMarkdownToText(n){if(!n)return"";let r=n;return r=r.replace(/\*\*(.*?)\*\*/g,"$1"),r=r.replace(/__(.*?)__/g,"$1"),r=r.replace(/\*(.*?)\*/g,"$1"),r=r.replace(/_(.*?)_/g,"$1"),r=r.replace(/~~(.*?)~~/g,"$1"),r=r.replace(/`([^`]+)`/g,"$1"),r=r.replace(/```[\s\S]*?```/g,""),r=r.replace(/^#{1,6}\s+/gm,""),r=r.replace(/\[([^\]]+)\]\([^)]+\)/g,"$1"),r.trim()}}function Lt({title:e,description:t}){console.error(`${e}: ${t}`)}const oy=ie.create($1),sy=ie.create(W1),iy=ie.create(Y1),ay=ie.create(J1);function cy({onClick:e,text:t="Open Chat",position:n="bottom-right",theme:r}){const o={"top-left":"top-4 left-4","top-right":"top-4 right-4","bottom-left":"bottom-4 left-4","bottom-right":"bottom-4 right-4"},s=Ne(r);return l.jsx(ie.button,{onClick:e,className:`fixed ${o[n]} z-50 px-4 py-2 rounded-full shadow-lg ${s.popupTrigger} transition-all duration-200 hover:scale-105`,initial:{scale:0,opacity:0},animate:{scale:1,opacity:1},exit:{scale:0,opacity:0},whileHover:{scale:1.05},whileTap:{scale:.95},children:t})}function Ga({children:e,theme:t,displayType:n="widget",onClose:r,popupPosition:o="bottom-right",onExpand:s}){const i=Ne(t);if(n==="fullscreen")return l.jsx("div",{className:"fixed inset-0 z-[9999] bg-black/40 bg-opacity-30 backdrop-blur-sm flex items-center justify-center p-8",onClick:a=>{a.target===a.currentTarget&&r&&r()},children:l.jsxs("div",{className:"w-full h-full max-w-6xl max-h-[90vh] rounded-2xl relative bg-transparent",onClick:a=>{a.stopPropagation()},children:[r&&l.jsx("button",{onClick:a=>{a.preventDefault(),a.stopPropagation(),r()},className:"absolute top-4 cursor-pointer right-4 z-[10000] w-12 h-12 rounded-full bg-gray-900 bg-opacity-90 text-white flex items-center justify-center hover:bg-gray-800 transition-all duration-200 shadow-lg border border-gray-700 backdrop-blur-sm",title:"Exit Fullscreen",type:"button",children:l.jsx("svg",{width:"20",height:"20",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",children:l.jsx("path",{d:"M8 3H5a2 2 0 0 0-2 2v3m18 0V5a2 2 0 0 0-2-2h-3m0 18h3a2 2 0 0 0 2-2v-3M3 16v3a2 2 0 0 0 2 2h3"})})}),l.jsxs("div",{id:"voice-card",className:`theme-${t} ${i.card} w-full h-full flex flex-col rounded-xl shadow-2xl`,style:{minHeight:"600px"},children:[l.jsx("div",{className:i.cardTopGradient}),l.jsx("div",{className:i.cardPurpleBlur}),l.jsx("div",{className:i.cardPinkBlur}),l.jsx("div",{className:" flex flex-col h-full w-full",children:e}),l.jsx("div",{className:i.cardPulse1}),l.jsx("div",{className:i.cardPulse2,style:{animationDelay:"1s"}})]})]})});if(n==="popup"){const a={"top-left":"top-4 left-4","top-right":"top-4 right-4","bottom-left":"bottom-4 left-4","bottom-right":"bottom-4 right-4"};return l.jsx("div",{className:"fixed rounded-2xl inset-0 z-[9999] pointer-events-none",children:l.jsxs("div",{className:`fixed rounded-2xl ${a[o]} pointer-events-auto`,children:[r&&l.jsx("button",{onClick:r,className:"absolute -top-2 -right-2 z-10 w-8 h-8 rounded-full bg-gray-900 bg-opacity-90 text-white flex items-center justify-center hover:bg-gray-800 transition-all duration-200 text-sm shadow-lg border border-gray-700",children:"ร"}),l.jsxs("div",{id:"voice-card",className:`theme-${t} ${i.card} rounded-2xl flex flex-col`,style:{width:"300px",height:"450px"},children:[l.jsx("div",{className:i.cardPurpleBlur}),l.jsx("div",{className:i.cardPinkBlur}),l.jsx("div",{className:" flex flex-col h-full w-full",children:e}),l.jsx("div",{className:i.cardPulse1}),l.jsx("div",{className:i.cardPulse2,style:{animationDelay:"1s"}})]})]})})}return l.jsxs("div",{id:"voice-card",className:`theme-${t} ${i.card}`,style:{height:"100%",maxHeight:"100%"},children:[l.jsx("div",{className:i.cardTopGradient}),l.jsx("div",{className:i.cardPurpleBlur}),l.jsx("div",{className:i.cardPinkBlur}),e,l.jsx("div",{className:i.cardPulse1}),l.jsx("div",{className:i.cardPulse2,style:{animationDelay:"1s"}})]})}function bd(e){if(typeof window>"u")return null;console.log("๐ฏ Widget component rendering with props:",{displayType:e.displayType,popupPosition:e.popupPosition,theme:e.theme});const{agentId:t,participantName:n,baseUrl:r,appSecret:o,appId:s,prompts:i,statusMessage:a,welcomeTitle:c,welcomeSubTitle:d,className:u,width:f,height:h,loadingText:x,suportsChatInput:y=!0,suportsVideoInput:m=!0,suportsScreenShare:b=!0,theme:C="vox",onSessionStart:v,onSessionEnd:T,enableSessionLogging:k=!0,onSessionLogsUpdate:S,onSessionMetricsUpdate:j,modalities:P=["voice"],displayType:A="widget",popupPosition:_="bottom-right",popupTriggerText:p="Open Chat",onPopupToggle:V,voxketClient:B,onDisplayTypeChange:G}=e,[te,ne]=g.useState(()=>B?!!B.getCurrentSession():!1),[oe,X]=g.useState(!1),[I,q]=g.useState(t||""),[M,z]=g.useState(n||"User"),[Q,W]=g.useState(()=>B?B.getCurrentSession():null),[U,E]=g.useState(()=>{var re,qe,We;if(B){const Se=B.getCurrentSession();if((re=Se==null?void 0:Se.activeModalities)!=null&&re.includes("chat"))return"chat";if((qe=Se==null?void 0:Se.activeModalities)!=null&&qe.includes("voice"))return"voice";if((We=Se==null?void 0:Se.activeModalities)!=null&&We.includes("video"))return"video"}return"welcome"}),[D,O]=g.useState(!1);g.useEffect(()=>{console.log("๐ฏ Widget displayType prop changed to:",A)},[A]),g.useEffect(()=>{console.log("๐ Session state changed:",{currentMode:U,sessionStarted:te,loading:oe,currentSession:Q==null?void 0:Q.id,isPopupOpen:D})},[U,te,oe,Q,D]);const $=g.useMemo(()=>{if(B)return console.log("๐ Using passed VoxketClient to preserve session state"),B;console.log("๐ Creating new VoxketClient instance");const re={appId:s,appSecret:o,baseUrl:r,agentId:I,participantName:M||"User",modalities:P};return new Rn(re)},[B,s,o,r,I,M,P]),F=P,L=g.useMemo(()=>$.getRoom()||new H.Room,[$]),J={suportsChatInput:y,suportsVideoInput:m,suportsScreenShare:b},{sessionMetrics:R,sessionLogs:ce,logEvent:xe}=md({room:L,onSessionStart:v,onSessionEnd:T,enableConsoleLogging:k,enableLocalStorage:k,voxketSessionId:Q==null?void 0:Q.id});g.useEffect(()=>{S&&S(ce)},[ce,S]),g.useEffect(()=>{j&&R&&j(R)},[R,j]),g.useEffect(()=>{const re=We=>{console.log("๐ด Room disconnected:",We),X(!1),ne(!1),W(null),E("welcome")},qe=We=>{console.log("๐น Media devices error:",We),Lt({title:"Allow access to your microphone/camera",description:`${We.name}: ${We.message}`})};return L.on(H.RoomEvent.MediaDevicesError,qe),L.on(H.RoomEvent.Disconnected,re),()=>{L.off(H.RoomEvent.Disconnected,re),L.off(H.RoomEvent.MediaDevicesError,qe)}},[L]);const pe=async()=>{try{console.log("๐ค Starting voice session...",{agentId:I,participantName:M}),console.log("๐ค Pre-start state:",{currentMode:U,sessionStarted:te,loading:oe}),X(!0),ne(!0),E("voice"),console.log("๐ค State after mode change:",{currentMode:"voice",sessionStarted:!0,loading:!0}),xe("USER_STARTED_VOICE_SESSION",{agentId:I,participantName:M});const re=await $.startSession(I,{participantName:M||"User",modalities:["voice",...m?["video"]:[]]});console.log("โ
Voice session started successfully:",re.id),W(re),X(!1),v&&v(re.id)}catch(re){console.error("โ Failed to start voice session:",re),Lt({title:"Failed to start voice session",description:re instanceof Error?re.message:"Unknown error occurred"}),X(!1),ne(!1),E("welcome")}},Re=async()=>{try{X(!0),ne(!0),E("chat"),xe("USER_STARTED_CHAT_SESSION",{agentId:I,participantName:M});const re=await $.startSession(I,{participantName:M||"User",modalities:["chat"]});W(re),X(!1),v&&v(re.id)}catch(re){console.error("Failed to start chat session:",re),Lt({title:"Failed to start chat session",description:re instanceof Error?re.message:"Unknown error occurred"}),X(!1),ne(!1),E("welcome")}},tt=async()=>{try{console.log("๐บ Starting video session...",{agentId:I,participantName:M}),console.log("๐บ Pre-start state:",{currentMode:U,sessionStarted:te,loading:oe}),X(!0),ne(!0),E("video"),console.log("๐บ State after mode change:",{currentMode:"video",sessionStarted:!0,loading:!0}),xe("USER_STARTED_VIDEO_SESSION",{agentId:I,participantName:M});const re=await $.startSession(I,{participantName:M||"User",modalities:["video","voice"]});console.log("โ
Video session started successfully:",re.id),W(re),X(!1),v&&v(re.id)}catch(re){console.error("โ Failed to start video session:",re),Lt({title:"Failed to start video session",description:re instanceof Error?re.message:"Unknown error occurred"}),X(!1),ne(!1),E("welcome")}},dt=()=>{E("welcome"),G&&G(e.displayType||"widget"),Q&&te&&(ne(!1),W(null),$.disconnect()),A==="popup"&&!D&&O(!0)},an=()=>{const re=!D;O(re),V&&V(re),!re&&!(Q&&te)&&(E("welcome"),ne(!1),W(null))},Dd=()=>{console.log("๐ Closing fullscreen, switching to widget display type"),e.onDisplayTypeChange?e.onDisplayTypeChange("widget"):console.warn("โ ๏ธ No onDisplayTypeChange callback provided")},$d=()=>{if(console.log("๐ Expand to fullscreen requested"),e.onDisplayTypeChange)e.onDisplayTypeChange("fullscreen");else{console.warn("โ ๏ธ No onDisplayTypeChange callback provided for expand functionality");const re=document.getElementById("voice-card")||document.querySelector(".voxket-widget-container");re&&re.requestFullscreen?re.requestFullscreen().catch(qe=>{console.warn("โ ๏ธ Fullscreen API not supported or failed:",qe),Lt({title:"Expand functionality unavailable",description:"Please implement onDisplayTypeChange callback for expand functionality"})}):Lt({title:"Expand functionality unavailable",description:"Please implement onDisplayTypeChange callback for expand functionality"})}};g.useEffect(()=>{var re,qe,We;if(B&&$){console.log("๐ Syncing widget state with existing client session state");const Se=$.getCurrentSession(),Fd=$.connected;console.log("๐ Existing session state:",{hasSession:!!Se,sessionId:Se==null?void 0:Se.id,isConnected:Fd,activeModalities:Se==null?void 0:Se.activeModalities}),Se&&(console.log("โ
Restoring session state from existing client"),W(Se),ne(!0),X(!1),(re=Se.activeModalities)!=null&&re.includes("chat")?E("chat"):(qe=Se.activeModalities)!=null&&qe.includes("voice")?E("voice"):(We=Se.activeModalities)!=null&&We.includes("video")&&E("video"))}},[B,$]),g.useEffect(()=>()=>{console.log("๐งน Cleaning up widget component"),B?console.log("๐ Widget cleanup: preserving passed client instance"):(console.log("๐งน Widget cleanup: disconnecting self-created client"),$.disconnect())},[$,B]);let Tr="w-96",Ar="h-[25rem]",jr={};if(f&&(f.startsWith("w-")?Tr=f:(jr.width=f,Tr="")),h&&(h.startsWith("h-")?Ar=h:(jr.height=h,Ar="")),A==="popup"&&!D)return console.log("๐ก Showing popup trigger button"),l.jsx(cy,{onClick:an,text:p,position:_,theme:C});console.log("๐ข Rendering widget content, displayType:",A,"isPopupOpen:",D,"currentMode:",U,"sessionStarted:",te,"loading:",oe);let Pr=`voxket-widget-root theme-${C}`,Dn={scrollMargin:0,scrollPadding:0,contain:"layout style paint"};A==="widget"?(Pr+=` flex items-center justify-center min-h-fit ${Tr} ${Ar} ${u}`,Dn={...Dn,...jr}):(Pr+=` ${u||""}`,Dn={});const Fs=l.jsx("div",{className:"h-full w-full flex flex-col overflow-hidden",children:l.jsxs(Wt,{mode:"wait",children:[U==="welcome"&&!oe&&l.jsx(ay,{agentId:I,participantName:M||"",onAgentIdChange:q,onParticipantNameChange:z,onStartCall:pe,onStartChat:Re,onStartVideo:tt,disabled:te||oe,prompts:i,statusMessage:a,title:c,subTitle:d,theme:C,modalities:F,displayType:A,initial:{opacity:0,y:0},animate:{opacity:1,y:0},exit:{opacity:0,y:40},transition:{duration:.3,ease:"easeInOut"}},"welcome"),U==="voice"&&l.jsxs(Ie.RoomContext.Provider,{value:L,children:[l.jsx(Ie.RoomAudioRenderer,{}),l.jsx(Ie.StartAudio,{label:"Start Audio"}),l.jsx(oy,{loadingText:x,participantName:M||"User",capabilities:J,sessionStarted:te,disabled:!te,theme:C,client:$,displayType:A,onBack:A==="popup"?an:dt,initial:{opacity:0,y:40},animate:{opacity:1,y:0},exit:{opacity:0,y:-40},transition:{duration:.3,ease:"easeInOut"}},"session-view")]}),U==="chat"&&l.jsx(sy,{client:$,theme:C,displayType:A,onBack:A==="popup"?an:dt,onEndChat:dt,disabled:!te,initial:{opacity:0,y:40},animate:{opacity:1,y:0},exit:{opacity:0,y:-40},transition:{duration:.3,ease:"easeInOut"}},"chat-view"),U==="video"&&l.jsxs(Ie.RoomContext.Provider,{value:L,children:[l.jsx(Ie.RoomAudioRenderer,{}),l.jsx(Ie.StartAudio,{label:"Start Audio"}),l.jsx(iy,{client:$,theme:C,displayType:A,onBack:A==="popup"?an:dt,onEndCall:dt,disabled:!te,initial:{opacity:0,y:40},animate:{opacity:1,y:0},exit:{opacity:0,y:-40},transition:{duration:.3,ease:"easeInOut"}},"video-view")]})]})});return A==="fullscreen"||A==="popup"?(console.log("๐ฑ Rendering fullscreen/popup mode, displayType:",A),l.jsx(Ga,{theme:C,displayType:A,popupPosition:_,onClose:A==="fullscreen"?Dd:an,children:Fs})):(console.log("๐ฆ Rendering widget mode"),l.jsx("div",{className:Pr,style:Dn,children:l.jsx(Ga,{theme:C,displayType:A,popupPosition:_,onExpand:$d,children:Fs})}))}class vd extends g.Component{constructor(t){super(t),this.state={hasError:!1}}static getDerivedStateFromError(t){return{hasError:!0,error:t}}componentDidCatch(t,n){console.error("VoxketWidget Error:",t,n)}render(){if(this.state.hasError){if(this.props.fallback){const t=this.props.fallback;return g.createElement(t,{error:this.state.error})}return g.createElement("div",{style:{padding:"20px",border:"1px solid #ff4444",borderRadius:"8px",background:"#fff5f5",color:"#cc0000"}},"VoxketWidget encountered an error. Please check the console for details.")}return this.props.children}}function ly({logs:e,onClear:t,onExport:n}){const[r,o]=w.useState(!1),[s,i]=w.useState(""),a=e.filter(c=>!s||c.event.toLowerCase().includes(s.toLowerCase()));return r?l.jsx("div",{className:"fixed inset-0 bg-black bg-opacity-50 flex items-center justify-center z-50",children:l.jsxs("div",{className:"bg-white rounded-lg shadow-xl max-w-4xl w-full max-h-[80vh] flex flex-col m-4",children:[l.jsxs("div",{className:"flex items-center justify-between p-4 border-b",children:[l.jsxs("h2",{className:"text-lg font-semibold",children:["Session Logs (",e.length,")"]}),l.jsxs("div",{className:"flex items-center gap-2",children:[l.jsx("input",{type:"text",placeholder:"Filter events...",value:s,onChange:c=>i(c.target.value),className:"px-3 py-1 border rounded text-sm"}),l.jsx("button",{onClick:t,className:"px-3 py-1 bg-red-600 text-white rounded text-sm hover:bg-red-700",children:"Clear"}),l.jsx("button",{onClick:n,className:"px-3 py-1 bg-green-600 text-white rounded text-sm hover:bg-green-700",children:"Export"}),l.jsx("button",{onClick:()=>o(!1),className:"px-3 py-1 bg-gray-600 text-white rounded text-sm hover:bg-gray-700",children:"Close"})]})]}),l.jsx("div",{className:"flex-1 overflow-auto p-4",children:a.length===0?l.jsx("p",{className:"text-gray-500 text-center py-8",children:"No logs found"}):l.jsx("div",{className:"space-y-2",children:a.map((c,d)=>l.jsxs("div",{className:"border rounded p-3 text-sm",children:[l.jsxs("div",{className:"flex items-center justify-between mb-1",children:[l.jsx("span",{className:"font-semibold text-blue-600",children:c.event}),l.jsx("span",{className:"text-gray-500 text-xs",children:new Date(c.timestamp).toLocaleTimeString()})]}),c.sessionId&&l.jsxs("div",{className:"text-xs text-gray-600 mb-1",children:["Session: ",c.sessionId]}),c.data&&l.jsx("div",{className:"bg-gray-50 p-2 rounded text-xs",children:l.jsx("pre",{className:"whitespace-pre-wrap overflow-auto",children:JSON.stringify(c.data,null,2)})})]},d))})})]})}):l.jsxs("button",{onClick:()=>o(!0),className:"fixed bottom-4 right-4 bg-blue-600 text-white px-4 py-2 rounded-lg shadow-lg hover:bg-blue-700 transition-colors text-sm z-50",children:["Session Logs (",e.length,")"]})}function dy({metrics:e}){return e?l.jsxs("div",{className:"bg-gray-100 p-4 rounded-lg",children:[l.jsx("h3",{className:"font-semibold mb-2",children:"Current Session"}),l.jsxs("div",{className:"grid grid-cols-2 gap-4 text-sm",children:[l.jsxs("div",{children:[l.jsx("span",{className:"text-gray-600",children:"Session ID:"}),l.jsx("div",{className:"font-mono text-xs",children:e.sessionId})]}),l.jsxs("div",{children:[l.jsx("span",{className:"text-gray-600",children:"Start Time:"}),l.jsx("div",{children:new Date(e.startTime).toLocaleString()})]}),l.jsxs("div",{children:[l.jsx("span",{className:"text-gray-600",children:"Messages:"}),l.jsx("div",{children:e.totalMessages})]}),l.jsxs("div",{children:[l.jsx("span",{className:"text-gray-600",children:"Participants:"}),l.jsx("div",{children:e.participantCount})]}),l.jsxs("div",{children:[l.jsx("span",{className:"text-gray-600",children:"Connection Issues:"}),l.jsx("div",{children:e.connectionIssues})]}),l.jsxs("div",{children:[l.jsx("span",{className:"text-gray-600",children:"Duration:"}),l.jsxs("div",{children:[Math.round((Date.now()-new Date(e.startTime).getTime())/1e3),"s"]})]})]})]}):null}function Vt(){const{currentSession:e,sessionState:t,sessionMetrics:n,createSession:r,endSession:o}=et(),s=w.useCallback(async(a,c)=>await r(a,c),[r]),i=w.useCallback(async()=>await o(),[o]);return{session:e,state:t,metrics:n,isActive:e!==null&&t!=="disconnected",isConnecting:t==="connecting",isConnected:t==="connected"||t==="active",start:s,stop:i}}function wd(){const{sessionMetrics:e,currentSession:t}=et();return{metrics:e,sessionId:t==null?void 0:t.id,duration:e==null?void 0:e.duration,participantCount:e==null?void 0:e.participantCount,messageCount:e==null?void 0:e.messageCount,audioQuality:e==null?void 0:e.audioQuality,networkStats:e==null?void 0:e.networkStats}}function Sd(){const{setMicrophoneEnabled:e,client:t}=et(),[n,r]=w.useState(!1),[o,s]=w.useState(!1),i=w.useCallback(async()=>{if(!o){s(!0);try{const d=!n;await e(d),r(d)}catch(d){console.error("Failed to toggle microphone:",d)}finally{s(!1)}}},[n,o,e]),a=w.useCallback(async()=>{if(!(n||o)){s(!0);try{await e(!0),r(!0)}catch(d){console.error("Failed to enable microphone:",d)}finally{s(!1)}}},[n,o,e]),c=w.useCallback(async()=>{if(!(!n||o)){s(!0);try{await e(!1),r(!1)}catch(d){console.error("Failed to disable microphone:",d)}finally{s(!1)}}},[n,o,e]);return{isEnabled:n,isLoading:o,toggle:i,enable:a,disable:c}}function kd(){const{setCameraEnabled:e}=et(),[t,n]=w.useState(!1),[r,o]=w.useState(!1),s=w.useCallback(async()=>{if(!r){o(!0);try{const c=!t;await e(c),n(c)}catch(c){console.error("Failed to toggle camera:",c)}finally{o(!1)}}},[t,r,e]),i=w.useCallback(async()=>{if(!(t||r)){o(!0);try{await e(!0),n(!0)}catch(c){console.error("Failed to enable camera:",c)}finally{o(!1)}}},[t,r,e]),a=w.useCallback(async()=>{if(!(!t||r)){o(!0);try{await e(!1),n(!1)}catch(c){console.error("Failed to disable camera:",c)}finally{o(!1)}}},[t,r,e]);return{isEnabled:t,isLoading:r,toggle:s,enable:i,disable:a}}function Cd(){const{startScreenShare:e,stopScreenShare:t}=et(),[n,r]=w.useState(!1),[o,s]=w.useState(!1),i=w.useCallback(async()=>{if(!(n||o)){s(!0);try{await e(),r(!0)}catch(d){console.error("Failed to start screen share:",d)}finally{s(!1)}}},[n,o,e]),a=w.useCallback(async()=>{if(!(!n||o)){s(!0);try{await t(),r(!1)}catch(d){console.error("Failed to stop screen share:",d)}finally{s(!1)}}},[n,o,t]),c=w.useCallback(async()=>{n?await a():await i()},[n,i,a]);return{isSharing:n,isLoading:o,start:i,stop:a,toggle:c}}function uy(){const{client:e}=et(),[t,n]=w.useState({tracks:[],layout:{type:"grid",showLocalVideo:!0,aspectRatio:"16:9"},isRecording:!1}),r=w.useMemo(()=>t.tracks.find(m=>m.isLocal),[t.tracks]),o=w.useMemo(()=>t.tracks.filter(m=>!m.isLocal),[t.tracks]),s=w.useCallback(async()=>{try{r!=null&&r.isEnabled?await(e==null?void 0:e.disableCamera()):await(e==null?void 0:e.enableCamera())}catch(m){throw console.error("Failed to toggle camera:",m),m}},[e,r]),i=w.useCallback(async()=>{try{t.tracks.find(b=>b.isScreenShare)?await(e==null?void 0:e.stopScreenShare()):await(e==null?void 0:e.startScreenShare())}catch(m){throw console.error("Failed to toggle screen share:",m),m}},[e,t.tracks]),a=w.useCallback(m=>{n(b=>({...b,layout:m}))},[]),c=w.useCallback(m=>{n(b=>({...b,pinnedTrack:m}))},[]),d=w.useCallback(()=>{n(m=>({...m,pinnedTrack:void 0}))},[]),u=w.useCallback(async()=>{try{await(e==null?void 0:e.startRecording()),n(m=>({...m,isRecording:!0}))}catch(m){throw console.error("Failed to start recording:",m),m}},[e]),f=w.useCallback(async()=>{try{await(e==null?void 0:e.stopRecording()),n(m=>({...m,isRecording:!1}))}catch(m){throw console.error("Failed to stop recording:",m),m}},[e]),h=w.useCallback(m=>t.tracks.find(b=>b.id===m),[t.tracks]),x=w.useCallback(m=>t.tracks.filter(b=>b.participantId===m),[t.tracks]),y=w.useCallback(m=>m.isEnabled&&t.tracks.includes(m),[t.tracks]);return w.useEffect(()=>{if(!e)return;const m=v=>{n(T=>({...T,tracks:[...T.tracks.filter(k=>k.id!==v.id),v]}))},b=v=>{n(T=>{var k;return{...T,tracks:T.tracks.filter(S=>S.id!==v),pinnedTrack:((k=T.pinnedTrack)==null?void 0:k.id)===v?void 0:T.pinnedTrack}})},C=v=>{n(T=>({...T,tracks:T.tracks.map(k=>k.id===v.id?v:k)}))};return e.on("videoTrackAdded",m),e.on("videoTrackRemoved",b),e.on("videoTrackUpdated",C),()=>{e.off("videoTrackAdded",m),e.off("videoTrackRemoved",b),e.off("videoTrackUpdated",C)}},[e]),{tracks:t.tracks,localTrack:r,remoteTraracks:o,pinnedTrack:t.pinnedTrack,layout:t.layout,isRecording:t.isRecording,toggleCamera:s,toggleScreenShare:i,setLayout:a,pinTrack:c,unpinTrack:d,startRecording:u,stopRecording:f,getTrackById:h,getTracksByParticipant:x,isTrackActive:y}}function Er(){const{chatMessages:e,sendChatMessage:t,currentSession:n}=et(),[r,o]=w.useState(!1),s=w.useCallback(async d=>{if(!(!d.trim()||r||!n)){o(!0);try{await t(d.trim())}catch(u){throw console.error("Failed to send chat message:",u),u}finally{o(!1)}}},[t,r,n]),{userMessages:i,agentMessages:a,allMessages:c}=w.useMemo(()=>{const d=e.filter(f=>f.sender.type==="participant"),u=e.filter(f=>f.sender.type==="agent");return{userMessages:d,agentMessages:u,allMessages:e}},[e]);return{messages:c,userMessages:i,agentMessages:a,messageCount:c.length,isSending:r,canSend:!!n&&!r,send:s}}function fy(){const{send:e,isSending:t,canSend:n}=Er(),[r,o]=w.useState(""),s=w.useCallback(async()=>{if(!(!r.trim()||!n))try{await e(r),o("")}catch(a){throw a}},[r,e,n]),i=w.useCallback(a=>{a.key==="Enter"&&!a.shiftKey&&(a.preventDefault(),s())},[s]);return{value:r,setValue:o,send:s,handleKeyPress:i,isSending:t,canSend:n&&r.trim().length>0}}function Rs(){const{isConnected:e,isConnecting:t,connectionError:n,connect:r,disconnect:o}=et(),s=w.useCallback(async()=>{if(!(e||t))try{await r()}catch(a){throw console.error("Failed to connect:",a),a}},[r,e,t]),i=w.useCallback(async()=>{if(e)try{await o()}catch(a){throw console.error("Failed to disconnect:",a),a}},[o,e]);return{isConnected:e,isConnecting:t,isDisconnected:!e&&!t,error:n,hasError:!!n,connect:s,disconnect:i}}function Ed(){const{participants:e}=et();return{participants:e,count:e.length,localParticipant:e.find(t=>t.isLocal),remoteParticipants:e.filter(t=>!t.isLocal)}}const Td=w.createContext({}),In=()=>w.useContext(Td);function Ad({children:e,...t}){return l.jsx(Td.Provider,{value:t,children:e})}function Qn({name:e,children:t,fallback:n,className:r}){return l.jsx("div",{className:`voxket-slot voxket-slot--${e} ${r||""}`,children:t||n})}function jd(e,t={}){return Object.assign(e,t)}function Pd({showMicrophoneControl:e=!0,showCameraControl:t=!0,showScreenShareControl:n=!0,showSessionActions:r=!0,customControls:o,className:s=""}){const i=Vt(),a=Sd(),c=kd(),d=Cd(),u=In(),f=["voxket-session-controls",`voxket-session-controls--${u.variant||"default"}`,`voxket-session-controls--${u.size||"md"}`,i.isActive?"voxket-session-controls--active":"voxket-session-controls--inactive",s].filter(Boolean).join(" ");return!i.isActive&&!r?l.jsx("div",{className:f,children:l.jsx("div",{className:"voxket-controls-inactive",children:l.jsx("p",{children:"Controls available during active session"})})}):l.jsxs("div",{className:f,children:[r&&l.jsx("div",{className:"voxket-session-actions",children:i.isActive?l.jsx("button",{onClick:i.stop,className:"voxket-button voxket-button--danger",children:"End Session"}):l.jsx(hy,{})}),i.isActive&&l.jsxs("div",{className:"voxket-media-controls",children:[e&&l.jsxs("button",{onClick:a.toggle,disabled:a.isLoading,className:`voxket-button voxket-button--media ${a.isEnabled?"voxket-button--active":""}`,title:a.isEnabled?"Mute microphone":"Unmute microphone",children:[l.jsx("span",{className:"voxket-icon",children:"๐ค"}),a.isLoading?"Loading...":a.isEnabled?"Mute":"Unmute"]}),t&&l.jsxs("button",{onClick:c.toggle,disabled:c.isLoading,className:`voxket-button voxket-button--media ${c.isEnabled?"voxket-button--active":""}`,title:c.isEnabled?"Stop camera":"Start camera",children:[l.jsx("span",{className:"voxket-icon",children:"๐น"}),c.isLoading?"Loading...":c.isEnabled?"Stop Video":"Start Video"]}),n&&l.jsxs("button",{onClick:d.toggle,disabled:d.isLoading,className:`voxket-button voxket-button--media ${d.isSharing?"voxket-button--active":""}`,title:d.isSharing?"Stop screen share":"Start screen share",children:[l.jsx("span",{className:"voxket-icon",children:"๐ฅ๏ธ"}),d.isLoading?"Loading...":d.isSharing?"Stop Share":"Share Screen"]})]}),o&&l.jsx("div",{className:"voxket-custom-controls",children:o})]})}function hy(){Vt();const[e,t]=w.useState(!1),n=async()=>{t(!0);try{console.log("Start session - agentId needed")}catch(r){console.error("Failed to start session:",r)}finally{t(!1)}};return l.jsx("button",{onClick:n,disabled:e,className:"voxket-button voxket-button--primary",children:e?"Starting...":"Start Session"})}function Is({showConnectionStatus:e=!0,showSessionInfo:t=!0,showAgentInfo:n=!0,className:r=""}){const o=Vt(),s=Rs(),i=In(),a=["voxket-session-header",`voxket-session-header--${i.variant||"default"}`,`voxket-session-header--${i.size||"md"}`,r].filter(Boolean).join(" ");return l.jsxs("div",{className:a,children:[e&&l.jsxs("div",{className:"voxket-connection-status",children:[l.jsx("div",{className:`voxket-status-indicator ${s.isConnected?"connected":"disconnected"}`}),l.jsx("span",{className:"voxket-status-text",children:s.isConnecting?"Connecting...":s.isConnected?"Connected":"Disconnected"})]}),t&&o.session&&l.jsxs("div",{className:"voxket-session-info",children:[l.jsxs("div",{className:"voxket-session-id",children:["Session: ",o.session.id.slice(-8)]}),l.jsxs("div",{className:"voxket-session-state",children:["State: ",o.state]})]}),n&&o.session&&l.jsxs("div",{className:"voxket-agent-info",children:[l.jsxs("div",{className:"voxket-agent-id",children:["Agent: ",o.session.agentId]}),l.jsxs("div",{className:"voxket-modalities",children:["Modalities: ",o.session.activeModalities.join(", ")]})]}),s.error&&l.jsxs("div",{className:"voxket-error-message",children:["Error: ",s.error.message]})]})}function Ds({showChat:e=!0,showTranscriptions:t=!1,customContent:n,className:r=""}){const o=Vt(),s=Er(),i=In(),a=["voxket-session-content",`voxket-session-content--${i.variant||"default"}`,`voxket-session-content--${i.size||"md"}`,r].filter(Boolean).join(" ");return o.isActive?l.jsx("div",{className:a,children:n||l.jsxs(l.Fragment,{children:[e&&l.jsxs("div",{className:"voxket-chat-container",children:[l.jsxs("div",{className:"voxket-chat-messages",children:[s.messages.map(c=>l.jsxs("div",{className:`voxket-message voxket-message--${c.sender.type}`,children:[l.jsxs("div",{className:"voxket-message-header",children:[l.jsx("span",{className:"voxket-message-sender",children:c.sender.name}),l.jsx("span",{className:"voxket-message-time",children:c.timestamp.toLocaleTimeString()})]}),l.jsx("div",{className:"voxket-message-content",children:c.content})]},c.id)),s.messages.length===0&&l.jsx("div",{className:"voxket-empty-messages",children:l.jsx("p",{children:"No messages yet. Start the conversation!"})})]}),l.jsx(my,{})]}),t&&l.jsx("div",{className:"voxket-transcriptions",children:l.jsx("div",{className:"voxket-transcription-placeholder",children:l.jsx("p",{children:"Voice transcriptions will appear here"})})})]})}):l.jsx("div",{className:a,children:l.jsx("div",{className:"voxket-inactive-state",children:l.jsxs("div",{className:"voxket-inactive-message",children:[l.jsx("h3",{children:"Start a conversation"}),l.jsx("p",{children:"Begin a session to start chatting with the AI agent"})]})})})}function my(){const e=Er(),[t,n]=w.useState(""),r=async()=>{if(!(!t.trim()||!e.canSend))try{await e.send(t),n("")}catch(s){console.error("Failed to send message:",s)}},o=s=>{s.key==="Enter"&&!s.shiftKey&&(s.preventDefault(),r())};return l.jsxs("div",{className:"voxket-chat-input",children:[l.jsx("input",{type:"text",value:t,onChange:s=>n(s.target.value),onKeyPress:o,placeholder:"Type your message...",disabled:!e.canSend,className:"voxket-input"}),l.jsx("button",{onClick:r,disabled:!e.canSend||!t.trim(),className:"voxket-send-button",children:e.isSending?"Sending...":"Send"})]})}function $s({showMetrics:e=!0,showParticipants:t=!0,showStatus:n=!0,customFooter:r,className:o=""}){const s=Vt(),i=wd(),a=Ed(),c=In(),d=["voxket-session-footer",`voxket-session-footer--${c.variant||"default"}`,`voxket-session-footer--${c.size||"md"}`,o].filter(Boolean).join(" ");return s.isActive?l.jsx("div",{className:d,children:r||l.jsxs(l.Fragment,{children:[n&&l.jsxs("div",{className:"voxket-session-status",children:[l.jsx("div",{className:"voxket-status-indicator voxket-status-indicator--active"}),l.jsx("span",{className:"voxket-status-text",children:"Session Active"})]}),e&&i.metrics&&l.jsxs("div",{className:"voxket-session-metrics",children:[l.jsxs("div",{className:"voxket-metric",children:[l.jsx("span",{className:"voxket-metric-label",children:"Duration:"}),l.jsx("span",{className:"voxket-metric-value",children:gy(i.duration||0)})]}),l.jsxs("div",{className:"voxket-metric",children:[l.jsx("span",{className:"voxket-metric-label",children:"Messages:"}),l.jsx("span",{className:"voxket-metric-value",children:i.metrics.messageCount})]})]}),t&&l.jsxs("div",{className:"voxket-participants-info",children:[l.jsxs("span",{className:"voxket-participants-count",children:[a.count," participant",a.count!==1?"s":""]}),a.remoteParticipants.length>0&&l.jsx("div",{className:"voxket-participant-list",children:a.remoteParticipants.map(u=>l.jsx("span",{className:"voxket-participant-name",children:u.name},u.id))})]})]})}):l.jsx("div",{className:d,children:l.jsx("div",{className:"voxket-footer-inactive",children:l.jsx("span",{className:"voxket-status-text",children:"Ready to start session"})})})}function gy(e){const t=Math.floor(e/1e3),n=Math.floor(t/60),r=Math.floor(n/60);return r>0?`${r}:${(n%60).toString().padStart(2,"0")}:${(t%60).toString().padStart(2,"0")}`:`${n}:${(t%60).toString().padStart(2,"0")}`}function py({agentId:e,sessionConfig:t,autoStart:n=!1,onSessionStart:r,onSessionEnd:o,variant:s="default",size:i="md",theme:a,className:c="",children:d}){var x;const u=Vt(),f=Rs();w.useEffect(()=>{n&&e&&f.isConnected&&!u.isActive&&u.start(e,t).catch(console.error)},[n,e,f.isConnected,u.isActive]),w.useEffect(()=>{var y;(y=u.session)!=null&&y.id&&r&&r(u.session.id)},[(x=u.session)==null?void 0:x.id,r]),w.useEffect(()=>()=>{u.isActive&&o&&u.stop().then(o).catch(console.error)},[]);const h=["voxket-session",`voxket-session--${s}`,`voxket-session--${i}`,u.isActive?"voxket-session--active":"voxket-session--inactive",c].filter(Boolean).join(" ");return l.jsx(Ad,{variant:s,size:i,theme:a,className:c,children:l.jsx("div",{className:h,children:d||l.jsxs(l.Fragment,{children:[l.jsx(Qn,{name:"header",fallback:l.jsx(Is,{})}),l.jsx(Qn,{name:"content",fallback:l.jsx(Ds,{})}),l.jsx(Qn,{name:"footer",fallback:l.jsx($s,{})})]})})})}const Md=jd(py,{Header:Is,Content:Ds,Footer:$s,Controls:Pd}),Pt={name:"default",colors:{primary:"#3B82F6",secondary:"#6B7280",accent:"#8B5CF6",background:"#FFFFFF",surface:"#F9FAFB",text:{primary:"#111827",secondary:"#6B7280",muted:"#9CA3AF",inverse:"#FFFFFF"},status:{success:"#10B981",warning:"#F59E0B",error:"#EF4444",info:"#3B82F6"},border:"#E5E7EB",shadow:"0 1px 3px 0 rgba(0, 0, 0, 0.1)"},typography:{fontFamily:"system-ui, -apple-system, sans-serif",fontSize:{xs:"0.75rem",sm:"0.875rem",md:"1rem",lg:"1.125rem",xl:"1.25rem"},fontWeight:{normal:400,medium:500,semibold:600,bold:700},lineHeight:{tight:1.25,normal:1.5,relaxed:1.75}},spacing:{xs:"0.25rem",sm:"0.5rem",md:"1rem",lg:"1.5rem",xl:"2rem"},borderRadius:{none:"0",sm:"0.25rem",md:"0.5rem",lg:"0.75rem",full:"9999px"},shadows:{sm:"0 1px 2px 0 rgba(0, 0, 0, 0.05)",md:"0 4px 6px -1px rgba(0, 0, 0, 0.1)",lg:"0 10px 15px -3px rgba(0, 0, 0, 0.1)"}},Do={...Pt,name:"dark",colors:{primary:"#60A5FA",secondary:"#9CA3AF",accent:"#A78BFA",background:"#111827",surface:"#1F2937",text:{primary:"#F9FAFB",secondary:"#D1D5DB",muted:"#9CA3AF",inverse:"#111827"},status:{success:"#34D399",warning:"#FBBF24",error:"#F87171",info:"#60A5FA"},border:"#374151",shadow:"0 1px 3px 0 rgba(0, 0, 0, 0.3)"}},$o={...Pt,name:"enterprise",colors:{primary:"#1E40AF",secondary:"#64748B",accent:"#7C3AED",background:"#FFFFFF",surface:"#F8FAFC",text:{primary:"#0F172A",secondary:"#475569",muted:"#94A3B8",inverse:"#FFFFFF"},status:{success:"#059669",warning:"#D97706",error:"#DC2626",info:"#1E40AF"},border:"#CBD5E1",shadow:"0 1px 3px 0 rgba(0, 0, 0, 0.1)"},borderRadius:{none:"0",sm:"0.125rem",md:"0.25rem",lg:"0.375rem",full:"9999px"}},Vd=w.createContext(null),Nd=()=>{const e=w.useContext(Vd);if(!e)throw new Error("useTheme must be used within a ThemeProvider");return e};function xy({theme:e="default",themes:t={},children:n,cssVariables:r=!0,className:o=""}){const[s,i]=w.useState(()=>{const h={default:Pt,dark:Do,enterprise:$o,...t};return typeof e=="string"?h[e]||Pt:e}),[a,c]=w.useState(()=>({default:Pt,dark:Do,enterprise:$o,...t})),d=h=>{if(typeof h=="string"){const x=a[h];x&&i(x)}else i(h)},u=h=>{c(x=>({...x,[h.name]:h}))};w.useEffect(()=>{if(r&&typeof document<"u"){const h=document.documentElement;Object.entries(Rd(s)).forEach(([x,y])=>{h.style.setProperty(`--voxket-${x}`,y)})}},[s,r]);const f={theme:s,setTheme:d,themes:a,registerTheme:u};return l.jsx(Vd.Provider,{value:f,children:l.jsx("div",{className:`voxket-theme voxket-theme--${s.name} ${o}`,children:n})})}function Rd(e){const t={},n=(r,o="")=>{for(const[s,i]of Object.entries(r)){const a=o?`${o}-${s}`:s;typeof i=="object"&&i!==null&&!Array.isArray(i)?n(i,a):t[a]=String(i)}};return n(e),t}function yy(e=Pt,t){return{...e,...t,colors:{...e.colors,...t.colors},typography:{...e.typography,...t.typography},spacing:{...e.spacing,...t.spacing},borderRadius:{...e.borderRadius,...t.borderRadius},shadows:{...e.shadows,...t.shadows}}}function by(e){var n;const{theme:t}=Nd();return((n=t.components)==null?void 0:n[e])||{}}const vy=Ns("voice-modality","voice",{onActivate:async e=>{const t=e.config;t.enableTranscription&&wy(e),t.enableVoiceActivation&&Sy(e,t),console.log("Voice modality activated",t)},onDeactivate:async e=>{console.log("Voice modality deactivated")},onMessage:async(e,t)=>{t.type==="audio"&&ky(e,t)}});function wy(e,t){e.on("participant.speaking.started",n=>{console.log("Transcription: Started for",n.name)}),e.on("participant.speaking.stopped",n=>{console.log("Transcription: Stopped for",n.name)})}function Sy(e,t){const n=t.silenceThreshold||-50;console.log("Voice activation setup with threshold:",n)}function ky(e,t){console.log("Playing audio response:",t.content)}const Cy=Ns("chat-modality","chat",{onActivate:async e=>{const t=e.config;t.enableRichText&&Ey(),t.enableFileUpload&&Ty(e),t.enableCustomComponents&&Ay(),console.log("Chat modality activated",t)},onDeactivate:async e=>{console.log("Chat modality deactivated")},onMessage:async(e,t)=>{const n=e.config;t.type==="ui_component"?jy(e,t):t.type==="text"&&n.enableRichText&&Py(e,t)}});function Ey(e){console.log("Rich text support enabled")}function Ty(e){console.log("File upload enabled"),e.on("chat.file.uploaded",t=>{console.log("File uploaded:",t.name)})}function Ay(e){console.log("Custom components enabled");const t=new Map;t.set("quick-actions",My),t.set("form",Vy),t.set("card",Ny),t.set("chart",Ry)}function jy(e,t){const{componentType:n,props:r}=t.metadata;console.log("Rendering custom component:",n,r),e.emit("chat.component.render",{type:n,props:r,timestamp:new Date})}function Py(e,t){console.log("Processing rich text message:",t.content)}function My(e){return{type:"quick-actions",actions:e.actions||[],layout:e.layout||"horizontal"}}function Vy(e){return{type:"form",fields:e.fields||[],submitAction:e.submitAction,validation:e.validation}}function Ny(e){return{type:"card",title:e.title,content:e.content,actions:e.actions,variant:e.variant||"default"}}function Ry(e){return{type:"chart",chartType:e.chartType||"line",data:e.data,options:e.options}}function er({track:e,participantName:t,showControls:n=!0,showName:r=!0,showMuteIndicator:o=!0,isPinned:s=!1,className:i="",onClick:a,onPin:c,onUnpin:d}){const u=w.useRef(null),[f,h]=w.useState(!1);w.useEffect(()=>{if(!u.current||!e.isEnabled)return;const b=u.current;return b.srcObject=null,()=>{b.srcObject&&(b.srcObject=null)}},[e]);const x=()=>{a==null||a(e)},y=b=>{b.stopPropagation(),s?d==null||d(e):c==null||c(e)},m=["voxket-video-tile",e.isLocal?"voxket-video-tile--local":"voxket-video-tile--remote",e.isScreenShare?"voxket-video-tile--screen-share":"voxket-video-tile--camera",s?"voxket-video-tile--pinned":"",e.isEnabled?"":"voxket-video-tile--disabled",f?"voxket-video-tile--hovered":"",i].filter(Boolean).join(" ");return l.jsxs("div",{className:m,onClick:x,onMouseEnter:()=>h(!0),onMouseLeave:()=>h(!1),style:{aspectRatio:e.dimensions?`${e.dimensions.width} / ${e.dimensions.height}`:"16 / 9"},children:[l.jsx("video",{ref:u,className:"voxket-video-element",autoPlay:!0,playsInline:!0,muted:e.isLocal}),!e.isEnabled&&l.jsxs("div",{className:"voxket-video-placeholder",children:[l.jsx("div",{className:"voxket-video-placeholder-icon",children:e.isScreenShare?"๐ฅ๏ธ":"๐น"}),l.jsx("p",{className:"voxket-video-placeholder-text",children:e.isScreenShare?"Screen sharing paused":"Camera off"})]}),l.jsxs("div",{className:"voxket-video-overlay",children:[r&&t&&l.jsxs("div",{className:"voxket-video-name",children:[t,e.isLocal&&" (You)"]}),o&&!e.isEnabled&&l.jsx("div",{className:"voxket-video-mute-indicator",children:"๐"}),n&&(f||s)&&l.jsxs("div",{className:"voxket-video-controls",children:[l.jsx("button",{className:`voxket-video-control-btn ${s?"voxket-video-control-btn--active":""}`,onClick:y,title:s?"Unpin video":"Pin video",children:"๐"}),e.isScreenShare&&l.jsx("div",{className:"voxket-video-indicator",children:"๐ฅ๏ธ"}),e.source&&l.jsx("div",{className:"voxket-video-source",children:e.source})]})]}),!e.isEnabled&&l.jsx("div",{className:"voxket-video-loading",children:l.jsx("div",{className:"voxket-spinner"})})]})}function Iy({tracks:e,layout:t,className:n="",onLayoutChange:r,onTrackClick:o,maxVisibleTracks:s=9,showPagination:i=!0}){const[a,c]=w.useState(0),[d,u]=w.useState(null),f=w.useMemo(()=>{let v=[...e];t.type==="speaker"&&d&&(v=[d,...e.filter(S=>S.id!==d.id)]);const T=a*s,k=T+s;return v.slice(T,k)},[e,t,d,a,s]),h=Math.ceil(e.length/s),x=w.useMemo(()=>{const v=f.length;switch(t.type){case"grid":const T=Math.ceil(Math.sqrt(v)),k=Math.ceil(v/T);return{display:"grid",gridTemplateColumns:`repeat(${T}, 1fr)`,gridTemplateRows:`repeat(${k}, 1fr)`,gap:"8px"};case"speaker":return{display:"flex",flexDirection:"column",gap:"8px"};case"sidebar":return{display:"flex",gap:"8px"};case"gallery":return{display:"flex",flexWrap:"wrap",gap:"8px",justifyContent:"center"};default:return{}}},[t.type,f.length]),y=v=>{u(v)},m=()=>{u(null)},b=v=>{r==null||r({...t,type:v})},C=["voxket-video-grid",`voxket-video-grid--${t.type}`,`voxket-video-grid--${f.length}-tracks`,n].filter(Boolean).join(" ");return e.length===0?l.jsx("div",{className:"voxket-video-grid-empty",children:l.jsxs("div",{className:"voxket-video-grid-empty-content",children:[l.jsx("div",{className:"voxket-video-grid-empty-icon",children:"๐น"}),l.jsx("p",{children:"No video tracks available"})]})}):l.jsxs("div",{className:C,children:[l.jsxs("div",{className:"voxket-video-grid-controls",children:[l.jsx("div",{className:"voxket-video-layout-controls",children:["grid","speaker","sidebar","gallery"].map(v=>l.jsx("button",{className:`voxket-layout-btn ${t.type===v?"voxket-layout-btn--active":""}`,onClick:()=>b(v),title:`Switch to ${v} layout`,children:Dy(v)},v))}),l.jsxs("div",{className:"voxket-video-count",children:[e.length," participant",e.length!==1?"s":""]})]}),l.jsx("div",{className:"voxket-video-grid-content",style:x,children:t.type==="speaker"&&d?l.jsxs(l.Fragment,{children:[l.jsx("div",{className:"voxket-video-speaker-main",children:l.jsx(er,{track:d,participantName:`Participant ${d.participantId}`,isPinned:!0,onClick:o,onUnpin:m})}),l.jsx("div",{className:"voxket-video-speaker-sidebar",children:f.filter(v=>v.id!==d.id).map(v=>l.jsx(er,{track:v,participantName:`Participant ${v.participantId}`,showControls:!1,onClick:o,onPin:y},v.id))})]}):f.map(v=>l.jsx(er,{track:v,participantName:`Participant ${v.participantId}`,isPinned:(d==null?void 0:d.id)===v.id,onClick:o,onPin:y,onUnpin:m},v.id))}),i&&h>1&&l.jsxs("div",{className:"voxket-video-pagination",children:[l.jsx("button",{className:"voxket-pagination-btn",onClick:()=>c(Math.max(0,a-1)),disabled:a===0,children:"โ"}),l.jsxs("span",{className:"voxket-pagination-info",children:["Page ",a+1," of ",h]}),l.jsx("button",{className:"voxket-pagination-btn",onClick:()=>c(Math.min(h-1,a+1)),disabled:a===h-1,children:"โ"})]})]})}function Dy(e){switch(e){case"grid":return"โ";case"speaker":return"๐ค";case"sidebar":return"โซธ";case"gallery":return"โก";case"picture-in-picture":return"โง";default:return"โ"}}function $y({localTrack:e,onToggleCamera:t,onToggleScreenShare:n,onLayoutChange:r,showLayoutControls:o=!0,showCameraControls:s=!0,showScreenShareControls:i=!0,className:a=""}){const c=["voxket-video-controls",a].filter(Boolean).join(" "),d=u=>{r==null||r({type:u,showLocalVideo:!0,aspectRatio:"16:9"})};return l.jsxs("div",{className:c,children:[s&&l.jsxs("div",{className:"voxket-video-controls-section",children:[l.jsx("h4",{className:"voxket-video-controls-title",children:"Camera"}),l.jsxs("button",{className:`voxket-control-btn ${e!=null&&e.isEnabled?"voxket-control-btn--active":""}`,onClick:t,title:e!=null&&e.isEnabled?"Turn off camera":"Turn on camera",children:[l.jsx("span",{className:"voxket-control-icon",children:e!=null&&e.isEnabled?"๐น":"๐ท"}),l.jsx("span",{className:"voxket-control-label",children:e!=null&&e.isEnabled?"Camera On":"Camera Off"})]}),(e==null?void 0:e.dimensions)&&l.jsxs("div",{className:"voxket-video-info",children:[e.dimensions.width," ร ",e.dimensions.height]})]}),i&&l.jsxs("div",{className:"voxket-video-controls-section",children:[l.jsx("h4",{className:"voxket-video-controls-title",children:"Screen Share"}),l.jsxs("button",{className:`voxket-control-btn ${e!=null&&e.isScreenShare?"voxket-control-btn--active":""}`,onClick:n,title:e!=null&&e.isScreenShare?"Stop screen sharing":"Start screen sharing",children:[l.jsx("span",{className:"voxket-control-icon",children:e!=null&&e.isScreenShare?"๐":"๐ฅ๏ธ"}),l.jsx("span",{className:"voxket-control-label",children:e!=null&&e.isScreenShare?"Stop Sharing":"Share Screen"})]})]}),o&&l.jsxs("div",{className:"voxket-video-controls-section",children:[l.jsx("h4",{className:"voxket-video-controls-title",children:"Layout"}),l.jsx("div",{className:"voxket-layout-buttons",children:[{type:"grid",icon:"โ",label:"Grid"},{type:"speaker",icon:"๐ค",label:"Speaker"},{type:"sidebar",icon:"โซธ",label:"Sidebar"},{type:"gallery",icon:"โก",label:"Gallery"}].map(({type:u,icon:f,label:h})=>l.jsxs("button",{className:"voxket-layout-control-btn",onClick:()=>d(u),title:`Switch to ${h} layout`,children:[l.jsx("span",{className:"voxket-control-icon",children:f}),l.jsx("span",{className:"voxket-control-label",children:h})]},u))})]}),l.jsxs("div",{className:"voxket-video-controls-section",children:[l.jsx("h4",{className:"voxket-video-controls-title",children:"Video Settings"}),l.jsxs("div",{className:"voxket-video-settings",children:[l.jsxs("div",{className:"voxket-setting-group",children:[l.jsx("label",{className:"voxket-setting-label",children:"Quality"}),l.jsxs("select",{className:"voxket-setting-select",children:[l.jsx("option",{value:"high",children:"High (720p)"}),l.jsx("option",{value:"medium",children:"Medium (480p)"}),l.jsx("option",{value:"low",children:"Low (240p)"})]})]}),l.jsxs("div",{className:"voxket-setting-group",children:[l.jsx("label",{className:"voxket-setting-label",children:"Frame Rate"}),l.jsxs("select",{className:"voxket-setting-select",children:[l.jsx("option",{value:"30",children:"30 fps"}),l.jsx("option",{value:"15",children:"15 fps"}),l.jsx("option",{value:"10",children:"10 fps"})]})]}),l.jsxs("div",{className:"voxket-setting-group",children:[l.jsx("label",{className:"voxket-setting-label",children:"Bandwidth"}),l.jsxs("select",{className:"voxket-setting-select",children:[l.jsx("option",{value:"unlimited",children:"Unlimited"}),l.jsx("option",{value:"1000",children:"1 Mbps"}),l.jsx("option",{value:"500",children:"500 Kbps"}),l.jsx("option",{value:"250",children:"250 Kbps"})]})]})]})]}),l.jsxs("div",{className:"voxket-video-controls-section",children:[l.jsx("h4",{className:"voxket-video-controls-title",children:"Statistics"}),l.jsxs("div",{className:"voxket-video-stats",children:[l.jsxs("div",{className:"voxket-stat-item",children:[l.jsx("span",{className:"voxket-stat-label",children:"Resolution:"}),l.jsx("span",{className:"voxket-stat-value",children:e!=null&&e.dimensions?`${e.dimensions.width}ร${e.dimensions.height}`:"N/A"})]}),l.jsxs("div",{className:"voxket-stat-item",children:[l.jsx("span",{className:"voxket-stat-label",children:"Source:"}),l.jsx("span",{className:"voxket-stat-value",children:(e==null?void 0:e.source)||"None"})]}),l.jsxs("div",{className:"voxket-stat-item",children:[l.jsx("span",{className:"voxket-stat-label",children:"Status:"}),l.jsx("span",{className:`voxket-stat-value ${e!=null&&e.isEnabled?"voxket-stat-value--active":"voxket-stat-value--inactive"}`,children:e!=null&&e.isEnabled?"Active":"Inactive"})]})]})]})]})}const Id=({handler:e,loadData:t,data:n,client:r,addLocalMessage:o})=>{const[s,i]=g.useState(null),[a,c]=g.useState(!0),[d,u]=g.useState(!1),[f]=g.useState(Date.now());g.useEffect(()=>{(async()=>{try{if(c(!0),console.log("๐ AssignmentView: Loading assignment data..."),console.log("๐ AssignmentView: Received data from RPC:",n),n&&typeof n=="object"){const b={title:n.title||"Untitled Assignment",description:n.description||"No description provided",estimated_time_of_completion:n.estimated_time_of_completion||"Unknown"};i(b),console.log("๐ AssignmentView: Assignment loaded from RPC data:",b)}}catch(b){console.error("๐ AssignmentView: Error loading assignment:",b),i({title:"Assignment Loading Error",description:"There was an error loading the assignment details. Please try again.",estimated_time_of_completion:"Unknown"})}finally{c(!1)}})()},[n,t]);const h=({message:m,assignment:b})=>{const C=m.toLowerCase().includes("declined"),v=C?"bg-red-50 border-red-200":"bg-green-50 border-green-200",T=C?"text-red-700":"text-green-700",k=C?"โ":"๐";return l.jsxs("div",{className:`max-w-sm mx-auto ${v} border rounded-lg shadow p-3 flex flex-col items-center`,children:[l.jsx("div",{className:"text-2xl mb-2",children:k}),l.jsx("div",{className:`${T} font-semibold text-sm mb-1`,children:m}),l.jsx("div",{className:"text-xs text-gray-600 text-center mb-1",children:b.title}),l.jsx("div",{className:"text-xs text-gray-500",children:"Thank you for your response!"})]})},x=async()=>{if(!(!s||!e)){u(!0);try{const m={message:"accepted"};console.log("๐ AssignmentView: Assignment accepted:",m),e.didSuccess(m,l.jsx(h,{message:"Assignment accepted!",assignment:s}))}catch(m){console.error("๐ AssignmentView: Error accepting assignment:",m),e.didFail({error:"Failed to accept assignment"})}finally{u(!1)}}},y=async()=>{if(!(!s||!e)){u(!0);try{const m={message:"declined"};console.log("๐ AssignmentView: Assignment declined:",m),e.didSuccess(m,l.jsx(h,{message:"Assignment declined",assignment:s}))}catch(m){console.error("๐ AssignmentView: Error declining assignment:",m),e.didFail({error:"Failed to decline assignment"})}finally{u(!1)}}};return a?l.jsx("div",{className:"max-w-sm mx-auto bg-white rounded-lg shadow-lg p-3",children:l.jsxs("div",{className:"flex items-center justify-center py-4",children:[l.jsx("div",{className:"animate-spin rounded-full h-4 w-4 border-b-2 border-blue-600"}),l.jsx("span",{className:"ml-2 text-xs text-gray-600",children:"Loading assignment..."})]})}):s?l.jsxs("div",{className:"max-w-sm mx-auto bg-white rounded-lg shadow-lg overflow-hidden",children:[l.jsx("div",{className:"bg-gradient-to-r from-blue-600 to-purple-600 text-white p-3",children:l.jsx("div",{className:"flex items-center justify-between",children:l.jsx("h3",{className:"text-xs font-semibold text-white truncate",children:s.title})})}),l.jsxs("div",{className:"p-3 text-black",children:[l.jsx("div",{className:"bg-gray-50 rounded p-2 mb-3",children:l.jsx("p",{className:"text-xs text-black leading-snug",children:s.description})}),l.jsx("div",{className:"mb-3 text-black",children:l.jsxs("div",{className:"flex items-center text-xs text-gray-600",children:[l.jsx("span",{className:"text-xs mr-1",children:"๐
"}),l.jsxs("span",{children:["Est: ",s.estimated_time_of_completion]})]})}),l.jsxs("div",{className:"flex gap-2",children:[l.jsx("button",{onClick:x,disabled:d,className:"flex-1 bg-green-600 text-white py-2 px-3 rounded text-xs font-medium hover:bg-green-700 transition-colors disabled:opacity-50 disabled:cursor-not-allowed",children:d?l.jsxs("span",{className:"flex items-center justify-center",children:[l.jsx("div",{className:"animate-spin rounded-full h-2 w-2 border-b-2 border-white mr-1"}),l.jsx("span",{className:"text-xs",children:"Processing..."})]}):"Accept"}),l.jsx("button",{onClick:y,disabled:d,className:"flex-1 bg-red-600 text-white py-2 px-3 rounded text-xs font-medium hover:bg-red-700 transition-colors disabled:opacity-50 disabled:cursor-not-allowed",children:"Decline"})]})]})]}):l.jsx("div",{className:"max-w-sm mx-auto bg-white rounded-lg shadow-lg p-3",children:l.jsxs("div",{className:"text-center py-4",children:[l.jsx("div",{className:"text-red-600 text-sm font-semibold mb-2",children:"โ ๏ธ Assignment Error"}),l.jsx("p",{className:"text-xs text-gray-600 mb-3",children:"Failed to load assignment details."})]})})};function Fy(){const[e,t]=g.useState(null),[n,r]=g.useState([]);g.useEffect(()=>{const a=new Rn({appId:"your-app-id",appSecret:"your-app-secret",baseUrl:"https://your-voxket-api.com",agentId:"your-agent-id",participantName:"User",modalities:["chat"]});return t(a),a.on("rpc.method.called",c=>{console.log("RPC Method Called:",c)}),a.on("rpc.interaction.completed",c=>{console.log("RPC Interaction Completed:",c)}),()=>{a.disconnect()}},[]);const o=async()=>{if(e)try{await e.registerFrontendRPC("give_assignment",Id,"embedded");const a=e.getRegisteredRpcMethods();r(a),console.log("โ
Assignment RPC registered successfully")}catch(a){console.error("โ Failed to register assignment RPC:",a)}},s=async()=>{if(!e)return;const a=({handler:c,timeout:d})=>{const[u,f]=g.useState(""),h=[{id:"pro",name:"Pro Plan",price:"$29/month"},{id:"enterprise",name:"Enterprise Plan",price:"$99/month"},{id:"basic",name:"Basic Plan",price:"$9/month"}],x=m=>{f(m)},y=()=>{const m=h.find(b=>b.id===u);c==null||c.didSuccess({selectedProduct:u,productName:m==null?void 0:m.name,price:m==null?void 0:m.price,timestamp:new Date().toISOString()})};return l.jsxs("div",{className:"p-6 bg-white rounded-lg",children:[l.jsx("h3",{className:"text-xl font-bold mb-4",children:"Choose Your Plan"}),l.jsx("p",{className:"text-gray-600 mb-4",children:"Select the plan that best fits your needs:"}),l.jsx("div",{className:"space-y-3 mb-6",children:h.map(m=>l.jsx("div",{onClick:()=>x(m.id),className:`p-4 border rounded-lg cursor-pointer transition-all ${u===m.id?"border-blue-500 bg-blue-50":"border-gray-200 hover:border-gray-300"}`,children:l.jsxs("div",{className:"flex justify-between items-center",children:[l.jsxs("div",{children:[l.jsx("h4",{className:"font-medium",children:m.name}),l.jsx("p",{className:"text-gray-600 text-sm",children:m.price})]}),l.jsx("div",{className:`w-4 h-4 rounded-full ${u===m.id?"bg-blue-500":"border-2 border-gray-300"}`})]})},m.id))}),l.jsxs("div",{className:"flex justify-end space-x-3",children:[l.jsx("button",{onClick:()=>c==null?void 0:c.dismissView(),className:"px-4 py-2 border border-gray-300 text-gray-700 rounded hover:bg-gray-50",children:"Cancel"}),l.jsx("button",{onClick:y,disabled:!u,className:"px-4 py-2 bg-blue-500 text-white rounded hover:bg-blue-600 disabled:opacity-50",children:"Select Plan"})]}),d&&l.jsxs("p",{className:"text-xs text-gray-500 mt-2",children:["Time remaining: ",d," seconds"]})]})};try{await e.registerFrontendRPC("recommend_product",a,"modal");const c=e.getRegisteredRpcMethods();r(c),console.log("โ
Product Recommendation RPC registered successfully")}catch(c){console.error("โ Failed to register product recommendation RPC:",c)}},i=async()=>{if(!e)return;const a=({handler:c})=>{const[d,u]=g.useState(0),[f,h]=g.useState(""),x=()=>{c==null||c.didSuccess({rating:d,comment:f,timestamp:new Date().toISOString()})};return l.jsxs("div",{className:"p-4 bg-white rounded-lg",children:[l.jsx("h3",{className:"text-lg font-semibold mb-3",children:"How was your experience?"}),l.jsxs("div",{className:"mb-4",children:[l.jsx("p",{className:"text-sm text-gray-600 mb-2",children:"Rate your experience:"}),l.jsx("div",{className:"flex space-x-1",children:[1,2,3,4,5].map(y=>l.jsx("button",{onClick:()=>u(y),className:`text-2xl ${y<=d?"text-yellow-400":"text-gray-300"}`,children:"โญ"},y))})]}),l.jsxs("div",{className:"mb-4",children:[l.jsx("p",{className:"text-sm text-gray-600 mb-2",children:"Additional comments:"}),l.jsx("textarea",{value:f,onChange:y=>h(y.target.value),className:"w-full p-2 border border-gray-300 rounded text-sm",rows:3,placeholder:"Tell us more about your experience..."})]}),l.jsxs("div",{className:"flex justify-end space-x-2",children:[l.jsx("button",{onClick:()=>c==null?void 0:c.dismissView(),className:"px-3 py-1 text-sm border border-gray-300 text-gray-700 rounded hover:bg-gray-50",children:"Skip"}),l.jsx("button",{onClick:x,disabled:d===0,className:"px-3 py-1 text-sm bg-blue-500 text-white rounded hover:bg-blue-600 disabled:opacity-50",children:"Submit"})]})]})};try{await e.registerFrontendRPC("collect_feedback",a,"embedded");const c=e.getRegisteredRpcMethods();r(c),console.log("โ
Feedback RPC registered successfully")}catch(c){console.error("โ Failed to register feedback RPC:",c)}};return l.jsxs("div",{className:"p-6",children:[l.jsx("h2",{className:"text-2xl font-bold mb-6",children:"Frontend RPC Examples"}),l.jsxs("div",{className:"space-y-4 mb-6",children:[l.jsxs("div",{children:[l.jsx("h3",{className:"text-lg font-semibold mb-2",children:"Register RPC Methods"}),l.jsxs("div",{className:"space-x-2",children:[l.jsx("button",{onClick:o,className:"px-4 py-2 bg-blue-500 text-white rounded hover:bg-blue-600",children:"Register Assignment RPC"}),l.jsx("button",{onClick:s,className:"px-4 py-2 bg-green-500 text-white rounded hover:bg-green-600",children:"Register Product Recommendation RPC"}),l.jsx("button",{onClick:i,className:"px-4 py-2 bg-purple-500 text-white rounded hover:bg-purple-600",children:"Register Feedback RPC"})]})]}),l.jsxs("div",{children:[l.jsx("h3",{className:"text-lg font-semibold mb-2",children:"Registered Methods"}),n.length>0?l.jsx("ul",{className:"list-disc list-inside space-y-1",children:n.map(a=>l.jsx("li",{className:"text-gray-700",children:l.jsx("code",{className:"bg-gray-100 px-2 py-1 rounded",children:a})},a))}):l.jsx("p",{className:"text-gray-500",children:"No methods registered yet"})]})]}),l.jsxs("div",{className:"bg-gray-50 p-4 rounded-lg",children:[l.jsx("h3",{className:"text-lg font-semibold mb-2",children:"How it works"}),l.jsxs("ol",{className:"list-decimal list-inside space-y-2 text-sm text-gray-700",children:[l.jsxs("li",{children:["Register RPC methods with React components using ",l.jsx("code",{children:"client.registerFrontendRPC()"})]}),l.jsx("li",{children:"When the agent calls an RPC method, the corresponding component will be displayed"}),l.jsx("li",{children:"Users interact with the component, and the response is sent back to the agent"}),l.jsx("li",{children:"Components can be displayed in different modes: embedded, modal, or fullscreen"}),l.jsx("li",{children:"Each component has a timeout and can handle success/failure scenarios"})]})]}),l.jsxs("div",{className:"mt-6 bg-blue-50 p-4 rounded-lg",children:[l.jsx("h3",{className:"text-lg font-semibold mb-2 text-blue-800",children:"Agent Side"}),l.jsx("p",{className:"text-sm text-blue-700 mb-2",children:"On the agent side, you can call these RPC methods like this:"}),l.jsx("pre",{className:"bg-white p-3 rounded text-xs text-gray-800 overflow-x-auto",children:`// Agent calls RPC method
|
|
1208
1379
|
const response = await participant.performRpc({
|
|
1209
1380
|
method: 'give_assignment',
|
|
1210
1381
|
data: JSON.stringify({
|
package/dist/index.js
CHANGED
|
@@ -13855,7 +13855,7 @@ function fb({ onSendMessage: e, onSendAttachments: t, disabled: n, theme: r, onE
|
|
|
13855
13855
|
A.type.startsWith("image/") ? t([A]) : console.warn("Selected file is not an image"), f.current && (f.current.value = "");
|
|
13856
13856
|
}
|
|
13857
13857
|
};
|
|
13858
|
-
return /* @__PURE__ */ u("div", { className: `${m ? "px-2 py-1" : "px-4 py-3"} !w-full backdrop-blur-xl border-0 shadow-lg `, children: /* @__PURE__ */ u("form", { onSubmit: v, className: `
|
|
13858
|
+
return /* @__PURE__ */ u("div", { className: `${m ? "px-2 py-1" : "px-4 py-3"} !w-full backdrop-blur-xl border-0 shadow-lg `, children: /* @__PURE__ */ u("form", { onSubmit: v, className: `w-full mx-auto ${m ? "max-w-xs" : ""}`, children: /* @__PURE__ */ S("div", { className: `flex items-center ${m ? "gap-1" : "gap-2"} !w-full backdrop-blur-md rounded-full ${m ? "px-2 py-1" : "px-3 py-2"} shadow-sm hover:shadow-md focus-within:shadow-lg focus-within:ring-2 focus-within:ring-blue-500/30 focus-within:border-blue-500/50 transition-all duration-200 border ${r === "light" ? "bg-white/90" : b.chatInput.container}`, children: [
|
|
13859
13859
|
/* @__PURE__ */ u(
|
|
13860
13860
|
se.button,
|
|
13861
13861
|
{
|
|
@@ -14425,7 +14425,7 @@ function xb({
|
|
|
14425
14425
|
}
|
|
14426
14426
|
)
|
|
14427
14427
|
] });
|
|
14428
|
-
const D = x && v ? "fullscreen" : o, Y = o === "popup", N = D === "fullscreen" ? x && v ? "fixed inset-0 z-[9999] flex flex-col h-screen w-screen bg-black" : "flex flex-col h-full w-full max-w-none" : "flex flex-col h-full w-full backdrop-blur-sm max-h-full overflow-hidden", z = D === "fullscreen" ? x && v ? "flex items-center w-full justify-between px-4 pt-3 pb-3 bg-black/80 text-white border-b border-gray-700" : `flex items-center w-full justify-between px-6 pt-
|
|
14428
|
+
const D = x && v ? "fullscreen" : o, Y = o === "popup", N = D === "fullscreen" ? x && v ? "fixed inset-0 z-[9999] flex flex-col h-screen w-screen bg-black" : "flex flex-col h-full w-full max-w-none" : "flex flex-col h-full w-full backdrop-blur-sm max-h-full overflow-hidden", z = D === "fullscreen" ? x && v ? "flex items-center w-full justify-between px-4 pt-3 pb-3 bg-black/80 text-white border-b border-gray-700" : `flex items-center w-full justify-between px-6 pt-3 pb-4 border-b ${A.chatHeader.container}` : `flex items-center w-full justify-between ${Y ? "px-3 pt-3 pb-3 text-xs" : "px-5 pt-3 pb-5"} border-b ${A.chatHeader.container}`, J = D === "fullscreen" ? x && v ? "flex-1 overflow-y-auto scrollbar-hide p-4 w-full max-w-none chat-scrollable min-h-0" : "flex-1 overflow-y-auto scrollbar-hide p-6 w-full max-w-none chat-scrollable min-h-0" : `flex-1 overflow-y-auto scrollbar-hide w-full ${Y ? "p-2 text-xs" : "p-4"} chat-scrollable min-h-0`, Z = "flex-shrink-0 !w-full", H = () => {
|
|
14429
14429
|
T(!1), n && n();
|
|
14430
14430
|
};
|
|
14431
14431
|
return /* @__PURE__ */ S("div", { className: `${N} chat-view`, children: [
|
|
@@ -16765,6 +16765,177 @@ function Rd() {
|
|
|
16765
16765
|
.voxket-widget-root .text-blue-600 {
|
|
16766
16766
|
color: #2563eb !important;
|
|
16767
16767
|
}
|
|
16768
|
+
|
|
16769
|
+
/* GLOBAL STYLES FOR POPUP AND FULLSCREEN MODES */
|
|
16770
|
+
/* These styles apply globally when popup/fullscreen elements are rendered outside normal widget scope */
|
|
16771
|
+
|
|
16772
|
+
/* Popup and fullscreen containers */
|
|
16773
|
+
.fixed.z-\\[9999\\],
|
|
16774
|
+
div[class*="fixed"][class*="z-[9999]"] {
|
|
16775
|
+
/* Ensure fixed positioned elements get theme context */
|
|
16776
|
+
}
|
|
16777
|
+
|
|
16778
|
+
/* Global theme classes for popup/fullscreen */
|
|
16779
|
+
.theme-vox {
|
|
16780
|
+
color: #ffffff;
|
|
16781
|
+
}
|
|
16782
|
+
|
|
16783
|
+
.theme-dark {
|
|
16784
|
+
color: #ffffff;
|
|
16785
|
+
}
|
|
16786
|
+
|
|
16787
|
+
.theme-light {
|
|
16788
|
+
color: #1f2937;
|
|
16789
|
+
}
|
|
16790
|
+
|
|
16791
|
+
/* Global background utilities for popup/fullscreen */
|
|
16792
|
+
.bg-gradient-to-br {
|
|
16793
|
+
background-image: linear-gradient(to bottom right, var(--tw-gradient-stops));
|
|
16794
|
+
}
|
|
16795
|
+
|
|
16796
|
+
.bg-gradient-to-b {
|
|
16797
|
+
background-image: linear-gradient(to bottom, var(--tw-gradient-stops));
|
|
16798
|
+
}
|
|
16799
|
+
|
|
16800
|
+
.bg-gradient-to-r {
|
|
16801
|
+
background-image: linear-gradient(to right, var(--tw-gradient-stops));
|
|
16802
|
+
}
|
|
16803
|
+
|
|
16804
|
+
/* Global gradient stops */
|
|
16805
|
+
.from-black {
|
|
16806
|
+
--tw-gradient-from: #000000;
|
|
16807
|
+
--tw-gradient-stops: var(--tw-gradient-from), var(--tw-gradient-to, rgba(0, 0, 0, 0));
|
|
16808
|
+
}
|
|
16809
|
+
|
|
16810
|
+
.to-gray-900 {
|
|
16811
|
+
--tw-gradient-to: #111827;
|
|
16812
|
+
}
|
|
16813
|
+
|
|
16814
|
+
.from-\\[\\#171727\\] {
|
|
16815
|
+
--tw-gradient-from: #171727;
|
|
16816
|
+
--tw-gradient-stops: var(--tw-gradient-from), var(--tw-gradient-to, rgba(23, 23, 39, 0));
|
|
16817
|
+
}
|
|
16818
|
+
|
|
16819
|
+
.to-\\[\\#12121F\\] {
|
|
16820
|
+
--tw-gradient-to: #12121F;
|
|
16821
|
+
}
|
|
16822
|
+
|
|
16823
|
+
.from-slate-950 {
|
|
16824
|
+
--tw-gradient-from: #020617;
|
|
16825
|
+
--tw-gradient-stops: var(--tw-gradient-from), var(--tw-gradient-to, rgba(2, 6, 23, 0));
|
|
16826
|
+
}
|
|
16827
|
+
|
|
16828
|
+
.via-slate-900 {
|
|
16829
|
+
--tw-gradient-to: rgba(15, 23, 42, 0);
|
|
16830
|
+
--tw-gradient-stops: var(--tw-gradient-from), #0f172a, var(--tw-gradient-to, rgba(15, 23, 42, 0));
|
|
16831
|
+
}
|
|
16832
|
+
|
|
16833
|
+
.to-gray-950 {
|
|
16834
|
+
--tw-gradient-to: #030712;
|
|
16835
|
+
}
|
|
16836
|
+
|
|
16837
|
+
.from-sky-50 {
|
|
16838
|
+
--tw-gradient-from: #f0f9ff;
|
|
16839
|
+
--tw-gradient-stops: var(--tw-gradient-from), var(--tw-gradient-to, rgba(240, 249, 255, 0));
|
|
16840
|
+
}
|
|
16841
|
+
|
|
16842
|
+
.via-white {
|
|
16843
|
+
--tw-gradient-to: rgba(255, 255, 255, 0);
|
|
16844
|
+
--tw-gradient-stops: var(--tw-gradient-from), #ffffff, var(--tw-gradient-to, rgba(255, 255, 255, 0));
|
|
16845
|
+
}
|
|
16846
|
+
|
|
16847
|
+
.to-indigo-50 {
|
|
16848
|
+
--tw-gradient-to: #eef2ff;
|
|
16849
|
+
}
|
|
16850
|
+
|
|
16851
|
+
.from-\\[\\#0a0a1a\\] {
|
|
16852
|
+
--tw-gradient-from: #0a0a1a;
|
|
16853
|
+
--tw-gradient-stops: var(--tw-gradient-from), var(--tw-gradient-to, rgba(10, 10, 26, 0));
|
|
16854
|
+
}
|
|
16855
|
+
|
|
16856
|
+
.to-\\[\\#0f0f23\\] {
|
|
16857
|
+
--tw-gradient-to: #0f0f23;
|
|
16858
|
+
}
|
|
16859
|
+
|
|
16860
|
+
/* Global background colors */
|
|
16861
|
+
.bg-black\\/40 {
|
|
16862
|
+
background-color: rgba(0, 0, 0, 0.4);
|
|
16863
|
+
}
|
|
16864
|
+
|
|
16865
|
+
.bg-\\[\\#171727\\]\\/90 {
|
|
16866
|
+
background-color: rgba(23, 23, 39, 0.9);
|
|
16867
|
+
}
|
|
16868
|
+
|
|
16869
|
+
.bg-\\[\\#1E1E2E\\] {
|
|
16870
|
+
background-color: #1E1E2E;
|
|
16871
|
+
}
|
|
16872
|
+
|
|
16873
|
+
.bg-\\[\\#0a0a1a\\] {
|
|
16874
|
+
background-color: #0a0a1a;
|
|
16875
|
+
}
|
|
16876
|
+
|
|
16877
|
+
.bg-\\[\\#0f0f23\\] {
|
|
16878
|
+
background-color: #0f0f23;
|
|
16879
|
+
}
|
|
16880
|
+
|
|
16881
|
+
.bg-slate-950 {
|
|
16882
|
+
background-color: #020617;
|
|
16883
|
+
}
|
|
16884
|
+
|
|
16885
|
+
.bg-slate-900 {
|
|
16886
|
+
background-color: #0f172a;
|
|
16887
|
+
}
|
|
16888
|
+
|
|
16889
|
+
.bg-sky-50 {
|
|
16890
|
+
background-color: #f0f9ff;
|
|
16891
|
+
}
|
|
16892
|
+
|
|
16893
|
+
.bg-indigo-50 {
|
|
16894
|
+
background-color: #eef2ff;
|
|
16895
|
+
}
|
|
16896
|
+
|
|
16897
|
+
/* Global backdrop blur */
|
|
16898
|
+
.backdrop-blur-sm {
|
|
16899
|
+
backdrop-filter: blur(8px);
|
|
16900
|
+
-webkit-backdrop-filter: blur(8px);
|
|
16901
|
+
}
|
|
16902
|
+
|
|
16903
|
+
/* Global layout utilities */
|
|
16904
|
+
.fixed {
|
|
16905
|
+
position: fixed;
|
|
16906
|
+
}
|
|
16907
|
+
|
|
16908
|
+
.inset-0 {
|
|
16909
|
+
inset: 0px;
|
|
16910
|
+
}
|
|
16911
|
+
|
|
16912
|
+
.flex {
|
|
16913
|
+
display: flex;
|
|
16914
|
+
}
|
|
16915
|
+
|
|
16916
|
+
.items-center {
|
|
16917
|
+
align-items: center;
|
|
16918
|
+
}
|
|
16919
|
+
|
|
16920
|
+
.justify-center {
|
|
16921
|
+
justify-content: center;
|
|
16922
|
+
}
|
|
16923
|
+
|
|
16924
|
+
.w-full {
|
|
16925
|
+
width: 100%;
|
|
16926
|
+
}
|
|
16927
|
+
|
|
16928
|
+
.h-full {
|
|
16929
|
+
height: 100%;
|
|
16930
|
+
}
|
|
16931
|
+
|
|
16932
|
+
.rounded-2xl {
|
|
16933
|
+
border-radius: 1rem;
|
|
16934
|
+
}
|
|
16935
|
+
|
|
16936
|
+
.shadow-2xl {
|
|
16937
|
+
box-shadow: 0 25px 50px -12px rgba(0, 0, 0, 0.25);
|
|
16938
|
+
}
|
|
16768
16939
|
`, t = document.createElement("style");
|
|
16769
16940
|
t.type = "text/css", t.setAttribute("data-voxket-styles", "true"), t.textContent = e, document.head.appendChild(t), Xa = !0;
|
|
16770
16941
|
}
|
|
@@ -18038,15 +18209,6 @@ function Ja({
|
|
|
18038
18209
|
className: `theme-${t} ${s.card}`,
|
|
18039
18210
|
style: { height: "100%", maxHeight: "100%" },
|
|
18040
18211
|
children: [
|
|
18041
|
-
i && /* @__PURE__ */ u(
|
|
18042
|
-
"button",
|
|
18043
|
-
{
|
|
18044
|
-
onClick: i,
|
|
18045
|
-
className: "absolute top-4 right-4 z-20 w-10 h-10 rounded-full bg-gray-900 bg-opacity-90 text-white flex items-center justify-center hover:bg-gray-800 transition-all duration-200 shadow-lg border border-gray-700 backdrop-blur-sm",
|
|
18046
|
-
title: "Enter Fullscreen",
|
|
18047
|
-
children: /* @__PURE__ */ u("svg", { width: "16", height: "16", viewBox: "0 0 24 24", fill: "none", stroke: "currentColor", strokeWidth: "2", children: /* @__PURE__ */ u("path", { d: "M15 3h6v6M9 21H3v-6M21 3l-7 7M3 21l7-7" }) })
|
|
18048
|
-
}
|
|
18049
|
-
),
|
|
18050
18212
|
/* @__PURE__ */ u("div", { className: s.cardTopGradient }),
|
|
18051
18213
|
/* @__PURE__ */ u("div", { className: s.cardPurpleBlur }),
|
|
18052
18214
|
/* @__PURE__ */ u("div", { className: s.cardPinkBlur }),
|