poll-test-widgets 0.0.4 → 0.0.5

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.
@@ -475,7 +475,6 @@ const ke = (t) => {
475
475
  const u = {
476
476
  credentials: "include",
477
477
  method: "GET",
478
- mode: "cors",
479
478
  headers: {
480
479
  "Content-Type": "application/json",
481
480
  "bypass-tunnel-reminder": "true"
@@ -506,7 +505,6 @@ const ke = (t) => {
506
505
  const u = c();
507
506
  return await p(l(`/${y}/`), {
508
507
  method: "DELETE",
509
- mode: "cors",
510
508
  headers: {
511
509
  "X-CSRFToken": u,
512
510
  "X-User-ID": f
@@ -526,7 +524,7 @@ const ke = (t) => {
526
524
  }, [p]), m = N(async (y) => {
527
525
  e(!0), i(null);
528
526
  try {
529
- return await p(l(`/${y}/`), { method: "GET", mode: "cors" });
527
+ return await p(l(`/${y}/`), { method: "GET" });
530
528
  } catch (f) {
531
529
  return i(f.message), null;
532
530
  } finally {
@@ -550,7 +548,6 @@ const ke = (t) => {
550
548
  try {
551
549
  return await p(l("/create/"), {
552
550
  method: "POST",
553
- mode: "cors",
554
551
  headers: {
555
552
  "X-CSRFToken": u
556
553
  },
@@ -1 +1 @@
1
- (function(Y,e){typeof exports=="object"&&typeof module<"u"?e(exports,require("react/jsx-runtime"),require("react"),require("@xyflow/react"),require("react-dom")):typeof define=="function"&&define.amd?define(["exports","react/jsx-runtime","react","@xyflow/react","react-dom"],e):(Y=typeof globalThis<"u"?globalThis:Y||self,e(Y.PollTestWidgets={},Y.jsxRuntime,Y.React,Y.ReactFlow,Y.ReactDOM))})(this,function(Y,e,h,X,we){"use strict";var H=function(){return H=Object.assign||function(o){for(var s,t=1,n=arguments.length;t<n;t++){s=arguments[t];for(var i in s)Object.prototype.hasOwnProperty.call(s,i)&&(o[i]=s[i])}return o},H.apply(this,arguments)},he={width:"100%",height:"10px",top:"0px",left:"0px",cursor:"row-resize"},fe={width:"10px",height:"100%",top:"0px",left:"0px",cursor:"col-resize"},ee={width:"20px",height:"20px",position:"absolute",zIndex:1},me={top:H(H({},he),{top:"-5px"}),right:H(H({},fe),{left:void 0,right:"-5px"}),bottom:H(H({},he),{top:void 0,bottom:"-5px"}),left:H(H({},fe),{left:"-5px"}),topRight:H(H({},ee),{right:"-10px",top:"-10px",cursor:"ne-resize"}),bottomRight:H(H({},ee),{right:"-10px",bottom:"-10px",cursor:"se-resize"}),bottomLeft:H(H({},ee),{left:"-10px",bottom:"-10px",cursor:"sw-resize"}),topLeft:H(H({},ee),{left:"-10px",top:"-10px",cursor:"nw-resize"})},Se=h.memo(function(o){var s=o.onResizeStart,t=o.direction,n=o.children,i=o.replaceStyles,l=o.className,c=h.useCallback(function(g){s(g,t)},[s,t]),r=h.useCallback(function(g){s(g,t)},[s,t]),p=h.useMemo(function(){return H(H({position:"absolute",userSelect:"none"},me[t]),i??{})},[i,t]);return e.jsx("div",{className:l||void 0,style:p,onMouseDown:c,onTouchStart:r,children:n})}),Ce=function(){var o=function(s,t){return o=Object.setPrototypeOf||{__proto__:[]}instanceof Array&&function(n,i){n.__proto__=i}||function(n,i){for(var l in i)Object.prototype.hasOwnProperty.call(i,l)&&(n[l]=i[l])},o(s,t)};return function(s,t){if(typeof t!="function"&&t!==null)throw new TypeError("Class extends value "+String(t)+" is not a constructor or null");o(s,t);function n(){this.constructor=s}s.prototype=t===null?Object.create(t):(n.prototype=t.prototype,new n)}}(),q=function(){return q=Object.assign||function(o){for(var s,t=1,n=arguments.length;t<n;t++){s=arguments[t];for(var i in s)Object.prototype.hasOwnProperty.call(s,i)&&(o[i]=s[i])}return o},q.apply(this,arguments)},ze={width:"auto",height:"auto"},te=function(o,s,t){return Math.max(Math.min(o,t),s)},ue=function(o,s,t){var n=Math.round(o/s);return n*s+t*(n-1)},Q=function(o,s){return new RegExp(o,"i").test(s)},oe=function(o){return!!(o.touches&&o.touches.length)},ke=function(o){return!!((o.clientX||o.clientX===0)&&(o.clientY||o.clientY===0))},ge=function(o,s,t){t===void 0&&(t=0);var n=s.reduce(function(l,c,r){return Math.abs(c-o)<Math.abs(s[l]-o)?r:l},0),i=Math.abs(s[n]-o);return t===0||i<t?s[n]:o},ce=function(o){return o=o.toString(),o==="auto"||o.endsWith("px")||o.endsWith("%")||o.endsWith("vh")||o.endsWith("vw")||o.endsWith("vmax")||o.endsWith("vmin")?o:"".concat(o,"px")},ie=function(o,s,t,n){if(o&&typeof o=="string"){if(o.endsWith("px"))return Number(o.replace("px",""));if(o.endsWith("%")){var i=Number(o.replace("%",""))/100;return s*i}if(o.endsWith("vw")){var i=Number(o.replace("vw",""))/100;return t*i}if(o.endsWith("vh")){var i=Number(o.replace("vh",""))/100;return n*i}}return o},Te=function(o,s,t,n,i,l,c){return n=ie(n,o.width,s,t),i=ie(i,o.height,s,t),l=ie(l,o.width,s,t),c=ie(c,o.height,s,t),{maxWidth:typeof n>"u"?void 0:Number(n),maxHeight:typeof i>"u"?void 0:Number(i),minWidth:typeof l>"u"?void 0:Number(l),minHeight:typeof c>"u"?void 0:Number(c)}},_e=function(o){return Array.isArray(o)?o:[o,o]},Ie=["as","ref","style","className","grid","gridGap","snap","bounds","boundsByDirection","size","defaultSize","minWidth","minHeight","maxWidth","maxHeight","lockAspectRatio","lockAspectRatioExtraWidth","lockAspectRatioExtraHeight","enable","handleStyles","handleClasses","handleWrapperStyle","handleWrapperClass","children","onResizeStart","onResize","onResizeStop","handleComponent","scale","resizeRatio","snapGap"],xe="__resizable_base__",ye=function(o){Ce(s,o);function s(t){var n,i,l,c,r=o.call(this,t)||this;return r.ratio=1,r.resizable=null,r.parentLeft=0,r.parentTop=0,r.resizableLeft=0,r.resizableRight=0,r.resizableTop=0,r.resizableBottom=0,r.targetLeft=0,r.targetTop=0,r.delta={width:0,height:0},r.appendBase=function(){if(!r.resizable||!r.window)return null;var p=r.parentNode;if(!p)return null;var g=r.window.document.createElement("div");return g.style.width="100%",g.style.height="100%",g.style.position="absolute",g.style.transform="scale(0, 0)",g.style.left="0",g.style.flex="0 0 100%",g.classList?g.classList.add(xe):g.className+=xe,p.appendChild(g),g},r.removeBase=function(p){var g=r.parentNode;g&&g.removeChild(p)},r.state={isResizing:!1,width:(i=(n=r.propsSize)===null||n===void 0?void 0:n.width)!==null&&i!==void 0?i:"auto",height:(c=(l=r.propsSize)===null||l===void 0?void 0:l.height)!==null&&c!==void 0?c:"auto",direction:"right",original:{x:0,y:0,width:0,height:0},backgroundStyle:{height:"100%",width:"100%",backgroundColor:"rgba(0,0,0,0)",cursor:"auto",opacity:0,position:"fixed",zIndex:9999,top:"0",left:"0",bottom:"0",right:"0"},flexBasis:void 0},r.onResizeStart=r.onResizeStart.bind(r),r.onMouseMove=r.onMouseMove.bind(r),r.onMouseUp=r.onMouseUp.bind(r),r}return Object.defineProperty(s.prototype,"parentNode",{get:function(){return this.resizable?this.resizable.parentNode:null},enumerable:!1,configurable:!0}),Object.defineProperty(s.prototype,"window",{get:function(){return!this.resizable||!this.resizable.ownerDocument?null:this.resizable.ownerDocument.defaultView},enumerable:!1,configurable:!0}),Object.defineProperty(s.prototype,"propsSize",{get:function(){return this.props.size||this.props.defaultSize||ze},enumerable:!1,configurable:!0}),Object.defineProperty(s.prototype,"size",{get:function(){var t=0,n=0;if(this.resizable&&this.window){var i=this.resizable.offsetWidth,l=this.resizable.offsetHeight,c=this.resizable.style.position;c!=="relative"&&(this.resizable.style.position="relative"),t=this.resizable.style.width!=="auto"?this.resizable.offsetWidth:i,n=this.resizable.style.height!=="auto"?this.resizable.offsetHeight:l,this.resizable.style.position=c}return{width:t,height:n}},enumerable:!1,configurable:!0}),Object.defineProperty(s.prototype,"sizeStyle",{get:function(){var t=this,n=this.props.size,i=function(r){var p;if(typeof t.state[r]>"u"||t.state[r]==="auto")return"auto";if(t.propsSize&&t.propsSize[r]&&(!((p=t.propsSize[r])===null||p===void 0)&&p.toString().endsWith("%"))){if(t.state[r].toString().endsWith("%"))return t.state[r].toString();var g=t.getParentSize(),b=Number(t.state[r].toString().replace("px","")),y=b/g[r]*100;return"".concat(y,"%")}return ce(t.state[r])},l=n&&typeof n.width<"u"&&!this.state.isResizing?ce(n.width):i("width"),c=n&&typeof n.height<"u"&&!this.state.isResizing?ce(n.height):i("height");return{width:l,height:c}},enumerable:!1,configurable:!0}),s.prototype.getParentSize=function(){if(!this.parentNode)return this.window?{width:this.window.innerWidth,height:this.window.innerHeight}:{width:0,height:0};var t=this.appendBase();if(!t)return{width:0,height:0};var n=!1,i=this.parentNode.style.flexWrap;i!=="wrap"&&(n=!0,this.parentNode.style.flexWrap="wrap"),t.style.position="relative",t.style.minWidth="100%",t.style.minHeight="100%";var l={width:t.offsetWidth,height:t.offsetHeight};return n&&(this.parentNode.style.flexWrap=i),this.removeBase(t),l},s.prototype.bindEvents=function(){this.window&&(this.window.addEventListener("mouseup",this.onMouseUp),this.window.addEventListener("mousemove",this.onMouseMove),this.window.addEventListener("mouseleave",this.onMouseUp),this.window.addEventListener("touchmove",this.onMouseMove,{capture:!0,passive:!1}),this.window.addEventListener("touchend",this.onMouseUp))},s.prototype.unbindEvents=function(){this.window&&(this.window.removeEventListener("mouseup",this.onMouseUp),this.window.removeEventListener("mousemove",this.onMouseMove),this.window.removeEventListener("mouseleave",this.onMouseUp),this.window.removeEventListener("touchmove",this.onMouseMove,!0),this.window.removeEventListener("touchend",this.onMouseUp))},s.prototype.componentDidMount=function(){if(!(!this.resizable||!this.window)){var t=this.window.getComputedStyle(this.resizable);this.setState({width:this.state.width||this.size.width,height:this.state.height||this.size.height,flexBasis:t.flexBasis!=="auto"?t.flexBasis:void 0})}},s.prototype.componentWillUnmount=function(){this.window&&this.unbindEvents()},s.prototype.createSizeForCssProperty=function(t,n){var i=this.propsSize&&this.propsSize[n];return this.state[n]==="auto"&&this.state.original[n]===t&&(typeof i>"u"||i==="auto")?"auto":t},s.prototype.calculateNewMaxFromBoundary=function(t,n){var i=this.props.boundsByDirection,l=this.state.direction,c=i&&Q("left",l),r=i&&Q("top",l),p,g;if(this.props.bounds==="parent"){var b=this.parentNode;b&&(p=c?this.resizableRight-this.parentLeft:b.offsetWidth+(this.parentLeft-this.resizableLeft),g=r?this.resizableBottom-this.parentTop:b.offsetHeight+(this.parentTop-this.resizableTop))}else this.props.bounds==="window"?this.window&&(p=c?this.resizableRight:this.window.innerWidth-this.resizableLeft,g=r?this.resizableBottom:this.window.innerHeight-this.resizableTop):this.props.bounds&&(p=c?this.resizableRight-this.targetLeft:this.props.bounds.offsetWidth+(this.targetLeft-this.resizableLeft),g=r?this.resizableBottom-this.targetTop:this.props.bounds.offsetHeight+(this.targetTop-this.resizableTop));return p&&Number.isFinite(p)&&(t=t&&t<p?t:p),g&&Number.isFinite(g)&&(n=n&&n<g?n:g),{maxWidth:t,maxHeight:n}},s.prototype.calculateNewSizeFromDirection=function(t,n){var i=this.props.scale||1,l=_e(this.props.resizeRatio||1),c=l[0],r=l[1],p=this.state,g=p.direction,b=p.original,y=this.props,x=y.lockAspectRatio,d=y.lockAspectRatioExtraHeight,m=y.lockAspectRatioExtraWidth,v=b.width,u=b.height,f=d||0,T=m||0;return Q("right",g)&&(v=b.width+(t-b.x)*c/i,x&&(u=(v-T)/this.ratio+f)),Q("left",g)&&(v=b.width-(t-b.x)*c/i,x&&(u=(v-T)/this.ratio+f)),Q("bottom",g)&&(u=b.height+(n-b.y)*r/i,x&&(v=(u-f)*this.ratio+T)),Q("top",g)&&(u=b.height-(n-b.y)*r/i,x&&(v=(u-f)*this.ratio+T)),{newWidth:v,newHeight:u}},s.prototype.calculateNewSizeFromAspectRatio=function(t,n,i,l){var c=this.props,r=c.lockAspectRatio,p=c.lockAspectRatioExtraHeight,g=c.lockAspectRatioExtraWidth,b=typeof l.width>"u"?10:l.width,y=typeof i.width>"u"||i.width<0?t:i.width,x=typeof l.height>"u"?10:l.height,d=typeof i.height>"u"||i.height<0?n:i.height,m=p||0,v=g||0;if(r){var u=(x-m)*this.ratio+v,f=(d-m)*this.ratio+v,T=(b-v)/this.ratio+m,z=(y-v)/this.ratio+m,_=Math.max(b,u),B=Math.min(y,f),S=Math.max(x,T),k=Math.min(d,z);t=te(t,_,B),n=te(n,S,k)}else t=te(t,b,y),n=te(n,x,d);return{newWidth:t,newHeight:n}},s.prototype.setBoundingClientRect=function(){var t=1/(this.props.scale||1);if(this.props.bounds==="parent"){var n=this.parentNode;if(n){var i=n.getBoundingClientRect();this.parentLeft=i.left*t,this.parentTop=i.top*t}}if(this.props.bounds&&typeof this.props.bounds!="string"){var l=this.props.bounds.getBoundingClientRect();this.targetLeft=l.left*t,this.targetTop=l.top*t}if(this.resizable){var c=this.resizable.getBoundingClientRect(),r=c.left,p=c.top,g=c.right,b=c.bottom;this.resizableLeft=r*t,this.resizableRight=g*t,this.resizableTop=p*t,this.resizableBottom=b*t}},s.prototype.onResizeStart=function(t,n){if(!(!this.resizable||!this.window)){var i=0,l=0;if(t.nativeEvent&&ke(t.nativeEvent)?(i=t.nativeEvent.clientX,l=t.nativeEvent.clientY):t.nativeEvent&&oe(t.nativeEvent)&&(i=t.nativeEvent.touches[0].clientX,l=t.nativeEvent.touches[0].clientY),this.props.onResizeStart&&this.resizable){var c=this.props.onResizeStart(t,n,this.resizable);if(c===!1)return}this.props.size&&(typeof this.props.size.height<"u"&&this.props.size.height!==this.state.height&&this.setState({height:this.props.size.height}),typeof this.props.size.width<"u"&&this.props.size.width!==this.state.width&&this.setState({width:this.props.size.width})),this.ratio=typeof this.props.lockAspectRatio=="number"?this.props.lockAspectRatio:this.size.width/this.size.height;var r,p=this.window.getComputedStyle(this.resizable);if(p.flexBasis!=="auto"){var g=this.parentNode;if(g){var b=this.window.getComputedStyle(g).flexDirection;this.flexDir=b.startsWith("row")?"row":"column",r=p.flexBasis}}this.setBoundingClientRect(),this.bindEvents();var y={original:{x:i,y:l,width:this.size.width,height:this.size.height},isResizing:!0,backgroundStyle:q(q({},this.state.backgroundStyle),{cursor:this.window.getComputedStyle(t.target).cursor||"auto"}),direction:n,flexBasis:r};this.setState(y)}},s.prototype.onMouseMove=function(t){var n=this;if(!(!this.state.isResizing||!this.resizable||!this.window)){if(this.window.TouchEvent&&oe(t))try{t.preventDefault(),t.stopPropagation()}catch{}var i=this.props,l=i.maxWidth,c=i.maxHeight,r=i.minWidth,p=i.minHeight,g=oe(t)?t.touches[0].clientX:t.clientX,b=oe(t)?t.touches[0].clientY:t.clientY,y=this.state,x=y.direction,d=y.original,m=y.width,v=y.height,u=this.getParentSize(),f=Te(u,this.window.innerWidth,this.window.innerHeight,l,c,r,p);l=f.maxWidth,c=f.maxHeight,r=f.minWidth,p=f.minHeight;var T=this.calculateNewSizeFromDirection(g,b),z=T.newHeight,_=T.newWidth,B=this.calculateNewMaxFromBoundary(l,c);this.props.snap&&this.props.snap.x&&(_=ge(_,this.props.snap.x,this.props.snapGap)),this.props.snap&&this.props.snap.y&&(z=ge(z,this.props.snap.y,this.props.snapGap));var S=this.calculateNewSizeFromAspectRatio(_,z,{width:B.maxWidth,height:B.maxHeight},{width:r,height:p});if(_=S.newWidth,z=S.newHeight,this.props.grid){var k=ue(_,this.props.grid[0],this.props.gridGap?this.props.gridGap[0]:0),E=ue(z,this.props.grid[1],this.props.gridGap?this.props.gridGap[1]:0),N=this.props.snapGap||0,I=N===0||Math.abs(k-_)<=N?k:_,w=N===0||Math.abs(E-z)<=N?E:z;_=I,z=w}var P={width:_-d.width,height:z-d.height};if(this.delta=P,m&&typeof m=="string"){if(m.endsWith("%")){var M=_/u.width*100;_="".concat(M,"%")}else if(m.endsWith("vw")){var U=_/this.window.innerWidth*100;_="".concat(U,"vw")}else if(m.endsWith("vh")){var j=_/this.window.innerHeight*100;_="".concat(j,"vh")}}if(v&&typeof v=="string"){if(v.endsWith("%")){var M=z/u.height*100;z="".concat(M,"%")}else if(v.endsWith("vw")){var U=z/this.window.innerWidth*100;z="".concat(U,"vw")}else if(v.endsWith("vh")){var j=z/this.window.innerHeight*100;z="".concat(j,"vh")}}var G={width:this.createSizeForCssProperty(_,"width"),height:this.createSizeForCssProperty(z,"height")};this.flexDir==="row"?G.flexBasis=G.width:this.flexDir==="column"&&(G.flexBasis=G.height);var W=this.state.width!==G.width,O=this.state.height!==G.height,V=this.state.flexBasis!==G.flexBasis,J=W||O||V;J&&we.flushSync(function(){n.setState(G)}),this.props.onResize&&J&&this.props.onResize(t,x,this.resizable,P)}},s.prototype.onMouseUp=function(t){var n,i,l=this.state,c=l.isResizing,r=l.direction;l.original,!(!c||!this.resizable)&&(this.props.onResizeStop&&this.props.onResizeStop(t,r,this.resizable,this.delta),this.props.size&&this.setState({width:(n=this.props.size.width)!==null&&n!==void 0?n:"auto",height:(i=this.props.size.height)!==null&&i!==void 0?i:"auto"}),this.unbindEvents(),this.setState({isResizing:!1,backgroundStyle:q(q({},this.state.backgroundStyle),{cursor:"auto"})}))},s.prototype.updateSize=function(t){var n,i;this.setState({width:(n=t.width)!==null&&n!==void 0?n:"auto",height:(i=t.height)!==null&&i!==void 0?i:"auto"})},s.prototype.renderResizer=function(){var t=this,n=this.props,i=n.enable,l=n.handleStyles,c=n.handleClasses,r=n.handleWrapperStyle,p=n.handleWrapperClass,g=n.handleComponent;if(!i)return null;var b=Object.keys(i).map(function(y){return i[y]!==!1?e.jsx(Se,{direction:y,onResizeStart:t.onResizeStart,replaceStyles:l&&l[y],className:c&&c[y],children:g&&g[y]?g[y]:null},y):null});return e.jsx("div",{className:p,style:r,children:b})},s.prototype.render=function(){var t=this,n=Object.keys(this.props).reduce(function(c,r){return Ie.indexOf(r)!==-1||(c[r]=t.props[r]),c},{}),i=q(q(q({position:"relative",userSelect:this.state.isResizing?"none":"auto"},this.props.style),this.sizeStyle),{maxWidth:this.props.maxWidth,maxHeight:this.props.maxHeight,minWidth:this.props.minWidth,minHeight:this.props.minHeight,boxSizing:"border-box",flexShrink:0});this.state.flexBasis&&(i.flexBasis=this.state.flexBasis);var l=this.props.as||"div";return e.jsxs(l,q({style:i,className:this.props.className},n,{ref:function(c){c&&(t.resizable=c)},children:[this.state.isResizing&&e.jsx("div",{style:this.state.backgroundStyle}),this.props.children,this.renderResizer()]}))},s.defaultProps={as:"div",onResizeStart:function(){},onResize:function(){},onResizeStop:function(){},enable:{top:!0,right:!0,bottom:!0,left:!0,topRight:!0,bottomRight:!0,bottomLeft:!0,topLeft:!0},style:{},grid:[1,1],gridGap:[0,0],lockAspectRatio:!1,lockAspectRatioExtraWidth:0,lockAspectRatioExtraHeight:0,scale:1,resizeRatio:1,snapGap:0},s}(h.PureComponent);const ve=o=>{o||(o="https://polls-tests-widgets-backend-1357.loca.lt");const[s,t]=h.useState(!1),[n,i]=h.useState(null),l=v=>`${o?o.replace(/\/$/,""):""}/api/polls${v}`,c=()=>{const v="csrftoken=",u=document.cookie?document.cookie.split(";"):[];for(let f of u)if(f=f.trim(),f.startsWith(v))return decodeURIComponent(f.substring(v.length));return null},r=async()=>{await fetch(l("/csrf/"),{credentials:"include"})},p=async(v,u={})=>{const f={credentials:"include",method:"GET",mode:"cors",headers:{"Content-Type":"application/json","bypass-tunnel-reminder":"true"}},T={...f,...u,headers:{...f.headers,...u.headers||{}}},z=await fetch(v,T),_=await z.text();let B=null;try{B=_?JSON.parse(_):null}catch{B=_}if(!z.ok){const S=new Error(B&&(B.detail||B.message)||z.statusText);throw S.status=z.status,S}return B},g=h.useCallback(async(v,u)=>{t(!0),i(null);try{await r();const f=c();return await p(l(`/${v}/`),{method:"DELETE",mode:"cors",headers:{"X-CSRFToken":f,"X-User-ID":u}})}catch(f){throw i(f.message),f}finally{t(!1)}},[]),b=h.useCallback(async()=>{try{return await p(l("/list/"),{method:"GET"})}catch(v){throw console.error("Ошибка получения списка опросов:",v),v}},[p]),y=h.useCallback(async v=>{t(!0),i(null);try{return await p(l(`/${v}/`),{method:"GET",mode:"cors"})}catch(u){return i(u.message),null}finally{t(!1)}},[]),x=h.useCallback(async(v,u)=>{t(!0),i(null),await r();const f=c();if(!f)throw new Error("CSRF token missing!");const T=(v.options||[]).filter(B=>B.trim()!=="").map(B=>({choice_text:B}));let z=null;u.endDate&&(z=new Date(`${u.endDate}T${u.endTime||"23:59:59"}`).toISOString());const _={owner:v.ownerID,title:v.title,choices:T,is_anonymous:u.isAnonymous,multiple_answers:u.multipleAnswers,end_date:z};try{return await p(l("/create/"),{method:"POST",mode:"cors",headers:{"X-CSRFToken":f},body:JSON.stringify(_)})}catch(B){throw i(B.message),B}finally{t(!1)}},[]);h.useCallback(async v=>{t(!0),i(null);try{return await p(l(`/${v}/`),{method:"GET"})}catch(u){return i(u.message),null}finally{t(!1)}},[]);const d=h.useCallback(async(v,u)=>{t(!0),i(null),await r();const f=c();if(!f)throw new Error("CSRF token missing!");try{return await p(l(`/${v}/vote/`),{method:"POST",headers:{"X-CSRFToken":f},body:JSON.stringify({choice_id:u.choiceId,user:u.userId})})}catch(T){throw i(T.message),T}finally{t(!1)}},[]),m=h.useCallback(async(v,u)=>{t(!0),i(null),await r();const f=c();try{return await p(l(`/${v}/unvote/}`),{method:"POST",headers:{"X-CSRFToken":f},body:JSON.stringify({user:u})})}catch(T){throw i(T.message),T}finally{t(!1)}},[]);return{createPoll:x,loading:s,error:n,setError:i,fetchAllPolls:b,fetchPoll:y,createPoll:x,votePoll:d,unvotePoll:m,deletePoll:g}},K=({placeholder:o,value:s,onChange:t,style:n,autoFocus:i,type:l="text"})=>e.jsx("input",{type:l,placeholder:o,value:s,onChange:t,autoFocus:i,className:"nodrag",style:{width:"100%",boxSizing:"border-box",padding:"12px 16px",marginBottom:"12px",backgroundColor:"#e0e0e0",border:"none",borderRadius:"0px",fontSize:"16px",color:"#333",outline:"none",fontFamily:"Arial, sans-serif",...n}}),F=({onClick:o,children:s,style:t,disabled:n})=>e.jsx("button",{onClick:n?void 0:o,disabled:n,className:"nodrag",style:{padding:"10px 30px",backgroundColor:n?"#f0f0f0":"#d9d9d9",border:"none",borderRadius:"0px",fontSize:"18px",color:n?"#999":"#000",cursor:n?"not-allowed":"pointer",fontWeight:"400",transition:"background-color 0.2s",whiteSpace:"nowrap",opacity:n?.7:1,...t},onMouseOver:i=>{n||(i.target.style.backgroundColor="#c0c0c0")},onMouseOut:i=>{n||(i.target.style.backgroundColor=(t==null?void 0:t.backgroundColor)||"#d9d9d9")},children:s}),Z=({checked:o,onChange:s})=>e.jsxs("label",{style:{display:"inline-flex",alignItems:"center",cursor:"pointer",userSelect:"none",position:"relative"},children:[e.jsx("input",{type:"checkbox",checked:o,onChange:s,style:{opacity:0,width:0,height:0,position:"absolute"}}),e.jsx("span",{style:{display:"inline-block",width:"24px",height:"24px",border:`2px solid ${o?"#000":"#6c757d"}`,borderRadius:"4px",backgroundColor:o?"#000":"#fff",transition:"background-color 0.2s, border-color 0.2s",position:"relative",flexShrink:0},children:o&&e.jsx("span",{style:{content:'""',position:"absolute",left:"8px",top:"3px",width:"6px",height:"14px",border:"solid white",borderWidth:"0 3px 3px 0",transform:"rotate(45deg)",transition:"opacity 0.2s",opacity:o?1:0}})})]}),We=({onClick:o})=>e.jsx("div",{onClick:o,className:"nodrag",style:{display:"flex",gap:"6px",cursor:"pointer",flexShrink:0,padding:"5px"},children:[1,2,3].map(s=>e.jsx("div",{style:{width:"14px",height:"14px",borderRadius:"50%",backgroundColor:"#757575"}},s))}),se=({id:o,name:s,value:t,checked:n,onChange:i,children:l})=>e.jsxs("label",{htmlFor:o,style:{display:"inline-flex",alignItems:"center",cursor:"pointer",userSelect:"none"},children:[e.jsx("input",{id:o,type:"radio",name:s,value:t,checked:n,onChange:i,style:{opacity:0,width:0,height:0,position:"absolute"}}),e.jsx("span",{style:{display:"inline-block",width:"20px",height:"20px",borderRadius:"50%",border:`2px solid ${n?"#000":"#6c757d"}`,backgroundColor:"#fff",position:"relative",flexShrink:0,transition:"border-color 0.2s"},children:n&&e.jsx("span",{style:{position:"absolute",top:"50%",left:"50%",transform:"translate(-50%, -50%)",width:"10px",height:"10px",borderRadius:"50%",backgroundColor:"#000",transition:"opacity 0.2s",opacity:1}})}),l]}),pe=({title:o,children:s,style:t,toggleSettings:n,showMenuDots:i=!0})=>e.jsxs("div",{style:{width:"100%",height:"100%",backgroundColor:"#fff",padding:"20px 24px",display:"flex",flexDirection:"column",boxSizing:"border-box",boxShadow:"0 2px 10px rgba(0,0,0,0.05)",position:"relative",overflow:"hidden",...t},children:[e.jsxs("div",{style:{display:"flex",justifyContent:"space-between",alignItems:"flex-start",marginBottom:"20px",flexShrink:0},children:[e.jsx("span",{style:{fontSize:"20px",fontWeight:"400",color:"#000",lineHeight:"1.2",wordBreak:"break-word",marginRight:"10px"},children:o}),i&&e.jsx(We,{onClick:n})]}),e.jsx("div",{style:{flexGrow:1,display:"flex",flexDirection:"column",overflow:"hidden",minHeight:0},children:s})]}),Be=({onSave:o,onDataChange:s,initialData:t})=>{var b;const n=t!=null&&t.options&&t.options.length>0&&t.options.some(y=>y.trim()==="")?t.options:[...((b=t==null?void 0:t.options)==null?void 0:b.filter(y=>y.trim()!==""))||[],""],[i,l]=h.useState((t==null?void 0:t.title)||""),[c,r]=h.useState(n),p=h.useRef(null);h.useEffect(()=>{s({title:i,options:c.filter(y=>y.trim()!=="")})},[i,c,s]);const g=(y,x)=>{let d=[...c];d[y]=x,y===d.length-1&&x.trim()!==""&&d.push(""),d=d.filter((m,v)=>m.trim()!==""||v===d.length-1),r(d)};return h.useEffect(()=>{p.current&&c.length>1&&c[c.length-1].trim()===""&&p.current.scrollIntoView({behavior:"smooth"})},[c.length]),e.jsxs("div",{style:{display:"flex",flexDirection:"column",height:"100%",width:"100%",overflow:"hidden"},children:[e.jsx("div",{style:{flexShrink:0,width:"100%"},children:e.jsx(K,{placeholder:"Название опроса",value:i,onChange:y=>l(y.target.value),style:{fontSize:"20px",padding:"14px 16px",marginBottom:"20px",color:"#333",fontWeight:"bold",borderRadius:"15px"}})}),e.jsxs("div",{className:"scroll-container nowheel",onWheel:y=>y.stopPropagation(),style:{flexGrow:1,overflowY:"auto",overflowX:"hidden",paddingRight:"5px",marginBottom:"10px",width:"100%"},children:[c.map((y,x)=>e.jsx("div",{style:{display:"flex",alignItems:"center"},children:e.jsx(K,{placeholder:`Вариант ${x+1}`,value:y,onChange:d=>g(x,d.target.value),style:{flexGrow:1,marginBottom:"10px",borderRadius:"15px"}})},x)),e.jsx("div",{ref:p})]}),e.jsx("div",{style:{flexShrink:0,marginTop:"20px"},children:e.jsx(F,{onClick:()=>o(),style:{width:"100%",borderRadius:"15px"},children:"Сохранить опрос"})})]})},Ee=({onDataChange:o,initialData:s,toggleSettings:t,onDelete:n})=>{const[i,l]=h.useState((s==null?void 0:s.isAnonymous)||!1),[c,r]=h.useState((s==null?void 0:s.multipleAnswers)||!1),[p,g]=h.useState((s==null?void 0:s.endDate)||""),[b,y]=h.useState((s==null?void 0:s.endTime)||"");h.useEffect(()=>{o({isAnonymous:i,multipleAnswers:c,endDate:p,endTime:b})},[i,c,p,b,o]);const x={boxSizing:"border-box",padding:"12px 16px",backgroundColor:"#e0e0e0",border:"none",borderRadius:"15px",fontSize:"16px",color:"#333",outline:"none",fontFamily:"Arial, sans-serif",flex:1};return e.jsxs("div",{className:"nodrag",style:{display:"flex",flexDirection:"column",height:"100%",width:"100%",paddingRight:"5px",overflowY:"auto",overflowX:"hidden",boxSizing:"border-box"},children:[e.jsx("h3",{style:{fontSize:"20px",fontWeight:"bold",color:"#000",marginBottom:"25px",flexShrink:0},children:"Параметры опроса"}),e.jsxs("div",{style:{display:"flex",gap:"10px",alignItems:"center",marginBottom:"25px"},children:[e.jsx(Z,{checked:i,onChange:()=>l(!i)}),e.jsx("span",{style:{fontSize:"18px",color:"#333"},children:"Анонимность"})]}),e.jsxs("div",{style:{display:"flex",gap:"10px",alignItems:"center",marginBottom:"25px"},children:[e.jsx(Z,{checked:c,onChange:()=>r(!c)}),e.jsx("span",{style:{fontSize:"18px",color:"#333"},children:"Несколько ответов"})]}),e.jsxs("div",{style:{flexShrink:0},children:[e.jsx("span",{style:{fontSize:"18px",color:"#333",marginBottom:"10px",display:"block"},children:"Дата и время окончания"}),e.jsxs("div",{style:{display:"flex",gap:"10px"},children:[e.jsx("input",{type:"date",className:"nodrag",value:p,onChange:d=>g(d.target.value),style:x}),e.jsx("input",{type:"time",className:"nodrag",value:b,onChange:d=>y(d.target.value),style:x})]})]}),e.jsx("div",{style:{flexShrink:0,display:"flex",justifyContent:"flex-end",marginTop:"auto",paddingTop:"20px"},children:e.jsx(F,{onClick:t,style:{width:"100%",borderRadius:"15px"},children:"Назад к опросу"})})]})},Pe=({pollData:o,setPollData:s})=>{var C;const{id:t,title:n,choices:i,all_votes:l=[],voted_users:c=[],is_anonymous:r,multiple_answers:p,end_date:g,total_votes:b}=o,x=(()=>{if(!g)return!1;const a=new Date(g);return new Date>a})(),{votePoll:d,loading:m,error:v,setError:u,fetchPoll:f,unvotePoll:T}=ve(),z=localStorage.getItem("userId")||"Anonymous",_=r?"Анонимно":"Неанонимно",B=g?`До ${g.split("T")[0]}`:"Нет даты",S=a=>!c||c.length===0?"0%":`${Math.round(a/c.length*100)}%`,[k,E]=h.useState(l.some(a=>a.user===String(z))),[N,I]=h.useState(),[w,P]=h.useState([]),[M,U]=h.useState(l.find(a=>a.user===String(z))),[j,G]=h.useState(!1),[W,O]=h.useState(0),[V,J]=h.useState(k||m||x||!p&&!N||p&&w.length===0);h.useEffect(()=>{J(k||m||x||!p&&!N||p&&w.length===0)},[k,m,p,N,w,x]);const $=a=>{I(a)},D=a=>{P(A=>A.includes(a)?A.filter(L=>L!==a):[...A,a])},re=a=>{r||(G(!0),O(a))},ne=()=>{G(!1)},le=async()=>{if(x){alert("Время прохождения теста истекло.");return}if(!(!p&&!N||p&&w.length===0))try{let a=!0;if(p){const A=w.map(L=>d(t,{choiceId:L,userId:z}));try{await Promise.all(A),a=!0}catch(L){console.error("Один из голосов не прошел",L),a=!1}}else a=await d(t,{choiceId:N,userId:z});a&&(E(!0),f&&f(t).then(A=>s(A)))}catch(a){console.error("Ошибка при голосовании:",a),u("Не удалось сохранить голос")}},de=async()=>{try{const a=await T(t,z);if(a)s(a);else if(f){const A=await f(t);s(A)}E(!1),U(null),I(null),P([])}catch(a){console.error("Ошибка при отмене голоса:",a),u("Не удалось отменить голос")}},ae=new Intl.PluralRules("ru-RU");function R(a){const A=ae.select(a),L={one:"голос",few:"голоса",many:"голосов",other:"голосов"};return L[A]||L.many}return e.jsxs("div",{className:"nodrag nowheel",onWheel:a=>a.stopPropagation(),style:{display:"flex",color:"#000",flexDirection:"column",height:"100%",width:"100%",overflow:"hidden",paddingRight:"5px"},children:[e.jsx("div",{style:{flexShrink:0,width:"100%"},children:e.jsx("h3",{style:{fontSize:"22px",fontWeight:"bold",backgroundColor:"#e0e0e0",padding:"12px 16px",borderRadius:"10px"},children:n})}),e.jsxs("div",{style:{fontSize:"14px",color:"#666",marginBottom:"10px"},children:[_," | ",B," | Голосов: ",c.length||0]}),x&&e.jsx("div",{style:{padding:"10px",backgroundColor:"#ffdddd",color:"red",borderRadius:"10px",textAlign:"center",fontWeight:"bold",marginBottom:"10px"},children:"Срок прохождения теста истек"}),v&&e.jsx("p",{style:{color:"red"},children:v}),j&&e.jsxs("div",{style:{display:"flex",color:"#000",flexDirection:"column",height:"100%",width:"100%",overflowY:"auto",gap:"10px"},children:[e.jsxs("div",{style:{display:"flex",justifyContent:"space-between",padding:"12px",position:"relative",overflow:"hidden"},children:[e.jsx("div",{style:{position:"absolute",bottom:0,left:0,height:"5px",width:"100%",backgroundColor:"#ccc"}}),e.jsx("div",{style:{position:"absolute",bottom:0,left:0,height:"5px",width:S(W==null?void 0:W.votes_count),backgroundColor:"#000",transition:"width 0.5s"}}),e.jsx("span",{style:{zIndex:1},children:W==null?void 0:W.choice_text}),e.jsx("span",{style:{fontWeight:"bold",zIndex:1},children:`${S(W==null?void 0:W.votes_count)}`})]}),e.jsxs("span",{style:{marginLeft:"12px",color:"#666"},children:[W==null?void 0:W.votes_count," ",R(W==null?void 0:W.votes_count)]}),e.jsx("div",{style:{overflowY:"auto",margin:"12px 16px",display:"flex",flexDirection:"column",gap:"15px"},children:(C=l==null?void 0:l.filter(a=>a.choice_id===(W==null?void 0:W.id)))==null?void 0:C.map((a,A)=>e.jsx("div",{style:{display:"flex",alignItems:"center",gap:"10px"},children:e.jsx("span",{style:{},children:a.user})},A))}),e.jsx(F,{style:{marginTop:"auto"},onClick:ne,children:"Назад"})]}),!j&&e.jsxs("div",{style:{display:"flex",color:"#000",flexDirection:"column",height:"100%",width:"100%",overflowY:"auto"},children:[k?e.jsx("div",{className:"scroll-container nowheel",style:{flexGrow:1,overflowY:"auto",minHeight:0,paddingRight:"5px"},children:i==null?void 0:i.map(a=>{const A=S(a.votes_count);return e.jsxs("div",{onClick:()=>{re(a)},style:{display:"flex",flexDirection:"column",marginBottom:"15px",cursor:"pointer",gap:"10px"},children:[e.jsxs("div",{style:{flexGrow:1,display:"flex",justifyContent:"space-between",padding:"12px",position:"relative",overflow:"hidden"},children:[e.jsx("div",{style:{position:"absolute",bottom:0,left:0,height:"5px",width:"100%",backgroundColor:"#ccc"}}),e.jsx("div",{style:{position:"absolute",bottom:0,left:0,height:"5px",width:A,backgroundColor:"#000",transition:"width 0.5s"}}),e.jsx("span",{style:{zIndex:1},children:a.choice_text}),e.jsx("span",{style:{zIndex:1,marginLeft:"auto",marginRight:"10px"},children:(M==null?void 0:M.choice_id)===a.id?"✔":""}),e.jsx("span",{style:{fontWeight:"bold",zIndex:1},children:`${A}`})]}),e.jsxs("span",{style:{marginLeft:"12px",color:"#666"},children:[a.votes_count," ",R(a.votes_count)]})]},a.id)})}):e.jsx("div",{className:"scroll-container nowheel",style:{flexGrow:1,overflowY:"auto",minHeight:0,paddingRight:"5px"},children:i==null?void 0:i.map(a=>{const A=a.id,L=p?w.includes(A):N===A;return e.jsxs("div",{onClick:()=>p?D(A):$(A),style:{display:"flex",alignItems:"center",marginBottom:"15px",cursor:"pointer",gap:"10px"},children:[p&&e.jsx(Z,{checked:L,onChange:()=>D(A)}),!p&&e.jsx(se,{name:`poll-${t}`,checked:L,onChange:()=>$(A)}),e.jsxs("div",{style:{flexGrow:1,display:"flex",justifyContent:"space-between",backgroundColor:L?"#d0d0d0":"#e0e0e0",padding:"12px 16px",borderRadius:"10px",position:"relative",overflow:"hidden"},children:[e.jsx("span",{style:{zIndex:1},children:a.choice_text}),e.jsx("span",{style:{fontWeight:"bold",zIndex:1},children:""})]})]},a.id)})}),e.jsxs("div",{style:{marginTop:"auto",paddingTop:"20px",display:"flex",flexDirection:"column",gap:"10px"},children:[!k&&e.jsx(F,{onClick:le,disabled:V,style:{width:"100%",backgroundColor:"#d9d9d9",borderRadius:"10px"},children:m?"Отправка...":"Сохранить"}),k&&e.jsxs("div",{style:{textAlign:"center",width:"100%"},children:[e.jsx("div",{style:{marginBottom:"10px",fontWeight:"bold",color:"#4caf50"},children:"Голос принят!"}),e.jsx(F,{onClick:de,disabled:m,style:{width:"100%",borderRadius:"10px"},children:m?"Отмена...":"Отменить мой голос"})]})]})]})]})},Ae=({initialTitle:o,pollId:s,nodeId:t,nodeProps:n,onSaved:i})=>{const[l,c]=h.useState({ownerID:"",title:o||"",options:[""]}),[r,p]=h.useState({isAnonymous:!1,multipleAnswers:!1,endDate:"",endTime:""}),g=async()=>{const I=b==null?void 0:b.id;if(localStorage.getItem("userId"),!I){alert("Ошибка: ID опроса не определен.");return}if(window.confirm("Вы уверены, что хотите полностью удалить этот опрос?"))try{await T(I,z),alert("Опрос успешно удален из базы"),setTimeout(()=>{window.location.reload()},100)}catch(w){console.error("Детали ошибки:",w),w.status===403?alert("У вас нет прав на удаление этого опроса. Удалять может только автор."):alert("Произошла ошибка при удалении: "+w.message),console.warn("Побочная ошибка (вероятно расширение браузера):",w)}},[b,y]=h.useState(null),[x,d]=h.useState("creator"),{createPoll:m,loading:v,error:u,fetchPoll:f,deletePoll:T}=ve(),[z,_]=h.useState();h.useEffect(()=>{let I=localStorage.getItem("userId");I||(I=getCookie("user_id")),I||(I="anon_"+Math.random().toString(36).substring(2,11),localStorage.setItem("userId",I)),I&&(_(I),console.log("ID пользователя загружен:",I))},[]),h.useCallback(I=>{if(!I)return;console.log("Poll Widget initialized with:",I);const{widgetId:w,userId:P,role:M,config:U,board:j}=I;w&&(async()=>{try{const W=await f(w);if(!W)return;y(W);const O=(W.choices||[]).map($=>$.choice_text);c({title:W.title,options:[...O.filter($=>$.trim()!==""),(O.length>0,"")]});let V="",J="";if(W.end_date){const $=W.end_date.split("T");V=$[0],J=$[1]?$[1].substring(0,5):""}p({isAnonymous:W.is_anonymous,multipleAnswers:W.multiple_answers,endDate:V,endTime:J}),d("display")}catch(W){console.error("Ошибка загрузки опроса:",W)}})();const G=["admin","editor","owner"].includes(M);d(G?W=>w?"display":"creator":"display")},[f]),h.useEffect(()=>{if(!s)return;let I=!0;return(async()=>{try{const w=await f(s);if(!I||!w)return;y(w);const P=(w.choices||[]).map(j=>j.choice_text);c({title:w.title,options:[...P.filter(j=>j.trim()!==""),(P.length>0,"")]});let M="",U="";if(w.end_date){const j=w.end_date.split("T");M=j[0],U=j[1]?j[1].substring(0,5):""}p({isAnonymous:w.is_anonymous,multipleAnswers:w.multiple_answers,endDate:M,endTime:U}),d("display")}catch(w){console.error("Ошибка загрузки опроса:",w)}})(),()=>{I=!1}},[s,f]);const B=async()=>{const I=l.options.filter(w=>w.trim()!=="");if(!l.title.trim()||I.length<1){alert("Заполните название и хотя бы один вариант ответа");return}try{const w={...l,options:I,ownerID:z},P=await m(w,r);y(P),typeof i=="function"&&(P!=null&&P.id)&&i(P.id),d("display")}catch(w){console.error("Ошибка сохранения опроса:",w),alert("Ошибка при сохранении опроса: "+(w.message||w))}},S=h.useCallback(()=>d(I=>I==="creator"?"settings":"creator"),[]),k=h.useCallback(()=>d("creator"),[]),E=h.useCallback(()=>d("creator"),[]),N=()=>"Опрос";return e.jsxs(pe,{style:{position:"relative"},title:N(),onSettingsClick:x==="display"?E:void 0,toggleSettings:x!=="settings"?S:void 0,showMenuDots:x==="creator",onTitleClick:x==="display"?E:void 0,children:[e.jsx("p",{style:{color:"red",textAlign:"center"},children:v?"Сохранение...":u}),e.jsx("div",{style:{position:"relative"},children:e.jsxs("div",{style:{fontSize:"10px",color:"#999",textAlign:"right",padding:"0 15px"},children:["User ID: ",z]})}),x==="creator"&&e.jsx(Be,{onSave:B,onDataChange:c,initialData:l}),x==="settings"&&e.jsx(Ee,{onDataChange:p,initialData:r,toggleSettings:k}),x==="display"&&b&&e.jsxs(e.Fragment,{children:[(b==null?void 0:b.id)&&String(b.owner)===String(z)&&e.jsx("div",{onClick:g,style:{position:"absolute",top:"15px",right:"15px",width:"24px",height:"24px",backgroundColor:"#ff4d4d",color:"white",borderRadius:"50%",display:"flex",alignItems:"center",justifyContent:"center",cursor:"pointer",fontSize:"18px",fontWeight:"bold",zIndex:100,boxShadow:"0 2px 5px rgba(0,0,0,0.2)",lineHeight:"1"},title:"Удалить опрос",children:"×"}),e.jsx(Pe,{pollData:b,setPollData:y})]})]})},Ne=({onSave:o,onDataChange:s,initialData:t})=>{const[n,i]=h.useState((t==null?void 0:t.title)||""),[l,c]=h.useState((t==null?void 0:t.tasks)||[]),[r,p]=h.useState((t==null?void 0:t.activeTaskIndex)||null);h.useEffect(()=>{s({title:n,tasks:l,activeTaskIndex:r})},[n,l,r,s]);const[g,b]=h.useState(!0),y=()=>{const S={id:Date.now(),question:"",type:"text",score:1,correctText:"",options:[""],correctRadioOption:"",correctBoxOptions:[]},k=[...l,S];c(k),p(k.length-1)},x=(S,k)=>{if(r===null)return;const E=[...l];E[r]={...E[r],[S]:k},c(E)},d=(S,k)=>{k.stopPropagation();const E=l.filter((N,I)=>I!==S);c(E),r>=E.length?p(E.length>0?E.length-1:null):S<r&&p(r-1)},m=()=>{r>0&&p(r-1)},v=()=>{r<l.length-1&&p(r+1)},u=(S,k)=>{let E=[...l[r].options];E[S]=k;const I=[...E.filter(w=>w.trim()!==""),""];x("options",I)},f=S=>{x("correctRadioOption",S)},T=(S,k)=>{let E=[];k.includes(S)?E=k.filter(N=>N!==S):E=[...k,S],x("correctBoxOptions",E)},z={display:"flex",gap:"10px",alignItems:"center",whiteSpace:"nowrap"},_={boxSizing:"border-box",padding:"10px",backgroundColor:"#e0e0e0",border:"none",fontSize:"14px",outline:"none",color:"#333",width:"100%",borderRadius:"10px"},B=S=>({padding:"8px",cursor:"pointer",backgroundColor:S?"#00a2ffff":"#e0e0e0",color:S?"#ffffffff":"#333",borderRadius:"10px 10px 0 0",fontSize:"14px",fontWeight:"bold",display:"flex",alignItems:"center",gap:"5px",whiteSpace:"nowrap"});return e.jsxs("div",{style:{display:"flex",flexDirection:"column",height:"100%",width:"100%",overflow:"hidden"},className:"nodrag nowheel",children:[e.jsx("div",{style:{flexShrink:0},children:e.jsx(K,{placeholder:"Название теста",value:n,onChange:S=>i(S.target.value),style:{fontSize:"20px",fontWeight:"bold",borderRadius:"10px"}})}),e.jsxs("div",{style:{display:"flex",borderBottom:"2px solid #333",flexShrink:0},children:[e.jsx(F,{onClick:m,style:{borderRadius:"10px"},children:"←"}),e.jsx("div",{style:{display:"flex",overflowX:"auto"},children:l.map((S,k)=>e.jsxs("div",{style:B(k===r),onClick:()=>p(k),children:["Задание ",k+1,e.jsx("span",{onClick:E=>d(k,E),style:{fontSize:"10px",fontWeight:"bold"},children:"✕"})]},S.id))}),e.jsx(F,{onClick:v,style:{borderRadius:"10px",marginLeft:"auto"},children:"→"})]}),e.jsx("div",{className:"nowheel",onWheel:S=>S.stopPropagation(),style:{padding:"10px",flexGrow:1,minHeight:0,overflowY:"auto",marginBottom:"10px",color:"#333"},children:r!==null&&l[r]?e.jsxs("div",{style:{display:"flex",flexDirection:"column",gap:"10px"},children:[e.jsxs("div",{style:{display:"flex",flex:1,flexDirection:"column",gap:"10px"},children:[e.jsx("label",{style:{fontSize:"18px",fontWeight:"bold"},children:"Вопрос:"}),e.jsx("textarea",{value:l[r].question,onChange:S=>x("question",S.target.value),style:{width:"100%",minHeight:"150px",fontSize:"18px",resize:"vertical",color:"#333",backgroundColor:"#ebebebff"},placeholder:"Введите текст вопроса..."})]}),e.jsxs("div",{onClick:()=>b(!g),style:{cursor:"pointer",fontWeight:"bold",marginBottom:"10px",display:"flex",gap:"5px"},children:[e.jsx("span",{children:"Параметры задания"}),e.jsx("span",{children:g?"▲":"▼"})]}),g&&e.jsxs("div",{style:{display:"flex",flexDirection:"column",gap:"10px",width:"50%"},children:[e.jsxs("div",{style:z,children:[e.jsx("span",{children:"Тип:"}),e.jsxs("select",{value:l[r].type,onChange:S=>x("type",S.target.value),style:_,children:[e.jsx("option",{value:"text",children:"Текст"}),e.jsx("option",{value:"single",children:"Один выбор"}),e.jsx("option",{value:"multiple",children:"Множ. выбор"})]})]}),e.jsxs("div",{style:z,children:[e.jsxs("span",{children:["Баллы: ",l[r].score]}),e.jsx("input",{type:"range",min:"1",max:"50",value:l[r].score,onChange:S=>x("score",S.target.value),style:_})]})]}),l[r].type==="text"&&e.jsx("textarea",{value:l[r].correctText,onChange:S=>x("correctText",S.target.value),style:{width:"100%",minHeight:"80px",fontSize:"18px",resize:"vertical",color:"#333",backgroundColor:"#ebebebff"},placeholder:"Введите правильные варианты с разделением через ENTER"}),l[r].type==="single"&&e.jsx("div",{children:l[r].options.map((S,k)=>e.jsxs("div",{style:{display:"flex",flexDirection:"row",gap:"10px",marginBottom:"5px"},children:[S!==""&&e.jsx(se,{checked:l[r].correctRadioOption===S,onChange:()=>f(S),name:l[r].id}),e.jsx(K,{placeholder:`Вариант ${k+1}`,value:S,onChange:E=>u(k,E.target.value),style:{borderRadius:"15px",marginBottom:"0px"}})]},k))}),l[r].type==="multiple"&&e.jsx("div",{children:l[r].options.map((S,k)=>e.jsxs("div",{style:{display:"flex",flexDirection:"row",gap:"10px",marginBottom:"5px"},children:[S!==""&&e.jsx(Z,{checked:l[r].correctBoxOptions.includes(S),onChange:()=>T(S,l[r].correctBoxOptions)}),e.jsx(K,{placeholder:`Вариант ${k+1}`,value:S,onChange:E=>u(k,E.target.value),style:{borderRadius:"15px",marginBottom:"0px"}})]},k))})]}):e.jsx("div",{style:{color:"#888",textAlign:"center",padding:"20px"},children:'Нет активных заданий. Нажмите "Добавить задание".'})}),e.jsxs("div",{style:{display:"flex",flexDirection:"row",justifyContent:"space-between",flexShrink:0,paddingTop:"10px",borderTop:"1px solid #eee"},children:[e.jsx(F,{onClick:y,style:{borderRadius:"10px"},children:"+ Добавить задание"}),e.jsx(F,{onClick:()=>o(),style:{borderRadius:"10px"},children:"Сохранить тест"})]})]})},Me=({onDataChange:o,initialData:s,toggleSettings:t})=>{const[n,i]=h.useState((s==null?void 0:s.completionTime)||""),[l,c]=h.useState((s==null?void 0:s.endDate)||""),[r,p]=h.useState((s==null?void 0:s.endTime)||""),[g,b]=h.useState((s==null?void 0:s.attemptNumber)||"");h.useEffect(()=>{o({completionTime:n,attemptNumber:g,endDate:l,endTime:r})},[n,g,l,r,o]);const y={boxSizing:"border-box",padding:"12px 16px",backgroundColor:"#e0e0e0",border:"none",fontSize:"16px",color:"#333",outline:"none",fontFamily:"Arial, sans-serif",flex:1,borderRadius:"10px"},x={display:"flex",gap:"10px",alignItems:"center",color:"#333"};return e.jsxs("div",{className:"nodrag",style:{display:"flex",flexDirection:"column",height:"100%",width:"100%",paddingRight:"5px",overflowY:"auto",overflowX:"hidden",boxSizing:"border-box"},children:[e.jsx("h3",{style:{fontSize:"20px",fontWeight:"bold",color:"#000",marginBottom:"25px",flexShrink:0},children:"Параметры теста"}),e.jsxs("div",{style:{display:"flex",flexDirection:"column",gap:"10px"},children:[e.jsxs("div",{style:x,children:[e.jsx("span",{children:"Время (мин):"}),e.jsx("input",{type:"number",value:n,onChange:d=>i(d.target.value),placeholder:"Неограниченно",style:y})]}),e.jsxs("div",{style:x,children:[e.jsx("span",{style:{},children:"Пройти до"}),e.jsx("input",{type:"date",value:l,onChange:d=>c(d.target.value),style:y}),e.jsx("input",{type:"time",value:r,onChange:d=>p(d.target.value),style:y})]}),e.jsxs("div",{style:x,children:[e.jsx("span",{style:{},children:"Кол-во попыток:"}),e.jsx("input",{type:"number",value:g,onChange:d=>b(d.target.value),style:y,placeholder:"Неограниченно"})]})]}),e.jsx("div",{style:{flexShrink:0,display:"flex",justifyContent:"flex-end",marginTop:"auto",paddingTop:"20px"},children:e.jsx(F,{onClick:t,style:{width:"100%",borderRadius:"5px"},children:"Назад к тесту"})})]})},be=o=>{o||(o="https://polls-tests-widgets-backend-1357.loca.lt");const[s,t]=h.useState(!1),[n,i]=h.useState(null),l=x=>`${o?o.replace(/\/$/,""):""}/api/polls/tests${x}`,c=()=>{const x="csrftoken=",d=document.cookie?document.cookie.split(";"):[];for(let m of d)if(m=m.trim(),m.startsWith(x))return decodeURIComponent(m.substring(x.length));return null},r=async(x,d={})=>{const m=await fetch(x,{credentials:"include",...d,headers:{"Content-Type":"application/json","bypass-tunnel-reminder":"true",...d.headers}}),v=await m.json().catch(()=>null);if(!m.ok){const u=new Error((v==null?void 0:v.detail)||m.statusText||"Ошибка сервера");throw u.status=m.status,u.data=v,u}return v},p=h.useCallback(async x=>{t(!0),i(null);try{return await r(l(`/${x}/`))}catch(d){throw i(d.message),d}finally{t(!1)}},[]),g=h.useCallback(async(x,d)=>{t(!0),i(null);try{const m=c();return await r(l(`/${x}/`),{method:"DELETE",headers:{"X-CSRFToken":m},body:JSON.stringify({owner:d})})}catch(m){throw i(m.message),m}finally{t(!1)}},[]),b=h.useCallback(async(x,d)=>{t(!0),i(null);try{let m=null;d.endDate&&(m=new Date(`${d.endDate}T${d.endTime||"23:59:59"}`).toISOString());const v={title:x.title,owner:localStorage.getItem("userId")||"Anonymous",tasks:x.tasks.map(u=>({question:u.question,task_type:u.type,score:u.score,correct_text:u.correctText,options:u.options.filter(f=>f.trim()!=="").map(f=>({text:f,is_correct:u.type==="single"?f===u.correctRadioOption:u.correctBoxOptions.includes(f)}))})),completion_time:d.completionTime===""?null:parseInt(d.completionTime),attempt_number:d.attemptNumber===""?null:parseInt(d.attemptNumber),end_date:m||null};return await r(l("/"),{method:"POST",body:JSON.stringify(v)})}catch(m){throw i(m.message),m}finally{t(!1)}},[]),y=h.useCallback(async x=>{t(!0),i(null);try{return await r(l("/submit/"),{method:"POST",body:JSON.stringify(x)})}catch(d){throw i(d.message),d}finally{t(!1)}},[]);return{loading:s,error:n,createTest:b,fetchTest:p,submitAttempt:y,deleteTest:g}},Oe=({testData:o,setTestData:s})=>{var $,D,re,ne,le,de,ae,R;const t=o==null?void 0:o.id,n=(o==null?void 0:o.title)||"",i=(o==null?void 0:o.tasks)||[];o!=null&&o.settings;const{submitAttempt:l,loading:c,fetchTest:r}=be(),p=localStorage.getItem("userId")||"Anonymous",[g,b]=h.useState(!0),[y,x]=h.useState(!1),[d,m]=h.useState(0),[v,u]=h.useState(null),[f,T]=h.useState([]),z=o==null?void 0:o.all_attempts.filter(C=>C.user===String(p)),_=o.attempt_number-z.length,[B,S]=h.useState(!1),[k,E]=h.useState(null),N=h.useRef(!1),I=()=>{if(!o.end_date)return!1;const C=new Date(o.end_date);return new Date>C},w=I();h.useEffect(()=>{},[]);const P=()=>{if(i&&Array.isArray(i)&&i.length>0){console.log("Инициализация задач в Display:",i);const C=i.map(a=>({id:a.id,question:a.question,type:a.task_type,score:a.score,options:Array.isArray(a.options)?a.options:[],completedText:"",completedRadioOptionId:"",completedBoxOptionIds:[]}));T(C),m(0)}},M=(C,a)=>{T(A=>{const L=[...A];return L[d]&&(L[d]={...L[d],[C]:a}),L})};h.useEffect(()=>{if(g||y||k===null)return;if(k<=0){O();return}const C=setInterval(()=>{E(a=>a-1)},1e3);return()=>clearInterval(C)},[k,g,y]);const U=C=>{const a=Math.floor(C/60),A=C%60;return`${a.toString().padStart(2,"0")}:${A.toString().padStart(2,"0")}`},j=()=>{d>0&&m(d-1)},G=()=>{d<i.length-1&&m(d+1)},W=C=>{const a=f[d];if(!a)return;const A=a.completedBoxOptionIds||[],L=A.includes(C)?A.filter(Ue=>Ue!==C):[...A,C];M("completedBoxOptionIds",L)},O=async()=>{if(N.current)return;N.current=!0;const C={test:t,user:p,answers:f.map(a=>{let A=[];if(a.type==="single"){const L=a.completedRadioOptionId;L&&(A=[L])}else a.type==="multiple"&&(A=a.completedBoxOptionIds);return{task:a.id,answer_text:a.completedText,selected_options:A}})};try{const a=await l(C);a&&(u(a),x(!0),b(!1),r&&s(await r(t)))}catch(a){console.error("Ошибка:",a)}finally{N.current=!1}},V=()=>{if(I()){alert("Время прохождения теста истекло.");return}P(),o.completion_time&&o.completion_time>0?E(o.completion_time*60):E(null),b(!1)},J=()=>{x(!1),b(!0)};return v&&y?e.jsxs("div",{style:{textAlign:"center",padding:"20px",color:"#000"},children:[e.jsx("h3",{style:{color:"#28a745"},children:"Тест завершен!"}),e.jsxs("p",{style:{fontSize:"18px"},children:["Результат: ",e.jsx("b",{children:v.score_obtained})," / ",v.total_score]}),e.jsx(F,{onClick:J,children:"ОК"})]}):!g&&f.length===0?e.jsx("div",{style:{color:"#000",padding:"20px"},children:"Загрузка..."}):e.jsxs("div",{style:{display:"flex",flexDirection:"column",width:"100%",color:"#000"},children:[e.jsxs("div",{style:{display:"flex",justifyContent:"space-between",alignItems:"center",marginBottom:"15px"},children:[e.jsx("h3",{style:{color:"#000",margin:0},children:n}),!g&&!y&&k!==null&&e.jsxs("div",{style:{fontWeight:"bold",fontSize:"18px",color:k<60?"red":"#00a2ff",border:"1px solid #ccc",padding:"5px 10px",borderRadius:"5px"},children:["⏱ ",U(k)]})]}),(o==null?void 0:o.owner)===p&&e.jsxs("div",{children:[e.jsxs("div",{style:{marginBottom:"15px"},children:[e.jsxs("p",{children:["Заданий: ",i.length]}),o.completion_time&&e.jsxs("p",{children:["Время: ",o.completion_time," мин."]}),o.end_date&&e.jsxs("p",{children:["Доступно до: ",new Date(o.end_date).toLocaleDateString()," ",new Date(o.end_date).toLocaleTimeString()]}),e.jsxs("p",{children:["Попыток: ",o.attempt_number]})]}),e.jsxs("div",{onClick:()=>S(C=>!C),style:{cursor:"pointer",fontWeight:"bold",marginBottom:"10px",display:"flex",gap:"5px"},children:[e.jsx("span",{children:"Посмотреть задания"}),e.jsx("span",{children:B?"▲":"▼"})]}),B&&e.jsxs("div",{children:[e.jsxs("div",{style:{display:"flex",borderBottom:"2px solid #333"},children:[e.jsx(F,{onClick:j,style:{borderRadius:"10px"},children:"←"}),e.jsx("div",{style:{display:"flex",overflowX:"auto"},children:i.map((C,a)=>e.jsx("div",{onClick:()=>m(a),style:{padding:"8px 12px",cursor:"pointer",backgroundColor:a===d?"#00a2ff":"#eee",color:a===d?"#fff":"#000",marginRight:"2px",borderRadius:"5px 5px 0 0",minWidth:"25px",textAlign:"center"},children:a+1},a))}),e.jsx(F,{onClick:G,style:{borderRadius:"10px",marginLeft:"auto"},children:"→"})]}),e.jsxs("div",{style:{color:"#000"},children:[e.jsx("p",{style:{fontWeight:"bold"},children:($=i[d])==null?void 0:$.question}),((D=i[d])==null?void 0:D.task_type)==="text"&&e.jsxs("span",{children:["Ответ: ",i[d].correct_text]}),((re=i[d])==null?void 0:re.task_type)==="single"&&i[d].options.map((C,a)=>e.jsxs("div",{style:{display:"flex",alignItems:"center",marginBottom:"15px",cursor:"pointer",gap:"10px"},children:[e.jsx(se,{checked:C.is_correct,onChange:()=>{}}),e.jsx("div",{style:{flexGrow:1,display:"flex",justifyContent:"space-between",backgroundColor:C.is_correct?"#d0d0d0":"#e0e0e0",padding:"12px 16px",borderRadius:"10px",position:"relative",overflow:"hidden"},children:e.jsx("span",{children:C.text})})]},a)),((ne=i[d])==null?void 0:ne.task_type)==="multiple"&&i[d].options.map((C,a)=>e.jsxs("div",{style:{display:"flex",alignItems:"center",marginBottom:"15px",cursor:"pointer",gap:"10px"},children:[e.jsx(Z,{checked:C.is_correct,onChange:()=>{}}),e.jsx("div",{style:{flexGrow:1,display:"flex",justifyContent:"space-between",backgroundColor:C.is_correct?"#d0d0d0":"#e0e0e0",padding:"12px 16px",borderRadius:"10px",position:"relative",overflow:"hidden"},children:e.jsx("span",{children:C.text})})]},a))]})]}),o!=null&&o.all_attempts&&(o==null?void 0:o.all_attempts.length)>0?e.jsxs("div",{style:{marginBottom:"20px",textAlign:"left"},children:[e.jsx("h4",{style:{marginBottom:"10px"},children:"Все результаты:"}),e.jsx("div",{style:{display:"flex",flexDirection:"column",backgroundColor:"#f5f5f5",borderRadius:"10px",padding:"10px",maxHeight:"200px",overflowY:"auto",border:"1px solid #ddd"},children:o==null?void 0:o.all_attempts.map((C,a)=>e.jsxs("div",{style:{display:"flex",justifyContent:"space-between",padding:"10px 5px",borderBottom:a!==(o==null?void 0:o.all_attempts.length)-1?"1px solid #ddd":"none"},children:[e.jsx("span",{style:{fontWeight:"bold",fontSize:"14px"},children:C.user}),e.jsx("span",{style:{fontSize:"14px"},children:new Date(C.completed_at).toLocaleDateString()}),e.jsxs("span",{style:{fontWeight:"bold",fontSize:"14px"},children:[C.score_obtained," / ",C.total_score," баллов"]})]},a))})]}):e.jsx("div",{style:{color:"#888",textAlign:"center",padding:"20px"},children:"Нет результатов"})]}),(o==null?void 0:o.owner)!==p&&e.jsx("div",{children:g?e.jsxs("div",{style:{color:"#000"},children:[e.jsxs("div",{style:{marginBottom:"15px"},children:[e.jsxs("p",{children:["Автор: ",o.owner]}),e.jsxs("p",{children:["Заданий: ",i.length]}),o.completion_time&&e.jsxs("p",{children:["Время: ",o.completion_time," мин."]}),o.end_date&&e.jsxs("p",{children:["Доступно до: ",new Date(o.end_date).toLocaleDateString()," ",new Date(o.end_date).toLocaleTimeString()]}),e.jsxs("p",{children:["Попыток: ",_,"/",o.attempt_number]})]}),w?e.jsx("div",{style:{padding:"10px",backgroundColor:"#ffdddd",color:"red",borderRadius:"10px",textAlign:"center",fontWeight:"bold"},children:"Срок прохождения теста истек"}):e.jsx(F,{onClick:V,style:{borderRadius:"10px"},disabled:_<=0,children:"Начать тест"}),z&&z.length>0?e.jsxs("div",{style:{marginBottom:"20px",textAlign:"left"},children:[e.jsx("h4",{style:{marginBottom:"10px"},children:"Ваши предыдущие результаты:"}),e.jsx("div",{style:{display:"flex",flexDirection:"column",backgroundColor:"#f5f5f5",borderRadius:"10px",padding:"10px",maxHeight:"200px",overflowY:"auto",border:"1px solid #ddd"},children:z.map((C,a)=>e.jsxs("div",{style:{display:"flex",justifyContent:"space-between",padding:"10px 5px",borderBottom:a!==z.length-1?"1px solid #ddd":"none"},children:[e.jsx("span",{style:{fontSize:"14px"},children:new Date(C.completed_at).toLocaleDateString()}),e.jsxs("span",{style:{fontWeight:"bold",fontSize:"14px"},children:[C.score_obtained," / ",C.total_score," баллов"]})]},a))})]}):e.jsx("div",{style:{color:"#888",textAlign:"center",padding:"20px"},children:"Нет результатов"})]}):e.jsxs(e.Fragment,{children:[e.jsxs("div",{style:{display:"flex",borderBottom:"2px solid #333"},children:[e.jsx(F,{onClick:j,style:{borderRadius:"10px"},children:"←"}),e.jsx("div",{style:{display:"flex",overflowX:"auto"},children:f.map((C,a)=>e.jsx("div",{onClick:()=>m(a),style:{padding:"8px 12px",cursor:"pointer",backgroundColor:a===d?"#00a2ff":"#eee",color:a===d?"#fff":"#000",marginRight:"2px",borderRadius:"5px 5px 0 0",minWidth:"25px",textAlign:"center"},children:a+1},a))}),e.jsx(F,{onClick:G,style:{borderRadius:"10px",marginLeft:"auto"},children:"→"})]}),e.jsxs("div",{style:{color:"#000"},children:[e.jsx("p",{style:{fontWeight:"bold"},children:(le=f[d])==null?void 0:le.question}),((de=f[d])==null?void 0:de.type)==="text"&&e.jsx("textarea",{value:f[d].completedText,onChange:C=>M("completedText",C.target.value),style:{width:"100%",height:"80px",padding:"5px"}}),((ae=f[d])==null?void 0:ae.type)==="single"&&f[d].options.map((C,a)=>e.jsxs("div",{style:{display:"flex",alignItems:"center",marginBottom:"15px",cursor:"pointer",gap:"10px"},children:[e.jsx(se,{checked:f[d].completedRadioOptionId===C.id,onChange:()=>M("completedRadioOptionId",C.id)}),e.jsx("div",{onClick:()=>M("completedRadioOptionId",C.id),style:{flexGrow:1,display:"flex",justifyContent:"space-between",backgroundColor:f[d].completedRadioOptionId===C.id?"#d0d0d0":"#e0e0e0",padding:"12px 16px",borderRadius:"10px",position:"relative",overflow:"hidden"},children:e.jsx("span",{children:C.text})})]},a)),((R=f[d])==null?void 0:R.type)==="multiple"&&f[d].options.map((C,a)=>e.jsxs("div",{style:{display:"flex",alignItems:"center",marginBottom:"15px",cursor:"pointer",gap:"10px"},children:[e.jsx(Z,{checked:f[d].completedBoxOptionIds.includes(C.id),onChange:()=>W(C.id)}),e.jsx("div",{onClick:()=>W(C.id),style:{flexGrow:1,display:"flex",justifyContent:"space-between",backgroundColor:f[d].completedBoxOptionIds.includes(C.id)?"#d0d0d0":"#e0e0e0",padding:"12px 16px",borderRadius:"10px",position:"relative",overflow:"hidden"},children:e.jsx("span",{children:C.text})})]},a))]}),e.jsx("div",{style:{marginTop:"20px",display:"flex",justifyContent:"flex-end"},children:d!==f.length-1&&e.jsx(F,{onClick:G,children:"Дальше"})}),e.jsx("div",{style:{marginTop:"20px",display:"flex",justifyContent:"flex-end"},children:d===f.length-1&&e.jsx(F,{onClick:O,disabled:c,children:c?"Сохранение...":"Завершить"})})]})})]})},Le=o=>{const t=`; ${document.cookie}`.split(`; ${o}=`);return t.length===2?t.pop().split(";").shift():null},He=({initialTitle:o,pollId:s,nodeId:t,nodeProps:n,onSaved:i})=>{const{createTest:l,loading:c,error:r,fetchTest:p,deleteTest:g}=be(),[b,y]=h.useState(s?"display":"creator"),[x,d]=h.useState(!1),[m,v]=h.useState(null),[u,f]=h.useState({id:null,owner:"",title:o||"",tasks:[]}),[T,z]=h.useState({completionTime:null,attemptNumber:1,endDate:null,endTime:null}),[_,B]=h.useState(null);h.useEffect(()=>{let w=localStorage.getItem("userId");w||(w=Le("user_id")),w||(w="anon_"+Math.random().toString(36).substring(2,11),localStorage.setItem("userId",w)),v(w)},[]),h.useCallback(w=>{if(!w)return;console.log("Test Widget initialized with:",w);const{widgetId:P,userId:M,role:U,config:j,board:G}=w;P&&(async()=>{try{const O=await p(P);if(!O)return;B(O),f({id:O.id,title:O.title,tasks:O.tasks||[],all_attempts:O.all_attempts,owner:O.owner}),O.settings&&z(O.settings),d(!0)}catch(O){console.error("Ошибка загрузки теста:",O)}})();const W=["admin","editor","owner"].includes(U);y(W?O=>P?"display":"creator":"display")},[p]),h.useEffect(()=>{if(!s)return;let w=!0;return(async()=>{try{const P=await p(s);if(!w||!P)return;B(P),f({id:P.id,title:P.title,tasks:P.tasks||[],all_attempts:P.all_attempts,owner:P.owner}),P.settings&&z(P.settings),d(!0)}catch(P){console.error("Ошибка загрузки теста:",P)}})(),()=>{w=!1}},[s,p]);const S=h.useCallback(()=>y("creator"),[]),k=h.useCallback(()=>{y(w=>w==="settings"?"creator":"settings")},[]),E=async()=>{const w=(u==null?void 0:u.id)||pollId,P=localStorage.getItem("userId")||"Anonymous";if(!w){alert("Ошибка: ID теста не найден");return}if(window.confirm("Вы уверены, что хотите полностью удалить этот тест?"))try{await g(w,P),alert("Тест успешно удален"),setTimeout(()=>{window.location.reload()},100)}catch(M){console.error("Ошибка удаления:",M),M.status===403?alert("У вас нет прав на удаление (вы не автор)."):alert("Не удалось удалить тест: "+M.message)}},N=h.useCallback(async()=>{try{const w=await l(u,T);w&&w.id&&(B(w),d(!0),y("display"),typeof i=="function"&&i(w.id))}catch(w){console.error("Ошибка при сохранении:",w)}},[l,u,T]),I=()=>b==="settings"?"Настройки":u.title||"Тест";return s&&!x?e.jsx(pe,{title:"Загрузка...",children:e.jsx("div",{style:{padding:"20px",textAlign:"center"},children:"Загрузка данных теста..."})}):e.jsxs(pe,{title:I(),toggleSettings:b!=="display"?k:void 0,showMenuDots:b==="creator",children:[c&&e.jsx("p",{style:{color:"blue",textAlign:"center",margin:"5px 0"},children:"Синхронизация..."}),e.jsx("div",{style:{position:"relative"},children:e.jsxs("div",{style:{fontSize:"10px",color:"#999",textAlign:"right",padding:"0 15px"},children:["User ID: ",m]})}),b==="creator"&&e.jsx(Ne,{onDataChange:f,initialData:u,onSave:N}),b==="settings"&&e.jsx(Me,{onDataChange:z,initialData:T,toggleSettings:S}),b==="display"&&x&&e.jsxs("div",{style:{position:"relative",height:"100%",display:"flex",flexDirection:"column"},children:[(u==null?void 0:u.id)&&String(u.owner)===String(m)&&e.jsx("div",{onClick:E,style:{position:"absolute",top:"15px",right:"15px",width:"24px",height:"24px",backgroundColor:"#ff4d4d",color:"white",borderRadius:"50%",display:"flex",alignItems:"center",justifyContent:"center",cursor:"pointer",fontSize:"18px",fontWeight:"bold",zIndex:1e3,boxShadow:"0 2px 5px rgba(0,0,0,0.2)",lineHeight:"1"},title:"Удалить тест",children:"×"}),e.jsx(Oe,{testData:_,setTestData:B})]}),r&&e.jsx("div",{style:{color:"red",fontSize:"12px",padding:"10px",textAlign:"center"},children:r})]})},je={display:"flex",flexDirection:"column",background:"transparent",pointerEvents:"all",position:"relative"},Fe=o=>{const{id:s,data:t,selected:n,xPos:i,yPos:l,dragging:c}=o,[r,p]=h.useState({width:280,height:450}),g=X.useUpdateNodeInternals(),{setNodes:b}=X.useReactFlow(),y=h.useCallback((v,u,f,T)=>{const z=f.offsetWidth,_=f.offsetHeight;p({width:z,height:_}),g(s)},[]),x=h.useCallback(()=>{},[]),d={bottom:"nodrag",right:"nodrag",bottomRight:"nodrag"},m={bottom:{height:10,bottom:-5,cursor:"ns-resize",zIndex:999},right:{width:10,right:-5,cursor:"ew-resize",zIndex:999},bottomRight:{width:20,height:20,right:-5,bottom:-5,cursor:"nwse-resize",zIndex:1e3}};return e.jsxs(ye,{size:r,minWidth:800,minHeight:750,style:je,onResize:x,handleClasses:d,handleStyles:m,onResizeStop:y,enable:{top:!1,right:!0,bottom:!0,left:!1,topRight:!1,bottomRight:!0,bottomLeft:!1,topLeft:!1},onPointerDown:v=>v.stopPropagation(),children:[e.jsx("div",{style:{position:"absolute",top:0,left:0,right:0,bottom:0,overflow:"hidden",outline:n?"2px solid #007bff":"none",borderRadius:"2px",boxShadow:"0 4px 15px rgba(0, 0, 0, 0.1)"},children:e.jsx(Ae,{initialTitle:t.label,pollId:t==null?void 0:t.pollId,nodeId:s,onSaved:v=>{b(u=>u.map(f=>f.id===s?{...f,data:{...f.data,pollId:v}}:f))}})}),e.jsx(X.Handle,{type:"source",position:X.Position.Left}),e.jsx(X.Handle,{type:"target",position:X.Position.Top})]})},Ge={display:"flex",flexDirection:"column",background:"transparent",pointerEvents:"all",position:"relative"},$e=o=>{const{id:s,data:t,selected:n,xPos:i,yPos:l,dragging:c}=o,[r,p]=h.useState({width:280,height:450}),g=X.useUpdateNodeInternals(),{setNodes:b}=X.useReactFlow(),y=u=>{b(f=>f.map(T=>T.id===s?{...T,data:{...T.data,pollId:u}}:T))},x=h.useCallback((u,f,T,z)=>{const _=T.offsetWidth,B=T.offsetHeight;p({width:_,height:B}),g(s)},[]),d=h.useCallback(()=>{},[]),m={bottom:"nodrag",right:"nodrag",bottomRight:"nodrag"},v={bottom:{height:10,bottom:-5,cursor:"ns-resize",zIndex:999},right:{width:10,right:-5,cursor:"ew-resize",zIndex:999},bottomRight:{width:20,height:20,right:-5,bottom:-5,cursor:"nwse-resize",zIndex:1e3}};return e.jsxs(ye,{size:r,minWidth:800,minHeight:750,style:Ge,onResize:d,handleClasses:m,handleStyles:v,onResizeStop:x,enable:{top:!1,right:!0,bottom:!0,left:!1,topRight:!1,bottomRight:!0,bottomLeft:!1,topLeft:!1},onPointerDown:u=>u.stopPropagation(),children:[e.jsx("div",{style:{position:"absolute",top:0,left:0,right:0,bottom:0,overflow:"hidden",outline:n?"2px solid #007bff":"none",borderRadius:"2px",boxShadow:"0 4px 15px rgba(0, 0, 0, 0.1)"},children:e.jsx(He,{nodeId:s,initialTitle:t.label,pollId:t.pollId,nodeProps:o,onSaved:y})}),e.jsx(X.Handle,{type:"source",position:X.Position.Left}),e.jsx(X.Handle,{type:"target",position:X.Position.Top})]})};Y.PollResizable=Fe,Y.TestResizable=$e,Object.defineProperty(Y,Symbol.toStringTag,{value:"Module"})});
1
+ (function(Y,e){typeof exports=="object"&&typeof module<"u"?e(exports,require("react/jsx-runtime"),require("react"),require("@xyflow/react"),require("react-dom")):typeof define=="function"&&define.amd?define(["exports","react/jsx-runtime","react","@xyflow/react","react-dom"],e):(Y=typeof globalThis<"u"?globalThis:Y||self,e(Y.PollTestWidgets={},Y.jsxRuntime,Y.React,Y.ReactFlow,Y.ReactDOM))})(this,function(Y,e,h,X,we){"use strict";var H=function(){return H=Object.assign||function(o){for(var s,t=1,n=arguments.length;t<n;t++){s=arguments[t];for(var i in s)Object.prototype.hasOwnProperty.call(s,i)&&(o[i]=s[i])}return o},H.apply(this,arguments)},he={width:"100%",height:"10px",top:"0px",left:"0px",cursor:"row-resize"},fe={width:"10px",height:"100%",top:"0px",left:"0px",cursor:"col-resize"},ee={width:"20px",height:"20px",position:"absolute",zIndex:1},me={top:H(H({},he),{top:"-5px"}),right:H(H({},fe),{left:void 0,right:"-5px"}),bottom:H(H({},he),{top:void 0,bottom:"-5px"}),left:H(H({},fe),{left:"-5px"}),topRight:H(H({},ee),{right:"-10px",top:"-10px",cursor:"ne-resize"}),bottomRight:H(H({},ee),{right:"-10px",bottom:"-10px",cursor:"se-resize"}),bottomLeft:H(H({},ee),{left:"-10px",bottom:"-10px",cursor:"sw-resize"}),topLeft:H(H({},ee),{left:"-10px",top:"-10px",cursor:"nw-resize"})},Se=h.memo(function(o){var s=o.onResizeStart,t=o.direction,n=o.children,i=o.replaceStyles,l=o.className,c=h.useCallback(function(g){s(g,t)},[s,t]),r=h.useCallback(function(g){s(g,t)},[s,t]),p=h.useMemo(function(){return H(H({position:"absolute",userSelect:"none"},me[t]),i??{})},[i,t]);return e.jsx("div",{className:l||void 0,style:p,onMouseDown:c,onTouchStart:r,children:n})}),Ce=function(){var o=function(s,t){return o=Object.setPrototypeOf||{__proto__:[]}instanceof Array&&function(n,i){n.__proto__=i}||function(n,i){for(var l in i)Object.prototype.hasOwnProperty.call(i,l)&&(n[l]=i[l])},o(s,t)};return function(s,t){if(typeof t!="function"&&t!==null)throw new TypeError("Class extends value "+String(t)+" is not a constructor or null");o(s,t);function n(){this.constructor=s}s.prototype=t===null?Object.create(t):(n.prototype=t.prototype,new n)}}(),q=function(){return q=Object.assign||function(o){for(var s,t=1,n=arguments.length;t<n;t++){s=arguments[t];for(var i in s)Object.prototype.hasOwnProperty.call(s,i)&&(o[i]=s[i])}return o},q.apply(this,arguments)},ze={width:"auto",height:"auto"},te=function(o,s,t){return Math.max(Math.min(o,t),s)},ue=function(o,s,t){var n=Math.round(o/s);return n*s+t*(n-1)},Q=function(o,s){return new RegExp(o,"i").test(s)},oe=function(o){return!!(o.touches&&o.touches.length)},ke=function(o){return!!((o.clientX||o.clientX===0)&&(o.clientY||o.clientY===0))},ge=function(o,s,t){t===void 0&&(t=0);var n=s.reduce(function(l,c,r){return Math.abs(c-o)<Math.abs(s[l]-o)?r:l},0),i=Math.abs(s[n]-o);return t===0||i<t?s[n]:o},ce=function(o){return o=o.toString(),o==="auto"||o.endsWith("px")||o.endsWith("%")||o.endsWith("vh")||o.endsWith("vw")||o.endsWith("vmax")||o.endsWith("vmin")?o:"".concat(o,"px")},ie=function(o,s,t,n){if(o&&typeof o=="string"){if(o.endsWith("px"))return Number(o.replace("px",""));if(o.endsWith("%")){var i=Number(o.replace("%",""))/100;return s*i}if(o.endsWith("vw")){var i=Number(o.replace("vw",""))/100;return t*i}if(o.endsWith("vh")){var i=Number(o.replace("vh",""))/100;return n*i}}return o},Te=function(o,s,t,n,i,l,c){return n=ie(n,o.width,s,t),i=ie(i,o.height,s,t),l=ie(l,o.width,s,t),c=ie(c,o.height,s,t),{maxWidth:typeof n>"u"?void 0:Number(n),maxHeight:typeof i>"u"?void 0:Number(i),minWidth:typeof l>"u"?void 0:Number(l),minHeight:typeof c>"u"?void 0:Number(c)}},_e=function(o){return Array.isArray(o)?o:[o,o]},Ie=["as","ref","style","className","grid","gridGap","snap","bounds","boundsByDirection","size","defaultSize","minWidth","minHeight","maxWidth","maxHeight","lockAspectRatio","lockAspectRatioExtraWidth","lockAspectRatioExtraHeight","enable","handleStyles","handleClasses","handleWrapperStyle","handleWrapperClass","children","onResizeStart","onResize","onResizeStop","handleComponent","scale","resizeRatio","snapGap"],xe="__resizable_base__",ye=function(o){Ce(s,o);function s(t){var n,i,l,c,r=o.call(this,t)||this;return r.ratio=1,r.resizable=null,r.parentLeft=0,r.parentTop=0,r.resizableLeft=0,r.resizableRight=0,r.resizableTop=0,r.resizableBottom=0,r.targetLeft=0,r.targetTop=0,r.delta={width:0,height:0},r.appendBase=function(){if(!r.resizable||!r.window)return null;var p=r.parentNode;if(!p)return null;var g=r.window.document.createElement("div");return g.style.width="100%",g.style.height="100%",g.style.position="absolute",g.style.transform="scale(0, 0)",g.style.left="0",g.style.flex="0 0 100%",g.classList?g.classList.add(xe):g.className+=xe,p.appendChild(g),g},r.removeBase=function(p){var g=r.parentNode;g&&g.removeChild(p)},r.state={isResizing:!1,width:(i=(n=r.propsSize)===null||n===void 0?void 0:n.width)!==null&&i!==void 0?i:"auto",height:(c=(l=r.propsSize)===null||l===void 0?void 0:l.height)!==null&&c!==void 0?c:"auto",direction:"right",original:{x:0,y:0,width:0,height:0},backgroundStyle:{height:"100%",width:"100%",backgroundColor:"rgba(0,0,0,0)",cursor:"auto",opacity:0,position:"fixed",zIndex:9999,top:"0",left:"0",bottom:"0",right:"0"},flexBasis:void 0},r.onResizeStart=r.onResizeStart.bind(r),r.onMouseMove=r.onMouseMove.bind(r),r.onMouseUp=r.onMouseUp.bind(r),r}return Object.defineProperty(s.prototype,"parentNode",{get:function(){return this.resizable?this.resizable.parentNode:null},enumerable:!1,configurable:!0}),Object.defineProperty(s.prototype,"window",{get:function(){return!this.resizable||!this.resizable.ownerDocument?null:this.resizable.ownerDocument.defaultView},enumerable:!1,configurable:!0}),Object.defineProperty(s.prototype,"propsSize",{get:function(){return this.props.size||this.props.defaultSize||ze},enumerable:!1,configurable:!0}),Object.defineProperty(s.prototype,"size",{get:function(){var t=0,n=0;if(this.resizable&&this.window){var i=this.resizable.offsetWidth,l=this.resizable.offsetHeight,c=this.resizable.style.position;c!=="relative"&&(this.resizable.style.position="relative"),t=this.resizable.style.width!=="auto"?this.resizable.offsetWidth:i,n=this.resizable.style.height!=="auto"?this.resizable.offsetHeight:l,this.resizable.style.position=c}return{width:t,height:n}},enumerable:!1,configurable:!0}),Object.defineProperty(s.prototype,"sizeStyle",{get:function(){var t=this,n=this.props.size,i=function(r){var p;if(typeof t.state[r]>"u"||t.state[r]==="auto")return"auto";if(t.propsSize&&t.propsSize[r]&&(!((p=t.propsSize[r])===null||p===void 0)&&p.toString().endsWith("%"))){if(t.state[r].toString().endsWith("%"))return t.state[r].toString();var g=t.getParentSize(),b=Number(t.state[r].toString().replace("px","")),y=b/g[r]*100;return"".concat(y,"%")}return ce(t.state[r])},l=n&&typeof n.width<"u"&&!this.state.isResizing?ce(n.width):i("width"),c=n&&typeof n.height<"u"&&!this.state.isResizing?ce(n.height):i("height");return{width:l,height:c}},enumerable:!1,configurable:!0}),s.prototype.getParentSize=function(){if(!this.parentNode)return this.window?{width:this.window.innerWidth,height:this.window.innerHeight}:{width:0,height:0};var t=this.appendBase();if(!t)return{width:0,height:0};var n=!1,i=this.parentNode.style.flexWrap;i!=="wrap"&&(n=!0,this.parentNode.style.flexWrap="wrap"),t.style.position="relative",t.style.minWidth="100%",t.style.minHeight="100%";var l={width:t.offsetWidth,height:t.offsetHeight};return n&&(this.parentNode.style.flexWrap=i),this.removeBase(t),l},s.prototype.bindEvents=function(){this.window&&(this.window.addEventListener("mouseup",this.onMouseUp),this.window.addEventListener("mousemove",this.onMouseMove),this.window.addEventListener("mouseleave",this.onMouseUp),this.window.addEventListener("touchmove",this.onMouseMove,{capture:!0,passive:!1}),this.window.addEventListener("touchend",this.onMouseUp))},s.prototype.unbindEvents=function(){this.window&&(this.window.removeEventListener("mouseup",this.onMouseUp),this.window.removeEventListener("mousemove",this.onMouseMove),this.window.removeEventListener("mouseleave",this.onMouseUp),this.window.removeEventListener("touchmove",this.onMouseMove,!0),this.window.removeEventListener("touchend",this.onMouseUp))},s.prototype.componentDidMount=function(){if(!(!this.resizable||!this.window)){var t=this.window.getComputedStyle(this.resizable);this.setState({width:this.state.width||this.size.width,height:this.state.height||this.size.height,flexBasis:t.flexBasis!=="auto"?t.flexBasis:void 0})}},s.prototype.componentWillUnmount=function(){this.window&&this.unbindEvents()},s.prototype.createSizeForCssProperty=function(t,n){var i=this.propsSize&&this.propsSize[n];return this.state[n]==="auto"&&this.state.original[n]===t&&(typeof i>"u"||i==="auto")?"auto":t},s.prototype.calculateNewMaxFromBoundary=function(t,n){var i=this.props.boundsByDirection,l=this.state.direction,c=i&&Q("left",l),r=i&&Q("top",l),p,g;if(this.props.bounds==="parent"){var b=this.parentNode;b&&(p=c?this.resizableRight-this.parentLeft:b.offsetWidth+(this.parentLeft-this.resizableLeft),g=r?this.resizableBottom-this.parentTop:b.offsetHeight+(this.parentTop-this.resizableTop))}else this.props.bounds==="window"?this.window&&(p=c?this.resizableRight:this.window.innerWidth-this.resizableLeft,g=r?this.resizableBottom:this.window.innerHeight-this.resizableTop):this.props.bounds&&(p=c?this.resizableRight-this.targetLeft:this.props.bounds.offsetWidth+(this.targetLeft-this.resizableLeft),g=r?this.resizableBottom-this.targetTop:this.props.bounds.offsetHeight+(this.targetTop-this.resizableTop));return p&&Number.isFinite(p)&&(t=t&&t<p?t:p),g&&Number.isFinite(g)&&(n=n&&n<g?n:g),{maxWidth:t,maxHeight:n}},s.prototype.calculateNewSizeFromDirection=function(t,n){var i=this.props.scale||1,l=_e(this.props.resizeRatio||1),c=l[0],r=l[1],p=this.state,g=p.direction,b=p.original,y=this.props,x=y.lockAspectRatio,d=y.lockAspectRatioExtraHeight,m=y.lockAspectRatioExtraWidth,v=b.width,u=b.height,f=d||0,T=m||0;return Q("right",g)&&(v=b.width+(t-b.x)*c/i,x&&(u=(v-T)/this.ratio+f)),Q("left",g)&&(v=b.width-(t-b.x)*c/i,x&&(u=(v-T)/this.ratio+f)),Q("bottom",g)&&(u=b.height+(n-b.y)*r/i,x&&(v=(u-f)*this.ratio+T)),Q("top",g)&&(u=b.height-(n-b.y)*r/i,x&&(v=(u-f)*this.ratio+T)),{newWidth:v,newHeight:u}},s.prototype.calculateNewSizeFromAspectRatio=function(t,n,i,l){var c=this.props,r=c.lockAspectRatio,p=c.lockAspectRatioExtraHeight,g=c.lockAspectRatioExtraWidth,b=typeof l.width>"u"?10:l.width,y=typeof i.width>"u"||i.width<0?t:i.width,x=typeof l.height>"u"?10:l.height,d=typeof i.height>"u"||i.height<0?n:i.height,m=p||0,v=g||0;if(r){var u=(x-m)*this.ratio+v,f=(d-m)*this.ratio+v,T=(b-v)/this.ratio+m,z=(y-v)/this.ratio+m,_=Math.max(b,u),B=Math.min(y,f),S=Math.max(x,T),k=Math.min(d,z);t=te(t,_,B),n=te(n,S,k)}else t=te(t,b,y),n=te(n,x,d);return{newWidth:t,newHeight:n}},s.prototype.setBoundingClientRect=function(){var t=1/(this.props.scale||1);if(this.props.bounds==="parent"){var n=this.parentNode;if(n){var i=n.getBoundingClientRect();this.parentLeft=i.left*t,this.parentTop=i.top*t}}if(this.props.bounds&&typeof this.props.bounds!="string"){var l=this.props.bounds.getBoundingClientRect();this.targetLeft=l.left*t,this.targetTop=l.top*t}if(this.resizable){var c=this.resizable.getBoundingClientRect(),r=c.left,p=c.top,g=c.right,b=c.bottom;this.resizableLeft=r*t,this.resizableRight=g*t,this.resizableTop=p*t,this.resizableBottom=b*t}},s.prototype.onResizeStart=function(t,n){if(!(!this.resizable||!this.window)){var i=0,l=0;if(t.nativeEvent&&ke(t.nativeEvent)?(i=t.nativeEvent.clientX,l=t.nativeEvent.clientY):t.nativeEvent&&oe(t.nativeEvent)&&(i=t.nativeEvent.touches[0].clientX,l=t.nativeEvent.touches[0].clientY),this.props.onResizeStart&&this.resizable){var c=this.props.onResizeStart(t,n,this.resizable);if(c===!1)return}this.props.size&&(typeof this.props.size.height<"u"&&this.props.size.height!==this.state.height&&this.setState({height:this.props.size.height}),typeof this.props.size.width<"u"&&this.props.size.width!==this.state.width&&this.setState({width:this.props.size.width})),this.ratio=typeof this.props.lockAspectRatio=="number"?this.props.lockAspectRatio:this.size.width/this.size.height;var r,p=this.window.getComputedStyle(this.resizable);if(p.flexBasis!=="auto"){var g=this.parentNode;if(g){var b=this.window.getComputedStyle(g).flexDirection;this.flexDir=b.startsWith("row")?"row":"column",r=p.flexBasis}}this.setBoundingClientRect(),this.bindEvents();var y={original:{x:i,y:l,width:this.size.width,height:this.size.height},isResizing:!0,backgroundStyle:q(q({},this.state.backgroundStyle),{cursor:this.window.getComputedStyle(t.target).cursor||"auto"}),direction:n,flexBasis:r};this.setState(y)}},s.prototype.onMouseMove=function(t){var n=this;if(!(!this.state.isResizing||!this.resizable||!this.window)){if(this.window.TouchEvent&&oe(t))try{t.preventDefault(),t.stopPropagation()}catch{}var i=this.props,l=i.maxWidth,c=i.maxHeight,r=i.minWidth,p=i.minHeight,g=oe(t)?t.touches[0].clientX:t.clientX,b=oe(t)?t.touches[0].clientY:t.clientY,y=this.state,x=y.direction,d=y.original,m=y.width,v=y.height,u=this.getParentSize(),f=Te(u,this.window.innerWidth,this.window.innerHeight,l,c,r,p);l=f.maxWidth,c=f.maxHeight,r=f.minWidth,p=f.minHeight;var T=this.calculateNewSizeFromDirection(g,b),z=T.newHeight,_=T.newWidth,B=this.calculateNewMaxFromBoundary(l,c);this.props.snap&&this.props.snap.x&&(_=ge(_,this.props.snap.x,this.props.snapGap)),this.props.snap&&this.props.snap.y&&(z=ge(z,this.props.snap.y,this.props.snapGap));var S=this.calculateNewSizeFromAspectRatio(_,z,{width:B.maxWidth,height:B.maxHeight},{width:r,height:p});if(_=S.newWidth,z=S.newHeight,this.props.grid){var k=ue(_,this.props.grid[0],this.props.gridGap?this.props.gridGap[0]:0),E=ue(z,this.props.grid[1],this.props.gridGap?this.props.gridGap[1]:0),N=this.props.snapGap||0,I=N===0||Math.abs(k-_)<=N?k:_,w=N===0||Math.abs(E-z)<=N?E:z;_=I,z=w}var P={width:_-d.width,height:z-d.height};if(this.delta=P,m&&typeof m=="string"){if(m.endsWith("%")){var M=_/u.width*100;_="".concat(M,"%")}else if(m.endsWith("vw")){var U=_/this.window.innerWidth*100;_="".concat(U,"vw")}else if(m.endsWith("vh")){var j=_/this.window.innerHeight*100;_="".concat(j,"vh")}}if(v&&typeof v=="string"){if(v.endsWith("%")){var M=z/u.height*100;z="".concat(M,"%")}else if(v.endsWith("vw")){var U=z/this.window.innerWidth*100;z="".concat(U,"vw")}else if(v.endsWith("vh")){var j=z/this.window.innerHeight*100;z="".concat(j,"vh")}}var G={width:this.createSizeForCssProperty(_,"width"),height:this.createSizeForCssProperty(z,"height")};this.flexDir==="row"?G.flexBasis=G.width:this.flexDir==="column"&&(G.flexBasis=G.height);var W=this.state.width!==G.width,O=this.state.height!==G.height,V=this.state.flexBasis!==G.flexBasis,J=W||O||V;J&&we.flushSync(function(){n.setState(G)}),this.props.onResize&&J&&this.props.onResize(t,x,this.resizable,P)}},s.prototype.onMouseUp=function(t){var n,i,l=this.state,c=l.isResizing,r=l.direction;l.original,!(!c||!this.resizable)&&(this.props.onResizeStop&&this.props.onResizeStop(t,r,this.resizable,this.delta),this.props.size&&this.setState({width:(n=this.props.size.width)!==null&&n!==void 0?n:"auto",height:(i=this.props.size.height)!==null&&i!==void 0?i:"auto"}),this.unbindEvents(),this.setState({isResizing:!1,backgroundStyle:q(q({},this.state.backgroundStyle),{cursor:"auto"})}))},s.prototype.updateSize=function(t){var n,i;this.setState({width:(n=t.width)!==null&&n!==void 0?n:"auto",height:(i=t.height)!==null&&i!==void 0?i:"auto"})},s.prototype.renderResizer=function(){var t=this,n=this.props,i=n.enable,l=n.handleStyles,c=n.handleClasses,r=n.handleWrapperStyle,p=n.handleWrapperClass,g=n.handleComponent;if(!i)return null;var b=Object.keys(i).map(function(y){return i[y]!==!1?e.jsx(Se,{direction:y,onResizeStart:t.onResizeStart,replaceStyles:l&&l[y],className:c&&c[y],children:g&&g[y]?g[y]:null},y):null});return e.jsx("div",{className:p,style:r,children:b})},s.prototype.render=function(){var t=this,n=Object.keys(this.props).reduce(function(c,r){return Ie.indexOf(r)!==-1||(c[r]=t.props[r]),c},{}),i=q(q(q({position:"relative",userSelect:this.state.isResizing?"none":"auto"},this.props.style),this.sizeStyle),{maxWidth:this.props.maxWidth,maxHeight:this.props.maxHeight,minWidth:this.props.minWidth,minHeight:this.props.minHeight,boxSizing:"border-box",flexShrink:0});this.state.flexBasis&&(i.flexBasis=this.state.flexBasis);var l=this.props.as||"div";return e.jsxs(l,q({style:i,className:this.props.className},n,{ref:function(c){c&&(t.resizable=c)},children:[this.state.isResizing&&e.jsx("div",{style:this.state.backgroundStyle}),this.props.children,this.renderResizer()]}))},s.defaultProps={as:"div",onResizeStart:function(){},onResize:function(){},onResizeStop:function(){},enable:{top:!0,right:!0,bottom:!0,left:!0,topRight:!0,bottomRight:!0,bottomLeft:!0,topLeft:!0},style:{},grid:[1,1],gridGap:[0,0],lockAspectRatio:!1,lockAspectRatioExtraWidth:0,lockAspectRatioExtraHeight:0,scale:1,resizeRatio:1,snapGap:0},s}(h.PureComponent);const ve=o=>{o||(o="https://polls-tests-widgets-backend-1357.loca.lt");const[s,t]=h.useState(!1),[n,i]=h.useState(null),l=v=>`${o?o.replace(/\/$/,""):""}/api/polls${v}`,c=()=>{const v="csrftoken=",u=document.cookie?document.cookie.split(";"):[];for(let f of u)if(f=f.trim(),f.startsWith(v))return decodeURIComponent(f.substring(v.length));return null},r=async()=>{await fetch(l("/csrf/"),{credentials:"include"})},p=async(v,u={})=>{const f={credentials:"include",method:"GET",headers:{"Content-Type":"application/json","bypass-tunnel-reminder":"true"}},T={...f,...u,headers:{...f.headers,...u.headers||{}}},z=await fetch(v,T),_=await z.text();let B=null;try{B=_?JSON.parse(_):null}catch{B=_}if(!z.ok){const S=new Error(B&&(B.detail||B.message)||z.statusText);throw S.status=z.status,S}return B},g=h.useCallback(async(v,u)=>{t(!0),i(null);try{await r();const f=c();return await p(l(`/${v}/`),{method:"DELETE",headers:{"X-CSRFToken":f,"X-User-ID":u}})}catch(f){throw i(f.message),f}finally{t(!1)}},[]),b=h.useCallback(async()=>{try{return await p(l("/list/"),{method:"GET"})}catch(v){throw console.error("Ошибка получения списка опросов:",v),v}},[p]),y=h.useCallback(async v=>{t(!0),i(null);try{return await p(l(`/${v}/`),{method:"GET"})}catch(u){return i(u.message),null}finally{t(!1)}},[]),x=h.useCallback(async(v,u)=>{t(!0),i(null),await r();const f=c();if(!f)throw new Error("CSRF token missing!");const T=(v.options||[]).filter(B=>B.trim()!=="").map(B=>({choice_text:B}));let z=null;u.endDate&&(z=new Date(`${u.endDate}T${u.endTime||"23:59:59"}`).toISOString());const _={owner:v.ownerID,title:v.title,choices:T,is_anonymous:u.isAnonymous,multiple_answers:u.multipleAnswers,end_date:z};try{return await p(l("/create/"),{method:"POST",headers:{"X-CSRFToken":f},body:JSON.stringify(_)})}catch(B){throw i(B.message),B}finally{t(!1)}},[]);h.useCallback(async v=>{t(!0),i(null);try{return await p(l(`/${v}/`),{method:"GET"})}catch(u){return i(u.message),null}finally{t(!1)}},[]);const d=h.useCallback(async(v,u)=>{t(!0),i(null),await r();const f=c();if(!f)throw new Error("CSRF token missing!");try{return await p(l(`/${v}/vote/`),{method:"POST",headers:{"X-CSRFToken":f},body:JSON.stringify({choice_id:u.choiceId,user:u.userId})})}catch(T){throw i(T.message),T}finally{t(!1)}},[]),m=h.useCallback(async(v,u)=>{t(!0),i(null),await r();const f=c();try{return await p(l(`/${v}/unvote/}`),{method:"POST",headers:{"X-CSRFToken":f},body:JSON.stringify({user:u})})}catch(T){throw i(T.message),T}finally{t(!1)}},[]);return{createPoll:x,loading:s,error:n,setError:i,fetchAllPolls:b,fetchPoll:y,createPoll:x,votePoll:d,unvotePoll:m,deletePoll:g}},K=({placeholder:o,value:s,onChange:t,style:n,autoFocus:i,type:l="text"})=>e.jsx("input",{type:l,placeholder:o,value:s,onChange:t,autoFocus:i,className:"nodrag",style:{width:"100%",boxSizing:"border-box",padding:"12px 16px",marginBottom:"12px",backgroundColor:"#e0e0e0",border:"none",borderRadius:"0px",fontSize:"16px",color:"#333",outline:"none",fontFamily:"Arial, sans-serif",...n}}),F=({onClick:o,children:s,style:t,disabled:n})=>e.jsx("button",{onClick:n?void 0:o,disabled:n,className:"nodrag",style:{padding:"10px 30px",backgroundColor:n?"#f0f0f0":"#d9d9d9",border:"none",borderRadius:"0px",fontSize:"18px",color:n?"#999":"#000",cursor:n?"not-allowed":"pointer",fontWeight:"400",transition:"background-color 0.2s",whiteSpace:"nowrap",opacity:n?.7:1,...t},onMouseOver:i=>{n||(i.target.style.backgroundColor="#c0c0c0")},onMouseOut:i=>{n||(i.target.style.backgroundColor=(t==null?void 0:t.backgroundColor)||"#d9d9d9")},children:s}),Z=({checked:o,onChange:s})=>e.jsxs("label",{style:{display:"inline-flex",alignItems:"center",cursor:"pointer",userSelect:"none",position:"relative"},children:[e.jsx("input",{type:"checkbox",checked:o,onChange:s,style:{opacity:0,width:0,height:0,position:"absolute"}}),e.jsx("span",{style:{display:"inline-block",width:"24px",height:"24px",border:`2px solid ${o?"#000":"#6c757d"}`,borderRadius:"4px",backgroundColor:o?"#000":"#fff",transition:"background-color 0.2s, border-color 0.2s",position:"relative",flexShrink:0},children:o&&e.jsx("span",{style:{content:'""',position:"absolute",left:"8px",top:"3px",width:"6px",height:"14px",border:"solid white",borderWidth:"0 3px 3px 0",transform:"rotate(45deg)",transition:"opacity 0.2s",opacity:o?1:0}})})]}),We=({onClick:o})=>e.jsx("div",{onClick:o,className:"nodrag",style:{display:"flex",gap:"6px",cursor:"pointer",flexShrink:0,padding:"5px"},children:[1,2,3].map(s=>e.jsx("div",{style:{width:"14px",height:"14px",borderRadius:"50%",backgroundColor:"#757575"}},s))}),se=({id:o,name:s,value:t,checked:n,onChange:i,children:l})=>e.jsxs("label",{htmlFor:o,style:{display:"inline-flex",alignItems:"center",cursor:"pointer",userSelect:"none"},children:[e.jsx("input",{id:o,type:"radio",name:s,value:t,checked:n,onChange:i,style:{opacity:0,width:0,height:0,position:"absolute"}}),e.jsx("span",{style:{display:"inline-block",width:"20px",height:"20px",borderRadius:"50%",border:`2px solid ${n?"#000":"#6c757d"}`,backgroundColor:"#fff",position:"relative",flexShrink:0,transition:"border-color 0.2s"},children:n&&e.jsx("span",{style:{position:"absolute",top:"50%",left:"50%",transform:"translate(-50%, -50%)",width:"10px",height:"10px",borderRadius:"50%",backgroundColor:"#000",transition:"opacity 0.2s",opacity:1}})}),l]}),pe=({title:o,children:s,style:t,toggleSettings:n,showMenuDots:i=!0})=>e.jsxs("div",{style:{width:"100%",height:"100%",backgroundColor:"#fff",padding:"20px 24px",display:"flex",flexDirection:"column",boxSizing:"border-box",boxShadow:"0 2px 10px rgba(0,0,0,0.05)",position:"relative",overflow:"hidden",...t},children:[e.jsxs("div",{style:{display:"flex",justifyContent:"space-between",alignItems:"flex-start",marginBottom:"20px",flexShrink:0},children:[e.jsx("span",{style:{fontSize:"20px",fontWeight:"400",color:"#000",lineHeight:"1.2",wordBreak:"break-word",marginRight:"10px"},children:o}),i&&e.jsx(We,{onClick:n})]}),e.jsx("div",{style:{flexGrow:1,display:"flex",flexDirection:"column",overflow:"hidden",minHeight:0},children:s})]}),Be=({onSave:o,onDataChange:s,initialData:t})=>{var b;const n=t!=null&&t.options&&t.options.length>0&&t.options.some(y=>y.trim()==="")?t.options:[...((b=t==null?void 0:t.options)==null?void 0:b.filter(y=>y.trim()!==""))||[],""],[i,l]=h.useState((t==null?void 0:t.title)||""),[c,r]=h.useState(n),p=h.useRef(null);h.useEffect(()=>{s({title:i,options:c.filter(y=>y.trim()!=="")})},[i,c,s]);const g=(y,x)=>{let d=[...c];d[y]=x,y===d.length-1&&x.trim()!==""&&d.push(""),d=d.filter((m,v)=>m.trim()!==""||v===d.length-1),r(d)};return h.useEffect(()=>{p.current&&c.length>1&&c[c.length-1].trim()===""&&p.current.scrollIntoView({behavior:"smooth"})},[c.length]),e.jsxs("div",{style:{display:"flex",flexDirection:"column",height:"100%",width:"100%",overflow:"hidden"},children:[e.jsx("div",{style:{flexShrink:0,width:"100%"},children:e.jsx(K,{placeholder:"Название опроса",value:i,onChange:y=>l(y.target.value),style:{fontSize:"20px",padding:"14px 16px",marginBottom:"20px",color:"#333",fontWeight:"bold",borderRadius:"15px"}})}),e.jsxs("div",{className:"scroll-container nowheel",onWheel:y=>y.stopPropagation(),style:{flexGrow:1,overflowY:"auto",overflowX:"hidden",paddingRight:"5px",marginBottom:"10px",width:"100%"},children:[c.map((y,x)=>e.jsx("div",{style:{display:"flex",alignItems:"center"},children:e.jsx(K,{placeholder:`Вариант ${x+1}`,value:y,onChange:d=>g(x,d.target.value),style:{flexGrow:1,marginBottom:"10px",borderRadius:"15px"}})},x)),e.jsx("div",{ref:p})]}),e.jsx("div",{style:{flexShrink:0,marginTop:"20px"},children:e.jsx(F,{onClick:()=>o(),style:{width:"100%",borderRadius:"15px"},children:"Сохранить опрос"})})]})},Ee=({onDataChange:o,initialData:s,toggleSettings:t,onDelete:n})=>{const[i,l]=h.useState((s==null?void 0:s.isAnonymous)||!1),[c,r]=h.useState((s==null?void 0:s.multipleAnswers)||!1),[p,g]=h.useState((s==null?void 0:s.endDate)||""),[b,y]=h.useState((s==null?void 0:s.endTime)||"");h.useEffect(()=>{o({isAnonymous:i,multipleAnswers:c,endDate:p,endTime:b})},[i,c,p,b,o]);const x={boxSizing:"border-box",padding:"12px 16px",backgroundColor:"#e0e0e0",border:"none",borderRadius:"15px",fontSize:"16px",color:"#333",outline:"none",fontFamily:"Arial, sans-serif",flex:1};return e.jsxs("div",{className:"nodrag",style:{display:"flex",flexDirection:"column",height:"100%",width:"100%",paddingRight:"5px",overflowY:"auto",overflowX:"hidden",boxSizing:"border-box"},children:[e.jsx("h3",{style:{fontSize:"20px",fontWeight:"bold",color:"#000",marginBottom:"25px",flexShrink:0},children:"Параметры опроса"}),e.jsxs("div",{style:{display:"flex",gap:"10px",alignItems:"center",marginBottom:"25px"},children:[e.jsx(Z,{checked:i,onChange:()=>l(!i)}),e.jsx("span",{style:{fontSize:"18px",color:"#333"},children:"Анонимность"})]}),e.jsxs("div",{style:{display:"flex",gap:"10px",alignItems:"center",marginBottom:"25px"},children:[e.jsx(Z,{checked:c,onChange:()=>r(!c)}),e.jsx("span",{style:{fontSize:"18px",color:"#333"},children:"Несколько ответов"})]}),e.jsxs("div",{style:{flexShrink:0},children:[e.jsx("span",{style:{fontSize:"18px",color:"#333",marginBottom:"10px",display:"block"},children:"Дата и время окончания"}),e.jsxs("div",{style:{display:"flex",gap:"10px"},children:[e.jsx("input",{type:"date",className:"nodrag",value:p,onChange:d=>g(d.target.value),style:x}),e.jsx("input",{type:"time",className:"nodrag",value:b,onChange:d=>y(d.target.value),style:x})]})]}),e.jsx("div",{style:{flexShrink:0,display:"flex",justifyContent:"flex-end",marginTop:"auto",paddingTop:"20px"},children:e.jsx(F,{onClick:t,style:{width:"100%",borderRadius:"15px"},children:"Назад к опросу"})})]})},Pe=({pollData:o,setPollData:s})=>{var C;const{id:t,title:n,choices:i,all_votes:l=[],voted_users:c=[],is_anonymous:r,multiple_answers:p,end_date:g,total_votes:b}=o,x=(()=>{if(!g)return!1;const a=new Date(g);return new Date>a})(),{votePoll:d,loading:m,error:v,setError:u,fetchPoll:f,unvotePoll:T}=ve(),z=localStorage.getItem("userId")||"Anonymous",_=r?"Анонимно":"Неанонимно",B=g?`До ${g.split("T")[0]}`:"Нет даты",S=a=>!c||c.length===0?"0%":`${Math.round(a/c.length*100)}%`,[k,E]=h.useState(l.some(a=>a.user===String(z))),[N,I]=h.useState(),[w,P]=h.useState([]),[M,U]=h.useState(l.find(a=>a.user===String(z))),[j,G]=h.useState(!1),[W,O]=h.useState(0),[V,J]=h.useState(k||m||x||!p&&!N||p&&w.length===0);h.useEffect(()=>{J(k||m||x||!p&&!N||p&&w.length===0)},[k,m,p,N,w,x]);const $=a=>{I(a)},D=a=>{P(A=>A.includes(a)?A.filter(L=>L!==a):[...A,a])},re=a=>{r||(G(!0),O(a))},ne=()=>{G(!1)},le=async()=>{if(x){alert("Время прохождения теста истекло.");return}if(!(!p&&!N||p&&w.length===0))try{let a=!0;if(p){const A=w.map(L=>d(t,{choiceId:L,userId:z}));try{await Promise.all(A),a=!0}catch(L){console.error("Один из голосов не прошел",L),a=!1}}else a=await d(t,{choiceId:N,userId:z});a&&(E(!0),f&&f(t).then(A=>s(A)))}catch(a){console.error("Ошибка при голосовании:",a),u("Не удалось сохранить голос")}},de=async()=>{try{const a=await T(t,z);if(a)s(a);else if(f){const A=await f(t);s(A)}E(!1),U(null),I(null),P([])}catch(a){console.error("Ошибка при отмене голоса:",a),u("Не удалось отменить голос")}},ae=new Intl.PluralRules("ru-RU");function R(a){const A=ae.select(a),L={one:"голос",few:"голоса",many:"голосов",other:"голосов"};return L[A]||L.many}return e.jsxs("div",{className:"nodrag nowheel",onWheel:a=>a.stopPropagation(),style:{display:"flex",color:"#000",flexDirection:"column",height:"100%",width:"100%",overflow:"hidden",paddingRight:"5px"},children:[e.jsx("div",{style:{flexShrink:0,width:"100%"},children:e.jsx("h3",{style:{fontSize:"22px",fontWeight:"bold",backgroundColor:"#e0e0e0",padding:"12px 16px",borderRadius:"10px"},children:n})}),e.jsxs("div",{style:{fontSize:"14px",color:"#666",marginBottom:"10px"},children:[_," | ",B," | Голосов: ",c.length||0]}),x&&e.jsx("div",{style:{padding:"10px",backgroundColor:"#ffdddd",color:"red",borderRadius:"10px",textAlign:"center",fontWeight:"bold",marginBottom:"10px"},children:"Срок прохождения теста истек"}),v&&e.jsx("p",{style:{color:"red"},children:v}),j&&e.jsxs("div",{style:{display:"flex",color:"#000",flexDirection:"column",height:"100%",width:"100%",overflowY:"auto",gap:"10px"},children:[e.jsxs("div",{style:{display:"flex",justifyContent:"space-between",padding:"12px",position:"relative",overflow:"hidden"},children:[e.jsx("div",{style:{position:"absolute",bottom:0,left:0,height:"5px",width:"100%",backgroundColor:"#ccc"}}),e.jsx("div",{style:{position:"absolute",bottom:0,left:0,height:"5px",width:S(W==null?void 0:W.votes_count),backgroundColor:"#000",transition:"width 0.5s"}}),e.jsx("span",{style:{zIndex:1},children:W==null?void 0:W.choice_text}),e.jsx("span",{style:{fontWeight:"bold",zIndex:1},children:`${S(W==null?void 0:W.votes_count)}`})]}),e.jsxs("span",{style:{marginLeft:"12px",color:"#666"},children:[W==null?void 0:W.votes_count," ",R(W==null?void 0:W.votes_count)]}),e.jsx("div",{style:{overflowY:"auto",margin:"12px 16px",display:"flex",flexDirection:"column",gap:"15px"},children:(C=l==null?void 0:l.filter(a=>a.choice_id===(W==null?void 0:W.id)))==null?void 0:C.map((a,A)=>e.jsx("div",{style:{display:"flex",alignItems:"center",gap:"10px"},children:e.jsx("span",{style:{},children:a.user})},A))}),e.jsx(F,{style:{marginTop:"auto"},onClick:ne,children:"Назад"})]}),!j&&e.jsxs("div",{style:{display:"flex",color:"#000",flexDirection:"column",height:"100%",width:"100%",overflowY:"auto"},children:[k?e.jsx("div",{className:"scroll-container nowheel",style:{flexGrow:1,overflowY:"auto",minHeight:0,paddingRight:"5px"},children:i==null?void 0:i.map(a=>{const A=S(a.votes_count);return e.jsxs("div",{onClick:()=>{re(a)},style:{display:"flex",flexDirection:"column",marginBottom:"15px",cursor:"pointer",gap:"10px"},children:[e.jsxs("div",{style:{flexGrow:1,display:"flex",justifyContent:"space-between",padding:"12px",position:"relative",overflow:"hidden"},children:[e.jsx("div",{style:{position:"absolute",bottom:0,left:0,height:"5px",width:"100%",backgroundColor:"#ccc"}}),e.jsx("div",{style:{position:"absolute",bottom:0,left:0,height:"5px",width:A,backgroundColor:"#000",transition:"width 0.5s"}}),e.jsx("span",{style:{zIndex:1},children:a.choice_text}),e.jsx("span",{style:{zIndex:1,marginLeft:"auto",marginRight:"10px"},children:(M==null?void 0:M.choice_id)===a.id?"✔":""}),e.jsx("span",{style:{fontWeight:"bold",zIndex:1},children:`${A}`})]}),e.jsxs("span",{style:{marginLeft:"12px",color:"#666"},children:[a.votes_count," ",R(a.votes_count)]})]},a.id)})}):e.jsx("div",{className:"scroll-container nowheel",style:{flexGrow:1,overflowY:"auto",minHeight:0,paddingRight:"5px"},children:i==null?void 0:i.map(a=>{const A=a.id,L=p?w.includes(A):N===A;return e.jsxs("div",{onClick:()=>p?D(A):$(A),style:{display:"flex",alignItems:"center",marginBottom:"15px",cursor:"pointer",gap:"10px"},children:[p&&e.jsx(Z,{checked:L,onChange:()=>D(A)}),!p&&e.jsx(se,{name:`poll-${t}`,checked:L,onChange:()=>$(A)}),e.jsxs("div",{style:{flexGrow:1,display:"flex",justifyContent:"space-between",backgroundColor:L?"#d0d0d0":"#e0e0e0",padding:"12px 16px",borderRadius:"10px",position:"relative",overflow:"hidden"},children:[e.jsx("span",{style:{zIndex:1},children:a.choice_text}),e.jsx("span",{style:{fontWeight:"bold",zIndex:1},children:""})]})]},a.id)})}),e.jsxs("div",{style:{marginTop:"auto",paddingTop:"20px",display:"flex",flexDirection:"column",gap:"10px"},children:[!k&&e.jsx(F,{onClick:le,disabled:V,style:{width:"100%",backgroundColor:"#d9d9d9",borderRadius:"10px"},children:m?"Отправка...":"Сохранить"}),k&&e.jsxs("div",{style:{textAlign:"center",width:"100%"},children:[e.jsx("div",{style:{marginBottom:"10px",fontWeight:"bold",color:"#4caf50"},children:"Голос принят!"}),e.jsx(F,{onClick:de,disabled:m,style:{width:"100%",borderRadius:"10px"},children:m?"Отмена...":"Отменить мой голос"})]})]})]})]})},Ae=({initialTitle:o,pollId:s,nodeId:t,nodeProps:n,onSaved:i})=>{const[l,c]=h.useState({ownerID:"",title:o||"",options:[""]}),[r,p]=h.useState({isAnonymous:!1,multipleAnswers:!1,endDate:"",endTime:""}),g=async()=>{const I=b==null?void 0:b.id;if(localStorage.getItem("userId"),!I){alert("Ошибка: ID опроса не определен.");return}if(window.confirm("Вы уверены, что хотите полностью удалить этот опрос?"))try{await T(I,z),alert("Опрос успешно удален из базы"),setTimeout(()=>{window.location.reload()},100)}catch(w){console.error("Детали ошибки:",w),w.status===403?alert("У вас нет прав на удаление этого опроса. Удалять может только автор."):alert("Произошла ошибка при удалении: "+w.message),console.warn("Побочная ошибка (вероятно расширение браузера):",w)}},[b,y]=h.useState(null),[x,d]=h.useState("creator"),{createPoll:m,loading:v,error:u,fetchPoll:f,deletePoll:T}=ve(),[z,_]=h.useState();h.useEffect(()=>{let I=localStorage.getItem("userId");I||(I=getCookie("user_id")),I||(I="anon_"+Math.random().toString(36).substring(2,11),localStorage.setItem("userId",I)),I&&(_(I),console.log("ID пользователя загружен:",I))},[]),h.useCallback(I=>{if(!I)return;console.log("Poll Widget initialized with:",I);const{widgetId:w,userId:P,role:M,config:U,board:j}=I;w&&(async()=>{try{const W=await f(w);if(!W)return;y(W);const O=(W.choices||[]).map($=>$.choice_text);c({title:W.title,options:[...O.filter($=>$.trim()!==""),(O.length>0,"")]});let V="",J="";if(W.end_date){const $=W.end_date.split("T");V=$[0],J=$[1]?$[1].substring(0,5):""}p({isAnonymous:W.is_anonymous,multipleAnswers:W.multiple_answers,endDate:V,endTime:J}),d("display")}catch(W){console.error("Ошибка загрузки опроса:",W)}})();const G=["admin","editor","owner"].includes(M);d(G?W=>w?"display":"creator":"display")},[f]),h.useEffect(()=>{if(!s)return;let I=!0;return(async()=>{try{const w=await f(s);if(!I||!w)return;y(w);const P=(w.choices||[]).map(j=>j.choice_text);c({title:w.title,options:[...P.filter(j=>j.trim()!==""),(P.length>0,"")]});let M="",U="";if(w.end_date){const j=w.end_date.split("T");M=j[0],U=j[1]?j[1].substring(0,5):""}p({isAnonymous:w.is_anonymous,multipleAnswers:w.multiple_answers,endDate:M,endTime:U}),d("display")}catch(w){console.error("Ошибка загрузки опроса:",w)}})(),()=>{I=!1}},[s,f]);const B=async()=>{const I=l.options.filter(w=>w.trim()!=="");if(!l.title.trim()||I.length<1){alert("Заполните название и хотя бы один вариант ответа");return}try{const w={...l,options:I,ownerID:z},P=await m(w,r);y(P),typeof i=="function"&&(P!=null&&P.id)&&i(P.id),d("display")}catch(w){console.error("Ошибка сохранения опроса:",w),alert("Ошибка при сохранении опроса: "+(w.message||w))}},S=h.useCallback(()=>d(I=>I==="creator"?"settings":"creator"),[]),k=h.useCallback(()=>d("creator"),[]),E=h.useCallback(()=>d("creator"),[]),N=()=>"Опрос";return e.jsxs(pe,{style:{position:"relative"},title:N(),onSettingsClick:x==="display"?E:void 0,toggleSettings:x!=="settings"?S:void 0,showMenuDots:x==="creator",onTitleClick:x==="display"?E:void 0,children:[e.jsx("p",{style:{color:"red",textAlign:"center"},children:v?"Сохранение...":u}),e.jsx("div",{style:{position:"relative"},children:e.jsxs("div",{style:{fontSize:"10px",color:"#999",textAlign:"right",padding:"0 15px"},children:["User ID: ",z]})}),x==="creator"&&e.jsx(Be,{onSave:B,onDataChange:c,initialData:l}),x==="settings"&&e.jsx(Ee,{onDataChange:p,initialData:r,toggleSettings:k}),x==="display"&&b&&e.jsxs(e.Fragment,{children:[(b==null?void 0:b.id)&&String(b.owner)===String(z)&&e.jsx("div",{onClick:g,style:{position:"absolute",top:"15px",right:"15px",width:"24px",height:"24px",backgroundColor:"#ff4d4d",color:"white",borderRadius:"50%",display:"flex",alignItems:"center",justifyContent:"center",cursor:"pointer",fontSize:"18px",fontWeight:"bold",zIndex:100,boxShadow:"0 2px 5px rgba(0,0,0,0.2)",lineHeight:"1"},title:"Удалить опрос",children:"×"}),e.jsx(Pe,{pollData:b,setPollData:y})]})]})},Ne=({onSave:o,onDataChange:s,initialData:t})=>{const[n,i]=h.useState((t==null?void 0:t.title)||""),[l,c]=h.useState((t==null?void 0:t.tasks)||[]),[r,p]=h.useState((t==null?void 0:t.activeTaskIndex)||null);h.useEffect(()=>{s({title:n,tasks:l,activeTaskIndex:r})},[n,l,r,s]);const[g,b]=h.useState(!0),y=()=>{const S={id:Date.now(),question:"",type:"text",score:1,correctText:"",options:[""],correctRadioOption:"",correctBoxOptions:[]},k=[...l,S];c(k),p(k.length-1)},x=(S,k)=>{if(r===null)return;const E=[...l];E[r]={...E[r],[S]:k},c(E)},d=(S,k)=>{k.stopPropagation();const E=l.filter((N,I)=>I!==S);c(E),r>=E.length?p(E.length>0?E.length-1:null):S<r&&p(r-1)},m=()=>{r>0&&p(r-1)},v=()=>{r<l.length-1&&p(r+1)},u=(S,k)=>{let E=[...l[r].options];E[S]=k;const I=[...E.filter(w=>w.trim()!==""),""];x("options",I)},f=S=>{x("correctRadioOption",S)},T=(S,k)=>{let E=[];k.includes(S)?E=k.filter(N=>N!==S):E=[...k,S],x("correctBoxOptions",E)},z={display:"flex",gap:"10px",alignItems:"center",whiteSpace:"nowrap"},_={boxSizing:"border-box",padding:"10px",backgroundColor:"#e0e0e0",border:"none",fontSize:"14px",outline:"none",color:"#333",width:"100%",borderRadius:"10px"},B=S=>({padding:"8px",cursor:"pointer",backgroundColor:S?"#00a2ffff":"#e0e0e0",color:S?"#ffffffff":"#333",borderRadius:"10px 10px 0 0",fontSize:"14px",fontWeight:"bold",display:"flex",alignItems:"center",gap:"5px",whiteSpace:"nowrap"});return e.jsxs("div",{style:{display:"flex",flexDirection:"column",height:"100%",width:"100%",overflow:"hidden"},className:"nodrag nowheel",children:[e.jsx("div",{style:{flexShrink:0},children:e.jsx(K,{placeholder:"Название теста",value:n,onChange:S=>i(S.target.value),style:{fontSize:"20px",fontWeight:"bold",borderRadius:"10px"}})}),e.jsxs("div",{style:{display:"flex",borderBottom:"2px solid #333",flexShrink:0},children:[e.jsx(F,{onClick:m,style:{borderRadius:"10px"},children:"←"}),e.jsx("div",{style:{display:"flex",overflowX:"auto"},children:l.map((S,k)=>e.jsxs("div",{style:B(k===r),onClick:()=>p(k),children:["Задание ",k+1,e.jsx("span",{onClick:E=>d(k,E),style:{fontSize:"10px",fontWeight:"bold"},children:"✕"})]},S.id))}),e.jsx(F,{onClick:v,style:{borderRadius:"10px",marginLeft:"auto"},children:"→"})]}),e.jsx("div",{className:"nowheel",onWheel:S=>S.stopPropagation(),style:{padding:"10px",flexGrow:1,minHeight:0,overflowY:"auto",marginBottom:"10px",color:"#333"},children:r!==null&&l[r]?e.jsxs("div",{style:{display:"flex",flexDirection:"column",gap:"10px"},children:[e.jsxs("div",{style:{display:"flex",flex:1,flexDirection:"column",gap:"10px"},children:[e.jsx("label",{style:{fontSize:"18px",fontWeight:"bold"},children:"Вопрос:"}),e.jsx("textarea",{value:l[r].question,onChange:S=>x("question",S.target.value),style:{width:"100%",minHeight:"150px",fontSize:"18px",resize:"vertical",color:"#333",backgroundColor:"#ebebebff"},placeholder:"Введите текст вопроса..."})]}),e.jsxs("div",{onClick:()=>b(!g),style:{cursor:"pointer",fontWeight:"bold",marginBottom:"10px",display:"flex",gap:"5px"},children:[e.jsx("span",{children:"Параметры задания"}),e.jsx("span",{children:g?"▲":"▼"})]}),g&&e.jsxs("div",{style:{display:"flex",flexDirection:"column",gap:"10px",width:"50%"},children:[e.jsxs("div",{style:z,children:[e.jsx("span",{children:"Тип:"}),e.jsxs("select",{value:l[r].type,onChange:S=>x("type",S.target.value),style:_,children:[e.jsx("option",{value:"text",children:"Текст"}),e.jsx("option",{value:"single",children:"Один выбор"}),e.jsx("option",{value:"multiple",children:"Множ. выбор"})]})]}),e.jsxs("div",{style:z,children:[e.jsxs("span",{children:["Баллы: ",l[r].score]}),e.jsx("input",{type:"range",min:"1",max:"50",value:l[r].score,onChange:S=>x("score",S.target.value),style:_})]})]}),l[r].type==="text"&&e.jsx("textarea",{value:l[r].correctText,onChange:S=>x("correctText",S.target.value),style:{width:"100%",minHeight:"80px",fontSize:"18px",resize:"vertical",color:"#333",backgroundColor:"#ebebebff"},placeholder:"Введите правильные варианты с разделением через ENTER"}),l[r].type==="single"&&e.jsx("div",{children:l[r].options.map((S,k)=>e.jsxs("div",{style:{display:"flex",flexDirection:"row",gap:"10px",marginBottom:"5px"},children:[S!==""&&e.jsx(se,{checked:l[r].correctRadioOption===S,onChange:()=>f(S),name:l[r].id}),e.jsx(K,{placeholder:`Вариант ${k+1}`,value:S,onChange:E=>u(k,E.target.value),style:{borderRadius:"15px",marginBottom:"0px"}})]},k))}),l[r].type==="multiple"&&e.jsx("div",{children:l[r].options.map((S,k)=>e.jsxs("div",{style:{display:"flex",flexDirection:"row",gap:"10px",marginBottom:"5px"},children:[S!==""&&e.jsx(Z,{checked:l[r].correctBoxOptions.includes(S),onChange:()=>T(S,l[r].correctBoxOptions)}),e.jsx(K,{placeholder:`Вариант ${k+1}`,value:S,onChange:E=>u(k,E.target.value),style:{borderRadius:"15px",marginBottom:"0px"}})]},k))})]}):e.jsx("div",{style:{color:"#888",textAlign:"center",padding:"20px"},children:'Нет активных заданий. Нажмите "Добавить задание".'})}),e.jsxs("div",{style:{display:"flex",flexDirection:"row",justifyContent:"space-between",flexShrink:0,paddingTop:"10px",borderTop:"1px solid #eee"},children:[e.jsx(F,{onClick:y,style:{borderRadius:"10px"},children:"+ Добавить задание"}),e.jsx(F,{onClick:()=>o(),style:{borderRadius:"10px"},children:"Сохранить тест"})]})]})},Me=({onDataChange:o,initialData:s,toggleSettings:t})=>{const[n,i]=h.useState((s==null?void 0:s.completionTime)||""),[l,c]=h.useState((s==null?void 0:s.endDate)||""),[r,p]=h.useState((s==null?void 0:s.endTime)||""),[g,b]=h.useState((s==null?void 0:s.attemptNumber)||"");h.useEffect(()=>{o({completionTime:n,attemptNumber:g,endDate:l,endTime:r})},[n,g,l,r,o]);const y={boxSizing:"border-box",padding:"12px 16px",backgroundColor:"#e0e0e0",border:"none",fontSize:"16px",color:"#333",outline:"none",fontFamily:"Arial, sans-serif",flex:1,borderRadius:"10px"},x={display:"flex",gap:"10px",alignItems:"center",color:"#333"};return e.jsxs("div",{className:"nodrag",style:{display:"flex",flexDirection:"column",height:"100%",width:"100%",paddingRight:"5px",overflowY:"auto",overflowX:"hidden",boxSizing:"border-box"},children:[e.jsx("h3",{style:{fontSize:"20px",fontWeight:"bold",color:"#000",marginBottom:"25px",flexShrink:0},children:"Параметры теста"}),e.jsxs("div",{style:{display:"flex",flexDirection:"column",gap:"10px"},children:[e.jsxs("div",{style:x,children:[e.jsx("span",{children:"Время (мин):"}),e.jsx("input",{type:"number",value:n,onChange:d=>i(d.target.value),placeholder:"Неограниченно",style:y})]}),e.jsxs("div",{style:x,children:[e.jsx("span",{style:{},children:"Пройти до"}),e.jsx("input",{type:"date",value:l,onChange:d=>c(d.target.value),style:y}),e.jsx("input",{type:"time",value:r,onChange:d=>p(d.target.value),style:y})]}),e.jsxs("div",{style:x,children:[e.jsx("span",{style:{},children:"Кол-во попыток:"}),e.jsx("input",{type:"number",value:g,onChange:d=>b(d.target.value),style:y,placeholder:"Неограниченно"})]})]}),e.jsx("div",{style:{flexShrink:0,display:"flex",justifyContent:"flex-end",marginTop:"auto",paddingTop:"20px"},children:e.jsx(F,{onClick:t,style:{width:"100%",borderRadius:"5px"},children:"Назад к тесту"})})]})},be=o=>{o||(o="https://polls-tests-widgets-backend-1357.loca.lt");const[s,t]=h.useState(!1),[n,i]=h.useState(null),l=x=>`${o?o.replace(/\/$/,""):""}/api/polls/tests${x}`,c=()=>{const x="csrftoken=",d=document.cookie?document.cookie.split(";"):[];for(let m of d)if(m=m.trim(),m.startsWith(x))return decodeURIComponent(m.substring(x.length));return null},r=async(x,d={})=>{const m=await fetch(x,{credentials:"include",...d,headers:{"Content-Type":"application/json","bypass-tunnel-reminder":"true",...d.headers}}),v=await m.json().catch(()=>null);if(!m.ok){const u=new Error((v==null?void 0:v.detail)||m.statusText||"Ошибка сервера");throw u.status=m.status,u.data=v,u}return v},p=h.useCallback(async x=>{t(!0),i(null);try{return await r(l(`/${x}/`))}catch(d){throw i(d.message),d}finally{t(!1)}},[]),g=h.useCallback(async(x,d)=>{t(!0),i(null);try{const m=c();return await r(l(`/${x}/`),{method:"DELETE",headers:{"X-CSRFToken":m},body:JSON.stringify({owner:d})})}catch(m){throw i(m.message),m}finally{t(!1)}},[]),b=h.useCallback(async(x,d)=>{t(!0),i(null);try{let m=null;d.endDate&&(m=new Date(`${d.endDate}T${d.endTime||"23:59:59"}`).toISOString());const v={title:x.title,owner:localStorage.getItem("userId")||"Anonymous",tasks:x.tasks.map(u=>({question:u.question,task_type:u.type,score:u.score,correct_text:u.correctText,options:u.options.filter(f=>f.trim()!=="").map(f=>({text:f,is_correct:u.type==="single"?f===u.correctRadioOption:u.correctBoxOptions.includes(f)}))})),completion_time:d.completionTime===""?null:parseInt(d.completionTime),attempt_number:d.attemptNumber===""?null:parseInt(d.attemptNumber),end_date:m||null};return await r(l("/"),{method:"POST",body:JSON.stringify(v)})}catch(m){throw i(m.message),m}finally{t(!1)}},[]),y=h.useCallback(async x=>{t(!0),i(null);try{return await r(l("/submit/"),{method:"POST",body:JSON.stringify(x)})}catch(d){throw i(d.message),d}finally{t(!1)}},[]);return{loading:s,error:n,createTest:b,fetchTest:p,submitAttempt:y,deleteTest:g}},Oe=({testData:o,setTestData:s})=>{var $,D,re,ne,le,de,ae,R;const t=o==null?void 0:o.id,n=(o==null?void 0:o.title)||"",i=(o==null?void 0:o.tasks)||[];o!=null&&o.settings;const{submitAttempt:l,loading:c,fetchTest:r}=be(),p=localStorage.getItem("userId")||"Anonymous",[g,b]=h.useState(!0),[y,x]=h.useState(!1),[d,m]=h.useState(0),[v,u]=h.useState(null),[f,T]=h.useState([]),z=o==null?void 0:o.all_attempts.filter(C=>C.user===String(p)),_=o.attempt_number-z.length,[B,S]=h.useState(!1),[k,E]=h.useState(null),N=h.useRef(!1),I=()=>{if(!o.end_date)return!1;const C=new Date(o.end_date);return new Date>C},w=I();h.useEffect(()=>{},[]);const P=()=>{if(i&&Array.isArray(i)&&i.length>0){console.log("Инициализация задач в Display:",i);const C=i.map(a=>({id:a.id,question:a.question,type:a.task_type,score:a.score,options:Array.isArray(a.options)?a.options:[],completedText:"",completedRadioOptionId:"",completedBoxOptionIds:[]}));T(C),m(0)}},M=(C,a)=>{T(A=>{const L=[...A];return L[d]&&(L[d]={...L[d],[C]:a}),L})};h.useEffect(()=>{if(g||y||k===null)return;if(k<=0){O();return}const C=setInterval(()=>{E(a=>a-1)},1e3);return()=>clearInterval(C)},[k,g,y]);const U=C=>{const a=Math.floor(C/60),A=C%60;return`${a.toString().padStart(2,"0")}:${A.toString().padStart(2,"0")}`},j=()=>{d>0&&m(d-1)},G=()=>{d<i.length-1&&m(d+1)},W=C=>{const a=f[d];if(!a)return;const A=a.completedBoxOptionIds||[],L=A.includes(C)?A.filter(Ue=>Ue!==C):[...A,C];M("completedBoxOptionIds",L)},O=async()=>{if(N.current)return;N.current=!0;const C={test:t,user:p,answers:f.map(a=>{let A=[];if(a.type==="single"){const L=a.completedRadioOptionId;L&&(A=[L])}else a.type==="multiple"&&(A=a.completedBoxOptionIds);return{task:a.id,answer_text:a.completedText,selected_options:A}})};try{const a=await l(C);a&&(u(a),x(!0),b(!1),r&&s(await r(t)))}catch(a){console.error("Ошибка:",a)}finally{N.current=!1}},V=()=>{if(I()){alert("Время прохождения теста истекло.");return}P(),o.completion_time&&o.completion_time>0?E(o.completion_time*60):E(null),b(!1)},J=()=>{x(!1),b(!0)};return v&&y?e.jsxs("div",{style:{textAlign:"center",padding:"20px",color:"#000"},children:[e.jsx("h3",{style:{color:"#28a745"},children:"Тест завершен!"}),e.jsxs("p",{style:{fontSize:"18px"},children:["Результат: ",e.jsx("b",{children:v.score_obtained})," / ",v.total_score]}),e.jsx(F,{onClick:J,children:"ОК"})]}):!g&&f.length===0?e.jsx("div",{style:{color:"#000",padding:"20px"},children:"Загрузка..."}):e.jsxs("div",{style:{display:"flex",flexDirection:"column",width:"100%",color:"#000"},children:[e.jsxs("div",{style:{display:"flex",justifyContent:"space-between",alignItems:"center",marginBottom:"15px"},children:[e.jsx("h3",{style:{color:"#000",margin:0},children:n}),!g&&!y&&k!==null&&e.jsxs("div",{style:{fontWeight:"bold",fontSize:"18px",color:k<60?"red":"#00a2ff",border:"1px solid #ccc",padding:"5px 10px",borderRadius:"5px"},children:["⏱ ",U(k)]})]}),(o==null?void 0:o.owner)===p&&e.jsxs("div",{children:[e.jsxs("div",{style:{marginBottom:"15px"},children:[e.jsxs("p",{children:["Заданий: ",i.length]}),o.completion_time&&e.jsxs("p",{children:["Время: ",o.completion_time," мин."]}),o.end_date&&e.jsxs("p",{children:["Доступно до: ",new Date(o.end_date).toLocaleDateString()," ",new Date(o.end_date).toLocaleTimeString()]}),e.jsxs("p",{children:["Попыток: ",o.attempt_number]})]}),e.jsxs("div",{onClick:()=>S(C=>!C),style:{cursor:"pointer",fontWeight:"bold",marginBottom:"10px",display:"flex",gap:"5px"},children:[e.jsx("span",{children:"Посмотреть задания"}),e.jsx("span",{children:B?"▲":"▼"})]}),B&&e.jsxs("div",{children:[e.jsxs("div",{style:{display:"flex",borderBottom:"2px solid #333"},children:[e.jsx(F,{onClick:j,style:{borderRadius:"10px"},children:"←"}),e.jsx("div",{style:{display:"flex",overflowX:"auto"},children:i.map((C,a)=>e.jsx("div",{onClick:()=>m(a),style:{padding:"8px 12px",cursor:"pointer",backgroundColor:a===d?"#00a2ff":"#eee",color:a===d?"#fff":"#000",marginRight:"2px",borderRadius:"5px 5px 0 0",minWidth:"25px",textAlign:"center"},children:a+1},a))}),e.jsx(F,{onClick:G,style:{borderRadius:"10px",marginLeft:"auto"},children:"→"})]}),e.jsxs("div",{style:{color:"#000"},children:[e.jsx("p",{style:{fontWeight:"bold"},children:($=i[d])==null?void 0:$.question}),((D=i[d])==null?void 0:D.task_type)==="text"&&e.jsxs("span",{children:["Ответ: ",i[d].correct_text]}),((re=i[d])==null?void 0:re.task_type)==="single"&&i[d].options.map((C,a)=>e.jsxs("div",{style:{display:"flex",alignItems:"center",marginBottom:"15px",cursor:"pointer",gap:"10px"},children:[e.jsx(se,{checked:C.is_correct,onChange:()=>{}}),e.jsx("div",{style:{flexGrow:1,display:"flex",justifyContent:"space-between",backgroundColor:C.is_correct?"#d0d0d0":"#e0e0e0",padding:"12px 16px",borderRadius:"10px",position:"relative",overflow:"hidden"},children:e.jsx("span",{children:C.text})})]},a)),((ne=i[d])==null?void 0:ne.task_type)==="multiple"&&i[d].options.map((C,a)=>e.jsxs("div",{style:{display:"flex",alignItems:"center",marginBottom:"15px",cursor:"pointer",gap:"10px"},children:[e.jsx(Z,{checked:C.is_correct,onChange:()=>{}}),e.jsx("div",{style:{flexGrow:1,display:"flex",justifyContent:"space-between",backgroundColor:C.is_correct?"#d0d0d0":"#e0e0e0",padding:"12px 16px",borderRadius:"10px",position:"relative",overflow:"hidden"},children:e.jsx("span",{children:C.text})})]},a))]})]}),o!=null&&o.all_attempts&&(o==null?void 0:o.all_attempts.length)>0?e.jsxs("div",{style:{marginBottom:"20px",textAlign:"left"},children:[e.jsx("h4",{style:{marginBottom:"10px"},children:"Все результаты:"}),e.jsx("div",{style:{display:"flex",flexDirection:"column",backgroundColor:"#f5f5f5",borderRadius:"10px",padding:"10px",maxHeight:"200px",overflowY:"auto",border:"1px solid #ddd"},children:o==null?void 0:o.all_attempts.map((C,a)=>e.jsxs("div",{style:{display:"flex",justifyContent:"space-between",padding:"10px 5px",borderBottom:a!==(o==null?void 0:o.all_attempts.length)-1?"1px solid #ddd":"none"},children:[e.jsx("span",{style:{fontWeight:"bold",fontSize:"14px"},children:C.user}),e.jsx("span",{style:{fontSize:"14px"},children:new Date(C.completed_at).toLocaleDateString()}),e.jsxs("span",{style:{fontWeight:"bold",fontSize:"14px"},children:[C.score_obtained," / ",C.total_score," баллов"]})]},a))})]}):e.jsx("div",{style:{color:"#888",textAlign:"center",padding:"20px"},children:"Нет результатов"})]}),(o==null?void 0:o.owner)!==p&&e.jsx("div",{children:g?e.jsxs("div",{style:{color:"#000"},children:[e.jsxs("div",{style:{marginBottom:"15px"},children:[e.jsxs("p",{children:["Автор: ",o.owner]}),e.jsxs("p",{children:["Заданий: ",i.length]}),o.completion_time&&e.jsxs("p",{children:["Время: ",o.completion_time," мин."]}),o.end_date&&e.jsxs("p",{children:["Доступно до: ",new Date(o.end_date).toLocaleDateString()," ",new Date(o.end_date).toLocaleTimeString()]}),e.jsxs("p",{children:["Попыток: ",_,"/",o.attempt_number]})]}),w?e.jsx("div",{style:{padding:"10px",backgroundColor:"#ffdddd",color:"red",borderRadius:"10px",textAlign:"center",fontWeight:"bold"},children:"Срок прохождения теста истек"}):e.jsx(F,{onClick:V,style:{borderRadius:"10px"},disabled:_<=0,children:"Начать тест"}),z&&z.length>0?e.jsxs("div",{style:{marginBottom:"20px",textAlign:"left"},children:[e.jsx("h4",{style:{marginBottom:"10px"},children:"Ваши предыдущие результаты:"}),e.jsx("div",{style:{display:"flex",flexDirection:"column",backgroundColor:"#f5f5f5",borderRadius:"10px",padding:"10px",maxHeight:"200px",overflowY:"auto",border:"1px solid #ddd"},children:z.map((C,a)=>e.jsxs("div",{style:{display:"flex",justifyContent:"space-between",padding:"10px 5px",borderBottom:a!==z.length-1?"1px solid #ddd":"none"},children:[e.jsx("span",{style:{fontSize:"14px"},children:new Date(C.completed_at).toLocaleDateString()}),e.jsxs("span",{style:{fontWeight:"bold",fontSize:"14px"},children:[C.score_obtained," / ",C.total_score," баллов"]})]},a))})]}):e.jsx("div",{style:{color:"#888",textAlign:"center",padding:"20px"},children:"Нет результатов"})]}):e.jsxs(e.Fragment,{children:[e.jsxs("div",{style:{display:"flex",borderBottom:"2px solid #333"},children:[e.jsx(F,{onClick:j,style:{borderRadius:"10px"},children:"←"}),e.jsx("div",{style:{display:"flex",overflowX:"auto"},children:f.map((C,a)=>e.jsx("div",{onClick:()=>m(a),style:{padding:"8px 12px",cursor:"pointer",backgroundColor:a===d?"#00a2ff":"#eee",color:a===d?"#fff":"#000",marginRight:"2px",borderRadius:"5px 5px 0 0",minWidth:"25px",textAlign:"center"},children:a+1},a))}),e.jsx(F,{onClick:G,style:{borderRadius:"10px",marginLeft:"auto"},children:"→"})]}),e.jsxs("div",{style:{color:"#000"},children:[e.jsx("p",{style:{fontWeight:"bold"},children:(le=f[d])==null?void 0:le.question}),((de=f[d])==null?void 0:de.type)==="text"&&e.jsx("textarea",{value:f[d].completedText,onChange:C=>M("completedText",C.target.value),style:{width:"100%",height:"80px",padding:"5px"}}),((ae=f[d])==null?void 0:ae.type)==="single"&&f[d].options.map((C,a)=>e.jsxs("div",{style:{display:"flex",alignItems:"center",marginBottom:"15px",cursor:"pointer",gap:"10px"},children:[e.jsx(se,{checked:f[d].completedRadioOptionId===C.id,onChange:()=>M("completedRadioOptionId",C.id)}),e.jsx("div",{onClick:()=>M("completedRadioOptionId",C.id),style:{flexGrow:1,display:"flex",justifyContent:"space-between",backgroundColor:f[d].completedRadioOptionId===C.id?"#d0d0d0":"#e0e0e0",padding:"12px 16px",borderRadius:"10px",position:"relative",overflow:"hidden"},children:e.jsx("span",{children:C.text})})]},a)),((R=f[d])==null?void 0:R.type)==="multiple"&&f[d].options.map((C,a)=>e.jsxs("div",{style:{display:"flex",alignItems:"center",marginBottom:"15px",cursor:"pointer",gap:"10px"},children:[e.jsx(Z,{checked:f[d].completedBoxOptionIds.includes(C.id),onChange:()=>W(C.id)}),e.jsx("div",{onClick:()=>W(C.id),style:{flexGrow:1,display:"flex",justifyContent:"space-between",backgroundColor:f[d].completedBoxOptionIds.includes(C.id)?"#d0d0d0":"#e0e0e0",padding:"12px 16px",borderRadius:"10px",position:"relative",overflow:"hidden"},children:e.jsx("span",{children:C.text})})]},a))]}),e.jsx("div",{style:{marginTop:"20px",display:"flex",justifyContent:"flex-end"},children:d!==f.length-1&&e.jsx(F,{onClick:G,children:"Дальше"})}),e.jsx("div",{style:{marginTop:"20px",display:"flex",justifyContent:"flex-end"},children:d===f.length-1&&e.jsx(F,{onClick:O,disabled:c,children:c?"Сохранение...":"Завершить"})})]})})]})},Le=o=>{const t=`; ${document.cookie}`.split(`; ${o}=`);return t.length===2?t.pop().split(";").shift():null},He=({initialTitle:o,pollId:s,nodeId:t,nodeProps:n,onSaved:i})=>{const{createTest:l,loading:c,error:r,fetchTest:p,deleteTest:g}=be(),[b,y]=h.useState(s?"display":"creator"),[x,d]=h.useState(!1),[m,v]=h.useState(null),[u,f]=h.useState({id:null,owner:"",title:o||"",tasks:[]}),[T,z]=h.useState({completionTime:null,attemptNumber:1,endDate:null,endTime:null}),[_,B]=h.useState(null);h.useEffect(()=>{let w=localStorage.getItem("userId");w||(w=Le("user_id")),w||(w="anon_"+Math.random().toString(36).substring(2,11),localStorage.setItem("userId",w)),v(w)},[]),h.useCallback(w=>{if(!w)return;console.log("Test Widget initialized with:",w);const{widgetId:P,userId:M,role:U,config:j,board:G}=w;P&&(async()=>{try{const O=await p(P);if(!O)return;B(O),f({id:O.id,title:O.title,tasks:O.tasks||[],all_attempts:O.all_attempts,owner:O.owner}),O.settings&&z(O.settings),d(!0)}catch(O){console.error("Ошибка загрузки теста:",O)}})();const W=["admin","editor","owner"].includes(U);y(W?O=>P?"display":"creator":"display")},[p]),h.useEffect(()=>{if(!s)return;let w=!0;return(async()=>{try{const P=await p(s);if(!w||!P)return;B(P),f({id:P.id,title:P.title,tasks:P.tasks||[],all_attempts:P.all_attempts,owner:P.owner}),P.settings&&z(P.settings),d(!0)}catch(P){console.error("Ошибка загрузки теста:",P)}})(),()=>{w=!1}},[s,p]);const S=h.useCallback(()=>y("creator"),[]),k=h.useCallback(()=>{y(w=>w==="settings"?"creator":"settings")},[]),E=async()=>{const w=(u==null?void 0:u.id)||pollId,P=localStorage.getItem("userId")||"Anonymous";if(!w){alert("Ошибка: ID теста не найден");return}if(window.confirm("Вы уверены, что хотите полностью удалить этот тест?"))try{await g(w,P),alert("Тест успешно удален"),setTimeout(()=>{window.location.reload()},100)}catch(M){console.error("Ошибка удаления:",M),M.status===403?alert("У вас нет прав на удаление (вы не автор)."):alert("Не удалось удалить тест: "+M.message)}},N=h.useCallback(async()=>{try{const w=await l(u,T);w&&w.id&&(B(w),d(!0),y("display"),typeof i=="function"&&i(w.id))}catch(w){console.error("Ошибка при сохранении:",w)}},[l,u,T]),I=()=>b==="settings"?"Настройки":u.title||"Тест";return s&&!x?e.jsx(pe,{title:"Загрузка...",children:e.jsx("div",{style:{padding:"20px",textAlign:"center"},children:"Загрузка данных теста..."})}):e.jsxs(pe,{title:I(),toggleSettings:b!=="display"?k:void 0,showMenuDots:b==="creator",children:[c&&e.jsx("p",{style:{color:"blue",textAlign:"center",margin:"5px 0"},children:"Синхронизация..."}),e.jsx("div",{style:{position:"relative"},children:e.jsxs("div",{style:{fontSize:"10px",color:"#999",textAlign:"right",padding:"0 15px"},children:["User ID: ",m]})}),b==="creator"&&e.jsx(Ne,{onDataChange:f,initialData:u,onSave:N}),b==="settings"&&e.jsx(Me,{onDataChange:z,initialData:T,toggleSettings:S}),b==="display"&&x&&e.jsxs("div",{style:{position:"relative",height:"100%",display:"flex",flexDirection:"column"},children:[(u==null?void 0:u.id)&&String(u.owner)===String(m)&&e.jsx("div",{onClick:E,style:{position:"absolute",top:"15px",right:"15px",width:"24px",height:"24px",backgroundColor:"#ff4d4d",color:"white",borderRadius:"50%",display:"flex",alignItems:"center",justifyContent:"center",cursor:"pointer",fontSize:"18px",fontWeight:"bold",zIndex:1e3,boxShadow:"0 2px 5px rgba(0,0,0,0.2)",lineHeight:"1"},title:"Удалить тест",children:"×"}),e.jsx(Oe,{testData:_,setTestData:B})]}),r&&e.jsx("div",{style:{color:"red",fontSize:"12px",padding:"10px",textAlign:"center"},children:r})]})},je={display:"flex",flexDirection:"column",background:"transparent",pointerEvents:"all",position:"relative"},Fe=o=>{const{id:s,data:t,selected:n,xPos:i,yPos:l,dragging:c}=o,[r,p]=h.useState({width:280,height:450}),g=X.useUpdateNodeInternals(),{setNodes:b}=X.useReactFlow(),y=h.useCallback((v,u,f,T)=>{const z=f.offsetWidth,_=f.offsetHeight;p({width:z,height:_}),g(s)},[]),x=h.useCallback(()=>{},[]),d={bottom:"nodrag",right:"nodrag",bottomRight:"nodrag"},m={bottom:{height:10,bottom:-5,cursor:"ns-resize",zIndex:999},right:{width:10,right:-5,cursor:"ew-resize",zIndex:999},bottomRight:{width:20,height:20,right:-5,bottom:-5,cursor:"nwse-resize",zIndex:1e3}};return e.jsxs(ye,{size:r,minWidth:800,minHeight:750,style:je,onResize:x,handleClasses:d,handleStyles:m,onResizeStop:y,enable:{top:!1,right:!0,bottom:!0,left:!1,topRight:!1,bottomRight:!0,bottomLeft:!1,topLeft:!1},onPointerDown:v=>v.stopPropagation(),children:[e.jsx("div",{style:{position:"absolute",top:0,left:0,right:0,bottom:0,overflow:"hidden",outline:n?"2px solid #007bff":"none",borderRadius:"2px",boxShadow:"0 4px 15px rgba(0, 0, 0, 0.1)"},children:e.jsx(Ae,{initialTitle:t.label,pollId:t==null?void 0:t.pollId,nodeId:s,onSaved:v=>{b(u=>u.map(f=>f.id===s?{...f,data:{...f.data,pollId:v}}:f))}})}),e.jsx(X.Handle,{type:"source",position:X.Position.Left}),e.jsx(X.Handle,{type:"target",position:X.Position.Top})]})},Ge={display:"flex",flexDirection:"column",background:"transparent",pointerEvents:"all",position:"relative"},$e=o=>{const{id:s,data:t,selected:n,xPos:i,yPos:l,dragging:c}=o,[r,p]=h.useState({width:280,height:450}),g=X.useUpdateNodeInternals(),{setNodes:b}=X.useReactFlow(),y=u=>{b(f=>f.map(T=>T.id===s?{...T,data:{...T.data,pollId:u}}:T))},x=h.useCallback((u,f,T,z)=>{const _=T.offsetWidth,B=T.offsetHeight;p({width:_,height:B}),g(s)},[]),d=h.useCallback(()=>{},[]),m={bottom:"nodrag",right:"nodrag",bottomRight:"nodrag"},v={bottom:{height:10,bottom:-5,cursor:"ns-resize",zIndex:999},right:{width:10,right:-5,cursor:"ew-resize",zIndex:999},bottomRight:{width:20,height:20,right:-5,bottom:-5,cursor:"nwse-resize",zIndex:1e3}};return e.jsxs(ye,{size:r,minWidth:800,minHeight:750,style:Ge,onResize:d,handleClasses:m,handleStyles:v,onResizeStop:x,enable:{top:!1,right:!0,bottom:!0,left:!1,topRight:!1,bottomRight:!0,bottomLeft:!1,topLeft:!1},onPointerDown:u=>u.stopPropagation(),children:[e.jsx("div",{style:{position:"absolute",top:0,left:0,right:0,bottom:0,overflow:"hidden",outline:n?"2px solid #007bff":"none",borderRadius:"2px",boxShadow:"0 4px 15px rgba(0, 0, 0, 0.1)"},children:e.jsx(He,{nodeId:s,initialTitle:t.label,pollId:t.pollId,nodeProps:o,onSaved:y})}),e.jsx(X.Handle,{type:"source",position:X.Position.Left}),e.jsx(X.Handle,{type:"target",position:X.Position.Top})]})};Y.PollResizable=Fe,Y.TestResizable=$e,Object.defineProperty(Y,Symbol.toStringTag,{value:"Module"})});
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "poll-test-widgets",
3
- "version": "0.0.4",
3
+ "version": "0.0.5",
4
4
  "type": "module",
5
5
  "files": [
6
6
  "dist"