PageSourceSearch

https://m-art.group/assets/Cabinet-DPCF5j4t.js

js m-art.group collected 2026-10-07 18:13:54 UTC 162,206 bytes, 1 lines download raw bytes

1import{d as U,r as l,q as Wa,s as Xe,t as k,v,j as e,F as Ja,e as Ya,S as Za,a as Ga,U as me,B as Os,P as T,D as Re,w as ae,X as Y,n as V,x as Ge,T as Xa,H as ke,k as sa,l as er,b as tr,I as Ht,y as I,z as As,o as Qt,E as sr,p as K}from"./index-DlDapNty.js";import{C as x,P as ar}from"./card-DRnLbOF4.js";import{S as Rt,C as fe,a as Mt}from"./schema-BprDufVf.js";import{F as Bt}from"./file-text-BkcDOLMn.js";import{G as _s,P as aa}from"./paperclip-ILUTml8q.js";import{C as zs}from"./calendar-days-CmyQZ5RH.js";import{T as Ot}from"./trash-2-BrEPwQfw.js";import{C as rr,a as Ks}from"./clipboard-list-BL9HQPc9.js";import{U as At}from"./users-BMbwE39R.js";import{E as Bs}from"./eye-C7uVHGeO.js";import{C as nr}from"./circle-check-BlN9GHOB.js";import{M as Z}from"./message-square-BNa60Dhi.js";import{A as Hs}from"./arrow-left-BGClCGWZ.js";import{S as _t}from"./shield-BJ792BsG.js";import{S as Qs}from"./search-cdgxDkic.js";import{R as Vs}from"./refresh-cw-CDBoYy4u.js";import{P as Ye}from"./package-iwWeRsp7.js";import{S as ir}from"./star-Ch9cRRNv.js";const Ws=U("Archive",[["rect",{width:"20",height:"5",x:"2",y:"3",rx:"1",key:"1wp1u1"}],["path",{d:"M4 8v11a2 2 0 0 0 2 2h12a2 2 0 0 0 2-2V8",key:"1s80jp"}],["path",{d:"M10 12h4",key:"a56b0p"}]]);const Js=U("BellOff",[["path",{d:"M8.7 3A6 6 0 0 1 18 8a21.3 21.3 0 0 0 .6 5",key:"o7mx20"}],["path",{d:"M17 17H3s3-2 3-9a4.67 4.67 0 0 1 .3-1.7",key:"16f1lm"}],["path",{d:"M10.3 21a1.94 1.94 0 0 0 3.4 0",key:"qgo35s"}],["path",{d:"m2 2 20 20",key:"1ooewy"}]]);const Ys=U("Bell",[["path",{d:"M6 8a6 6 0 0 1 12 0c0 7 3 9 3 9H3s3-2 3-9",key:"1qo2s2"}],["path",{d:"M10.3 21a1.94 1.94 0 0 0 3.4 0",key:"qgo35s"}]]);const lr=U("CircleAlert",[["circle",{cx:"12",cy:"12",r:"10",key:"1mglay"}],["line",{x1:"12",x2:"12",y1:"8",y2:"12",key:"1pkeuh"}],["line",{x1:"12",x2:"12.01",y1:"16",y2:"16",key:"4dfq90"}]]);const dr=U("CircleCheckBig",[["path",{d:"M21.801 10A10 10 0 1 1 17 3.335",key:"yps3ct"}],["path",{d:"m9 11 3 3L22 4",key:"1pflzl"}]]);const ra=U("Circle",[["circle",{cx:"12",cy:"12",r:"10",key:"1mglay"}]]);const or=U("Copy",[["rect",{width:"14",height:"14",x:"8",y:"8",rx:"2",ry:"2",key:"17jyea"}],["path",{d:"M4 16c-1.1 0-2-.9-2-2V4c0-1.1.9-2 2-2h10c1.1 0 2 .9 2 2",key:"zix9uf"}]]);const Vt=U("File",[["path",{d:"M15 2H6a2 2 0 0 0-2 2v16a2 2 0 0 0 2 2h12a2 2 0 0 0 2-2V7Z",key:"1rqfz7"}],["path",{d:"M14 2v4a2 2 0 0 0 2 2h4",key:"tnqrlb"}]]);const cr=U("LogOut",[["path",{d:"M9 21H5a2 2 0 0 1-2-2V5a2 2 0 0 1 2-2h4",key:"1uf3rs"}],["polyline",{points:"16 17 21 12 16 7",key:"1gabdz"}],["line",{x1:"21",x2:"9",y1:"12",y2:"12",key:"1uyos4"}]]);const Zs=U("Newspaper",[["path",{d:"M4 22h16a2 2 0 0 0 2-2V4a2 2 0 0 0-2-2H8a2 2 0 0 0-2 2v16a2 2 0 0 1-2 2Zm0 0a2 2 0 0 1-2-2v-9c0-1.1.9-2 2-2h2",key:"7pis2x"}],["path",{d:"M18 14h-8",key:"sponae"}],["path",{d:"M15 18h-5",key:"95g1m2"}],["path",{d:"M10 6h8v4h-8V6Z",key:"smlsk5"}]]);const Ze=U("Pencil",[["path",{d:"M21.174 6.812a1 1 0 0 0-3.986-3.987L3.842 16.174a2 2 0 0 0-.5.83l-1.321 4.352a.5.5 0 0 0 .623.622l4.353-1.32a2 2 0 0 0 .83-.497z",key:"1a8usu"}],["path",{d:"m15 5 4 4",key:"1mk7zo"}]]);const mr=U("Settings",[["path",{d:"M12.22 2h-.44a2 2 0 0 0-2 2v.18a2 2 0 0 1-1 1.73l-.43.25a2 2 0 0 1-2 0l-.15-.08a2 2 0 0 0-2.73.73l-.22.38a2 2 0 0 0 .73 2.73l.15.1a2 2 0 0 1 1 1.72v.51a2 2 0 0 1-1 1.74l-.15.09a2 2 0 0 0-.73 2.73l.22.38a2 2 0 0 0 2.73.73l.15-.08a2 2 0 0 1 2 0l.43.25a2 2 0 0 1 1 1.73V20a2 2 0 0 0 2 2h.44a2 2 0 0 0 2-2v-.18a2 2 0 0 1 1-1.73l.43-.25a2 2 0 0 1 2 0l.15.08a2 2 0 0 0 2.73-.73l.22-.39a2 2 0 0 0-.73-2.73l-.15-.08a2 2 0 0 1-1-1.74v-.5a2 2 0 0 1 1-1.74l.15-.09a2 2 0 0 0 .73-2.73l-.22-.38a2 2 0 0 0-2.73-.73l-.15.08a2 2 0 0 1-2 0l-.43-.25a2 2 0 0 1-1-1.73V4a2 2 0 0 0-2-2z",key:"1qme2f"}],["circle",{cx:"12",cy:"12",r:"3",key:"1v7zrd"}]]);const xr=U("ToggleLeft",[["rect",{width:"20",height:"12",x:"2",y:"6",rx:"6",ry:"6",key:"f2vt7d"}],["circle",{cx:"8",cy:"12",r:"2",key:"1nvbw3"}]]);const ur=U("ToggleRight",[["rect",{width:"20",height:"12",x:"2",y:"6",rx:"6",ry:"6",key:"f2vt7d"}],["circle",{cx:"16",cy:"12",r:"2",key:"4ma0v8"}]]);const re=U("Trash",[["path",{d:"M3 6h18",key:"d0wm0j"}],["path",{d:"M19 6v14c0 1-1 2-2 2H7c-1 0-2-1-2-2V6",key:"4alrt4"}
1],["path",{d:"M8 6V4c0-1 1-2 2-2h4c1 0 2 1 2 2v2",key:"v07s0e"}]]);const hr=U("TriangleAlert",[["path",{d:"m21.73 18-8-14a2 2 0 0 0-3.48 0l-8 14A2 2 0 0 0 4 21h16a2 2 0 0 0 1.73-3",key:"wmoenq"}],["path",{d:"M12 9v4",key:"juzpu7"}],["path",{d:"M12 17h.01",key:"p32p05"}]]);const Gs=U("Upload",[["path",{d:"M21 15v4a2 2 0 0 1-2 2H5a2 2 0 0 1-2-2v-4",key:"ih7n3h"}],["polyline",{points:"17 8 12 3 7 8",key:"t8dd8p"}],["line",{x1:"12",x2:"12",y1:"3",y2:"15",key:"widbto"}]]);const na=U("Video",[["path",{d:"m16 13 5.223 3.482a.5.5 0 0 0 .777-.416V7.87a.5.5 0 0 0-.752-.432L16 10.5",key:"ftymec"}],["rect",{x:"2",y:"6",width:"14",height:"12",rx:"2",key:"158x01"}]]);function pr(o){const p="=".repeat((4-o.length%4)%4),c=(o+p).replace(/-/g,"+").replace(/_/g,"/"),b=atob(c),i=new Uint8Array(b.length);for(let u=0;u<b.length;++u)i[u]=b.charCodeAt(u);return i}function gr(){const[o,p]=l.useState("loading"),[c,b]=l.useState(null),i=l.useCallback(async()=>{if(!("serviceWorker"in navigator)||!("PushManager"in window)){p("unsupported");return}if(Notification.permission==="denied"){p("denied");return}try{const S=await(await navigator.serviceWorker.ready).pushManager.getSubscription();p(S?"subscribed":"unsubscribed")}catch{p("unsubscribed")}},[]);l.useEffect(()=>{i()},[i]);const u=l.useCallback(async()=>{b(null);try{if(!("serviceWorker"in navigator)||!("PushManager"in window))return b("Браузер не поддерживает push-уведомления"),!1;const g=await fetch("/api/push/vapid-key");if(!g.ok)throw new Error("Не удалось получить ключ");const{publicKey:N}=await g.json(),E=(await(await navigator.serviceWorker.ready).pushManager.subscribe({userVisibleOnly:!0,applicationServerKey:pr(N)})).toJSON();if(!(await fetch("/api/push/subscribe",{method:"POST",headers:{"Content-Type":"application/json"},credentials:"include",body:JSON.stringify({endpoint:E.endpoint,keys:E.keys})})).ok)throw new Error("Ошибка сохранения подписки");return p("subscribed"),!0}catch(g){const N=g?.message||"Ошибка подписки";return b(N),await i(),!1}},[i]),P=l.useCallback(async()=>{b(null);try{const N=await(await navigator.serviceWorker.ready).pushManager.getSubscription();if(N){const S=N.endpoint;await N.unsubscribe(),await fetch("/api/push/unsubscribe",{method:"DELETE",headers:{"Content-Type":"application/json"},credentials:"include",body:JSON.stringify({endpoint:S})})}return p("unsubscribed"),!0}catch(g){return b(g?.message||"Ошибка отписки"),!1}},[]);return{state:o,error:c,subscribe:u,unsubscribe:P}}function De(o){return new Date(o).toLocaleDateString("ru-RU",{day:"numeric",month:"long",year:"numeric"})}function Xs(o){return o.toLocaleString("ru-RU")+" ₽"}function br({text:o}){const[p,c]=l.useState(!1),b=()=>{navigator.clipboard.writeText(o),c(!0),setTimeout(()=>c(!1),2e3)};return e.jsxs("button",{onClick:b,className:"inline-flex items-center gap-1 text-xs text-muted-foreground hover:text-foreground transition-colors","data-testid":"button-copy-promo",children:[p?e.jsx(Ge,{className:"h-3 w-3 text-[hsl(var(--accent))]"}):e.jsx(or,{className:"h-3 w-3"}),p?"Скопировано":o]})}const zt={admin:"Администратор",supervisor:"Супервайзер",employee:"Сотрудник",user:"Пользователь",architect:"Архитектор",designer:"Дизайнер интерьеров",complectator:"Комплектатор",decorator:"Декоратор",replanner:"Перепланировщик",inspector:"Приёмщик квартир",engineer:"Инженер-проектировщик",landscape:"Ландшафтный дизайнер",lighting:"Дизайнер освещения",stylist:"Стилист интерьера"},fr={architect:"🏛️",designer:"🎨",complectator:"📦",decorator:"🌿",replanner:"📐",inspector:"🔍",engineer:"⚙️",landscape:"🌳",lighting:"💡",stylist:"✨"};function ea(o){return new Date(o).toLocaleTimeString("ru-RU",{hour:"2-digit",minute:"2-digit"})}function ia(o){const p=new Date(o),c=new Date;return p.toDateString()===c.toDateString()?ea(o):p.toLocaleDateString("ru-RU",{day:"numeric",month:"short"})+" "+ea(o)}function jr({currentStatus:o}){const p=fe.indexOf(o);return e.jsx("div",{className:"space-y-0",children:fe.map((c,b)=>{const i=b<p,u=b===p;return e.jsxs("div",{className:"flex items-start gap-3",children:[e.jsxs("div",{className:"flex flex-col items-center",children:[e.jsx("div",{className:`h-7 w-7 rounded-full flex items-center justify-center flex-shrink-0 transition-all ${i?"bg-[hsl(var(--accent))] text-black":u?"border-2 border-[hsl(var(--accent))] text-[hsl(var(--accent))] bg-[hsl(var(--accent)/0.1)]":"border border-border text-muted-foreground bg-muted/30"}`,children:i?e.jsx(Ge,{className:"h-3.5 w-3.5"}):u?e.jsx(sa,{className:"h-3.5 w-3.5"}):e.jsx(ra,{className:"h-3 w-3"})}),b<fe.length-1&&e.jsx("div",{className:`w-0.5 h-6 mt-0.5 ${i?"bg-[hsl(var(--accent))]":"bg-border"}`})]}),e.jsxs("div",{className:`pb-1 pt-0.5 text-sm font-medium ${u?"text-[hsl(var(--accent))]":i?"text-muted-foreground line-through":"text-muted-foreground"}`,children:[c,u&&e.jsx("span",{className:"ml-2 text-[10px] font-semibold uppercase tracking-wider px-1.5 py-0.5 rounded bg-[hsl(var(--accent)/0.15)] text-[hsl(var(--accent))]",children:"Текущий"})]})]},c)})})}function la({att:o,compact:p=!1}){const c=o.fileType==="photo",b=o.fileType==="video",i=o.fileType==="invoice";return c?e.jsx("a",{href:o.fileUrl,target:"_blank",rel:"noopener noreferrer",className:`block rounded-xl overflow-hidden border border-border ${p?"w-24 h-24":"max-w-xs"}`,children:e.jsx("img",{src:o.fileUrl,alt:o.fileName,className:"w-full h-full object-cover"})}):b?e.jsx("div",{className:`rounded-xl overflow-hidden border border-border ${p?"w-48":"max-w-xs"}`,children:e.jsxs("video",{controls:!0,className:"w-full",preload:"metadata",children:[e.jsx("source",{src:o.fileUrl}),e.jsx("a",{href:o.fileUrl,className:"text-xs text-[hsl(var(--accent))]",children:o.fileName})]})}):e.jsxs("a",{href:o.fileUrl,target:"_blank",rel:"noopener noreferrer",className:"flex items-center gap-2 px-3 py-2 rounded-xl border border-border bg-muted/30 hover:bg-muted/60 transition-colors max-w-xs text-sm",children:[i?e.jsx(Bt,{className:"h-4 w-4 text-[hsl(var(--accent))] flex-shrink-0"}):e.jsx(Vt,{className:"h-4 w-4 text-muted-foreground flex-shrink-0"}),e.jsxs("div",{className:"min-w-0",children:[e.jsx("div",{className:"truncate font-medium",children:o.fileName}),o.fileSize&&e.jsxs("div",{className:"text-xs text-muted-foreground",children:[(o.fileSize/1024).toFixed(0)," KB"]}
1)]}),e.jsx(Re,{className:"h-3.5 w-3.5 text-muted-foreground flex-shrink-0 ml-auto"})]})}function Kt({contractId:o,currentUserId:p,isAdminView:c}){const{toast:b}=Xe(),[i,u]=l.useState(""),[P,g]=l.useState([]),[N,S]=l.useState(!1),[M,E]=l.useState(null),F=l.useRef(null),q=l.useRef(null),{data:D=[],refetch:O}=k({queryKey:["/api/contracts",o,"messages"],queryFn:async()=>{const d=await fetch(`/api/contracts/${o}/messages`,{credentials:"include"});if(!d.ok)throw new Error("Ошибка загрузки сообщений");return d.json()},refetchInterval:3e3});l.useEffect(()=>{q.current?.scrollIntoView({behavior:"smooth"})},[D.length]);const A=async()=>{if(!(!i.trim()&&P.length===0)){S(!0);try{const d=new FormData;i.trim()&&d.append("text",i.trim()),P.forEach(r=>d.append("files",r));const m=await fetch(`/api/contracts/${o}/messages`,{method:"POST",credentials:"include",body:d});if(!m.ok){const r=await m.json().catch(()=>({}));throw new Error(r.error||"Ошибка отправки")}u(""),g([]),await O()}catch(d){b({title:"Ошибка",description:d.message,variant:"destructive"})}finally{S(!1)}}},B=d=>{d.key==="Enter"&&!d.shiftKey&&(d.preventDefault(),A())},G=d=>{d.target.files&&g(Array.from(d.target.files)),d.target.value=""},W=async d=>{if(c){E(d);try{if(!(await fetch(`/api/admin/contracts/${o}/messages/${d}`,{method:"DELETE",credentials:"include"})).ok)throw new Error("Ошибка удаления");await O()}catch(m){b({title:"Ошибка",description:m.message,variant:"destructive"})}finally{E(null)}}},ie=D.reduce((d,m)=>{const r=new Date(m.createdAt).toLocaleDateString("ru-RU",{day:"numeric",month:"long"});return d[r]||(d[r]=[]),d[r].push(m),d},{});return e.jsxs("div",{className:"flex flex-col h-[520px] rounded-2xl border border-border overflow-hidden",children:[e.jsxs("div",{className:"flex-1 overflow-y-auto px-4 py-3 space-y-1 bg-[hsl(var(--background)/0.5)]","data-testid":"chat-messages",children:[D.length===0&&e.jsxs("div",{className:"flex flex-col items-center justify-center h-full text-muted-foreground gap-2",children:[e.jsx(Z,{className:"h-8 w-8 opacity-30"}),e.jsx("p",{className:"text-sm",children:"Сообщений пока нет"}),e.jsx("p",{className:"text-xs",children:"Напишите первое сообщение"})]}),Object.entries(ie).map(([d,m])=>e.jsxs("div",{children:[e.jsx("div",{className:"text-center text-[10px] text-muted-foreground my-3 uppercase tracking-widest",children:d}),m.map(r=>{const h=r.senderId===p,J=r.senderRole==="admin";return e.jsxs("div",{className:`group flex mb-2 items-end gap-1.5 ${h?"justify-end":"justify-start"}`,"data-testid":`msg-${r.id}`,children:[c&&h&&e.jsx("button",{onClick:()=>W(r.id),disabled:M===r.id,className:"opacity-0 group-hover:opacity-100 h-5 w-5 flex items-center justify-center rounded text-muted-foreground hover:text-red-400 transition-all",title:"Удалить сообщение","data-testid":`button-delete-contractmsg-${r.id}`,children:M===r.id?e.jsx(V,{className:"h-3 w-3 animate-spin"}):e.jsx(re,{className:"h-3 w-3"})}),e.jsxs("div",{className:`max-w-[75%] ${h?"items-end":"items-start"} flex flex-col gap-1`,children:[!h&&e.jsx("span",{className:"text-[10px] text-muted-foreground px-1 font-medium",children:J?"М-АРТ":r.senderName||"Клиент"}),r.text&&e.jsx("div",{className:`px-4 py-2.5 rounded-2xl text-sm leading-relaxed ${h?"bg-[hsl(var(--accent))] text-black rounded-br-sm":"bg-muted/60 text-foreground rounded-bl-sm border border-border"}`,children:r.text}),(r.attachments||[]).map(_=>e.jsx(la,{att:_},_.id)),e.jsx("span",{className:"text-[10px] text-muted-foreground px-1",children:ia(r.createdAt)})]}),c&&!h&&e.jsx("button",{onClick:()=>W(r.id),disabled:M===r.id,className:"opacity-0 group-hover:opacity-100 h-5 w-5 flex items-center justify-center rounded text-muted-foreground hover:text-red-400 transition-all",title:"Удалить сообщение","data-testid":`button-delete-contractmsg-${r.id}`,children:M===r.id?e.jsx(V,{className:"h-3 w-3 animate-spin"}):e.jsx(re,{className:"h-3 w-3"})})]},r.id)})]},d)),e.jsx("div",{ref:q})]}),P.length>0&&e.jsx("div",{className:"px-4 py-2 border-t border-border bg-muted/20 flex flex-wrap gap-2",children:P.map((d,m)=>e.jsxs("div",{className:"flex items-center gap-1.5 px-2 py-1 rounded-lg bg-muted text-xs",children:[d.type.startsWith("image/")?e.jsx(Ht,{className:"h-3 w-3"}):d.type.startsWith("video/")?e.jsx(na,{className:"h-3 w-3"}):e.jsx(Vt,{className:"h-3 w-3"}),e.jsx("span",{className:"max-w-[120px] truncate",children:d.name}),e.jsx("button",{onClick:()=>g(P.filter((r,h)=>h!==m)),className:"text-muted-foreground hover:text-foreground",children:e.jsx(Y,{className:"h-3 w-3"})})]},m))}),e.jsxs("div",{className:"border-t border-border bg-background px-3 py-3 flex items-end gap-2",children:[e.jsx("input",{type:"file",ref:F,onChange:G,multiple:!0,accept:"image/*,video/*,.pdf,.xlsx,.xls,.doc,.docx",className:"hidden"}),e.jsx("button",{onClick:()=>F.current?.click(),className:"h-9 w-9 flex-shrink-0 rounded-xl border border-border hover:bg-muted transition-colors flex items-center justify-center",title:"Прикрепить файл","data-testid":"button-attach-file",children:e.jsx(aa,{className:"h-4 w-4 text-muted-foreground"})}),e.jsx("textarea",{value:i,onChange:d=>u(d.target.value),onKeyDown:B,placeholder:c?"Написать клиенту...":"Написать в М-АРТ...",rows:1,className:"flex-1 resize-none px-3 py-2 rounded-xl border border-border bg-background text-sm focus:outline-none focus:ring-1 focus:ring-[hsl(var(--accent))] placeholder:text-muted-foreground
1/50 min-h-[36px] max-h-[120px]",style:{height:"auto"},onInput:d=>{const m=d.target;m.style.height="auto",m.style.height=Math.min(m.scrollHeight,120)+"px"},"data-testid":"input-chat-message"}),e.jsx("button",{onClick:A,disabled:N||!i.trim()&&P.length===0,className:"h-9 w-9 flex-shrink-0 rounded-xl bg-[hsl(var(--accent))] text-black hover:opacity-90 transition-all flex items-center justify-center disabled:opacity-40","data-testid":"button-send-message",children:N?e.jsx(V,{className:"h-4 w-4 animate-spin"}):e.jsx(Qt,{className:"h-4 w-4"})})]})]})}function ta({onSubmit:o,onCancel:p,loading:c,showRoleSelect:b,showOrgFields:i}){const[u,P]=l.useState(""),[g,N]=l.useState(""),[S,M]=l.useState(""),[E,F]=l.useState(""),[q,D]=l.useState(""),[O,A]=l.useState("supervisor"),[B,G]=l.useState(""),[W,ie]=l.useState(""),d=m=>{m.preventDefault(),o({email:u,password:g,firstName:S,lastName:E||void 0,phone:q||void 0,role:b?O:"employee",organizationName:B||void 0,promoCode:W||void 0})};return e.jsxs(x,{className:"p-5 border-[hsl(var(--accent)/0.2)]",children:[e.jsxs("div",{className:"flex items-center justify-between mb-4",children:[e.jsx("h3",{className:"font-semibold text-sm",children:b?"Создать учётную запись":"Добавить сотрудника"}),e.jsx("button",{onClick:p,className:"h-7 w-7 rounded-full border border-border grid place-items-center hover:bg-muted transition-colors","data-testid":"button-cancel-create",children:e.jsx(Y,{className:"h-3.5 w-3.5"})})]}),e.jsxs("form",{onSubmit:d,className:"space-y-3",children:[e.jsxs("div",{className:"grid grid-cols-1 sm:grid-cols-2 gap-3",children:[e.jsxs("div",{children:[e.jsx("label",{className:"text-xs text-muted-foreground mb-1 block",children:"Email *"}),e.jsx("input",{type:"email",value:u,onChange:m=>P(m.target.value),required:!0,placeholder:"[email protected]",className:"w-full px-3 py-2 rounded-xl border border-border bg-background text-sm focus:outline-none focus:ring-1 focus:ring-[hsl(var(--accent))] placeholder:text-muted-foreground/50","data-testid":"input-create-email"})]}),e.jsxs("div",{children:[e.jsx("label",{className:"text-xs text-muted-foreground mb-1 block",children:"Пароль *"}),e.jsx("input",{type:"password",value:g,onChange:m=>N(m.target.value),required:!0,minLength:6,placeholder:"Минимум 6 символов",className:"w-full px-3 py-2 rounded-xl border border-border bg-background text-sm focus:outline-none focus:ring-1 focus:ring-[hsl(var(--accent))] placeholder:text-muted-foreground/50","data-testid":"input-create-password"})]}),e.jsxs("div",{children:[e.jsx("label",{className:"text-xs text-muted-foreground mb-1 block",children:"Имя *"}),e.jsx("input",{type:"text",value:S,onChange:m=>M(m.target.value),required:!0,placeholder:"Имя",className:"w-full px-3 py-2 rounded-xl border border-border bg-background text-sm focus:outline-none focus:ring-1 focus:ring-[hsl(var(--accent))] placeholder:text-muted-foreground/50","data-testid":"input-create-firstName"})]}),e.jsxs("div",{children:[e.jsx("label",{className:"text-xs text-muted-foreground mb-1 block",children:"Фамилия"}),e.jsx("input",{type:"text",value:E,onChange:m=>F(m.target.value),placeholder:"Фамилия",className:"w-full px-3 py-2 rounded-xl border border-border bg-background text-sm focus:outline-none focus:ring-1 focus:ring-[hsl(var(--accent))] placeholder:text-muted-foreground/50","data-testid":"input-create-lastName"})]}),e.jsxs("div",{children:[e.jsx("label",{className:"text-xs text-muted-foreground mb-1 block",children:"Телефон"}),e.jsx("input",{type:"tel",value:q,onChange:m=>D(m.target.value),placeholder:"+7 999 123-45-67",className:"w-full px-3 py-2 rounded-xl border border-border bg-background text-sm focus:outline-none focus:ring-1 focus:ring-[hsl(var(--accent))] placeholder:text-muted-foreground/50","data-testid":"input-create-phone"})]}),b&&e.jsxs("div",{children:[e.jsx("label",{className:"text-xs text-muted-foreground mb-1 block",children:"Роль *"}),e.jsxs("select",{value:O,onChange:m=>A(m.target.value),className:"w-full px-3 py-2 rounded-xl border border-border bg-background text-sm focus:outline-none focus:ring-1 focus:ring-[hsl(var(--accent))]","data-testid":"select-create-role",children:[e.jsx("option",{value:"admin",children:"Администратор"}),e.jsx("option",{value:"supervisor",children:"Супервайзер"}),e.jsx("option",{value:"employee",children:"Сотрудник"}),e.jsx("option",{value:"user",children:"Пользователь"})]})]})]}),(i||O==="supervisor")&&e.jsxs("div",{className:"grid grid-cols-1 sm:grid-cols-2 gap-3 pt-1",children:[e.jsxs("div",{children:[e.jsx("label",{className:"text-xs text-muted-foreground mb-1 block",children:"Организация"}),e.jsx("input",{type:"text",value:B,onChange:m=>
1G(m.target.value),placeholder:"Название компании",className:"w-full px-3 py-2 rounded-xl border border-border bg-background text-sm focus:outline-none focus:ring-1 focus:ring-[hsl(var(--accent))] placeholder:text-muted-foreground/50","data-testid":"input-create-org"})]}),e.jsxs("div",{children:[e.jsx("label",{className:"text-xs text-muted-foreground mb-1 block",children:"Промокод"}),e.jsx("input",{type:"text",value:W,onChange:m=>ie(m.target.value.toUpperCase()),placeholder:"ETAZHI",className:"w-full px-3 py-2 rounded-xl border border-border bg-background text-sm focus:outline-none focus:ring-1 focus:ring-[hsl(var(--accent))] placeholder:text-muted-foreground/50 uppercase","data-testid":"input-create-promo"})]})]}),e.jsxs(T,{type:"submit",variant:"primary",size:"sm",onClick:()=>{},disabled:c,"data-testid":"button-submit-create",children:[c?e.jsx(V,{className:"h-4 w-4 animate-spin"}):e.jsx(ae,{className:"h-4 w-4"}),b?"Создать":"Добавить сотрудника"]})]})]})}function vr({chatId:o,currentUserId:p,apiPrefix:c,isAdmin:b}){const{toast:i}=Xe(),[u,P]=l.useState(""),[g,N]=l.useState([]),[S,M]=l.useState(!1),[E,F]=l.useState(null),q=l.useRef(null),D=l.useRef(null),O=c==="admin"?`/api/admin/work-chats/${o}/messages`:`/api/my-work-chats/${o}/messages`,{data:A=[],refetch:B}=k({queryKey:[O],queryFn:async()=>{const d=await fetch(O,{credentials:"include"});if(!d.ok)throw new Error("Ошибка загрузки");return d.json()},refetchInterval:3e3});l.useEffect(()=>{D.current?.scrollIntoView({behavior:"smooth"})},[A.length]);const G=async()=>{if(!(!u.trim()&&g.length===0)){M(!0);try{const d=new FormData;u.trim()&&d.append("text",u.trim()),g.forEach(r=>d.append("files",r));const m=await fetch(O,{method:"POST",credentials:"include",body:d});if(!m.ok){const r=await m.json().catch(()=>({}));throw new Error(r.error||"Ошибка")}P(""),N([]),await B()}catch(d){i({title:"Ошибка",description:d.message,variant:"destructive"})}finally{M(!1)}}},W=async d=>{if(b){F(d);try{const m=`/api/admin/work-chats/${o}/messages/${d}`;if(!(await fetch(m,{method:"DELETE",credentials:"include"})).ok)throw new Error("Ошибка удаления");await B()}catch(m){i({title:"Ошибка",description:m.message,variant:"destructive"})}finally{F(null)}}},ie=A.reduce((d,m)=>{const r=new Date(m.createdAt).toLocaleDateString("ru-RU",{day:"numeric",month:"long"});return d[r]||(d[r]=[]),d[r].push(m),d},{});return e.jsxs("div",{className:"flex flex-col h-full",children:[e.jsxs("div",{className:"flex-1 overflow-y-auto px-4 py-3 space-y-1 bg-[hsl(var(--background)/0.5)]","data-testid":"work-chat-messages",children:[A.length===0&&e.jsxs("div",{className:"flex flex-col items-center justify-center h-full text-muted-foreground gap-2",children:[e.jsx(Z,{className:"h-8 w-8 opacity-30"}),e.jsx("p",{className:"text-sm",children:"Сообщений пока нет"})]}),Object.entries(ie).map(([d,m])=>e.jsxs("div",{children:[e.jsx("div",{className:"text-center text-[10px] text-muted-foreground my-3 uppercase tracking-widest",children:d}),m.map(r=>{const h=r.senderId===p,J=r.senderRole==="admin";return e.jsxs("div",{className:`group flex mb-2 items-end gap-1.5 ${h?"justify-end":"justify-start"}`,"data-testid":`work-msg-${r.id}`,children:[b&&h&&e.jsx("button",{onClick:()=>W(r.id),disabled:E===r.id,className:"opacity-0 group-hover:opacity-100 h-5 w-5 flex items-center justify-center rounded text-muted-foreground hover:text-red-400 transition-all",title:"Удалить сообщение","data-testid":`button-delete-workmsg-${r.id}`,children:E===r.id?e.jsx(V,{className:"h-3 w-3 animate-spin"}):e.jsx(re,{className:"h-3 w-3"})}),e.jsxs("div",{className:`max-w-[75%] ${h?"items-end":"items-start"} flex flex-col gap-1`,children:[!h&&e.jsx("span",{className:"text-[10px] text-muted-foreground px-1 font-medium",children:J?"М-АРТ":r.senderName||"Пользователь"}),r.text&&e.jsx("div",{className:`px-4 py-2.5 rounded-2xl text-sm leading-relaxed ${h?"bg-[hsl(var(--accent))] text-black rounded-br-sm":"bg-muted/60 text-foreground rounded-bl-sm border border-border"}`,children:r.text}),(r.attachments||[]).map(_=>e.jsx(la,{att:_},_.id)),e.jsx("span",{className:"text-[10px] text-muted-foreground px-1",children:ia(r.createdAt)})]}),b&&!h&&e.jsx("button",{onClick:()=>W(r.id),disabled:E===r.id,className:"opacity-0 group-hover:opacity-100 h-5 w-5 flex items-center justify-center rounded text-muted-foreground hover:text-red-400 transition-all",title:"Удалить сообщение","data-testid":`button-delete-workmsg-${r.id}`,children:E===r.id?e.jsx(V,{className:"h-3 w-3 animate-spin"}):e.jsx(re,{className:"h-3 w-3"})})]},r.id)})]},d)),e.jsx("div",{ref:D})]}),g.length>0&&e.jsx("div",{className:"px-4 py-2 border-t border-border bg-muted/20 flex flex-wrap gap-2",children:g.map((d,m)=>e.jsxs("div",{className:"flex items-center gap-1.5 px-2 py-1 rounded-lg bg-muted text-xs",children:[d.type.startsWith("image/")?e.jsx(Ht,{className:"h-3 w-3"}):d.type.startsWith("video/")?e.jsx(na,{className:"h-3 w-3"}):e.jsx(Vt,{className:"h-3 w-3"}),e.jsx("span",{className:"max-w-[120px] truncate",children:d.name}),e.jsx("button",{onClick:()=>N(g.filter((r,h)=>h!==m)),className:"text-muted-foreground hover:text-foreground",children:e.jsx(Y,{className:"h-3 w-3"})})]},m))}),e.jsxs("div",{className:"border-t border-border bg-background px-3 py-3 flex items-end gap-2",children:[e.jsx("input",{type:"file",ref:q,onChange:d=>{d.target.files&&N(m=>[...m,...Array.from(d.target.files)]),d.target.value=""},multiple:!0,accept:"image/*,video/*,.pdf,.xlsx,.xls,.doc,.docx",className:"hidden"}),e.jsx("button",{onClick:()=>q.current?.click(),className:"h-9 w-9 flex-shrink-0 rounded-xl border border-border hover:bg-muted transition-colors flex items-center justify-center",title:"Прикрепить файл","data-testid":"button-work-chat-attach",children:e.jsx(aa,{className:"h-4 w-4 text-muted-foreground"})}),e.jsx("textarea",{value:u,onChange:d=>P(d.target.value),onKeyDown:d=>
1{d.key==="Enter"&&!d.shiftKey&&(d.preventDefault(),G())},placeholder:"Написать сообщение...",rows:1,className:"flex-1 resize-none min-h-[36px] max-h-[120px] rounded-xl border border-border bg-muted/30 px-3 py-2 text-sm focus:outline-none focus:ring-1 focus:ring-[hsl(var(--accent))] placeholder:text-muted-foreground/50","data-testid":"input-work-chat-message"}),e.jsx("button",{onClick:G,disabled:S||!u.trim()&&g.length===0,className:"h-9 w-9 flex-shrink-0 rounded-xl bg-[hsl(var(--accent))] hover:bg-[hsl(var(--accent)/0.85)] disabled:opacity-40 transition-colors flex items-center justify-center","data-testid":"button-work-chat-send",children:S?e.jsx(V,{className:"h-4 w-4 animate-spin text-black"}):e.jsx(Qt,{className:"h-4 w-4 text-black"})})]})]})}function Nr({currentUserId:o}){const{toast:p}=Xe(),[c,b]=l.useState(null),[i,u]=l.useState(!1),[P,g]=l.useState(!1),[N,S]=l.useState(""),[M,E]=l.useState(""),{data:F=[],refetch:q}=k({queryKey:["/api/admin/work-chats"],queryFn:async()=>{const r=await fetch("/api/admin/work-chats",{credentials:"include"});if(!r.ok)throw new Error("Ошибка");return r.json()},refetchInterval:5e3}),{data:D=[]}=k({queryKey:["/api/admin/users"],queryFn:async()=>{const r=await fetch("/api/admin/users",{credentials:"include"});if(!r.ok)throw new Error("Ошибка");return r.json()},enabled:i||P}),A=F.find(r=>r.id===c)?.participants||[],B=D.filter(r=>F.map(_=>_.userId).includes(r.id)?!1:`${r.firstName||""} ${r.lastName||""} ${r.email||""}`.toLowerCase().includes(N.toLowerCase())),G=D.filter(r=>A.some(J=>J.userId===r.id)?!1:`${r.firstName||""} ${r.lastName||""} ${r.email||""}`.toLowerCase().includes(M.toLowerCase())),W=async r=>{try{const h=await fetch("/api/admin/work-chats",{method:"POST",credentials:"include",headers:{"Content-Type":"application/json"},body:JSON.stringify({userId:r})});if(!h.ok)throw new Error("Ошибка создания чата");const J=await h.json();await q(),b(J.id),u(!1),S("")}catch(h){p({title:"Ошибка",description:h.message,variant:"destructive"})}},ie=async r=>{if(c)try{if(!(await fetch(`/api/admin/work-chats/${c}/participants`,{method:"POST",credentials:"include",headers:{"Content-Type":"application/json"},body:JSON.stringify({userId:r})})).ok)throw new Error("Ошибка");await q(),g(!1),E(""),p({title:"Участник добавлен"})}catch(h){p({title:"Ошибка",description:h.message,variant:"destructive"})}},d=async r=>{if(c)try{if(!(await fetch(`/api/admin/work-chats/${c}/participants/${r}`,{method:"DELETE",credentials:"include"})).ok)throw new Error("Ошибка");await q(),p({title:"Участник удалён"})}catch(h){p({title:"Ошибка",description:h.message,variant:"destructive"})}},m=async r=>{try{if(!(await fetch(`/api/admin/work-chats/${r}`,{method:"DELETE",credentials:"include"})).ok)throw new Error("Ошибка");await q(),c===r&&b(null),p({title:"Чат удалён"})}catch(h){p({title:"Ошибка",description:h.message,variant:"destructive"})}};return e.jsxs("section",{"data-testid":"section-work-chats",children:[e.jsxs("div",{className:"flex items-center justify-between mb-4",children:[e.jsx("h2",{className:"text-lg font-semibold",children:"Рабочие чаты"}),e.jsxs("button",{onClick:()=>{u(!0),S(""),g(!1)},className:"flex items-center gap-2 px-3 py-1.5 rounded-xl border border-[hsl(var(--accent)/0.4)] text-[hsl(var(--accent))] text-sm hover:bg-[hsl(var(--accent)/0.08)] transition-colors","data-testid":"button-add-work-chat",children:[e.jsx(ae,{className:"h-4 w-4"}),"Новый чат"]})]}),i&&e.jsxs(x,{className:"p-4 mb-4 border-[hsl(var(--accent)/0.2)]",children:[e.jsxs("div",{className:"flex items-center justify-between mb-3",children:[e.jsx("h3",{className:"text-sm font-semibold",children:"Создать чат с пользователем"}),e.jsx("button",{onClick:()=>u(!1),className:"h-7 w-7 rounded-full border border-border grid place-items-center hover:bg-muted transition-colors",children:e.jsx(Y,{className:"h-3.5 w-3.5"})})]}),e.jsx("input",{type:"text",value:N,onChange:r=>S(r.target.value),placeholder:"Поиск по имени или email...",className:"w-full px-3 py-2 rounded-xl border border-border bg-background text-sm focus:outline-none focus:ring-1 focus:ring-[hsl(var(--accent))] mb-3","data-testid":"input-user-search"}),e.jsx("div",{className:"max-h-48 overflow-y-auto space-y-1",children:B.length===0?e.jsx("p",{className:"text-sm text-muted-foreground text-center py-4",children:D.length===0?"Загрузка...":"Нет доступных пользователей"}):B.map(r=>e.jsxs("button",{onClick:()=>W(r.id),className:"w-full flex items-center gap-3 px-3 py-2 rounded-xl hover:bg-muted/60 transition-colors text-left","data-testid":`button-select-user-${r.id}`,children:[e.jsx("div",{className:"h-8 w-8 rounded-full bg-muted border border-border grid place-items-center flex-shrink-0",children:e.jsx(me,{className:"h-4 w-4 text-muted-foreground"})}),e.jsxs("div",{className:"min-w-0",children:[e.jsx("div",{className:"text-sm font-medium truncate",children:[r.firstName,r.lastName].filter(
1Boolean).join(" ")||r.email}),e.jsx("div",{className:"text-xs text-muted-foreground truncate",children:r.email})]}),e.jsx(Z,{className:"h-4 w-4 text-muted-foreground flex-shrink-0 ml-auto"})]},r.id))})]}),e.jsxs("div",{className:"grid grid-cols-1 lg:grid-cols-[280px_1fr] gap-4",children:[e.jsx("div",{className:"space-y-1",children:F.length===0?e.jsxs(x,{className:"p-6 text-center",children:[e.jsx(Z,{className:"h-8 w-8 mx-auto text-muted-foreground mb-2 opacity-40"}),e.jsx("p",{className:"text-sm text-muted-foreground",children:"Нет активных чатов"}),e.jsx("p",{className:"text-xs text-muted-foreground mt-1",children:"Нажмите «Новый чат»"})]}):F.map(r=>{const h=r.participants||[],J=h.map(_=>_.userName||_.userEmail||"Участник").join(", ");return e.jsxs("div",{className:`group flex items-center gap-3 px-3 py-3 rounded-xl border cursor-pointer transition-colors ${c===r.id?"border-[hsl(var(--accent)/0.5)] bg-[hsl(var(--accent)/0.06)]":"border-border hover:bg-muted/40"}`,onClick:()=>{b(r.id),g(!1)},"data-testid":`work-chat-item-${r.id}`,children:[e.jsx("div",{className:"relative h-9 w-9 flex-shrink-0",children:h.length>1?e.jsxs(e.Fragment,{children:[e.jsx("div",{className:"absolute top-0 left-0 h-6 w-6 rounded-full bg-muted border border-border grid place-items-center",children:e.jsx(me,{className:"h-3 w-3 text-muted-foreground"})}),e.jsx("div",{className:"absolute bottom-0 right-0 h-5 w-5 rounded-full bg-[hsl(var(--accent)/0.2)] border border-border flex items-center justify-center",children:e.jsxs("span",{className:"text-[8px] font-bold text-[hsl(var(--accent))]",children:["+",h.length-1]})})]}):e.jsx("div",{className:"h-9 w-9 rounded-full bg-muted border border-border grid place-items-center",children:e.jsx(me,{className:"h-4 w-4 text-muted-foreground"})})}),e.jsxs("div",{className:"min-w-0 flex-1",children:[e.jsx("div",{className:"text-sm font-medium truncate",children:J||r.userName||r.userEmail||"Пользователь"}),r.lastMessage?e.jsx("div",{className:"text-xs text-muted-foreground truncate",children:r.lastMessage}):e.jsx("div",{className:"text-xs text-muted-foreground/50 italic",children:"Нет сообщений"})]}),e.jsx("button",{onClick:_=>{_.stopPropagation(),m(r.id)},className:"opacity-0 group-hover:opacity-100 h-6 w-6 rounded-lg border border-border grid place-items-center text-muted-foreground hover:text-red-400 hover:border-red-400/50 transition-all","data-testid":`button-delete-work-chat-${r.id}`,title:"Удалить чат",children:e.jsx(re,{className:"h-3 w-3"})})]},r.id)})}),e.jsx("div",{className:"rounded-2xl border border-border overflow-hidden",style:{minHeight:"480px"},children:c?e.jsxs("div",{className:"flex flex-col h-full",style:{height:"520px"},children:[e.jsxs("div",{className:"px-4 py-3 border-b border-border bg-muted/20",children:[e.jsx("div",{className:"flex items-start justify-between gap-3",children:e.jsx("div",{className:"min-w-0 flex-1",children:e.jsxs("div",{className:"flex items-center gap-2 flex-wrap",children:[A.length===0?e.jsx("span",{className:"text-sm font-medium text-muted-foreground",children:"Нет участников"}):A.map((r,h)=>e.jsxs("div",{className:"flex items-center gap-1 bg-muted/60 rounded-full px-2 py-0.5 border border-border","data-testid":`participant-chip-${r.userId}`,children:[e.jsx(me,{className:"h-3 w-3 text-muted-foreground"}),e.jsx("span",{className:"text-xs font-medium",children:r.userName||r.userEmail||"Участник"}),e.jsx("button",{onClick:()=>d(r.userId),className:"h-3.5 w-3.5 rounded-full text-muted-foreground hover:text-red-400 transition-colors ml-0.5",title:"Удалить из чата","data-testid":`button-remove-participant-${r.userId}`,children:e.jsx(Y,{className:"h-3 w-3"})})]},r.userId)),e.jsxs("button",{onClick:()=>{g(!P),E("")},className:"flex items-center gap-1 px-2 py-0.5 rounded-full border border-dashed border-[hsl(var(--accent)/0.5)] text-[hsl(var(--accent))] text-xs hover:bg-[hsl(var(--accent)/0.1)] transition-colors","data-testid":"button-add-participant",children:[e.jsx(ae,{className:"h-3 w-3"}),"Добавить"]})]})})}),P&&e.jsxs("div",{className:"mt-3 p-3 rounded-xl border border-[hsl(var(--accent)/0.2)] bg-background",children:[e.jsx("input",{type:"text",value:M,onChange:r=>E(r.target.value),placeholder:"Поиск пользователя...",className:"w-full px-3 py-1.5 rounded-lg border border-border bg-muted/40 text-sm focus:outline-none focus:ring-1 focus:ring-[hsl(var(--accent))] mb-2",autoFocus:!0,"data-testid":"input-participant-search"}),e.jsx("div",{className:"max-h-36 overflow-y-auto space-y-0.5",children:G.length===0?e.jsx("p",{className:"text-xs text-muted-foreground text-center py-2",children:"Нет пользователей для добавления"}):G.map(r=>e.jsxs("button",{onClick:()=>ie(r.id),className:"w-full flex items-center gap-2 px-2 py-1.5 rounded-lg hover:bg-muted/60 transition-colors text-left","data-testid":`button-add-participant-user-${r.id}`,children:[e.jsx(me,{className:"h-3.5 w-3.5 text-muted-foreground flex-shrink-0"}),e.jsxs("div",{className:"min-w-0",children:[e.jsx("div",{className:"text-xs font-medium truncate",children:[r.firstName,r.lastName].filter(
1Boolean).join(" ")||r.email}),e.jsx("div",{className:"text-[10px] text-muted-foreground truncate",children:r.email})]})]},r.id))})]})]}),e.jsx(vr,{chatId:c,currentUserId:o,apiPrefix:"admin",isAdmin:!0})]}):e.jsxs("div",{className:"h-full flex flex-col items-center justify-center text-muted-foreground gap-3 py-20",children:[e.jsx(Z,{className:"h-10 w-10 opacity-20"}),e.jsx("p",{className:"text-sm",children:"Выберите чат или создайте новый"})]})})]})]})}function zr(){const{user:o,isLoading:p,isAuthenticated:c,logout:b}=Wa(),{toast:i}=Xe(),[u,P]=l.useState("estimates"),[g,N]=l.useState(!1),[S,M]=l.useState(""),[E,F]=l.useState(null),[q,D]=l.useState(!1),[O,A]=l.useState(""),[B,G]=l.useState(""),[W,ie]=l.useState(""),[d,m]=l.useState(!1),[r,h]=l.useState(""),[J,_]=l.useState(null),Ce={partnerName:"",title:"",description:"",discountPercent:"",promoCode:"",coverUrl:"",validUntil:""},[da,Me]=l.useState(!1),[Se,Oe]=l.useState(null),[X,ee]=l.useState(Ce),j=o?.role==="admin",te=o?.role==="supervisor",H=Rt.includes(o?.role),$=gr(),[Wt,Ee]=l.useState(!1),[ne,$e]=l.useState(null),[L,Q]=l.useState({userId:"",profession:"architect",bio:"",website:"",phone:"",contactEmail:"",experienceYears:"0",isFeatured:!1,specializations:"",firstName:"",lastName:"",portraitUrl:""}),[Jt,je]=l.useState([]),[he,ve]=l.useState(null),[Yt,et]=l.useState(null),[pe,tt]=l.useState("new"),[le,ge]=l.useState({email:"",password:"",firstName:"",lastName:""}),[Zt,st]=l.useState(null),[xe,Pe]=l.useState(null),[Ie,Ue]=l.useState(""),[de,Gt]=l.useState(null),[Ae,Xt]=l.useState(""),[at,oa]=l.useState("products"),[_e,ca]=l.useState("all"),[ze,ma]=l.useState("all"),[Ke,xa]=l.useState(""),[Fe,Ne]=l.useState({open:!1}),[Le,ye]=l.useState({open:!1}),[ua,rt]=l.useState(null),[ha,nt]=l.useState(null),[C,se]=l.useState({categoryId:"",section:"catalog",name:"",brand:"",description:"",price:"",unit:"шт.",inStock:!0,featured:!1,imageUrl:""}),[ue,be]=l.useState({name:"",slug:"",icon:"Package",sortOrder:"0"}),[ce,Te]=l.useState(null),es=l.useRef(null),[it,ts]=l.useState(!1),[lt,ss]=l.useState(!1),[dt,as]=l.useState(!1),[rs,ns]=l.useState(null),[is,ls]=l.useState(null),ds=l.useRef(null);l.useEffect(()=>{!p&&!c&&(window.location.href="/auth")},[p,c]);const{data:os=[],isLoading:pa}=k({queryKey:["/api/my/estimates"],enabled:c}),{data:cs=[],isLoading:ga}=k({queryKey:["/api/promotions"],enabled:c}),{data:ot=[],isLoading:ms}=k({queryKey:["/api/admin/users"],enabled:c&&j}),{data:xs=[],isLoading:ba,refetch:fa}=k({queryKey:["/api/admin/content-items"],queryFn:async()=>{const t=await fetch("/api/admin/content-items",{credentials:"include"});return t.ok?t.json():[]},enabled:c&&j}),{data:us=[],isLoading:ja,refetch:va}=k({queryKey:["/api/admin/rss-posts"],queryFn:async()=>{const t=await fetch("/api/admin/rss-posts",{credentials:"include"});return t.ok?t.json():[]},enabled:c&&j}),{data:qe,refetch:Na}=k({queryKey:["/api/settings"],queryFn:async()=>(await fetch("/api/settings")).json(),enabled:c&&j}),hs=v({mutationFn:async t=>(await K("POST","/api/admin/settings",t)).json(),onSuccess:()=>{Na(),I.invalidateQueries({queryKey:["/api/settings"]}),i({title:"Настройки сохранены"})},onError:()=>i({title:"Ошибка сохранения настроек",variant:"destructive"})}),[ps,ya]=l.useState(""),[ct,wa]=l.useState("all"),[mt,ka]=l.useState("all"),[gs,Be]=l.useState(null),bs=v({mutationFn:async t=>{const s=await fetch(`/api/admin/content-items/${t}`,{method:"DELETE",credentials:"include"});if(!s.ok)throw new Error((await s.json()).message||"Ошибка")},onSuccess:()=>{fa(),i({title:"Запись удалена"}),Be(null)},onError:t=>i({title:"Ошибка",description:t.message,variant:"destructive"})}),fs=v({mutationFn:async t=>{const s=await fetch(`/api/admin/rss-posts/${t}`,{method:"DELETE",credentials:"include"});if(!s.ok)throw new Error((await s.json()).message||"Ошибка")},onSuccess:()=>{va(),i({title:"Пост удалён"}),Be(null)},onError:t=>i({title:"Ошибка",description:t.message,variant:"destructive"})}),{data:xt=[],isLoading:Ca,refetch:js}=k({queryKey:["/api/reels"],enabled:c&&j}),[ut,vs]=l.useState(""),[ht,Ns]=l.useState(null),[ys,ws]=l.useState(null),[Sa,pt]=l.useState(null),gt=v({mutationFn:async()=>
1{if(!ht)throw new Error("Выберите видеофайл");const t=new FormData;t.append("video",ht),ys&&t.append("poster",ys),ut.trim()&&t.append("title",ut.trim());const s=await fetch("/api/admin/reels",{method:"POST",credentials:"include",body:t});if(!s.ok)throw new Error((await s.json()).message||"Ошибка");return s.json()},onSuccess:()=>{js(),I.invalidateQueries({queryKey:["/api/reels"]}),vs(""),Ns(null),ws(null),i({title:"Видео загружено"})},onError:t=>i({title:"Ошибка",description:t.message,variant:"destructive"})}),ks=v({mutationFn:async t=>{const s=await fetch(`/api/admin/reels/${t}`,{method:"DELETE",credentials:"include"});if(!s.ok)throw new Error((await s.json()).message||"Ошибка")},onSuccess:()=>{js(),I.invalidateQueries({queryKey:["/api/reels"]}),i({title:"Видео удалено"}),pt(null)},onError:t=>i({title:"Ошибка",description:t.message,variant:"destructive"})}),{data:we=[],isLoading:Ea,refetch:He}=k({queryKey:["/api/admin/market/categories"],queryFn:async()=>{const t=await fetch("/api/admin/market/categories",{credentials:"include"});return t.ok?t.json():[]},enabled:c&&j}),{data:Qe=[],isLoading:$a,refetch:Ve}=k({queryKey:["/api/admin/market/products",_e,ze,Ke],queryFn:async()=>{const t=new URLSearchParams;_e!=="all"&&t.set("section",_e),ze!=="all"&&t.set("categoryId",ze),Ke&&t.set("search",Ke);const s=await fetch(`/api/admin/market/products?${t}`,{credentials:"include"});return s.ok?s.json():[]},enabled:c&&j}),{data:Cs=[],isLoading:Pa,refetch:bt}=k({queryKey:["/api/admin/specialists"],queryFn:async()=>{const t=await fetch("/api/admin/specialists",{credentials:"include"});return t.ok?t.json():[]},enabled:c&&j}),{data:Ss=[]}=k({queryKey:["/api/admin/users-for-spec"],queryFn:async()=>{const t=await fetch("/api/admin/users",{credentials:"include"});return t.ok?t.json():[]},enabled:c&&j&&Wt}),{data:ft=[],isLoading:Ia,refetch:Ua}=k({queryKey:["/api/my/specialist-inquiries"],queryFn:async()=>{const t=await fetch("/api/my/specialist-inquiries",{credentials:"include"});return t.ok?t.json():[]},enabled:c&&H}),{data:jt=[],isLoading:Fa,refetch:La}=k({queryKey:["/api/my/sent-inquiries"],queryFn:async()=>{const t=await fetch("/api/my/sent-inquiries",{credentials:"include"});return t.ok?t.json():[]},enabled:c&&!j&&!te}),{data:Ta=[],refetch:qa}=k({queryKey:["/api/inquiries",de,"messages"],queryFn:async()=>{if(!de)return[];const t=await fetch(`/api/inquiries/${de}/messages`,{credentials:"include"});return t.ok?t.json():[]},enabled:!!de,refetchInterval:de?5e3:!1}),vt=v({mutationFn:async()=>!de||!Ae.trim()?void 0:(await K("POST",`/api/inquiries/${de}/messages`,{text:Ae.trim()})).json(),onSuccess:()=>{Xt(""),qa(),H?Ua():La()},onError:t=>i({title:"Ошибка",description:t.message,variant:"destructive"})}),Nt=v({mutationFn:async()=>{const t=new FormData;Object.entries(L).forEach(([n,f])=>t.append(n,String(f))),Jt.forEach(n=>t.append("portfolio",n)),pe==="new"&&(t.append("newUserEmail",le.email),t.append("newUserPassword",le.password),t.append("newUserFirstName",le.firstName),t.append("newUserLastName",le.lastName),t.delete("userId"));const s=await fetch("/api/admin/specialists",{method:"POST",body:t,credentials:"include"});if(!s.ok)throw new Error((await s.json()).message||"Ошибка");return s.json()},onSuccess:()=>{bt(),Ee(!1),$e(null),je([]),ge({email:"",password:"",firstName:"",lastName:""}),i({title:"Специалист добавлен"})},onError:t=>i({title:"Ошибка",description:t.message,variant:"destructive"})}),yt=v({mutationFn:async t=>{const s=new FormData;Object.entries(L).forEach(([f,y])=>s.append(f,String(y))),Jt.forEach(f=>s.append("portfolio",f)),he&&s.append("portrait",he);const n=await fetch(`/api/admin/specialists/${t}`,{method:"PATCH",body:s,credentials:"include"});if(!n.ok)throw new Error((await n.json()).message||"Ошибка");return n.json()},onSuccess:()=>{bt(),Ee(!1),$e(null),je([]),ve(null),i({title:"Профиль обновлён"})},onError:t=>i({title:"Ошибка",description:t.message,variant:"destructive"})}),wt=v({mutationFn:async t=>{const s=await fetch(`/api/admin/specialists/${t}`,{method:"DELETE",credentials:"include"});if(!s.ok)throw new Error((await s.json()).message||"Ошибка");return s.json()},onSuccess:()=>{bt(),et(null),i({title:"Профиль удалён"})},onError:t=>i({title:"Ошибка",description:t.message,variant:"destructive"})}),kt=v({mutationFn:async t=>{const s=await fetch("/api/admin/market/products",{method:"POST",body:t,credentials:"include"});if(!s.ok)throw new Error((await s.json()).message||"Ошибка");return s.json()},onSuccess:()=>{Ve(),Ne({open:!1}),Te(null),i({title:"Товар добавлен"})},onError:t=>i({title:"Ошибка",description:t.message,variant:"destructive"})}),Ct=v({mutationFn:async({id:t,data:s})=>{const n=await fetch(`/api/admin/market/products/${t}`,{method:"PATCH",body:s,credentials:"include"});if(!n.ok)throw new Error((await n.json()).message||"Ошибка");return n.json()},onSuccess:()=>{Ve(),Ne({open:!1}),Te(null),i({title:"Товар обновлён"})},onError:t=>i({title:"Ошибка",description:t.message,variant:"destructive"})}),Es=v({mutationFn:async t=>{const s=await fetch(`/api/admin/market/products/${t}`,{method:"DELETE",credentials:"include"});if(!s.ok)throw new Error((await s.json()).message||"Ошибка")},onSuccess:()=>{Ve(),rt(null),i({title:"Товар удалён"})},onError:t=>i({title:"Ошибка",description:t.message,variant:"destructive"})}),St=v({mutationFn:async t=>{const s=await fetch("/api/admin/market/categories",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(t),credentials:"include"});if(!s.ok)throw new Error((await s.json()).message||"Ошибка");return s.json()},onSuccess:()=>{He(),ye({open:!1}),be({name:"",slug:"",icon:"Package",sortOrder:"0"}),i({title:"Категория добавлена"})},onError:t=>i({title:"Ошибка",description:t.message,variant:"destructive"})}),Et=v({mutationFn:async({id:t,data:s})=>{const n=await fetch(`/api/admin/market/categories/${t}`,{method:"PATCH",headers:{"Content-Type":"application/json"},body:JSON.stringify(s),credentials:"include"});if(!n.ok)throw new Error((await n.json()).message||"Ошибка");return n.json()},onSuccess:()=>{He(),ye({open:!1}),i({title:"Категория обновлена"})},onError:t=>i({title:"Ошибка",description:t.message,variant:"destructive"})}),$s=v({mutationFn:async t=>{const s=await fetch(`/api/admin/market/categories/${t}`,{method:"DELETE",credentials:"include"});if(!s.ok)throw new Error((await s.json()).message||"Ошибка")},onSuccess:()=>{He(),nt(null),i({title:"Категория удалена"})},onError:t=>i({title:"Ошибка",description:t.message,variant:"destructive"})}),Ps=v({mutationFn:async t=>{const s=await fetch(`/api/admin/market/categories/${t}/toggle`,{method:"PATCH",credentials:"include"});if(!s.ok)throw new Error((await s.json()).message||"Ошибка");return s.json()},onSuccess:t=>{He(),I.invalidateQueries({queryKey:["/api/market/categories"]}),i({title:t.enabled?"Категория включена":"Категория отключена"})},onError:t=>i({title:"Ошибка",description:t.message,variant:"destructive"})}),Da=async()=>{ts(!0);try{const t=await fetch("/api/admin/moodboard/seed",{method:"POST",credentials:"include"}),s=await t.json();if(!t.ok)throw new Error(s.message||"Ошибка");i({title:"Мудборд заполнен",description:`Добавлено ${s.seeded} фото, пропущено дублей: ${s.skipped}`}),Ve(),I.invalidateQueries({queryKey:["/api/market/products","moodboard"]})}catch(t){const s=t instanceof Error?t.message:"Неизвестная ошибка";i({title:"Ошибка заполнения",description:s,variant:"destructive"})}ts(!1)},{data:Is=[],isLoading:Ra}=k({queryKey:["/api/supervisor/employees"],enabled:c&&te}),{data:Us=[],isLoading:Ma}=k({queryKey:["/api/supervisor/estimates"],enabled:c&&te}),{data:Fs=[],isLoading:Oa}=k({queryKey:["/api/supervisor/contracts"],queryFn:async()=>{const t=await fetch("/api/supervisor/contracts",{credentials:"include"});return t.ok?t.json():[]},enabled:c&&te,refetchInterval:3e4}),{data:R,isLoading:Aa,refetch:_a}=k({queryKey:["/api/contracts/my"],queryFn:async()=>{const t=await fetch("/api/contracts/my",{credentials:"include"});return t.ok?t.json():null},enabled:c&&!j}
1),{data:$t=[],refetch:yr}=k({queryKey:["/api/contracts",R?.id,"supervisors"],queryFn:async()=>{if(!R?.id)return[];const t=await fetch(`/api/contracts/${R.id}/supervisors`,{credentials:"include"});return t.ok?t.json():[]},enabled:c&&!!R?.id&&!j}),{data:Ls=[]}=k({queryKey:["/api/supervisors/list"],queryFn:async()=>{const t=await fetch("/api/supervisors/list",{credentials:"include"});return t.ok?t.json():[]},enabled:c&&!!R?.id&&!j}),{data:Pt=[],isLoading:wr}=k({queryKey:["/api/supervisor/invited-chats"],queryFn:async()=>{const t=await fetch("/api/supervisor/invited-chats",{credentials:"include"});return t.ok?t.json():[]},enabled:c&&te,refetchInterval:3e4}),Ts=v({mutationFn:async t=>(await K("POST",`/api/contracts/${R.id}/supervisors`,{supervisorId:t})).json(),onSuccess:()=>{I.invalidateQueries({queryKey:["/api/contracts",R?.id,"supervisors"]}),m(!1),h(""),i({title:"Участник добавлен",description:"Супервайзер теперь может писать в чате договора"})},onError:()=>i({title:"Ошибка",description:"Не удалось добавить участника",variant:"destructive"})}),qs=v({mutationFn:async t=>(await K("DELETE",`/api/contracts/${R.id}/supervisors/${t}`)).json(),onSuccess:()=>{I.invalidateQueries({queryKey:["/api/contracts",R?.id,"supervisors"]}),i({title:"Участник удалён"})},onError:()=>i({title:"Ошибка",description:"Не удалось удалить участника",variant:"destructive"})}),{data:It=[],isLoading:za,refetch:Ut}=k({queryKey:["/api/admin/contracts"],queryFn:async()=>{const t=await fetch("/api/admin/contracts",{credentials:"include"});return t.ok?t.json():[]},enabled:c&&j}),We=v({mutationFn:async t=>(await K("POST","/api/contracts/link",{contractNumber:t})).json(),onSuccess:()=>{_a(),i({title:"Договор привязан",description:"Раздел «Объект в работе» теперь доступен"})},onError:t=>{i({title:"Ошибка",description:t.message||"Не удалось привязать договор",variant:"destructive"})}}),Ft=v({mutationFn:async t=>(await K("POST","/api/admin/contracts",t)).json(),onSuccess:()=>{Ut(),D(!1),A(""),G(""),ie(""),i({title:"Договор создан"})},onError:t=>{i({title:"Ошибка",description:t.message||"Не удалось создать договор",variant:"destructive"})}}),Ka=v({mutationFn:async({id:t,currentStatus:s})=>(await K("PATCH",`/api/admin/contracts/${t}`,{currentStatus:s})).json(),onSuccess:()=>{Ut(),i({title:"Статус обновлён"})},onError:t=>{i({title:"Ошибка",description:t.message,variant:"destructive"})}}),Ba=v({mutationFn:async t=>{await K("DELETE",`/api/admin/contracts/${t}`)},onSuccess:()=>{Ut(),E&&F(null),i({title:"Договор удалён"})},onError:t=>{i({title:"Ошибка",description:t.message,variant:"destructive"})}}),Ha=v({mutationFn:async t=>{await K("DELETE",`/api/my/estimates/${t}`)},onSuccess:()=>{I.invalidateQueries({queryKey:["/api/my/estimates"]}),i({title:"Смета удалена"})}}),Je=v({mutationFn:async t=>(await K("POST",j?"/api/admin/users":"/api/supervisor/employees",t)).json(),onSuccess:()=>{I.invalidateQueries({queryKey:["/api/admin/users"]}),I.invalidateQueries({queryKey:["/api/supervisor/employees"]}),N(!1),i({title:"Учётная запись создана"})},onError:t=>{i({title:"Ошибка",description:t.message||"Не удалось создать",variant:"destructive"})}}),Ds=v({mutationFn:async t=>{const s=j?`/api/admin/users/${t}`:`/api/supervisor/employees/${t}`;await K("DELETE",s)},onSuccess:()=>{I.invalidateQueries({queryKey:["/api/admin/users"]}),I.invalidateQueries({queryKey:["/api/supervisor/employees"]}),i({title:"Учётная запись удалена"})},onError:t=>{i({title:"Ошибка",description:t.message||"Не удалось удалить",variant:"destructive"})}}),Qa=v({mutationFn:async({id:t,role:s})=>{const n=await K("PATCH",`/api/admin/users/${t}`,{role:s});if(!n.ok)throw new Error((await n.json()).message||"Ошибка");return n.json()},onSuccess:()=>{I.invalidateQueries({queryKey:["/api/admin/users"]}),i({title:"Роль изменена"})},onError:t=>{i({title:"Ошибка",description:t.message,variant:"destructive"})}}),Lt=v({mutationFn:async({userId:t,file:s,url:n})=>{const f=new FormData;s?f.append("avatar",s):f.append("avatarUrl",n);const y=await fetch(`/api/admin/users/${t}/avatar`,{method:"PATCH",body:f});if(!y.ok)throw new Error((await y.json()).message||"Ошибка");return y.json()},onSuccess:()=>{I.invalidateQueries({queryKey:["/api/admin/users"]}),st(null),Pe(null),Ue(""),i({title:"Аватар обновлён"})},onError:t=>{i({title:"Ошибка",description:t.message,variant:"destructive"})}}),Tt=v({mutationFn:async t=>{const s=await K("POST","/api/admin/promotions",{...t,discountPercent:t.discountPercent?parseInt(t.discountPercent,10):void 0,validUntil:t.validUntil||void 0});if(!s.ok)throw new Error((await s.json()).error||"Ошибка");return s.json()},onSuccess:()=>{I.invalidateQueries({queryKey:["/api/promotions"]}),Me(!1),ee(Ce),i({title:"Акция создана"})},onError:t=>i({title:"Ошибка",description:t.message,variant:"destructive"})}),qt=v({mutationFn:async({id:t,data:s})=>{const n=await K("PATCH",`/api/admin/promotions/${t}`,{...s,discountPercent:s.discountPercent?parseInt(s.discountPercent,10):null,validUntil:s.validUntil||null});if(!n.ok)throw new Error((await n.json()).error||"Ошибка");return n.json()},onSuccess:()=>{I.invalidateQueries({queryKey:["/api/promotions"]}),Oe(null),ee(Ce),i({title:"Акция обновлена"})},onError:t=>i({title:"Ошибка",description:t.message,variant:"destructive"})}),Va=v({mutationFn:async t=>{const s=await K("DELETE",`/api/admin/promotions/${t}`);if(!s.ok)throw new Error((await s.json()).error||"Ошибка")},onSuccess:()=>{I.invalidateQueries({queryKey:["/api/promotions"]}),i({title:"Акция удалена"})},onError:t=>i({title:"Ошибка",description:t.message,variant:"destructive"})}),Rs=async t=>{try{const s=await fetch("/api/estimate/pdf",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({requestId:t.requestId,customerName:t.customerName,phone:t.phone,email:t.email,items:t.items,grandTotal:t.grandTotal})});if(!s.ok)throw new Error("PDF error");const n=await s.blob(),f=URL.createObjectURL(n),y=document.createElement("a");y.href=f,y.download=`smeta-${t.requestId}.pdf`,y.click(),URL.revokeObjectURL(f)}catch{i({title:"Ошибка",description:"Не удалось скачать PDF",variant:"destructive"})}};if(p)return e.jsx("div",{className:"min-h-screen mesh-bg-animated relative flex items-center justify-center",children:e.jsx("div",{className:"text-muted-foreground",children:"Загрузка..."})});if(!c)return null;
1const Ms=[o?.firstName,o?.lastName].filter(Boolean).join(" ")||o?.email||"Пользователь",z=[{key:"estimates",label:"Мои сметы",icon:Bt},{key:"promotions",label:"Акции",icon:_s}];return j||z.push({key:"myContract",label:"Мой объект",icon:ke}),j&&(z.push({key:"contracts",label:"Договоры",icon:ke}),z.push({key:"workChats",label:"Рабочие чаты",icon:Z}),z.push({key:"management",label:"Управление",icon:_t}),z.push({key:"registry",label:"Реестр",icon:Ks}),z.push({key:"content",label:"Контент",icon:Zs}),z.push({key:"market",label:"Маркет",icon:sr}),z.push({key:"specialists",label:"Специалисты",icon:As}),z.push({key:"backup",label:"Бэкап",icon:Ws})),te&&(z.push({key:"supervisorObjects",label:"Привлечённые объекты",icon:ke}),z.push({key:"employees",label:"Сотрудники",icon:At}),z.push({key:"clientEstimates",label:"Сметы клиентов",icon:Bs})),H&&z.push({key:"inquiries",label:"Обращения",icon:Z}),!j&&!te&&!H&&z.push({key:"inquiries",label:"Мои обращения",icon:Z}),e.jsxs("div",{className:"min-h-screen mesh-bg-animated relative",children:[e.jsx(Ja,{className:"fixed inset-0 z-0"}),e.jsx(Ya,{count:8,className:"fixed z-0"}),e.jsxs("div",{className:"relative z-10",children:[e.jsx(Za,{title:"Личный кабинет — М-АРТ",description:"Личный кабинет клиента М-АРТ: сохранённые сметы, акции и промокоды от партнёров.",canonicalPath:"/cabinet"}),e.jsx(Ga,{}),e.jsxs("main",{className:"container-premium pt-8 pb-16",children:[e.jsxs("div",{className:"flex flex-col sm:flex-row items-start sm:items-center justify-between gap-4 mb-8",children:[e.jsxs("div",{className:"flex items-center gap-4",children:[o?.profileImageUrl?e.jsx("img",{src:o.profileImageUrl,alt:Ms,className:"h-12 w-12 rounded-full border border-border object-cover","data-testid":"img-avatar"}):e.jsx("div",{className:"h-12 w-12 rounded-full border border-border bg-muted flex items-center justify-center","data-testid":"img-avatar-fallback",children:e.jsx(me,{className:"h-5 w-5 text-muted-foreground"})}),e.jsxs("div",{children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx("h1",{className:"text-2xl font-semibold","data-testid":"text-user-name",children:Ms}),(j||te)&&e.jsx("span",{className:"px-2 py-0.5 rounded-md text-[10px] font-semibold uppercase tracking-wider bg-[hsl(var(--accent)/0.15)] text-[hsl(var(--accent))] border border-[hsl(var(--accent)/0.3)]","data-testid":"badge-role",children:zt[o?.role||"user"]})]}),e.jsx("p",{className:"text-sm text-muted-foreground","data-testid":"text-user-email",children:o?.email||""}),te&&o?.organizationName&&e.jsxs("p",{className:"text-xs text-muted-foreground mt-0.5 flex items-center gap-1",children:[e.jsx(Os,{className:"h-3 w-3"}),o.organizationName,o.promoCode&&e.jsx("span",{className:"ml-2 px-1.5 py-0.5 rounded bg-[hsl(var(--accent)/0.1)] text-[hsl(var(--accent))] text-[10px] font-semibold",children:o.promoCode})]})]})]}),e.jsxs(T,{variant:"ghost",size:"sm",onClick:()=>b(),"data-testid":"button-logout",children:[e.jsx(cr,{className:"h-4 w-4"}),"Выйти"]})]}),e.jsx("div",{className:"flex flex-wrap gap-2 mb-6",children:z.map(({key:t,label:s,icon:n})=>e.jsxs(T,{variant:u===t?"primary":"secondary",size:"sm",onClick:()=>{P(t),N(!1)},"data-testid":`tab-${t}`,children:[e.jsx(n,{className:"h-4 w-4"}),s]},t))}),u==="estimates"&&e.jsx("section",{"data-testid":"section-estimates",children:pa?e.jsx("div",{className:"text-muted-foreground py-12 text-center",children:"Загрузка смет..."}):os.length===0?e.jsxs(x,{className:"p-8 text-center",children:[e.jsx(Bt,{className:"h-10 w-10 mx-auto text-muted-foreground mb-3"}),e.jsx("p",{className:"text-lg font-medium mb-1",children:"У вас пока нет сохранённых смет"}),e.jsx("p",{className:"text-sm text-muted-foreground mb-4",children:"Рассчитайте смету на главной странице — она автоматически сохранится здесь."}),e.jsx("a",{href:"/",children:e.jsx(T,{variant:"gold",onClick:()=>{},"data-testid":"button-go-calc",children:"Рассчитать смету"})})]}):e.jsx("div",{className:"space-y-4",children:os.map(t=>e.jsxs(x,{className:"p-5","data-testid":`card-estimate-${t.id}`,children:[e.jsxs("div",{className:"flex flex-col sm:flex-row sm:items-center justify-between gap-3 mb-3",children:[e.jsxs("div",{children:[e.jsx("div",{className:"font-semibold text-lg","data-testid":`text-estimate-total-${t.id}`,children:Xs(t.grandTotal)}),e.jsxs("div",{className:"flex items-center gap-2 text-xs text-muted-foreground mt-1",children:[e.jsx(zs,{className:"h-3 w-3"}),De(t.createdAt)]})]}),e.jsxs("div",{className:"flex gap-2",children:[e.jsxs(T,{variant:"secondary",size:"sm",onClick:()=>Rs(t),"data-testid":`button-pdf-${t.id}`,children:[e.jsx(Re,{className:"h-4 w-4"}),"PDF"]}),e.jsx(T,{variant:"ghost",size:"icon",onClick:()=>Ha.mutate(t.id),"data-testid":`button-delete-${t.id}`,children:e.jsx(Ot,{className:"h-4 w-4"})})]})]}),t.brief&&e.jsx("p",{className:"text-sm text-muted-foreground mb-3 line-clamp-2",children:t.brief}),e.jsxs("div",{className:"text-xs text-muted-foreground",children:[t.items.length," позиций"]})]},t.id))})}),u==="promotions"&&e.jsxs("section",{"data-testid":"section-promotions",children:[j&&e.jsxs("div",{className:"flex items-center justify-between mb-5",children:[e.jsx("h2",{className:"text-lg font-semibold",children:"Акции и спецпредложения"}),e.jsxs(T,{variant:"primary",size:"sm",onClick:()=>{Me(!0),Oe(null),ee(Ce)},"data-testid":"button-create-promo",children:[e.jsx(ae,{className:"h-4 w-4"}),"Добавить акцию"]})]}),(da||Se)&&j&&e.jsxs(x,{className:"p-5 mb-5 border-[hsl(var(--accent)/0.2)]","data-testid":"form-promo",children:[e.jsxs("div",{className:"flex items-center justify-between mb-4",children:[e.jsx("h3",{className:"font-semibold text-sm",children:Se?"Редактировать акцию":"Новая акция"}),e.jsx("button",{onClick:()=>{Me(!1),Oe(null),ee(Ce)},className:"h-7 w-7 rounded-full border border-border grid place-items-center hover:bg-muted transition-colors","data-testid":"button-cancel-promo",children:e.jsx(Y,{className:"h-3.5 w-3.5"})})]}),e.jsxs("div",{className:"space-y-3",children:[e.jsxs("div",{className:"grid grid-cols-1 sm:grid-cols-2 gap-3",children:[e.jsxs("div",{children:[e.jsx("label",{className:"text-xs text-muted-foreground mb-1 block",children:"Партнёр / Организатор *"}),e.jsx("input",{value:X.partnerName,onChange:t=>ee(s=>({...s,partnerName:t.target.value})),placeholder:"Например: М-АРТ",className:"w-full px-3 py-2 rounded-xl border border-border bg-background text-sm focus:outline-none focus:ring-1 focus:ring-[hsl(var(--accent))] placeholder:text-muted-foreground
1/50","data-testid":"input-promo-partner"})]}),e.jsxs("div",{children:[e.jsx("label",{className:"text-xs text-muted-foreground mb-1 block",children:"Название акции *"}),e.jsx("input",{value:X.title,onChange:t=>ee(s=>({...s,title:t.target.value})),placeholder:"Летняя скидка на ремонт",className:"w-full px-3 py-2 rounded-xl border border-border bg-background text-sm focus:outline-none focus:ring-1 focus:ring-[hsl(var(--accent))] placeholder:text-muted-foreground/50","data-testid":"input-promo-title"})]}),e.jsxs("div",{className:"sm:col-span-2",children:[e.jsx("label",{className:"text-xs text-muted-foreground mb-1 block",children:"Описание *"}),e.jsx("textarea",{value:X.description,onChange:t=>ee(s=>({...s,description:t.target.value})),placeholder:"Условия акции...",rows:2,className:"w-full px-3 py-2 rounded-xl border border-border bg-background text-sm focus:outline-none focus:ring-1 focus:ring-[hsl(var(--accent))] placeholder:text-muted-foreground/50 resize-none","data-testid":"input-promo-description"})]}),e.jsxs("div",{children:[e.jsx("label",{className:"text-xs text-muted-foreground mb-1 block",children:"Скидка %"}),e.jsx("input",{type:"number",min:"1",max:"100",value:X.discountPercent,onChange:t=>ee(s=>({...s,discountPercent:t.target.value})),placeholder:"15",className:"w-full px-3 py-2 rounded-xl border border-border bg-background text-sm focus:outline-none focus:ring-1 focus:ring-[hsl(var(--accent))] placeholder:text-muted-foreground/50","data-testid":"input-promo-discount"})]}),e.jsxs("div",{children:[e.jsx("label",{className:"text-xs text-muted-foreground mb-1 block",children:"Промокод"}),e.jsx("input",{value:X.promoCode,onChange:t=>ee(s=>({...s,promoCode:t.target.value.toUpperCase()})),placeholder:"MART15",className:"w-full px-3 py-2 rounded-xl border border-border bg-background text-sm focus:outline-none focus:ring-1 focus:ring-[hsl(var(--accent))] placeholder:text-muted-foreground/50 uppercase","data-testid":"input-promo-code"})]}),e.jsxs("div",{children:[e.jsx("label",{className:"text-xs text-muted-foreground mb-1 block",children:"Действует до"}),e.jsx("input",{type:"date",value:X.validUntil,onChange:t=>ee(s=>({...s,validUntil:t.target.value})),className:"w-full px-3 py-2 rounded-xl border border-border bg-background text-sm focus:outline-none focus:ring-1 focus:ring-[hsl(var(--accent))]","data-testid":"input-promo-valid-until"})]}),e.jsxs("div",{children:[e.jsx("label",{className:"text-xs text-muted-foreground mb-1 block",children:"URL обложки"}),e.jsx("input",{value:X.coverUrl,onChange:t=>ee(s=>({...s,coverUrl:t.target.value})),placeholder:"https://...",className:"w-full px-3 py-2 rounded-xl border border-border bg-background text-sm focus:outline-none focus:ring-1 focus:ring-[hsl(var(--accent))] placeholder:text-muted-foreground/50","data-testid":"input-promo-cover"})]})]}),e.jsxs(T,{variant:"primary",size:"sm",onClick:()=>{if(!X.partnerName.trim()||!X.title.trim()||!X.description.trim()){i({title:"Заполните обязательные поля",variant:"destructive"});return}Se?qt.mutate({id:Se.id,data:X}):Tt.mutate(X)},disabled:Tt.isPending||qt.isPending,"data-testid":"button-submit-promo",children:[Tt.isPending||qt.isPending?e.jsx(V,{className:"h-4 w-4 animate-spin"}):e.jsx(Ge,{className:"h-4 w-4"}),Se?"Сохранить":"Создать акцию"]})]})]}),ga?e.jsx("div",{className:"text-muted-foreground py-12 text-center",children:"Загрузка акций..."}):cs.length===0?e.jsxs(x,{className:"p-8 text-center",children:[e.jsx(_s,{className:"h-10 w-10 mx-auto text-muted-foreground mb-3"}),e.jsx("p",{className:"text-lg font-medium",children:"Акции скоро появятся"}),e.jsx("p",{className:"text-sm text-muted-foreground",children:j?"Нажмите «Добавить акцию», чтобы создать первую.":"Следите за обновлениями от наших партнёров."})]}):e.jsx("div",{className:"grid grid-cols-1 md:grid-cols-2 gap-4",children:cs.map(t=>e.jsxs(x,{className:"p-5 flex flex-col","data-testid":`card-promo-${t.id}`,children:[t.coverUrl&&e.jsx("img",{src:t.coverUrl,alt:t.title,className:"w-full h-36 object-cover rounded-xl mb-3 border border-border"}),e.jsxs("div",{className:"flex items-start justify-between gap-3 mb-3",children:[e.jsxs("div",{className:"min-w-0 flex-1",children:[e.jsx("div",{className:"text-xs tracking-widest uppercase text-muted-foreground mb-1",children:t.partnerName}),e.jsx("h3",{className:"font-semibold text-base leading-snug","data-testid":`text-promo-title-${t.id}`,children:t.title})]}),e.jsxs("div",{className:"flex items-center gap-1.5 shrink-0",children:[t.discountPercent&&e.jsxs("span",{className:"rounded-xl bg-[hsl(var(--accent)/0.15)] text-[hsl(var(--accent))] px-3 py-1 text-sm font-bold",children:["-",t.discountPercent,"%"]}),j&&e.jsxs(e.Fragment,{children:[e.jsx("button",{onClick:()=>
1{Oe(t),Me(!1),ee({partnerName:t.partnerName,title:t.title,description:t.description,discountPercent:t.discountPercent?.toString()||"",promoCode:t.promoCode||"",coverUrl:t.coverUrl||"",validUntil:t.validUntil?new Date(t.validUntil).toISOString().split("T")[0]:""})},className:"h-7 w-7 flex items-center justify-center rounded-lg border border-border text-muted-foreground hover:text-foreground hover:bg-muted transition-colors","data-testid":`button-edit-promo-${t.id}`,children:e.jsx(Ze,{className:"h-3 w-3"})}),e.jsx("button",{onClick:()=>{confirm("Удалить эту акцию?")&&Va.mutate(t.id)},className:"h-7 w-7 flex items-center justify-center rounded-lg border border-border text-muted-foreground hover:text-red-400 hover:border-red-400/50 transition-colors","data-testid":`button-delete-promo-${t.id}`,children:e.jsx(re,{className:"h-3 w-3"})})]})]})]}),e.jsx("p",{className:"text-sm text-muted-foreground mb-4 flex-1",children:t.description}),e.jsxs("div",{className:"flex flex-wrap items-center gap-3 text-xs",children:[t.promoCode&&e.jsxs("div",{className:"flex items-center gap-1.5",children:[e.jsx(Xa,{className:"h-3 w-3 text-[hsl(var(--accent))]"}),e.jsx(br,{text:t.promoCode})]}),t.validUntil&&e.jsxs("span",{className:"text-muted-foreground",children:["до ",De(t.validUntil)]})]})]},t.id))})]}),u==="management"&&j&&e.jsxs("section",{"data-testid":"section-management",children:[e.jsxs("div",{className:"mb-6 p-4 rounded-xl border border-border bg-card",children:[e.jsxs("h3",{className:"text-sm font-semibold text-foreground mb-3 flex items-center gap-2",children:[e.jsx(mr,{className:"h-4 w-4 text-muted-foreground"}),"Настройки сайта"]}),e.jsxs("div",{className:"flex items-center justify-between gap-4",children:[e.jsxs("div",{children:[e.jsx("div",{className:"text-sm font-medium",children:"Раздел «М-АРТ Маркет»"}),e.jsx("div",{className:"text-xs text-muted-foreground mt-0.5",children:qe?.marketEnabled?"Раздел виден всем пользователям":"Раздел скрыт для пользователей"})]}),e.jsx("button",{"data-testid":"button-toggle-market",onClick:()=>hs.mutate({marketEnabled:!qe?.marketEnabled}),disabled:hs.isPending,className:`relative inline-flex h-6 w-11 shrink-0 cursor-pointer rounded-full border-2 border-transparent transition-colors duration-200 focus:outline-none ${qe?.marketEnabled?"bg-[hsl(var(--accent))]":"bg-muted"} disabled:opacity-50`,role:"switch","aria-checked":qe?.marketEnabled,children:e.jsx("span",{className:`pointer-events-none inline-block h-5 w-5 transform rounded-full bg-white shadow-lg ring-0 transition duration-200 ${qe?.marketEnabled?"translate-x-5":"translate-x-0"}`})})]})]}),e.jsxs("div",{className:"flex items-center justify-between mb-4",children:[e.jsx("h2",{className:"text-lg font-semibold",children:"Все пользователи"}),e.jsxs(T,{variant:"primary",size:"sm",onClick:()=>N(!g),"data-testid":"button-toggle-create",children:[g?e.jsx(Y,{className:"h-4 w-4"}):e.jsx(ae,{className:"h-4 w-4"}),g?"Отмена":"Создать"]})]}),g&&e.jsx("div",{className:"mb-6",children:e.jsx(ta,{onSubmit:t=>Je.mutate(t),onCancel:()=>N(!1),loading:Je.isPending,showRoleSelect:!0,showOrgFields:!1})}),ms?e.jsx("div",{className:"text-muted-foreground py-12 text-center",children:"Загрузка..."}):e.jsx("div",{className:"space-y-3",children:ot.map(t=>e.jsx(x,{className:"p-4","data-testid":`card-user-${t.id}`,children:e.jsxs("div",{className:"flex flex-col sm:flex-row sm:items-center justify-between gap-3",children:[e.jsxs("div",{className:"flex items-center gap-3",children:[e.jsxs("div",{className:"relative shrink-0 group",children:[t.profileImageUrl?e.jsx("img",{src:t.profileImageUrl,alt:"avatar",className:"h-10 w-10 rounded-full object-cover border border-border"}):e.jsx("div",{className:"h-10 w-10 rounded-full bg-muted flex items-center justify-center",children:e.jsx(me,{className:"h-4 w-4 text-muted-foreground"})}),e.jsx("button",{onClick:()=>{st(Zt===t.id?null:t.id),Pe(null),Ue(t.profileImageUrl||"")},className:"absolute -bottom-1 -right-1 h-5 w-5 rounded-full bg-[hsl(var(--accent))] text-black flex items-center justify-center opacity-0 group-hover:opacity-100 transition-opacity",title:"Изменить фото","data-testid":`button-edit-avatar-${t.id}`,children:e.jsx(rr,{className:"h-2.5 w-2.5"})})]}),e.jsxs("div",{className:"min-w-0",children:[Zt===t.id&&e.jsxs("div",{className:"mb-2 p-3 rounded-xl border border-border bg-card/80 flex flex-col gap-2",style:{minWidth:260},children:[e.jsx("div",{className:"text-xs font-semibold text-foreground mb-1",children:"Фото профиля"}),(xe||Ie)&&e.jsx("img",{src:xe?URL.createObjectURL(xe):Ie,alt:"preview",className:"w-14 h-14 roun
1ded-full object-cover border border-border mx-auto"}),e.jsxs("label",{className:"flex items-center gap-2 text-xs text-muted-foreground cursor-pointer",children:[e.jsx("input",{type:"file",accept:"image/*",className:"hidden",onChange:s=>{Pe(s.target.files?.[0]||null),Ue("")}}),e.jsx("span",{className:"px-2 py-1 rounded bg-muted border border-border text-xs",children:"Загрузить файл"}),xe&&e.jsx("span",{className:"truncate max-w-[120px]",children:xe.name})]}),e.jsx("input",{type:"text",placeholder:"Или вставить ссылку на фото",value:xe?"":Ie,onChange:s=>{Pe(null),Ue(s.target.value)},className:"px-2 py-1.5 rounded-lg border border-border bg-background text-xs focus:outline-none focus:ring-1 focus:ring-[hsl(var(--accent))]","data-testid":`input-avatar-url-${t.id}`}),e.jsxs("div",{className:"flex gap-2",children:[e.jsx("button",{onClick:()=>Lt.mutate({userId:t.id,file:xe,url:Ie}),disabled:Lt.isPending||!xe&&!Ie.trim(),className:"flex-1 py-1.5 rounded-lg text-xs font-semibold text-black disabled:opacity-50",style:{background:"hsl(var(--accent))"},"data-testid":`button-save-avatar-${t.id}`,children:Lt.isPending?"Сохранение...":"Сохранить"}),e.jsx("button",{onClick:()=>{st(null),Pe(null),Ue("")},className:"px-3 py-1.5 rounded-lg text-xs border border-border","data-testid":`button-cancel-avatar-${t.id}`,children:"Отмена"})]})]}),e.jsxs("div",{className:"flex items-center gap-2 flex-wrap",children:[e.jsx("span",{className:"font-medium text-sm","data-testid":`text-user-name-${t.id}`,children:[t.firstName,t.lastName].filter(Boolean).join(" ")||t.email}),e.jsx("span",{className:`px-1.5 py-0.5 rounded text-[10px] font-semibold uppercase tracking-wider ${t.role==="admin"?"bg-amber-500/15 text-amber-400 border border-amber-500/30":t.role==="supervisor"?"bg-blue-500/15 text-blue-400 border border-blue-500/30":t.role==="employee"?"bg-purple-500/15 text-purple-400 border border-purple-500/30":"bg-muted text-muted-foreground border border-border"}`,"data-testid":`badge-role-${t.id}`,children:zt[t.role]||t.role})]}),e.jsxs("div",{className:"flex items-center gap-3 text-xs text-muted-foreground mt-0.5 flex-wrap",children:[t.email&&e.jsx("span",{children:t.email}),t.phone&&e.jsx("span",{children:t.phone}),t.organizationName&&e.jsxs("span",{className:"flex items-center gap-1",children:[e.jsx(Os,{className:"h-3 w-3"}),t.organizationName]}),t.promoCode&&e.jsx("span",{className:"px-1.5 py-0.5 rounded bg-[hsl(var(--accent)/0.1)] text-[hsl(var(--accent))] text-[10px] font-semibold",children:t.promoCode})]})]})]}),e.jsxs("div",{className:"flex items-center gap-2 shrink-0",children:[t.role!=="admin"&&e.jsxs("select",{value:t.role,onChange:s=>Qa.mutate({id:t.id,role:s.target.value}),className:"px-2 py-1.5 rounded-lg border border-border bg-background text-xs text-foreground focus:outline-none focus:ring-1 focus:ring-[hsl(var(--accent))] cursor-pointer","data-testid":`select-user-role-${t.id}`,children:[e.jsx("option",{value:"user",children:"Пользователь"}),e.jsx("option",{value:"supervisor",children:"Супервайзер"}),e.jsx("option",{value:"employee",children:"Сотрудник"}),e.jsx("option",{value:"admin",children:"Администратор"})]}),t.role!=="admin"&&e.jsx(T,{variant:"ghost",size:"icon",onClick:()=>{confirm(`Удалить ${t.email}?`)&&Ds.mutate(t.id)},"data-testid":`button-delete-user-${t.id}`,children:e.jsx(Ot,{className:"h-4 w-4"})})]})]})},t.id))})]}),u==="employees"&&te&&e.jsxs("section",{"data-testid":"section-employees",children:[e.jsxs("div",{className:"flex items-center justify-between mb-4",children:[e.jsx("h2",{className:"text-lg font-semibold",children:"Мои сотрудники"}),e.jsxs(T,{variant:"primary",size:"sm",onClick:()=>N(!g),"data-testid":"button-toggle-create-employee",children:[g?e.jsx(Y,{className:"h-4 w-4"}):e.jsx(ae,{className:"h-4 w-4"}),g?"Отмена":"Добавить"]})]}),g&&e.jsx("div",{className:"mb-6",children:e.jsx(ta,{onSubmit:t=>Je.mutate(t),onCancel:()=>N(!1),loading:Je.isPending,showRoleSelect:!1,showOrgFields:!1})}),Ra?e.jsx("div",{className:"text-muted-foreground py-12 text-center",children:"Загрузка..."}):Is.length===0?e.jsxs(x,{className:"p-8 text-center",children:[e.jsx(At,{className:"h-10 w-10 mx-auto text-muted-foreground mb-3"}),e.jsx("p",{className:"text-lg font-medium mb-1",children:"Нет сотрудников"}),e.jsx("p",{className:"text-sm text-muted-foreground",children:"Добавьте сотрудников, чтобы оÐ
1½Ð¸ могли работать от имени вашей организации."})]}):e.jsx("div",{className:"space-y-3",children:Is.map(t=>e.jsx(x,{className:"p-4","data-testid":`card-employee-${t.id}`,children:e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsxs("div",{className:"flex items-center gap-3",children:[e.jsx("div",{className:"h-9 w-9 rounded-full bg-muted flex items-center justify-center shrink-0",children:e.jsx(me,{className:"h-4 w-4 text-muted-foreground"})}),e.jsxs("div",{children:[e.jsx("div",{className:"font-medium text-sm","data-testid":`text-employee-name-${t.id}`,children:[t.firstName,t.lastName].filter(Boolean).join(" ")||t.email}),e.jsxs("div",{className:"text-xs text-muted-foreground flex items-center gap-2",children:[t.email&&e.jsx("span",{children:t.email}),t.phone&&e.jsx("span",{children:t.phone})]})]})]}),e.jsx(T,{variant:"ghost",size:"icon",onClick:()=>{confirm("Удалить сотрудника?")&&Ds.mutate(t.id)},"data-testid":`button-delete-employee-${t.id}`,children:e.jsx(Ot,{className:"h-4 w-4"})})]})},t.id))})]}),u==="clientEstimates"&&te&&e.jsxs("section",{"data-testid":"section-client-estimates",children:[e.jsx("div",{className:"flex items-center justify-between mb-4",children:e.jsxs("div",{children:[e.jsx("h2",{className:"text-lg font-semibold",children:"Сметы клиентов"}),o?.promoCode&&e.jsxs("p",{className:"text-xs text-muted-foreground mt-0.5",children:["Сметы с промокодом ",e.jsx("span",{className:"text-[hsl(var(--accent))] font-semibold",children:o.promoCode})]})]})}),Ma?e.jsx("div",{className:"text-muted-foreground py-12 text-center",children:"Загрузка..."}):Us.length===0?e.jsxs(x,{className:"p-8 text-center",children:[e.jsx(Bs,{className:"h-10 w-10 mx-auto text-muted-foreground mb-3"}),e.jsx("p",{className:"text-lg font-medium mb-1",children:"Нет смет"}),e.jsxs("p",{className:"text-sm text-muted-foreground",children:["Здесь появятся сметы клиентов, которые использовали ваш промокод"," ",o?.promoCode&&e.jsx("span",{className:"text-[hsl(var(--accent))] font-semibold",children:o.promoCode})]})]}):e.jsx("div",{className:"space-y-4",children:Us.map(t=>e.jsxs(x,{className:"p-5","data-testid":`card-client-estimate-${t.id}`,children:[e.jsxs("div",{className:"flex flex-col sm:flex-row sm:items-center justify-between gap-3 mb-3",children:[e.jsxs("div",{children:[e.jsx("div",{className:"font-semibold text-lg","data-testid":`text-client-estimate-total-${t.id}`,children:Xs(t.grandTotal)}),e.jsxs("div",{className:"flex items-center gap-3 text-xs text-muted-foreground mt-1",children:[e.jsxs("span",{className:"flex items-center gap-1",children:[e.jsx(zs,{className:"h-3 w-3"}),De(t.createdAt)]}),e.jsx("span",{children:t.customerName}),t.phone&&e.jsx("span",{children:t.phone})]})]}),e.jsxs(T,{variant:"secondary",size:"sm",onClick:()=>Rs(t),"data-testid":`button-client-pdf-${t.id}`,children:[e.jsx(Re,{className:"h-4 w-4"}),"PDF"]})]}),t.brief&&e.jsx("p",{className:"text-sm text-muted-foreground mb-3 line-clamp-2",children:t.brief}),e.jsxs("div",{className:"text-xs text-muted-foreground",children:[t.items.length," позиций"]})]},t.id))})]}),u==="supervisorObjects"&&te&&e.jsxs("section",{"data-testid":"section-supervisor-objects",children:[e.jsx("div",{className:"flex items-center justify-between mb-6",children:e.jsxs("div",{children:[e.jsx("h2",{className:"text-lg font-semibold",children:"Привлечённые объекты"}),o?.promoCode&&e.jsxs("p",{className:"text-xs text-muted-foreground mt-0.5",children:["Объекты клиентов, зарегистрированных по промокоду"," ",e.jsx("span",{className:"text-[hsl(var(--accent))] font-semibold",children:o.promoCode})]})]})}),Oa?e.jsx("div",{className:"text-muted-foreground py-12 text-center",children:"Загрузка объектов..."}):Fs.length===0?e.jsxs(x,{className:"p-8 text-center",children:[e.jsx(ke,{className:"h-10 w-10 mx-auto text-muted-foreground mb-3"}),e.jsx("p",{className:"text-lg font-medium mb-1",children:"Нет привлечённых объектов"}),e.jsxs("p",{className:"text-sm text-muted-foreground",children:["Здесь появятся объекты клиентов, которые зарегистрировались по вашему промокоду"," ",o?.promoCode&&e.jsx("span",{className:"text-[hsl(var(--accent))] font-semibold",children:o.promoCode})]})]}):e.jsx("div",{className:"space-y-4",children:Fs.map(t=>{const s=fe.indexOf(t.currentStatus),n=s>=0?Math.round((s+1)/fe.length*100):0;return e.jsx(x,{className:"p-5 border-[hsl(var(--accent)/0.15)]","data-testid":`card-supervisor-contract-${t.id}`,children:e.jsxs("div",{className:"flex flex-col sm:flex-row sm:items-start justify-between gap-4",children:[e.jsxs("div",{className:"flex-1 min-w-0",children:[e.jsxs("div",{className:"flex items-center gap-2 flex-wrap mb-1",children:[e.jsx("span",{className:"font-semibold text-sm","data-testid":`text-contract-number-${t.id}`,children:t.contractNumber}),e.jsx("span",{className:"px-2 py-0.5 rounded-full text-[10px] font-medium bg-[hsl(var(--accent)/0.15)] text-[hsl(var(--accent))] border border-[hsl(var(--accent)/0.3)]",children:t.currentStatus})]}),e.jsx("p",{className:"text-sm text-foreground font-medium mb-0.5","data-testid":`text-contract-title-${t.id}`,children:t.title}),t.address&&e.jsx("p",{className:"text-xs text-muted-foreground",children:t.address}),t.clientName&&e.jsxs("p",{className:"text-xs text-muted-foreground mt-1",children:["Клиент: ",e.jsx("span",{className:"text-foreground",children:t.clientName}),t.clientPhone&&e.jsx("span",{className:"ml-2",children:t.clientPhone})]})]}),e.jsxs("div",{className:"w-full sm:w-48 shrink-0",children:[e.jsxs("div",{className:"flex items-center justify-between text-xs text-muted-foreground mb-1.5",children:[e.jsx("span",{children:"Прогресс"}),e.jsxs("span",{className:"text-[hsl(var(--accent))] font-semibold",children:[n,"%"]})]}),e.jsx("div",{className:"w-full h-2 rounded-full bg-muted overflow-hidden",children:e.jsx("div",{className:"h-full rounded-full bg-[hsl(var(--accent))] transition-all duration-500",style:{width:`${n}%`}})}),e.jsx("div",{className:"mt-3 space-y-1",children:fe.map((f,y)=>e.jsxs("div",{className:"flex items-center gap-2",children:[y<s?e.jsx(nr,{className:"h-3 w-3 text-[hsl(var(--accent))] shrink-0"}):y===s?e.jsx(sa,{className:"h-3 w-3 text-[hsl(var(--accent))] shrink-0"}
1):e.jsx(ra,{className:"h-3 w-3 text-muted-foreground/40 shrink-0"}),e.jsx("span",{className:`text-[10px] leading-tight ${y===s?"text-[hsl(var(--accent))] font-semibold":y<s?"text-muted-foreground line-through":"text-muted-foreground/50"}`,children:f})]},f))})]})]})},t.id)})}),Pt.length>0&&e.jsxs("div",{className:"mt-8",children:[e.jsxs("div",{className:"flex items-center gap-3 mb-4",children:[e.jsx("div",{className:"h-px flex-1 bg-border"}),e.jsxs("h3",{className:"text-sm font-semibold text-muted-foreground uppercase tracking-wider flex items-center gap-2",children:[e.jsx(Z,{className:"h-3.5 w-3.5"}),"Приглашённые в чат"]}),e.jsx("div",{className:"h-px flex-1 bg-border"})]}),J!==null?e.jsxs("div",{children:[e.jsxs("button",{onClick:()=>_(null),className:"flex items-center gap-1.5 text-sm text-muted-foreground hover:text-foreground transition-colors mb-4","data-testid":"button-back-invited-chats",children:[e.jsx(Hs,{className:"h-4 w-4"}),"Назад к списку"]}),(()=>{const t=Pt.find(s=>s.id===J);return t?e.jsxs(x,{className:"p-6",children:[e.jsxs("div",{className:"mb-4",children:[e.jsxs("div",{className:"text-xs text-muted-foreground mb-0.5",children:["Договор № ",t.contractNumber]}),e.jsx("h2",{className:"text-lg font-semibold",children:t.title}),t.clientName&&e.jsxs("p",{className:"text-sm text-muted-foreground mt-0.5",children:["Клиент: ",t.clientName]})]}),e.jsx(Kt,{contractId:t.id,currentUserId:o.id,isAdminView:!1})]}):null})()]}):e.jsx("div",{className:"space-y-3",children:Pt.map(t=>e.jsx(x,{className:"p-4 border-[hsl(var(--accent)/0.15)]","data-testid":`card-invited-chat-${t.id}`,children:e.jsxs("div",{className:"flex items-center justify-between gap-4",children:[e.jsxs("div",{className:"min-w-0",children:[e.jsxs("div",{className:"flex items-center gap-2 flex-wrap mb-0.5",children:[e.jsx("span",{className:"font-semibold text-sm",children:t.contractNumber}),e.jsx("span",{className:"px-2 py-0.5 rounded-full text-[10px] font-medium bg-[hsl(var(--accent)/0.15)] text-[hsl(var(--accent))] border border-[hsl(var(--accent)/0.3)]",children:t.currentStatus})]}),e.jsx("p",{className:"text-sm font-medium text-foreground truncate",children:t.title}),t.clientName&&e.jsxs("p",{className:"text-xs text-muted-foreground mt-0.5",children:["Клиент: ",t.clientName]})]}),e.jsxs("button",{onClick:()=>_(t.id),className:"flex items-center gap-1.5 px-3 py-1.5 rounded-lg text-xs font-medium bg-[hsl(var(--accent)/0.1)] border border-[hsl(var(--accent)/0.3)] text-[hsl(var(--accent))] hover:bg-[hsl(var(--accent)/0.2)] transition-colors shrink-0","data-testid":`button-open-invited-chat-${t.id}`,children:[e.jsx(Z,{className:"h-3.5 w-3.5"}),"Чат"]})]})},t.id))})]})]}),u==="myContract"&&!j&&e.jsx("section",{"data-testid":"section-my-contract",children:Aa?e.jsx("div",{className:"text-muted-foreground py-12 text-center",children:"Загрузка..."}):R?e.jsxs("div",{className:"space-y-6 max-w-3xl",children:[e.jsxs(x,{className:"p-6",children:[e.jsxs("div",{className:"flex items-start justify-between mb-6",children:[e.jsxs("div",{children:[e.jsxs("div",{className:"text-xs text-muted-foreground mb-1",children:["Договор № ",R.contractNumber]}),e.jsx("h2",{className:"text-xl font-semibold","data-testid":"text-contract-title",children:R.title}),R.address&&e.jsx("p",{className:"text-sm text-muted-foreground mt-1",children:R.address})]}),e.jsxs("div",{className:"flex items-center gap-2",children:[$.state!=="unsupported"&&$.state!=="loading"&&e.jsxs("button",{"data-testid":"button-push-toggle-client",onClick:async()=>{$.state==="subscribed"?await $.unsubscribe()&&i({title:"Уведомления отключены"}):await $.subscribe()?i({title:"Уведомления включены",description:"Вы будете получать оповещения об ответах M-АРТ"}):$.state==="denied"&&i({title:"Доступ запрещён",description:"Разрешите уведомления в настройках браузера",variant:"destructive"})},title:$.state==="subscribed"?"Отключить уведомления":"Включить уведомления об ответах",className:`flex items-center gap-1.5 px-2.5 py-1.5 rounded-lg text-xs font-medium border transition-colors ${$.state==="subscribed"?"bg-[hsl(var(--accent)/0.15)] border-[hsl(var(--accent)/0.5)] text-[hsl(var(--accent))]":"bg-transparent border-foreground
1/20 text-foreground/50 hover:border-foreground/40 hover:text-foreground/70"}`,children:[$.state==="subscribed"?e.jsx(Ys,{className:"h-3.5 w-3.5"}):e.jsx(Js,{className:"h-3.5 w-3.5"}),e.jsx("span",{className:"hidden sm:inline",children:($.state==="subscribed","Уведомл.")})]}),e.jsx("div",{className:"px-3 py-1 rounded-lg bg-[hsl(var(--accent)/0.1)] border border-[hsl(var(--accent)/0.3)] text-[hsl(var(--accent))] text-xs font-semibold",children:"В работе"})]})]}),e.jsx("h3",{className:"text-sm font-semibold mb-4 text-muted-foreground uppercase tracking-wider",children:"Этапы работ"}),e.jsx(jr,{currentStatus:R.currentStatus})]}),e.jsxs(x,{className:"p-6",children:[e.jsxs("div",{className:"flex items-center justify-between mb-4",children:[e.jsxs("h3",{className:"text-base font-semibold flex items-center gap-2",children:[e.jsx(At,{className:"h-4 w-4 text-[hsl(var(--accent))]"}),"Участники чата"]}),e.jsxs("button",{onClick:()=>m(!d),className:"flex items-center gap-1.5 px-3 py-1.5 rounded-lg text-xs font-medium border border-[hsl(var(--accent)/0.4)] text-[hsl(var(--accent))] hover:bg-[hsl(var(--accent)/0.1)] transition-colors","data-testid":"button-add-supervisor",children:[e.jsx(ae,{className:"h-3 w-3"}),"Добавить"]})]}),d&&e.jsxs("div",{className:"mb-4 p-4 rounded-xl border border-border bg-muted/30",children:[e.jsx("p",{className:"text-xs text-muted-foreground mb-3",children:"Выберите супервайзера, которого хотите пригласить в чат:"}),e.jsx("input",{type:"text",value:r,onChange:t=>h(t.target.value),placeholder:"Поиск по имени или организации...",className:"w-full px-3 py-2 rounded-lg border border-border bg-background text-sm focus:outline-none focus:ring-1 focus:ring-[hsl(var(--accent))] placeholder:text-muted-foreground/50 mb-2","data-testid":"input-supervisor-search"}),e.jsxs("div",{className:"space-y-1 max-h-48 overflow-y-auto",children:[Ls.filter(t=>{const s=r.toLowerCase();return s?t.email?.toLowerCase().includes(s)||t.firstName?.toLowerCase().includes(s)||t.lastName?.toLowerCase().includes(s)||t.organizationName?.toLowerCase().includes(s):!0}).filter(t=>!$t.some(s=>s.supervisorId===t.id)).map(t=>e.jsxs("button",{onClick:()=>Ts.mutate(t.id),disabled:Ts.isPending,className:"w-full flex items-center gap-3 px-3 py-2 rounded-lg text-left hover:bg-[hsl(var(--accent)/0.1)] transition-colors border border-transparent hover:border-[hsl(var(--accent)/0.2)]","data-testid":`button-invite-supervisor-${t.id}`,children:[e.jsx("div",{className:"w-7 h-7 rounded-full bg-[hsl(var(--accent)/0.15)] flex items-center justify-center shrink-0",children:e.jsx(_t,{className:"h-3.5 w-3.5 text-[hsl(var(--accent))]"})}),e.jsxs("div",{className:"min-w-0",children:[e.jsx("div",{className:"text-sm font-medium leading-tight",children:t.firstName||t.lastName?`${t.firstName||""} ${t.lastName||""}`.trim():t.email}),t.organizationName&&e.jsx("div",{className:"text-xs text-muted-foreground truncate",children:t.organizationName})]})]},t.id)),Ls.length===0&&e.jsx("p",{className:"text-sm text-muted-foreground text-center py-4",children:"Нет доступных супервайзеров"})]})]}),$t.length===0?e.jsx("p",{className:"text-sm text-muted-foreground",children:"Нет дополнительных участников. Нажмите «Добавить», чтобы пригласить супервайзера в переписку."}):e.jsx("div",{className:"space-y-2",children:$t.map(t=>{const s=t.supervisor;return s?e.jsxs("div",{className:"flex items-center gap-3 px-3 py-2.5 rounded-xl border border-border bg-muted/20","data-testid":`row-supervisor-${t.supervisorId}`,children:[e.jsx("div",{className:"w-8 h-8 rounded-full bg-[hsl(var(--accent)/0.15)] flex items-center justify-center shrink-0",children:e.jsx(_t,{className:"h-4 w-4 text-[hsl(var(--accent))]"})}),e.jsxs("div",{className:"flex-1 min-w-0",children:[e.jsx("div",{className:"text-sm font-medium leading-tight",children:s.firstName||s.lastName?`${s.firstName||""} ${s.lastName||""}`.trim():s.email}),s.organizationName&&e.jsx("div",{className:"text-xs text-muted-foreground",children:s.organizationName})]}),e.jsx("span",{className:"text-[10px] px-2 py-0.5 rounded-full bg-[hsl(var(--accent)/0.1)] text-[hsl(var(--accent))] border border-[hsl(var(--accent)/0.3)] shrink-0",children:"Супервайзер"}),e.jsx("button",{onClick:()=>qs.mutate(t.supervisorId),disabled:qs.isPending,className:"p-1.5 rounded-lg text-muted-foreground hover:text-destructive hover:bg-destructive/10 transition-colors",title:"Удалить из чата","data-testid":`button-remove-supervisor-${t.supervisorId}`,children:e.jsx(Y,{className:"h-3.5 w-3.5"})})]},t.id):null})})]}),e.jsxs(x,{className:"p-6",children:[e.jsxs("h3",{className:"text-base font-semibold mb-4 flex items-center gap-2",children:[e.jsx(Z,{className:"h-4 w-4 text-[hsl(var(--accent))]"}),"Чат с М-АРТ"]}),e.jsx(Kt,{contractId:R.id,currentUserId:o.id,isAdminView:!1})]})]}):e.jsx("div",{className:"max-w-lg mx-auto",children:e.jsxs(x,{className:"p-8",children:[e.jsx(ke,{className:"h-10 w-10 mx-auto text-muted-foreground mb-4"}),e.jsx("h2",{className:"text-xl font-semibold text-center mb-2",children:"Привязать договор"}),e.jsx("p",{className:"text-sm text-muted-foreground text-center mb-6",children:"Введите номер вашего договора с M-АРТ, чтобы отслеживать статус работ и общаться с командой"}),e.jsxs("div",{className:"flex gap-3",children:[e.jsx("input",{type:"text",value:S,onChange:t=>M(t.target.value),placeholder:"Номер договора, например №123",className:"flex-1 px-3 py-2 rounded-xl border border-border bg-background text-sm focus:outline-none focus:ring-1 focus:ring-[hsl(var(--accent))] placeholder:text-muted-foreground
1/50",onKeyDown:t=>t.key==="Enter"&&S.trim()&&We.mutate(S.trim()),"data-testid":"input-contract-number"}),e.jsxs(T,{variant:"primary",size:"sm",onClick:()=>S.trim()&&We.mutate(S.trim()),disabled:We.isPending||!S.trim(),"data-testid":"button-link-contract",children:[We.isPending?e.jsx(V,{className:"h-4 w-4 animate-spin"}):e.jsx(Ge,{className:"h-4 w-4"}),"Привязать"]})]})]})})}),u==="contracts"&&j&&e.jsx("section",{"data-testid":"section-admin-contracts",children:E!==null?e.jsxs("div",{className:"max-w-3xl",children:[e.jsx("div",{className:"flex items-center gap-3 mb-6",children:e.jsxs("button",{onClick:()=>F(null),className:"flex items-center gap-1.5 text-sm text-muted-foreground hover:text-foreground transition-colors","data-testid":"button-back-contracts",children:[e.jsx(Hs,{className:"h-4 w-4"}),"Назад к договорам"]})}),(()=>{const t=It.find(s=>s.id===E);return t?e.jsxs(x,{className:"p-6",children:[e.jsxs("div",{className:"mb-4",children:[e.jsxs("div",{className:"text-xs text-muted-foreground mb-0.5",children:["Договор № ",t.contractNumber]}),e.jsx("h2",{className:"text-lg font-semibold",children:t.title}),t.clientName&&e.jsxs("p",{className:"text-sm text-muted-foreground mt-0.5",children:["Клиент: ",t.clientName]})]}),e.jsx(Kt,{contractId:t.id,currentUserId:o.id,isAdminView:!0})]}):null})()]}):e.jsxs("div",{className:"space-y-4",children:[e.jsxs("div",{className:"flex items-center justify-between mb-2 flex-wrap gap-2",children:[e.jsx("h2",{className:"text-lg font-semibold",children:"Все договоры"}),e.jsxs("div",{className:"flex items-center gap-2",children:[$.state!=="unsupported"&&$.state!=="loading"&&e.jsxs("button",{"data-testid":"button-push-toggle",onClick:async()=>{$.state==="subscribed"?await $.unsubscribe()&&i({title:"Уведомления отключены"}):await $.subscribe()?i({title:"Уведомления включены",description:"Вы будете получать оповещения о новых сообщениях"}):$.state==="denied"&&i({title:"Доступ запрещён",description:"Разрешите уведомления в настройках браузера",variant:"destructive"})},title:$.state==="subscribed"?"Отключить push-уведомления":"Включить push-уведомления",className:`flex items-center gap-1.5 px-3 py-1.5 rounded-lg text-xs font-medium border transition-colors ${$.state==="subscribed"?"bg-[hsl(var(--accent)/0.15)] border-[hsl(var(--accent)/0.5)] text-[hsl(var(--accent))]":"bg-transparent border-foreground
1/20 text-foreground/60 hover:border-foreground/40 hover:text-foreground/80"}`,children:[$.state==="subscribed"?e.jsx(Ys,{className:"h-3.5 w-3.5"}):e.jsx(Js,{className:"h-3.5 w-3.5"}),$.state==="subscribed"?"Уведомления вкл.":"Уведомления"]}),e.jsxs(T,{variant:"primary",size:"sm",onClick:()=>D(!q),"data-testid":"button-create-contract",children:[e.jsx(ae,{className:"h-4 w-4"}),"Новый договор"]})]})]}),q&&e.jsxs(x,{className:"p-5 border-[hsl(var(--accent)/0.2)]",children:[e.jsxs("div",{className:"flex items-center justify-between mb-4",children:[e.jsx("h3",{className:"font-semibold text-sm",children:"Создать договор"}),e.jsx("button",{onClick:()=>D(!1),className:"h-7 w-7 rounded-full border border-border grid place-items-center hover:bg-muted transition-colors",children:e.jsx(Y,{className:"h-3.5 w-3.5"})})]}),e.jsxs("div",{className:"space-y-3",children:[e.jsxs("div",{className:"grid grid-cols-1 sm:grid-cols-2 gap-3",children:[e.jsxs("div",{children:[e.jsx("label",{className:"text-xs text-muted-foreground mb-1 block",children:"Номер договора *"}),e.jsx("input",{type:"text",value:O,onChange:t=>A(t.target.value),placeholder:"Например: №2024-001",className:"w-full px-3 py-2 rounded-xl border border-border bg-background text-sm focus:outline-none focus:ring-1 focus:ring-[hsl(var(--accent))]","data-testid":"input-new-contract-number"})]}),e.jsxs("div",{children:[e.jsx("label",{className:"text-xs text-muted-foreground mb-1 block",children:"Адрес объекта"}),e.jsx("input",{type:"text",value:W,onChange:t=>ie(t.target.value),placeholder:"Адрес объекта",className:"w-full px-3 py-2 rounded-xl border border-border bg-background text-sm focus:outline-none focus:ring-1 focus:ring-[hsl(var(--accent))]","data-testid":"input-new-contract-address"})]})]}),e.jsxs("div",{children:[e.jsx("label",{className:"text-xs text-muted-foreground mb-1 block",children:"Название проекта *"}),e.jsx("input",{type:"text",value:B,onChange:t=>G(t.target.value),placeholder:"Например: Ремонт квартиры, 65 м²",className:"w-full px-3 py-2 rounded-xl border border-border bg-background text-sm focus:outline-none focus:ring-1 focus:ring-[hsl(var(--accent))]","data-testid":"input-new-contract-title"})]}),e.jsxs(T,{variant:"primary",size:"sm",onClick:()=>{if(!O.trim()||!B.trim()){i({title:"Заполните обязательные поля",variant:"destructive"});return}Ft.mutate({contractNumber:O.trim(),title:B.trim(),address:W.trim()||void 0})},disabled:Ft.isPending,"data-testid":"button-submit-contract",children:[Ft.isPending?e.jsx(V,{className:"h-4 w-4 animate-spin"}):e.jsx(ae,{className:"h-4 w-4"}),"Создать"]})]})]}),za?e.jsx("div",{className:"text-muted-foreground py-12 text-center",children:"Загрузка..."}):It.length===0?e.jsxs(x,{className:"p-8 text-center",children:[e.jsx(ke,{className:"h-10 w-10 mx-auto text-muted-foreground mb-3"}),e.jsx("p",{className:"text-lg font-medium mb-1",children:"Нет договоров"}),e.jsx("p",{className:"text-sm text-muted-foreground",children:"Создайте первый договор, чтобы клиент мог привязать его к своему кабинету"})]}):e.jsx("div",{className:"space-y-3",children:It.map(t=>e.jsx(x,{className:"p-5","data-testid":`card-contract-${t.id}`,children:e.jsxs("div",{className:"flex flex-col sm:flex-row sm:items-start justify-between gap-4",children:[e.jsxs("div",{className:"min-w-0 flex-1",children:[e.jsxs("div",{className:"flex items-center gap-2 flex-wrap mb-1",children:[e.jsxs("span",{className:"text-xs text-muted-foreground font-mono",children:["№ ",t.contractNumber]}),e.jsx("span",{className:"px-2 py-0.5 rounded-md text-[10px] font-semibold bg-[hsl(var(--accent)/0.1)] text-[hsl(var(--accent))] border border-[hsl(var(--accent)/0.2)]",children:t.currentStatus})]}),e.jsx("h3",{className:"font-semibold text-sm",children:t.title}),t.address&&e.jsx("p",{className:"text-xs text-muted-foreground mt-0.5",children:t.address}),t.clientName?e.jsxs("p",{className:"text-xs text-muted-foreground mt-1 flex items-center gap-1",children:[e.jsx(me,{className:"h-3 w-3"}),t.clientName," ",t.clientEmail?`(${t.clientEmail})`:""]}
1):e.jsx("p",{className:"text-xs text-muted-foreground/50 mt-1 italic",children:"Клиент не привязан"})]}),e.jsxs("div",{className:"flex flex-wrap gap-2 items-center",children:[e.jsx("select",{value:t.currentStatus,onChange:s=>Ka.mutate({id:t.id,currentStatus:s.target.value}),className:"px-2 py-1.5 rounded-xl border border-border bg-background text-xs focus:outline-none focus:ring-1 focus:ring-[hsl(var(--accent))] cursor-pointer","data-testid":`select-status-${t.id}`,children:fe.map(s=>e.jsx("option",{value:s,children:s},s))}),e.jsxs(T,{variant:"secondary",size:"sm",onClick:()=>F(t.id),"data-testid":`button-chat-${t.id}`,children:[e.jsx(Z,{className:"h-3.5 w-3.5"}),"Чат"]}),e.jsx("button",{onClick:()=>{confirm(`Удалить договор ${t.contractNumber}?`)&&Ba.mutate(t.id)},className:"h-8 w-8 flex items-center justify-center rounded-xl border border-border text-muted-foreground hover:text-red-400 hover:border-red-400/50 transition-colors","data-testid":`button-delete-contract-${t.id}`,children:e.jsx(re,{className:"h-3.5 w-3.5"})})]})]})},t.id))})]})}),u==="registry"&&j&&(()=>{const t=ot.filter(s=>{const n=ps.toLowerCase(),f=!n||[s.email,s.firstName,s.lastName,s.phone,s.promoCode,s.organizationName].some(oe=>oe?.toLowerCase().includes(n)),y=ct==="all"||s.role===ct;return f&&y});return e.jsxs("section",{"data-testid":"section-registry",children:[e.jsxs("div",{className:"flex flex-col sm:flex-row sm:items-center justify-between gap-4 mb-5",children:[e.jsxs("div",{children:[e.jsx("h2",{className:"text-lg font-semibold",children:"Реестр пользователей"}),e.jsxs("p",{className:"text-xs text-muted-foreground mt-0.5",children:[ot.length," записей"]})]}),e.jsxs("div",{className:"flex gap-2 flex-wrap",children:[e.jsxs("div",{className:"relative",children:[e.jsx(Qs,{className:"absolute left-2.5 top-1/2 -translate-y-1/2 h-3.5 w-3.5 text-muted-foreground"}),e.jsx("input",{type:"text",value:ps,onChange:s=>ya(s.target.value),placeholder:"Поиск...",className:"pl-8 pr-3 py-1.5 rounded-xl border border-border bg-background text-sm focus:outline-none focus:ring-1 focus:ring-[hsl(var(--accent))] placeholder:text-muted-foreground/50 w-48","data-testid":"input-registry-search"})]}),e.jsxs("select",{value:ct,onChange:s=>wa(s.target.value),className:"px-3 py-1.5 rounded-xl border border-border bg-background text-xs focus:outline-none focus:ring-1 focus:ring-[hsl(var(--accent))] cursor-pointer","data-testid":"select-registry-role",children:[e.jsx("option",{value:"all",children:"Все роли"}),e.jsx("option",{value:"admin",children:"Администратор"}),e.jsx("option",{value:"supervisor",children:"Супервайзер"}),e.jsx("option",{value:"employee",children:"Сотрудник"}),e.jsx("option",{value:"user",children:"Пользователь"})]})]})]}),ms?e.jsx("div",{className:"text-muted-foreground py-12 text-center",children:"Загрузка..."}):t.length===0?e.jsxs(x,{className:"p-8 text-center",children:[e.jsx(Ks,{className:"h-10 w-10 mx-auto text-muted-foreground mb-3"}),e.jsx("p",{className:"text-lg font-medium",children:"Ничего не найдено"}),e.jsx("p",{className:"text-sm text-muted-foreground",children:"Измените параметры поиска"})]}):e.jsx("div",{className:"overflow-x-auto rounded-2xl border border-border",children:e.jsxs("table",{className:"w-full text-sm",children:[e.jsx("thead",{children:e.jsxs("tr",{className:"border-b border-border bg-muted/30",children:[e.jsx("th",{className:"text-left px-4 py-3 text-xs text-muted-foreground font-semibold uppercase tracking-wider",children:"Имя"}),e.jsx("th",{className:"text-left px-4 py-3 text-xs text-muted-foreground font-semibold uppercase tracking-wider hidden sm:table-cell",children:"Email"}),e.jsx("th",{className:"text-left px-4 py-3 text-xs text-muted-foreground font-semibold uppercase tracking-wider hidden md:table-cell",children:"Телефон"}),e.jsx("th",{className:"text-left px-4 py-3 text-xs text-muted-foreground font-semibold uppercase tracking-wider",children:"Роль"}),e.jsx("th",{className:"text-left px-4 py-3 text-xs text-muted-foreground font-semibold uppercase tracking-wider hidden lg:table-cell",children:"Промокод"}),e.jsx("th",{className:"text-left px-4 py-3 text-xs text-muted-foreground font-semibold uppercase tracking-wider hidden lg:table-cell",children:"Зарегистрирован"})]})}),e.jsx("tbody",{children:t.map((s,n)=>e.jsxs("tr",{className:`border-b border-border last:border-0 hover:bg-muted/20 transition-colors ${n%2===0?"":"bg-muted/10"}`,"data-testid":`row-registry-${s.id}`,children:[e.jsx("td",{className:"px-4 py-3",children:e.jsxs("div",{className:"flex items-center gap-2.5",children:[e.jsx("div",{className:"h-7 w-7 rounded-full bg-muted flex items-center justify-center shrink-0 text-[10px] font-semibold text-muted-foreground",children:(s.firstName?.[0]||s.email?.[0]||"?").toUpperCase()}),e.jsx("span",{className:"font-medium truncate max-w-[120px]","data-testid":`text-registry-name-${s.id}
1`,children:[s.firstName,s.lastName].filter(Boolean).join(" ")||"—"})]})}),e.jsx("td",{className:"px-4 py-3 text-muted-foreground hidden sm:table-cell",children:e.jsxs("span",{className:"flex items-center gap-1.5",children:[e.jsx(er,{className:"h-3 w-3 shrink-0"}),e.jsx("span",{className:"truncate max-w-[160px]",children:s.email||"—"})]})}),e.jsx("td",{className:"px-4 py-3 text-muted-foreground hidden md:table-cell",children:s.phone?e.jsxs("span",{className:"flex items-center gap-1.5",children:[e.jsx(tr,{className:"h-3 w-3 shrink-0"}),s.phone]}):"—"}),e.jsx("td",{className:"px-4 py-3",children:e.jsx("span",{className:`px-1.5 py-0.5 rounded text-[10px] font-semibold uppercase tracking-wider ${s.role==="admin"?"bg-amber-500/15 text-amber-400 border border-amber-500/30":s.role==="supervisor"?"bg-blue-500/15 text-blue-400 border border-blue-500/30":s.role==="employee"?"bg-purple-500/15 text-purple-400 border border-purple-500/30":"bg-muted text-muted-foreground border border-border"}`,"data-testid":`badge-registry-role-${s.id}`,children:zt[s.role]||s.role})}),e.jsx("td",{className:"px-4 py-3 hidden lg:table-cell",children:s.promoCode?e.jsx("span",{className:"px-2 py-0.5 rounded bg-[hsl(var(--accent)/0.1)] text-[hsl(var(--accent))] text-[10px] font-semibold font-mono",children:s.promoCode}):s.referralPromoCode?e.jsxs("span",{className:"text-xs text-muted-foreground",children:["→ ",s.referralPromoCode]}):"—"}),e.jsx("td",{className:"px-4 py-3 text-xs text-muted-foreground hidden lg:table-cell",children:De(s.createdAt)})]},s.id))})]})})]})})(),u==="workChats"&&j&&o&&e.jsx(Nr,{currentUserId:o.id}),u==="content"&&j&&(()=>{const t=[...xs.map(n=>({...n,_type:"content"})),...us.map(n=>({...n,_type:"rss"}))].sort((n,f)=>new Date(f.publishedAt).getTime()-new Date(n.publishedAt).getTime()),s=mt==="content"?t.filter(n=>n._type==="content"):mt==="rss"?t.filter(n=>n._type==="rss"):t;return e.jsxs("section",{"data-testid":"section-content",children:[e.jsxs("div",{className:"flex flex-col sm:flex-row sm:items-center justify-between gap-4 mb-5",children:[e.jsxs("div",{children:[e.jsx("h2",{className:"text-lg font-semibold",children:"Управление контентом"}),e.jsxs("p",{className:"text-xs text-muted-foreground mt-0.5",children:[xs.length," статей · ",us.length," RSS-постов"]})]}),e.jsx("div",{className:"flex gap-2",children:["all","content","rss"].map(n=>e.jsx("button",{onClick:()=>ka(n),className:`px-3 py-1.5 rounded-xl text-xs font-medium border transition-colors ${mt===n?"bg-[hsl(var(--accent))] text-black border-[hsl(var(--accent))]":"border-border text-muted-foreground hover:text-foreground"}`,"data-testid":`filter-content-${n}`,children:n==="all"?"Все":n==="content"?"Статьи":"RSS"},n))})]}),e.jsxs(x,{className:"p-4 mb-5","data-testid":"section-reels-admin",children:[e.jsxs("div",{className:"flex items-center gap-2 mb-3",children:[e.jsx(ar,{className:"h-4 w-4 text-[hsl(var(--accent))]"}),e.jsx("h3",{className:"font-semibold text-sm",children:"Reels — вертикальные видео"}),e.jsx("span",{className:"text-xs text-muted-foreground",children:xt.length})]}),e.jsxs("div",{className:"grid gap-2 sm:grid-cols-2",children:[e.jsxs("label",{className:"flex flex-col gap-1 text-xs",children:[e.jsx("span",{className:"text-muted-foreground",children:"Видеофайл *"}),e.jsx("input",{type:"file",accept:"video/*",onChange:n=>Ns(n.target.files?.[0]||null),className:"text-xs file:mr-2 file:rounded-lg file:border-0 file:bg-[hsl(var(--accent))] file:px-3 file:py-1.5 file:text-black file:text-xs","data-testid":"input-reel-video"})]}),e.jsxs("label",{className:"flex flex-col gap-1 text-xs",children:[e.jsx("span",{className:"text-muted-foreground",children:"Обложка (необязательно)"}),e.jsx("input",{type:"file",accept:"image/*",onChange:n=>ws(n.target.files?.[0]||null),className:"text-xs file:mr-2 file:rounded-lg file:border file:border-border file:bg-transparent file:px-3 file:py-1.5 file:text-foreground file:text-xs","data-testid":"input-reel-poster"})]})]}),e.jsxs("div",{className:"flex flex-col sm:flex-row gap-2 mt-2",children:[e.jsx("input",{type:"text",value:ut,onChange:n=>vs(n.target.value),placeholder:"Подпись (необязательно)",className:"flex-1 rounded-xl border border-border bg-transparent px-3 py-2 text-sm","data-testid":"input-reel-title"}),e.jsx("button",{onClick:()=>gt.mutate(),disabled:!ht||gt.isPending,className:"px-4 py-2 rounded-xl text-sm font-medium bg-[hsl(var(--accent))] text-black disabled:opacity-50 transition-opacity","data-testid":"button-upload-reel",children:gt.isPending?"Загрузка...":"Загрузить"})]}),xt.length>0&&e.jsx("div",{className:"flex gap-3 overflow-x-auto mt-4 pb-1",children:xt.map(n=>e.jsxs("div",{className:"relative w-[90px] shrink-0","data-testid":`card-admin-reel-${n.id}`,children:[e.jsx("video",{src:n.videoUrl,poster:n.posterUrl||void 0,muted:!0,preload:"metadata",className:"aspect-[9/16] w-full rounded-lg object-cover border border-border bg-black/40"}),Sa===n.id?e.jsxs("div",{className:"absolute inset-0 flex flex-col items-center justify-center gap-1 rounded-lg bg-black/70 p-1",children:[e.jsx("button",{onClick:()=>ks.mutate(n.id),disabled:ks.isPending,className:"px-2 py-1 rounded text-[10px] bg-red-500/80 text-white","data-testid":`button-confirm-delete-reel-${n.id}`,children:"Удалить"}),e.jsx("button",{onClick:()=>pt(null),className:"px-2 py-1 rounded text-[10px] border border-white/30 text-white",children:"Отмена"})]}):e.jsx("button",{onClick:()=>pt(n.id),className:"absolute right-1 top-1 h-6 w-6 flex items-center justify-center rounded-lg bg-black/60 text-white hover:text-red-400","data-testid":`button-delete-reel-${n.id}`,children:e.jsx(re,{className:"h-3 w-3"})})]},n.id))})]}),ba||ja||Ca?e.jsx("div",{className:"text-muted-foreground py-12 text-center",children:"Загрузка..."}):s.length===0?e.jsxs(x,{className:"p-8 text-center",children:[e.jsx(Zs,{className:"h-10 w-10 mx-auto text-muted-foreground mb-3"}),e.jsx("p",{className:"text-lg font-medium",children:"Контент не найден"})]}):e.jsx("div",{className:"space-y-3",children:s.map(n=>{const f=n._type==="content",y=f?n.coverUrl:n.imageUrl,oe=f?null:n.author,a=f?n.type:n.category,w={id:n.id,type:n._type},Dt=gs?.id===n.id&&gs?.type===n._type;return e.jsx(x,{className:"p-4","data-testid":`card-content-${n._type}-${n.id}`,children:e.jsxs("div",{className:"flex items-start gap-4",children:[y&&e.jsx("img",{src:y,alt:n.title,className:"h-14 w-20 rounded-xl object-cover shrink-0 hidden sm:block border border-border"}),e.jsxs("div",{className:"flex-1 min-w-0",children:[e.jsxs("div",{className:"flex items-center gap-2 flex-wrap mb-1",children:[e.jsx("span",{className:`px-1.5 py-0.5 rounded text-[10px] font-semibold uppercase tracking-wider ${f?"bg-blue-500/15 text-blue-400 border border-blue-500/30":"bg-orange-500/15 text-orange-400 border border-orange-500/30"}`,children:f?a:"RSS"}),oe&&e.jsx("span",{className:"text-xs text-muted-foreground",children:oe})]}),e.jsx("h3",{className:"font-medium text-sm leading-snug truncate","data-testid":`text-content-title-${n._type}-${n.id}`,children:n.title}),n.excerpt&&e.jsx("p",{className:"text-xs text-muted-foreground mt-1 line-clamp-1",children:n.excerpt}),e.jsx("p",{className:"text-xs text-muted-foreground mt-1",children:De(n.publishedAt)})]}),e.jsx("div",{className:"flex flex-col gap-2 shrink-0",children:Dt?e.jsxs("div",{className:"flex flex-col gap-1",children:[e.jsx("p",{className:"text-xs text-red-400 font-medium",children:"Удалить?"}),e.jsxs("div",{className:"flex gap-1.5",children:[e.jsx("button",{onClick:()=>{f?bs.mutate(n.id):fs.mutate(n.id)},disabled:bs.isPending||fs.isPending,className:"px-2.5 py-1 rounded-lg text-xs bg-red-500/15 text-red-400 border border-red-500/30 hover:bg-red-500/25 transition-colors","data-testid":`button-confirm-delete-content-${n._type}-${n.id}`,children:"Да"}),e.jsx("button",{onClick:()=>Be(null),className:"px-2.5 py-1 rounded-lg text-xs border border-border text-muted-foreground hover:text-foreground transition-colors",children:"Нет"})]})]}):e.jsx("button",{onClick:()=>Be(w),className:"h-8 w-8 flex items-center justify-center rounded-xl border border-border text-muted-foreground hover:text-red-400 hover:border-red-400/50 transition-colors","data-testid":`button-delete-content-${n._type}-${n.id}`,children:e.jsx(re,{className:"h-3.5 w-3.5"})})})]})},`${n._type}-${n.id}`)})})]})})(),u==="market"&&j&&(()=>{const t=()=>{se({categoryId:we[0]?.id?.toString()||"",section:"catalog",name:"",brand:"",description:"",price:"",unit:"шт.",inStock:!0,featured:!1,imageUrl:""}),Te(null),Ne({open:!0})},s=a=>{se({categoryId:String(a.categoryId),section:a.section,name:a.name,brand:a.brand||"",description:a.description||"",price:String(a.price),unit:a.unit,inStock:a.inStock,featured:a.featured,imageUrl:a.imageUrl||""}),Te(null),Ne({open:!0,product:a})},n=()=>{const a=new FormData;a.append("categoryId",C.categoryId),a.append("section",C.section),a.append("name",C.name),a.append("brand",C.brand),a.append("description",C.description),a.append("price",C.price),a.append("unit",C.unit),a.append("inStock",String(C.inStock)),a.append("featured",String(C.featured)),ce?a.append("image",ce):C.imageUrl&&a.append("imageUrl",C.imageUrl),Fe.product?Ct.mutate({id:Fe.product.id,data:a}):kt.mutate(a)},f=()=>{be({name:"",slug:"",icon:"Package",sortOrder:"0"}),ye({open:!0})},y=a=>{be({name:a.name,slug:a.slug,icon:a.icon,sortOrder:String(a.sortOrder)}),ye({open:!0,category:a})},oe=()=>{Le.category?Et.mutate({id:Le.category.id,data:{...ue,sortOrder:parseInt(ue.sortOrder)}}):St.mutate({...ue,sortOrder:parseInt(ue.sortOrder)})};return e.jsxs("section",{"data-testid":"section-market-admin",children:[Fe.open&&e.jsx("div",{className:"fixed inset-0 z-50 bg-black/60 backdrop-blur-sm flex items-center justify-center p-4",children:e.jsxs(x,{className:"w-full max-w-lg max-h-[90vh] overflow-y-auto p-6",children:[e.jsxs("div",{className:"flex items-center justify-between mb-5",children:[e.jsx("h3",{className:"text-lg font-semibold",children:Fe.product?"Редактировать товар":"Добавить товар"}),e.jsx("button",{onClick:()=>Ne({open:!1}),className:"text-muted-foreground hover:text-foreground",children:e.jsx(Y,{className:"h-5 w-5"})})]}),e.jsxs("div",{className:"space-y-3",children:[e.jsxs("div",{className:"grid grid-cols-2 gap-3",children:[e.jsxs("div",{children:[e.jsx("label",{className:"text-xs text-muted-foreground mb-1 block",children:"Раздел"}),e.jsxs("select",{value:C.section,onChange:a=>se(w=>({...w,section:a.target.value})),className:"w-full bg-background border border-border rounded-xl px-3 py-2 text-sm","data-testid":"select-product-section",children:[e.jsx("option",{value:"catalog",children:"Каталог"}),e.jsx("option",{value:"moodboard",children:"Мудборд"})]})]}),e.jsxs("div",{children:[e.jsx("label",{className:"text-xs text-muted-foreground mb-1 block",children:"Категория"}),e.jsxs("select",{value:C.categoryId,onChange:a=>se(w=>({...w,categoryId:a.target.value})),className:"w-full bg-background border border-border rounded-xl px-3 py-2 text-sm","data-testid":"select-product-category",children:[e.jsx("option",{value:"",children:"— выберите —"}),we.map(a=>e.jsx("option",{value:a.id,children:a.name},a.id))]})]})]}),e.jsxs("div",{children:[e.jsx("label",{className:"text-xs text-muted-foreground mb-1 block",children:"Название *"}),e.jsx("input",{value:C.name,onChange:a=>se(w=>({...w,name:a.target.value})),className:"w-full bg-background border border-border rounded-xl px-3 py-2 text-sm",placeholder:"НаÐ
1·Ð²Ð°Ð½Ð¸Ðµ товара","data-testid":"input-product-name"})]}),e.jsxs("div",{className:"grid grid-cols-2 gap-3",children:[e.jsxs("div",{children:[e.jsx("label",{className:"text-xs text-muted-foreground mb-1 block",children:"Бренд"}),e.jsx("input",{value:C.brand,onChange:a=>se(w=>({...w,brand:a.target.value})),className:"w-full bg-background border border-border rounded-xl px-3 py-2 text-sm",placeholder:"Например, IKEA","data-testid":"input-product-brand"})]}),e.jsxs("div",{children:[e.jsx("label",{className:"text-xs text-muted-foreground mb-1 block",children:"Единица"}),e.jsx("input",{value:C.unit,onChange:a=>se(w=>({...w,unit:a.target.value})),className:"w-full bg-background border border-border rounded-xl px-3 py-2 text-sm",placeholder:"шт.","data-testid":"input-product-unit"})]})]}),e.jsxs("div",{children:[e.jsx("label",{className:"text-xs text-muted-foreground mb-1 block",children:"Цена (₽) *"}),e.jsx("input",{type:"number",value:C.price,onChange:a=>se(w=>({...w,price:a.target.value})),className:"w-full bg-background border border-border rounded-xl px-3 py-2 text-sm",placeholder:"0","data-testid":"input-product-price"})]}),e.jsxs("div",{children:[e.jsx("label",{className:"text-xs text-muted-foreground mb-1 block",children:"Описание"}),e.jsx("textarea",{value:C.description,onChange:a=>se(w=>({...w,description:a.target.value})),className:"w-full bg-background border border-border rounded-xl px-3 py-2 text-sm resize-none",rows:2,placeholder:"Краткое описание","data-testid":"input-product-description"})]}),e.jsxs("div",{children:[e.jsx("label",{className:"text-xs text-muted-foreground mb-1 block",children:"Изображение"}),e.jsxs("div",{className:"flex gap-2 items-center",children:[e.jsx("input",{ref:es,type:"file",accept:"image/*",className:"hidden",onChange:a=>Te(a.target.files?.[0]||null)}),e.jsxs("button",{type:"button",onClick:()=>es.current?.click(),className:"flex items-center gap-2 px-3 py-2 rounded-xl border border-border text-sm text-muted-foreground hover:text-foreground transition-colors","data-testid":"button-upload-image",children:[e.jsx(Gs,{className:"h-4 w-4"}),ce?ce.name:"Загрузить файл"]}),(C.imageUrl||ce)&&!ce&&e.jsx("img",{src:C.imageUrl,className:"h-10 w-10 rounded-lg object-cover border border-border",alt:""}),ce&&e.jsx("img",{src:URL.createObjectURL(ce),className:"h-10 w-10 rounded-lg object-cover border border-border",alt:""})]}),!ce&&e.jsx("input",{value:C.imageUrl,onChange:a=>se(w=>({...w,imageUrl:a.target.value})),className:"w-full bg-background border border-border rounded-xl px-3 py-2 text-xs mt-2 text-muted-foreground",placeholder:"или вставьте URL изображения","data-testid":"input-product-image-url"})]}),e.jsxs("div",{className:"flex gap-4",children:[e.jsxs("label",{className:"flex items-center gap-2 cursor-pointer select-none","data-testid":"toggle-product-instock",children:[e.jsx("button",{type:"button",onClick:()=>se(a=>({...a,inStock:!a.inStock})),className:`w-9 h-5 rounded-full transition-colors relative ${C.inStock?"bg-[hsl(var(--accent))]":"bg-muted"}`,children:e.jsx("span",{className:`absolute top-0.5 left-0.5 w-4 h-4 rounded-full bg-white transition-transform ${C.inStock?"translate-x-4":"translate-x-0"}`})}),e.jsx("span",{className:"text-sm",children:"В наличии"})]}),e.jsxs("label",{className:"flex items-center gap-2 cursor-pointer select-none","data-testid":"toggle-product-featured",children:[e.jsx("button",{type:"button",onClick:()=>se(a=>({...a,featured:!a.featured})),className:`w-9 h-5 rounded-full transition-colors relative ${C.featured?"bg-[hsl(var(--accent))]":"bg-muted"}`,children:e.jsx("span",{className:`absolute top-0.5 left-0.5 w-4 h-4 rounded-full bg-white transition-transform ${C.featured?"translate-x-4":"translate-x-0"}`})}),e.jsx("span",{className:"text-sm",children:"Рекомендуемый"})]})]})]}),e.jsxs("div",{className:"flex gap-2 mt-5",children:[e.jsx("button",{onClick:n,disabled:kt.isPending||Ct.isPending,className:"flex-1 py-2.5 rounded-xl bg-[hsl(var(--accent))] text-black text-sm font-semibold hover:opacity-90 transition-opacity disabled:opacity-50","data-testid":"button-submit-product",children:kt.isPending||Ct.isPending?"Сохранение...":Fe.product?"Сохранить":"Добавить"}),e.jsx("button",{onClick:()=>Ne({open:!1}),className:"px-4 py-2.5 rounded-xl border border-border text-sm text-muted-foreground hover:text-foreground transition-colors","data-testid":"button-cancel-product",children:"Отмена"})]})]})}),Le.open&&e.jsx("div",{className:"fixed inset-0 z-50 bg-black/60 backdrop-blur-sm flex items-center justify-center p-4",children:e.jsxs(x,{className:"w-full max-w-sm p-6",children:[e.jsxs("div",{className:"flex items-center justify-between mb-5",children:[e.jsx("h3",{className:"text-lg font-semibold",children:Le.category?"Редактировать категорию":"Добавить категорию"}),e.jsx("button",{onClick:()=>ye({open:!1}),className:"text-muted-foreground hover:text-foreground",children:e.jsx(Y,{className:"h-5 w-5"})})]}),e.jsxs("div",{className:"space-y-3",children:[e.jsxs("div",{children:[e.jsx("label",{className:"text-xs text-muted-foreground mb-1 block",children:"Название *"}),e.jsx("input",{value:ue.name,onChange:a=>be(w=>({...w,name:a.target.value})),className:"w-full bg-background border border-border rounded-xl px-3 py-2 text-sm",placeholder:"Напр. Напольные покрытия","data-testid":"input-category-name"})]}),e.jsxs("div",{children:[e.jsx("label",{className:"text-xs text-muted-foreground mb-1 block",children:"Slug (URL) *"}),e.jsx("input",{value:ue.slug,onChange:a=>be(w=>({...w,slug:a.target.value})),className:"w-full bg-background border border-border rounded-xl px-3 py-2 text-sm",placeholder:"floors","data-testid":"input-category-slug"})]}),e.jsxs("div",{className:"grid grid-cols-2 gap-3",children:[e.jsxs("div",{children:[e.jsx("label",{className:"text-xs text-muted-foreground mb-1 block",children:"Иконка (lucide)"}),e.jsx("input",{value:ue.icon,onChange:a=>be(w=>({...w,icon:a.target.value})),className:"w-full bg-background border border-border rounded-xl px-3 py-2 text-sm",placeholder:"Package","data-testid":"input-category-icon"})]}),e.jsxs("div",{children:[e.jsx("label",{className:"text-xs text-muted-foreground mb-1 block",children:"Порядок"}),e.jsx("input",{type:"number",value:ue.sortOrder,onChange:a=>be(w=>({...w,sortOrder:a.target.value})),className:"w-full bg-background border border-border rounded-xl px-3 py-2 text-sm","data-testid":"input-category-sort"})]})]})]}),e.jsxs("div",{className:"flex gap-2 mt-5",children:[e.jsx("button",{onClick:oe,disabled:St.isPending||Et.isPending,className:"flex-1 py-2.5 rounded-xl bg-[hsl(var(--accent))] text-black text-sm font-semibold hover:opacity-90 disabled:opacity-50 transition-opacity","data-testid":"button-submit-category",children:St.isPending||Et.isPending?"Сохранение...":Le.category?"Сохранить":"Добавить"}),e.jsx("button",{onClick:()=>ye({open:!1}),className:"px-4 py-2.5 rounded-xl border border-border text-sm text-muted-foreground hover:text-foreground transition-colors","data-testid":"button-cancel-category",children:"Отмена"})]})]})}),e.jsxs("div",{className:"flex flex-col sm:flex-row sm:items-center justify-between gap-4 mb-5",children:[e.jsxs("div",{children:[e.jsx("h2",{className:"text-lg font-semibold",children:"Управление маркетом"}),e.jsxs("p",{className:"text-xs text-muted-foreground mt-0.5",children:[we.length," категорий · ",Qe.length," товаров"]})]}),e.jsxs("div",{className:"flex gap-2 flex-wrap",children:[e.jsxs("button",{onClick:Da,disabled:it,className:"flex items-center gap-1.5 px-3 py-1.5 rounded-xl text-xs font-medium border border-border text-muted-foreground hover:text-foreground hover:border-[hsl(var(--accent))]/50 transition-colors disabled:opacity-50","data-testid":"button-seed-moodboard",title:"Заполнить мудборд фотографиями интерьеров из Pixabay (требуется PIXABAY_API_KEY)",children:[it?e.jsx(Vs,{className:"h-3.5 w-3.5 animate-spin"}):e.jsx(Ht,{className:"h-3.5 w-3.5"}),it?"Заполняем...":"Заполнить мудборд"]}),["products","categories"].map(a=>e.jsx("button",{onClick:()=>oa(a),className:`px-3 py-1.5 rounded-xl text-xs font-medium border transition-colors ${at===a?"bg-[hsl(var(--accent))] text-black border-[hsl(var(--accent))]":"border-border text-muted-foreground hover:text-foreground"}`,"data-testid":`tab-market-${a}`,children:a==="products"?"Товары":"Категории"},a))]})]}),at==="products"&&e.jsxs(e.Fragment,{children:[e.jsxs("div",{className:"flex flex-wrap gap-2 mb-4",children:[e.jsx("div",{className:"flex gap-1",children:["all","catalog","moodboard"].map(a=>e.jsx("button",{onClick:()=>ca(a),className:`px-3 py-1.5 rounded-xl text-xs font-medium border transition-colors ${_e===a?"bg-[hsl(var(--accent))] text-black border-[hsl(var(--accent))]":"border-border text-muted-foreground hover:text-foreground"}`,"data-testid":`filter-market-section-${a}`,children:a==="all"?"Все":a==="catalog"?"Каталог":"Мудборд"},a))}),e.jsxs("select",{value:ze,onChange:a=>ma(a.target.value),className:"bg-background border border-border rounded-xl px-3 py-1.5 text-xs text-muted-foreground","data-testid":"filter-market-category",children:[e.jsx("option",{value:"all",children:"Все категории"}),we.map(a=>e.jsx("option",{value:a.id,children:a.name},a.id))]}),e.jsxs("div",{className:"relative flex-1 min-w-[180px]",children:[e.jsx(Qs,{className:"absolute left-3 top-1/2 -translate-y-1/2 h-3.5 w-3.5 text-muted-foreground"}),e.jsx("input",{value:Ke,onChange:a=>xa(a.target.value),className:"w-full bg-background border border-border rounded-xl pl-9 pr-3 py-1.5 text-xs",placeholder:"Поиск по Ð
1½Ð°Ð·Ð²Ð°Ð½Ð¸ÑŽ...","data-testid":"input-market-search"})]}),e.jsxs("button",{onClick:t,className:"flex items-center gap-1.5 px-3 py-1.5 rounded-xl bg-[hsl(var(--accent))] text-black text-xs font-semibold hover:opacity-90 transition-opacity whitespace-nowrap","data-testid":"button-add-product",children:[e.jsx(ae,{className:"h-3.5 w-3.5"})," Добавить товар"]})]}),$a?e.jsx("div",{className:"text-center py-12 text-muted-foreground",children:"Загрузка..."}):Qe.length===0?e.jsxs(x,{className:"p-8 text-center",children:[e.jsx(Ye,{className:"h-10 w-10 mx-auto text-muted-foreground mb-3"}),e.jsx("p",{className:"text-lg font-medium",children:"Товары не найдены"})]}):e.jsx("div",{className:"space-y-2",children:Qe.map(a=>e.jsx(x,{className:"p-3","data-testid":`card-market-product-${a.id}`,children:e.jsxs("div",{className:"flex items-center gap-3",children:[a.imageUrl?e.jsx("img",{src:a.imageUrl,alt:a.name,className:"h-12 w-12 rounded-xl object-cover flex-shrink-0 border border-border"}):e.jsx("div",{className:"h-12 w-12 rounded-xl bg-muted flex items-center justify-center flex-shrink-0 border border-border",children:e.jsx(Ye,{className:"h-5 w-5 text-muted-foreground"})}),e.jsxs("div",{className:"flex-1 min-w-0",children:[e.jsxs("div",{className:"flex items-center gap-2 flex-wrap",children:[e.jsx("span",{className:"font-medium text-sm truncate",children:a.name}),a.featured&&e.jsx(ir,{className:"h-3.5 w-3.5 text-yellow-400 flex-shrink-0"}),e.jsx("span",{className:`px-1.5 py-0.5 rounded text-[10px] font-semibold ${a.section==="moodboard"?"bg-violet-500/15 text-violet-400":"bg-blue-500/15 text-blue-400"}`,children:a.section==="moodboard"?"Мудборд":"Каталог"}),!a.inStock&&e.jsx("span",{className:"px-1.5 py-0.5 rounded text-[10px] font-semibold bg-red-500/15 text-red-400",children:"Нет в наличии"})]}),e.jsxs("div",{className:"flex items-center gap-3 mt-0.5",children:[e.jsx("span",{className:"text-xs text-muted-foreground",children:a.categoryName||"—"}),a.brand&&e.jsx("span",{className:"text-xs text-muted-foreground",children:a.brand}),e.jsxs("span",{className:"text-xs font-semibold text-[hsl(var(--accent))]",children:[a.price.toLocaleString("ru")," ₽ / ",a.unit]})]})]}),e.jsxs("div",{className:"flex items-center gap-1 flex-shrink-0",children:[e.jsx("button",{onClick:()=>s(a),className:"h-8 w-8 flex items-center justify-center rounded-xl border border-border text-muted-foreground hover:text-foreground transition-colors","data-testid":`button-edit-product-${a.id}`,children:e.jsx(Ze,{className:"h-3.5 w-3.5"})}),ua===a.id?e.jsxs("div",{className:"flex items-center gap-1",children:[e.jsx("button",{onClick:()=>Es.mutate(a.id),disabled:Es.isPending,className:"px-2.5 py-1 rounded-lg text-xs bg-red-500 text-white hover:bg-red-600 transition-colors disabled:opacity-50","data-testid":`button-confirm-delete-product-${a.id}`,children:"Да"}),e.jsx("button",{onClick:()=>rt(null),className:"px-2.5 py-1 rounded-lg text-xs border border-border text-muted-foreground hover:text-foreground transition-colors",children:"Нет"})]}):e.jsx("button",{onClick:()=>rt(a.id),className:"h-8 w-8 flex items-center justify-center rounded-xl border border-border text-muted-foreground hover:text-red-400 hover:border-red-400/50 transition-colors","data-testid":`button-delete-product-${a.id}`,children:e.jsx(re,{className:"h-3.5 w-3.5"})})]})]})},a.id))})]}),at==="categories"&&e.jsxs(e.Fragment,{children:[e.jsx("div",{className:"flex justify-end mb-4",children:e.jsxs("button",{onClick:f,className:"flex items-center gap-1.5 px-3 py-1.5 rounded-xl bg-[hsl(var(--accent))] text-black text-xs font-semibold hover:opacity-90 transition-opacity","data-testid":"button-add-category",children:[e.jsx(ae,{className:"h-3.5 w-3.5"})," Добавить категорию"]})}),Ea?e.jsx("div",{className:"text-center py-12 text-muted-foreground",children:"Загрузка..."}):we.length===0?e.jsxs(x,{className:"p-8 text-center",children:[e.jsx(Ye,{className:"h-10 w-10 mx-auto text-muted-foreground mb-3"}),e.jsx("p",{className:"text-lg font-medium",children:"Категории не найдены"})]}):e.jsx("div",{className:"space-y-2",children:we.map(a=>{const w=Qe.filter(Dt=>Dt.categoryId===a.id).length;return e.jsx(x,{className:`p-3 transition-opacity ${a.enabled?"":"opacity-60"}`,"data-testid":`card-market-category-${a.id}`,children:e.jsxs("div",{className:"flex items-center gap-3",children:[e.jsx("div",{className:`h-9 w-9 rounded-xl flex items-center justify-center flex-shrink-0 border transition-colors ${a.enabled?"bg-[hsl(var(--accent)/0.1)] border-[hsl(var(--accent)/0.2)]":"bg-muted border-border"}`,children:e.jsx(Ye,{className:`h-4 w-4 ${a.enabled?"text-[hsl(var(--accent))]":"text-muted-foreground"}`})}),e.jsxs("div",{className:"flex-1 min-w-0",children:[e.jsxs("div",{className:"flex items-center gap-2 flex-wrap",children:[e.jsx("span",{className:`font-medium text-sm ${a.enabled?"":"text-muted-foreground"}`,children:a.name}),e.jsxs("span",{className:"text-xs text-muted-foreground font-mono",children:["/",a.slug]}),!a.enabled&&e.jsx("span",{className:"px-1.5 py-0.5 rounded text-[10px] font-semibold bg-red-500/15 text-red-400",children:"Скрыта"})]}),e.jsxs("div",{className:"flex items-center gap-2 mt-0.5",children:[e.jsxs("span",{className:"text-xs text-muted-foreground",children:["Иконка: ",a.icon]}),e.jsx("span",{className:"text-xs text-muted-foreground",children:"·"}),e.jsxs("span",{className:"text-xs text-muted-foreground",children:["Порядок: ",a.sortOrder]}),e.jsx("span",{className:"text-xs text-muted-foreground",children:"·"}),e.jsxs("span",{className:"text-xs text-[hsl(var(--accent))]",children:[w," товаров"]})]})]}),e.jsxs("div",{className:"flex items-center gap-1 flex-shrink-0",children:[e.jsxs("button",{onClick:()=>Ps.mutate(a.id),disabled:Ps.isPending,title:a.enabled?"Скрыть категорию":"Показать категорию",className:`h-8 px-2.5 flex items-center gap-1.5 rounded-xl border text-xs font-medium transition-colors disabled:opacity-50 ${a.enabled?"border-[hsl(var(--accent)/0.4)] text-[hsl(var(--accent))] hover:bg-[hsl(var(--accent)/0.1)]":"border-red-400/40 text-red-400 hover:bg-red-400/10"}`,"data-testid":`button-toggle-category-${a.id}`,children:[a.enabled?e.jsx(ur,{className:"h-3.5 w-3.5"}):e.jsx(xr,{className:"h-3.5 w-3.5"}),a.enabled?"Вкл":"Выкл"]}),e.jsx("button",{onClick:()=>y(a),className:"h-8 w-8 flex items-center justify-center rounded-xl border border-border text-muted-foreground hover:text-foreground transition-colors","data-testid":`button-edit-category-${a.id}`,children:e.jsx(Ze,{className:"h-3.5 w-3.5"})}),ha===a.id?e.jsxs("div",{className:"flex items-center gap-1",children:[e.jsx("button",{onClick:()=>$s.mutate(a.id),disabled:$s.isPending,className:"px-2.5 py-1 rounded-lg text-xs bg-red-500 text-white hover:bg-red-600 disabled:opacity-50 transition-colors","data-testid":`button-confirm-delete-category-${a.id}`,children:"Да"}),e.jsx("button",{onClick:()=>nt(null),className:"px-2.5 py-1 rounded-lg text-xs border border-border text-muted-foreground hover:text-foreground transition-colors",children:"Нет"})]}):e.jsx("button",{onClick:()=>nt(a.id),className:"h-8 w-8 flex items-center justify-center rounded-xl border border-border text-muted-foreground hover:text-red-400 hover:border-red-400/50 transition-colors","data-testid":`button-delete-category-${a.id}`,children:e.jsx(re,{className:"h-3.5 w-3.5"})})]})]})},a.id)})})]})]})})(),u==="backup"&&j&&e.jsxs("section",{className:"max-w-2xl mx-auto py-8 px-4 space-y-6",children:[e.jsxs("div",{className:"flex items-center gap-3 mb-2",children:[e.jsx(Ws,{className:"h-6 w-6 text-[hsl(var(--accent))]"}),e.jsx("h2",{className:"text-xl font-semibold",children:"Резервное копирование"})]}),e.jsx("p",{className:"text-sm text-muted-foreground",children:"Экспортируйте все учётные записи, договоры, переписки и прикреплённые файлы в один файл. Храните его у себя и загружайте обратно при необходимости — данные восстановятся полностью."}),e.jsxs(x,{className:"p-6 space-y-4",children:[e.jsxs("div",{className:"flex items-center gap-2 mb-1",children:[e.jsx(Re,{className:"h-5 w-5 text-[hsl(var(--accent))]"}),e.jsx("h3",{className:"font-medium",children:"Скачать резервную копию"})]}),e.jsxs("p",{className:"text-sm text-muted-foreground",children:["Создаёт файл ",e.jsx("code",{className:"bg-muted px-1 rounded text-xs",children:".json"})," со всеми пользователями, договорами, сообщениями, чатами и вложениями (закодированы в base64)."]}),e.jsxs("div",{className:"text-xs text-muted-foreground space-y-1",children:[e.jsx("div",{className:"font-medium text-foreground mb-1",children:"Что входит в бэкап:"}),e.jsx("div",{children:"✓ Все пользователи (логины, пароли, роли)"}),e.jsx("div",{children:"✓ Договоры и история статусов"}),e.jsx("div",{children:"✓ Переписка по договорам и рабочие чаты"}),e.jsx("div",{children:"✓ Прикреплённые файлы (фото, документы)"}),e.jsx("div",{children:"✓ Сметы, акции, беседы AI-консультанта"})]}),e.jsxs("button",{"data-testid":"button-download-backup",disabled:lt,onClick:async()=>{ss(!0);try{const t=await fetch("/api/admin/backup",{credentials:"include"});if(!t.ok)throw new Error("Ошибка сервера");const s=await t.blob(),f=(t.headers.get("Content-Disposition")||"").match(/filename="([^"]+)"/)?.[1]||`mart_backup_${new Date().toISOString().slice(0,10)}.json`,y=URL.createObjectURL(s),oe=document.createElement("a");oe.href=y,oe.download=f,oe.click(),URL.revokeObjectURL(y),i({title:"Бэкап скачан",description:f})}catch(t){i({title:"Ошибка",description:t.message,variant:"destructive"})}finally{ss(!1)}},className:"flex items-center gap-2 px-5 py-2.5 rounded-xl font-medium text-sm transition-colors bg-[hsl(var(--accent))] text-black hover:bg-[hsl(var(--accent)/0.85)] disabled:opacity-60",children:[lt?e.jsx(V,{className:"h-4 w-4 animate-spin"}):e.jsx(Re,{className:"h-4 w-4"}),lt?"Создаю бэкап...":"Скачать бэкап"]})]}),e.jsxs(x,{className:"p-6 space-y-4",children:[e.jsxs("div",{className:"flex items-center gap-2 mb-1",children:[e.jsx(Vs,{className:"h-5 w-5 text-blue-400"}),e.jsx("h3",{className:"font-medium",children:"Восстановить из файла"})]}),e.jsx("p",{className:"text-sm text-muted-foreground",children:"Загрузите ранее скачанный файл бэкапа. Существующие данные будут обновлены, новые — добавлены. Ничего не удаляется."}),e.jsxs("div",{className:"p-3 rounded-xl border border-yellow-500/30 bg-yellow-500/5 text-xs text-yellow-400 flex gap-2",children:[e.jsx(hr,{className:"h-4 w-4 shrink-0 mt-0.5"}),e.jsx("span",{children:"Восстановление перезапишет данные пользователей и сообщений из файла бэкапа. Существующие записи, которых нет в файле, останутся нетронутыми."})]}),e.jsx("input",{ref:ds,type:"file",accept:".json,application/json",className:"hidden","data-testid":"input-restore-backup",onChange:async t=>{const s=t.target.files?.[0];if(s){t.target.value="",as(!0),ns(null),ls(null);try{const n=new FormData;n.append("backup",s);const f=await fetch("/api/admin/restore",{method:"POST",body:n,credentials:"include"}),y=await f.json();if(!f.ok)throw new Error(y.message||"Ошибка восстановления");ns(y.report||[]),i({title:"Восстановление завершено",description:"Данные из бэкапа загружены."}),I.invalidateQueries()}catch(n){ls(n.message),i({title:"Ошибка",description:n.message,variant:"destructive"})}finally{as(!1)}}}}),e.jsxs("button",{"data-testid":"button-restore-backup",disabled:dt,onClick:()=>ds.current?.click(),className:"flex items-center gap-2 px-5 py-2.5 rounded-xl font-medium text-sm transition-colors border border-blue-400/40 text-blue-400 hover:bg-blue-400/10 disabled:opacity-60",children:[dt?e.jsx(V,{className:"h-4 w-4 animate-spin"}):e.jsx(Gs,{className:"h-4 w-4"}
1),dt?"Восстанавливаю...":"Выбрать файл бэкапа"]}),is&&e.jsxs("div",{className:"flex items-start gap-2 p-3 rounded-xl border border-red-400/30 bg-red-400/5 text-sm text-red-400",children:[e.jsx(lr,{className:"h-4 w-4 shrink-0 mt-0.5"}),e.jsx("span",{children:is})]}),rs&&e.jsxs("div",{className:"space-y-2",children:[e.jsxs("div",{className:"flex items-center gap-2 text-sm font-medium text-green-400",children:[e.jsx(dr,{className:"h-4 w-4"}),"Отчёт о восстановлении"]}),e.jsx("div",{className:"bg-muted/50 rounded-xl p-3 font-mono text-xs space-y-0.5 max-h-64 overflow-y-auto",children:rs.map((t,s)=>e.jsx("div",{className:t.startsWith("  ⚠")?"text-yellow-400":"text-muted-foreground",children:t},s))})]})]}),e.jsxs(x,{className:"p-4 text-xs text-muted-foreground space-y-1",children:[e.jsx("div",{className:"font-medium text-foreground mb-2",children:"Рекомендации по хранению бэкапов"}),e.jsx("div",{children:"• Скачивайте бэкап перед каждым крупным обновлением сайта"}),e.jsx("div",{children:"• Храните файл в облаке (Google Drive, Яндекс.Диск) или локально на компьютере"}),e.jsx("div",{children:"• Файл содержит пароли пользователей в зашифрованном виде — не публикуйте его"}),e.jsx("div",{children:"• После восстановления обновите страницу для отображения актуальных данных"})]})]}),u==="specialists"&&j&&e.jsxs("section",{className:"space-y-6",children:[e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsxs("div",{children:[e.jsx("h2",{className:"text-xl font-bold",children:"Биржа специалистов"}),e.jsx("p",{className:"text-sm text-muted-foreground mt-0.5",children:"Управление карточками специалистов"})]}),e.jsxs("button",{onClick:()=>{$e(null),Q({userId:"",profession:"architect",bio:"",website:"",phone:"",contactEmail:"",experienceYears:"0",isFeatured:!1,specializations:"",firstName:"",lastName:"",portraitUrl:""}),je([]),ve(null),tt("new"),ge({email:"",password:"",firstName:"",lastName:""}),Ee(!0)},className:"flex items-center gap-2 px-4 py-2 rounded-xl text-sm font-semibold text-black",style:{background:"hsl(var(--accent))"},"data-testid":"button-add-specialist",children:[e.jsx(ae,{className:"h-4 w-4"})," Добавить специалиста"]})]}),Pa?e.jsx("div",{className:"text-center py-12",children:e.jsx(V,{className:"h-6 w-6 animate-spin mx-auto"})}):Cs.length===0?e.jsxs(x,{className:"p-8 text-center text-muted-foreground",children:[e.jsx(As,{className:"h-10 w-10 mx-auto mb-3 opacity-30"}),e.jsx("p",{className:"text-sm",children:"Нет добавленных специалистов"})]}):e.jsx("div",{className:"grid grid-cols-1 md:grid-cols-2 gap-4",children:Cs.map(t=>e.jsx(x,{className:"p-4","data-testid":`card-admin-specialist-${t.id}`,children:e.jsxs("div",{className:"flex items-start gap-3",children:[t.profile_image_url?e.jsx("img",{src:t.profile_image_url,alt:"avatar",className:"w-12 h-12 rounded-xl object-cover"}):e.jsx("div",{className:"w-12 h-12 rounded-xl flex items-center justify-center text-2xl bg-muted",children:fr[t.profession]||"👤"}),e.jsxs("div",{className:"flex-1 min-w-0",children:[e.jsx("div",{className:"font-semibold text-sm",children:[t.first_name,t.last_name].filter(Boolean).join(" ")||t.email||"—"}),e.jsx("div",{className:"text-xs mt-0.5",style:{color:"hsl(var(--accent))"},children:Mt[t.profession]||t.profession}),e.jsx("div",{className:"text-xs text-muted-foreground mt-1",children:t.email}),e.jsxs("div",{className:"flex items-center gap-2 mt-2",children:[t.is_featured&&e.jsx("span",{className:"px-1.5 py-0.5 rounded text-[10px] font-semibold bg-yellow-500/20 text-yellow-400",children:"Топ"}),!t.is_active&&e.jsx("span",{className:"px-1.5 py-0.5 rounded text-[10px] font-semibold bg-red-500/20 text-red-400",children:"Неактивен"}),e.jsxs("span",{className:"text-[10px] text-muted-foreground",children:[t.portfolio_images?.length||0," фото"]})]})]}),e.jsxs("div",{className:"flex gap-1",children:[e.jsx("button",{onClick:()=>{$e(t),Q({userId:t.user_id,profession:t.profession,bio:t.bio||"",website:t.website||"",phone:t.phone||"",contactEmail:t.contact_email||"",experienceYears:String(t.experience_years||0),isFeatured:t.is_featured,specializations:(t.specializations||[]).join(", "),firstName:t.first_name||"",lastName:t.last_name||"",portraitUrl:t.profile_image_url||""}),je([]),ve(null),Ee(!0)},className:"p-1.5 rounded-lg hover:bg-muted transition-colors","data-testid":`button-edit-specialist-${t.id}`,children:e.jsx(Ze,{className:"h-3.5 w-3.5"})}),e.jsx("button",{onClick:()=>
1et(t.id),className:"p-1.5 rounded-lg hover:bg-red-500/10 text-red-400 transition-colors","data-testid":`button-delete-specialist-${t.id}`,children:e.jsx(re,{className:"h-3.5 w-3.5"})})]})]})},t.id))}),Yt!==null&&e.jsx("div",{className:"fixed inset-0 z-50 flex items-center justify-center",style:{background:"rgba(0,0,0,0.7)"},children:e.jsxs(x,{className:"p-6 max-w-sm w-full mx-4 space-y-4",children:[e.jsx("h3",{className:"font-semibold",children:"Удалить специалиста?"}),e.jsx("p",{className:"text-sm text-muted-foreground",children:'Профиль будет удалён, роль пользователя сброшена до "user".'}),e.jsxs("div",{className:"flex gap-3",children:[e.jsx("button",{onClick:()=>et(null),className:"flex-1 py-2 rounded-xl border text-sm",children:"Отмена"}),e.jsx("button",{onClick:()=>wt.mutate(Yt),disabled:wt.isPending,className:"flex-1 py-2 rounded-xl bg-red-500 text-white text-sm font-semibold","data-testid":"button-confirm-delete-specialist",children:wt.isPending?"Удаляю...":"Удалить"})]})]})}),Wt&&e.jsx("div",{className:"fixed inset-0 z-50 flex items-center justify-center p-4",style:{background:"rgba(0,0,0,0.7)"},children:e.jsxs(x,{className:"w-full max-w-lg max-h-[90vh] overflow-y-auto p-6 space-y-4",children:[e.jsx("h3",{className:"font-semibold text-lg",children:ne?"Редактировать специалиста":"Добавить специалиста"}),!ne&&e.jsxs("div",{className:"space-y-3",children:[e.jsxs("div",{className:"flex rounded-xl overflow-hidden border text-sm",style:{borderColor:"hsl(var(--border))"},children:[e.jsx("button",{type:"button",onClick:()=>tt("new"),className:"flex-1 py-2 font-medium transition-colors",style:{background:pe==="new"?"hsl(var(--accent))":"transparent",color:pe==="new"?"#000":"hsl(var(--muted-foreground))"},"data-testid":"toggle-specialist-new-user",children:"Новый пользователь"}),e.jsx("button",{type:"button",onClick:()=>tt("existing"),className:"flex-1 py-2 font-medium transition-colors",style:{background:pe==="existing"?"hsl(var(--accent))":"transparent",color:pe==="existing"?"#000":"hsl(var(--muted-foreground))"},"data-testid":"toggle-specialist-existing-user",children:"Существующий"})]}),pe==="new"?e.jsxs("div",{className:"space-y-2",children:[e.jsxs("div",{className:"grid grid-cols-2 gap-2",children:[e.jsxs("div",{children:[e.jsx("label",{className:"text-xs text-muted-foreground mb-1 block",children:"Имя"}),e.jsx("input",{value:le.firstName,onChange:t=>ge(s=>({...s,firstName:t.target.value})),placeholder:"Александр",className:"w-full px-3 py-2 rounded-xl border bg-background text-sm","data-testid":"input-new-specialist-firstname"})]}),e.jsxs("div",{children:[e.jsx("label",{className:"text-xs text-muted-foreground mb-1 block",children:"Фамилия"}),e.jsx("input",{value:le.lastName,onChange:t=>ge(s=>({...s,lastName:t.target.value})),placeholder:"Громов",className:"w-full px-3 py-2 rounded-xl border bg-background text-sm","data-testid":"input-new-specialist-lastname"})]})]}),e.jsxs("div",{children:[e.jsx("label",{className:"text-xs text-muted-foreground mb-1 block",children:"Email *"}),e.jsx("input",{type:"email",value:le.email,onChange:t=>ge(s=>({...s,email:t.target.value})),placeholder:"[email protected]",className:"w-full px-3 py-2 rounded-xl border bg-background text-sm","data-testid":"input-new-specialist-email"})]}),e.jsxs("div",{children:[e.jsx("label",{className:"text-xs text-muted-foreground mb-1 block",children:"Пароль * (мин. 6 символов)"}),e.jsx("input",{type:"password",value:le.password,onChange:t=>ge(s=>({...s,password:t.target.value})),placeholder:"••••••••",className:"w-full px-3 py-2 rounded-xl border bg-background text-sm","data-testid":"input-new-specialist-password"})]})]}):e.jsxs("div",{children:[e.jsx("label",{className:"text-xs text-muted-foreground mb-1 block",children:"Пользователь *"}),e.jsxs("select",{value:L.userId,onChange:t=>Q(s=>({...s,userId:t.target.value})),className:"w-full px-3 py-2 rounded-xl border bg-background text-sm","data-testid":"select-specialist-user",children:[e.jsx("option",{value:"",children:"Выберите пользователя"}),Ss.filter(t=>!Rt.includes(t.role)&&t.role!=="admin").map(t=>e.jsxs("option",{value:t.id,children:[[t.firstName,t.lastName].filter(
1Boolean).join(" ")||t.email," (",t.email,")"]},t.id))]}),Ss.filter(t=>!Rt.includes(t.role)&&t.role!=="admin").length===0&&e.jsx("p",{className:"text-xs text-amber-400 mt-1",children:'Нет доступных пользователей. Переключитесь на "Новый пользователь".'})]})]}),ne&&e.jsxs("div",{className:"grid grid-cols-2 gap-3",children:[e.jsxs("div",{children:[e.jsx("label",{className:"text-xs text-muted-foreground mb-1 block",children:"Имя"}),e.jsx("input",{value:L.firstName,onChange:t=>Q(s=>({...s,firstName:t.target.value})),placeholder:"Александр",className:"w-full px-3 py-2 rounded-xl border bg-background text-sm","data-testid":"input-specialist-firstname"})]}),e.jsxs("div",{children:[e.jsx("label",{className:"text-xs text-muted-foreground mb-1 block",children:"Фамилия"}),e.jsx("input",{value:L.lastName,onChange:t=>Q(s=>({...s,lastName:t.target.value})),placeholder:"Громов",className:"w-full px-3 py-2 rounded-xl border bg-background text-sm","data-testid":"input-specialist-lastname"})]})]}),ne&&e.jsxs("div",{children:[e.jsx("label",{className:"text-xs text-muted-foreground mb-1 block",children:"Фото профиля"}),e.jsxs("div",{className:"flex items-start gap-3",children:[(he?URL.createObjectURL(he):L.portraitUrl)&&e.jsx("img",{src:he?URL.createObjectURL(he):L.portraitUrl,alt:"portrait",className:"w-14 h-14 rounded-xl object-cover flex-shrink-0 border"}),e.jsxs("div",{className:"flex-1 space-y-2",children:[e.jsx("input",{type:"file",accept:"image/*",onChange:t=>ve(t.target.files?.[0]||null),className:"w-full text-xs text-muted-foreground","data-testid":"input-specialist-portrait-file"}),e.jsx("input",{value:he?"":L.portraitUrl,onChange:t=>{ve(null),Q(s=>({...s,portraitUrl:t.target.value}))},placeholder:"или вставьте ссылку на фото...",className:"w-full px-3 py-1.5 rounded-xl border bg-background text-xs","data-testid":"input-specialist-portrait-url"})]})]})]}),e.jsxs("div",{children:[e.jsx("label",{className:"text-xs text-muted-foreground mb-1 block",children:"Профессия *"}),e.jsx("select",{value:L.profession,onChange:t=>Q(s=>({...s,profession:t.target.value})),className:"w-full px-3 py-2 rounded-xl border bg-background text-sm","data-testid":"select-specialist-profession",children:Object.entries(Mt).map(([t,s])=>e.jsx("option",{value:t,children:s},t))})]}),e.jsxs("div",{children:[e.jsx("label",{className:"text-xs text-muted-foreground mb-1 block",children:"О себе"}),e.jsx("textarea",{value:L.bio,onChange:t=>Q(s=>({...s,bio:t.target.value})),placeholder:"Описание опыта и подхода к работе...",rows:3,className:"w-full px-3 py-2 rounded-xl border bg-background text-sm resize-none","data-testid":"textarea-specialist-bio"})]}),e.jsxs("div",{children:[e.jsx("label",{className:"text-xs text-muted-foreground mb-1 block",children:"Специализации (через запятую)"}),e.jsx("input",{value:L.specializations,onChange:t=>Q(s=>({...s,specializations:t.target.value})),placeholder:"Жилые интерьеры, Коммерческие пространства...",className:"w-full px-3 py-2 rounded-xl border bg-background text-sm","data-testid":"input-specialist-specializations"})]}),e.jsxs("div",{className:"grid grid-cols-2 gap-3",children:[e.jsxs("div",{children:[e.jsx("label",{className:"text-xs text-muted-foreground mb-1 block",children:"Телефон"}),e.jsx("input",{value:L.phone,onChange:t=>Q(s=>({...s,phone:t.target.value})),placeholder:"+7 999 000-00-00",className:"w-full px-3 py-2 rounded-xl border bg-background text-sm","data-testid":"input-specialist-phone"})]}),e.jsxs("div",{children:[e.jsx("label",{className:"text-xs text-muted-foreground mb-1 block",children:"Email для связи"}),e.jsx("input",{value:L.contactEmail,onChange:t=>Q(s=>({...s,contactEmail:t.target.value})),placeholder:"[email protected]",className:"w-full px-3 py-2 rounded-xl border bg-background text-sm","data-testid":"input-specialist-email"})]})]}),e.jsxs("div",{className:"grid grid-cols-2 gap-3",children:[e.jsxs("div",{children:[e.jsx("label",{className:"text-xs text-muted-foreground mb-1 block",children:"Сайт"}),e.jsx("input",{value:L.website,onChange:t=>Q(s=>({...s,website:t.target.value})),placeholder:"https://...",className:"w-full px-3 py-2 rounded-xl border bg-background text-sm","data-testid":"input-specialist-website"})]}),e.jsxs("div",{children:[e.jsx("label",{className:"text-xs text-muted-foreground mb-1 block",children:"Опыт (лет)"}),e.jsx("input",{type:"number",min:"0",max:"50",value:L.experienceYears,onChange:t=>Q(s=>({...s,experienceYears:t.target.value})),className:"w-full px-3 py-2 rounded-xl border bg-background text-sm","data-testid":"input-specialist-experience"})]})]}),e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx("input",{type:"checkbox",id:"spec-featured",checked:L.isFeatured,onChange:t=>Q(s=>({...s,isFeatured:t.target.checked})),className:"rounded","data-testid":"checkbox-specialist-featured"}),e.jsx("label",{htmlFor:"spec-featured",className:"text-sm",children:"Топ специалист (показывать первым)"})]}),e.jsxs("div",{children:[e.jsx("label",{className:"text-xs text-muted-foreground mb-1 block",children:"Фотографии портфолио"}),e.jsx("input",{type:"file",accept:"image/*",multiple:!0,onChange:t=>je(Array.from(t.target.files||[])),className:"w-full text-sm text-muted-foreground","data-testid":"input-specialist-portfolio"}),e.jsx("p",{className:"text-[10px] text-muted-foreground mt-1",children:"Выберите несколько изображений для портфолио"}),ne&&ne.portfolio_images?.length>0&&e.jsx("div",{className:"flex flex-wrap gap-1 mt-2",children:ne.portfolio_images.map((t,s)=>e.jsx("img",{src:t,alt:"",className:"w-12 h-12 object-cover rounded-lg"},s))})]}),e.jsxs("div",{className:"flex gap-3 pt-2",children:[e.jsx("button",{onClick:()=>{Ee(!1),$e(null),je([]),ve(null),ge({email:"",password:"",firstName:"",lastName:""})},className:"flex-1 py-2.5 rounded-xl border text-sm",children:"Отмена"}),e.jsx("button",{onClick:()=>ne?yt.mutate(ne.id):Nt.mutate(),disabled:Nt.isPending||yt.isPending||!ne&&(pe==="new"?!le.email||!le.password:!L.userId),className:"flex-1 py-2.5 rounded-xl text-sm font-semibold text-black disabled:opacity-50",style:{background:"hsl(var(--accent))"},"data-testid":"button-save-specialist",children:Nt.isPending||yt.isPending?"Сохранение...":ne?"Сохранить":"Добавить"})]})]})})]}),u==="inquiries"&&e.jsxs("section",{className:"space-y-4",children:[e.jsxs("div",{children:[e.jsx("h2",{className:"text-xl font-bold",children:H?"Обращения клиентов":"Мои обращения к специалистам"}),e.jsx("p",{className:"text-sm text-muted-foreground mt-0.5",children:H?"Переписка с клиентами, обратившимися к вам":"Ваши обращения к специалистам биржи"})]}),e.jsxs("div",{className:"grid grid-cols-1 lg:grid-cols-3 gap-4",children:[e.jsx("div",{className:"lg:col-span-1 space-y-2",children:(H?Ia:Fa)?e.jsx("div",{className:"text-center py-8",children:e.jsx(V,{className:"h-5 w-5 animate-spin mx-auto"})}):(H?ft:jt).length===0?e.jsxs(x,{className:"p-6 text-center text-muted-foreground text-sm",children:[e.jsx(Z,{className:"h-8 w-8 mx-auto mb-2 opacity-30"}),e.jsx("p",{children:H?"Нет обращений":"Вы ещё не писали специалистам"}),!H&&e.jsx("a",{href:"/market",className:"mt-2 inline-block text-xs",style:{color:"hsl(var(--accent))"},children:"Перейти в биржу специалистов →"})]}):(H?ft:jt).map(t=>e.jsx(x,{className:`p-3 cursor-pointer transition-all hover:border-[hsl(var(--accent)/0.3)] ${de===t.id?"border-[hsl(var(--accent)/0.4)] bg-[hsl(var(--accent)/0.05)]":""}`,onClick:()=>Gt(t.id),"data-testid":`card-inquiry-${t.id}`,children:e.jsxs("div",{className:"flex items-start justify-between gap-2",children:[e.jsxs("div",{className:"min-w-0",children:[e.jsx("div",{className:"font-medium text-sm truncate",children:H?[t.client_first_name,t.client_last_name].filter(
1Boolean).join(" ")||t.client_email:[t.specialist_first_name,t.specialist_last_name].filter(Boolean).join(" ")||"Специалист"}),!H&&t.profession&&e.jsx("div",{className:"text-[10px] mt-0.5",style:{color:"hsl(var(--accent))"},children:Mt[t.profession]||t.profession}),e.jsx("div",{className:"text-xs text-muted-foreground mt-1 truncate",children:t.subject}),t.last_message&&e.jsx("div",{className:"text-[11px] text-muted-foreground truncate mt-0.5",children:t.last_message})]}),e.jsxs("div",{className:"flex flex-col items-end gap-1",children:[parseInt(t.unread_count)>0&&e.jsx("span",{className:"px-1.5 py-0.5 rounded-full text-[10px] font-bold text-black",style:{background:"hsl(var(--accent))"},children:t.unread_count}),e.jsx("span",{className:`px-1.5 py-0.5 rounded text-[9px] ${t.status==="open"?"bg-green-500/20 text-green-400":"bg-muted text-muted-foreground"}`,children:t.status==="open"?"открыто":"закрыто"})]})]})},t.id))}),e.jsx("div",{className:"lg:col-span-2",children:de?e.jsxs(x,{className:"flex flex-col h-[520px]",children:[e.jsxs("div",{className:"p-3 border-b flex items-center justify-between",children:[e.jsx("div",{className:"text-sm font-medium",children:(H?ft:jt).find(t=>t.id===de)?.subject}),e.jsx("button",{onClick:()=>Gt(null),className:"p-1 rounded hover:bg-muted",children:e.jsx(Y,{className:"h-4 w-4"})})]}),e.jsx("div",{className:"flex-1 overflow-y-auto p-3 space-y-3",children:Ta.map(t=>{const s=t.sender_id===o?.id;return e.jsx("div",{className:`flex ${s?"justify-end":"justify-start"}`,children:e.jsxs("div",{className:`max-w-[80%] rounded-xl px-3 py-2 text-sm ${s?"text-black":"bg-muted text-foreground"}`,style:s?{background:"hsl(var(--accent))"}:{},children:[e.jsx("div",{className:"text-[10px] mb-1 opacity-60",children:[t.first_name,t.last_name].filter(Boolean).join(" ")||"—"}),t.text,e.jsx("div",{className:"text-[9px] mt-1 opacity-50 text-right",children:new Date(t.created_at).toLocaleTimeString("ru-RU",{hour:"2-digit",minute:"2-digit"})})]})},t.id)})}),e.jsxs("div",{className:"p-3 border-t flex gap-2",children:[e.jsx("input",{value:Ae,onChange:t=>Xt(t.target.value),onKeyDown:t=>{t.key==="Enter"&&!t.shiftKey&&(t.preventDefault(),vt.mutate())},placeholder:"Написать сообщение...",className:"flex-1 px-3 py-2 rounded-xl border bg-background text-sm outline-none","data-testid":"input-inquiry-message"}),e.jsx("button",{onClick:()=>vt.mutate(),disabled:!Ae.trim()||vt.isPending,className:"p-2 rounded-xl text-black disabled:opacity-50",style:{background:"hsl(var(--accent))"},"data-testid":"button-send-inquiry-message",children:e.jsx(Qt,{className:"h-4 w-4"})})]})]}):e.jsx(x,{className:"h-64 flex items-center justify-center text-muted-foreground text-sm",children:"Выберите обращение для просмотра переписки"})})]})]})]})]})]})}export{zr as default};

Line numbers count LF bytes from the start of the resource, as the search results do. Vendor segments are library code the classifier recognised; they are stored but not indexed. Bytes are shown as Latin1 characters, one per byte.