1import{r as h,j as e,q as ue,t as Ye,v as Je,l as Ja,w as We,x as Ba,u as oe,y as Wa,s as B,C as G,z as Q,A as se,B as be,e as ee,D as Za,I as Y,E as te,G as Ne,X as Ve,H as Xa,f as Ga,J as Qa,M as H,N as et,O as D,P as at,Q as tt,V as Ue,W as Pe,Y as Fe,Z as Le,_ as Ae,$ as Re,a0 as Oe,a1 as Ie,a2 as Ze,a3 as le,a4 as z,a5 as ce,a6 as pe,a7 as st,a8 as rt,a9 as it,aa as nt,ab as wa,ac as _e,ad as ve,F as lt,ae as ha,af as Ge,ag as De,ah as Ha,ai as za,aj as Qe,ak as Ke,al as he,am as xe,an as ge,ao as fe,ap as ye,aq as xa,ar as ea,as as ga,at as Se,au as Ee,av as fa,aw as ot,ax as ct,ay as aa,az as ta,aA as Me,aB as ya,aC as dt,aD as mt,aE as la,aF as ja,aG as oa,aH as Ca,aI as pt,aJ as va,aK as ca,aL as ut,aM as ht,aN as xt,aO as gt,aP as ft,aQ as da,aR as ka,aS as yt,aT as jt,aU as vt,aV as bt,aW as Nt,aX as _t,aY as $e,aZ as Sa,a_ as Tt,a$ as Ea,b0 as wt,b1 as Ct,b2 as kt,n as St,b3 as Et,b4 as Ut,b5 as Pt,b6 as qa,b7 as $a,b8 as me,b9 as de,S as ma,ba as Ft,bb as Ua,h as Lt,bc as At,bd as Rt,be as Ot,bf as It,bg as Dt,bh as Mt}from"./index-DCRT2xrB.js";import{f as Bt,a as Va,u as Ht,b as zt}from"./formatCooldown-IRdMA-B2.js";import{U as qt}from"./user-D49yArWB.js";import{U as Pa}from"./user-plus-D030tqLa.js";import{S as Be}from"./StickyActionBar-Bq8IThzL.js";import{S as $t}from"./save-DFliKtzU.js";import{L as Vt}from"./layers-rZvqawuV.js";import{u as Kt,a as Yt,B as Jt}from"./useBillingSettings-_WmsiX1p.js";const Wt=({aggregate:t})=>{const[,n]=h.useState(0);return h.useEffect(()=>{if(t.status!=="cooldown")return;const c=setInterval(()=>n(o=>o+1),6e4);return()=>clearInterval(c)},[t.status]),t.status==="running"?e.jsxs("span",{className:"inline-flex items-center gap-1.5 px-2 py-1 text-xs rounded-md bg-primary/10 text-primary border border-primary/20 whitespace-nowrap",children:[e.jsx(ue,{className:"h-3 w-3 animate-spin"}),"ÐдÑÑ Ð¼Ð¾Ð½Ð¸ÑоÑинг"]}):e.jsxs(Ye,{children:[e.jsx(Je,{asChild:!0,children:e.jsxs("span",{className:"inline-flex items-center gap-1.5 px-2 py-1 text-xs rounded-md bg-muted text-muted-foreground border border-border whitespace-nowrap cursor-default",children:[e.jsx(Ja,{className:"h-3 w-3"}),Bt(t.earliestFreeAt)]})}),e.jsxs(We,{children:["ÐÑвободиÑÑÑ ",Va(t.earliestFreeAt)]})]})},Zt=({companyId:t,trademarks:n,maxTrademarks:c,maxProducts:o,onTrademarksChange:m})=>{const{canEditMonitoringProducts:l}=Ba(),{t:p}=oe(),{language:_}=Wa(),{getProductDisplayName:a,translateProducts:C}=Ht(),{data:j}=zt(t),[N,d]=h.useState([]),[T,A]=h.useState(!1),[L,P]=h.useState(""),[x,f]=h.useState(null),[E,S]=h.useState(""),[y,s]=h.useState(!1),[v,u]=h.useState(!1),[U,q]=h.useState(null);h.useEffect(()=>{U?I():d([])},[U]);const I=async()=>{if(U){s(!0);try{const{data:b}=await B.from("company_products").select("id, name, name_en, name_cn, trademark_id").eq("trademark_id",U).order("created_at",{ascending:!0}),M=b||[];d(M),(_==="en"||_==="cn")&&M.length>0&&C(M)}catch(b){console.error("Error loading products:",b)}finally{s(!1)}}},re=b=>{U===b?q(null):(q(b),A(!1))},R=async()=>{var b;if(!(!L.trim()||!U)){if(N.length>=o){H.error(`${p("productLimitReached")} (${o})`);return}if(N.some(M=>M.name.toLowerCase()===L.trim().toLowerCase())){H.error(p("productExists"));return}u(!0);try{const{data:M}=await B.auth.getUser(),{data:X,error:W}=await B.from("company_products").insert({company_id:t,trademark_id:U,name:L.trim(),created_by:(b=M.user)==null?void 0:b.id}).select("id, name, trademark_id").single();if(W)throw W;d([...N,X]),P(""),H.success(p("productAdded"))}catch(M){console.error("Error adding product:",M),H.error(p("errorAddingProduct"))}finally{u(!1)}}},ie=async b=>{const M=E.trim();if(!M)return;const X=N.find(W=>W.id===b);if(X&&X.name===M){f(null),S("");return}if(N.some(W=>W.id!==b&&W.name.toLowerCase()===M.toLowerCase())){H.error(p("productExists"));return}u(!0);try{const{error:W}=await B.from("company_products").update({name:E.trim()}).eq("id",b);if(W)throw W;d(N.map(r=>r.id===b?{...r,name:E.trim()}:r)),f(null),S(""),H.success(p("productUpdated"))}catch(W){console.error("Error updating product:",W),H.error(p("errorUpdatingProduct"))}finally{u(!1)}},$=async b=>{u(!0);try{const{error:M}=await B.from("company_products").delete().eq("id",b);if(M)throw M;d(N.filter(X=>X.id!==b)),H.success(p("productDeleted"))}catch(M){console.error("Error deleting product:",M),H.error(p("errorDeletingProduct"))}finally{u(!1)}},J=b=>{f(b.id),S(b.name)},ae=()=>{f(null),S("")},g=T?N:N.slice(0,5),V=N.length-5,ne=N.length<o,w=N.length<=5&&ne,F=N.length>5&&T&≠return e.jsxs("div",{className:"space-y-6",children:[e.jsxs(G,{className:"border-0 shadow-soft",children:[e.jsx(Q,{children:e.jsxs(se,{className:"text-lg flex items-center justify-between",children:[e.jsx("span",{children:p("trademarks")}),e.jsxs(be,{variant:"secondary",className:"font-normal",children:[n.length," / ",c]})]})}),e.jsx(ee,{className:"space-y-3",children:n.length>0?e.jsxs("div",{className:"space-y-3",children:[e.jsx("div",{className:"flex flex-wrap gap-2",children:n.map(b=>e.jsx(be,{variant:U===b.id?"default":"secondary",className:`px-4 py-2 text-sm cursor-pointer border transition-colors ${U===b.id?"bg-primary text-primary-foreground border-primary":"bg-muted border-border hover:bg-muted/80"}`,onClick:()=>re(b.id),children:b.name},b.id))}),e.jsx("p",{className:"text-sm text-muted-foreground",children:p("trademarksChangeContact")})]}):e.jsx("p",{className:"text-sm text-muted-foreground",children:p("noTrademarksAssigned")})})]}),e.jsxs(G,{className:"border-0 shadow-soft",children:[e.jsx(Q,{children:e.jsxs(se,{className:"text-lg flex items-center justify-between",children:[e.jsx("span",{children:p("products")}),U&&e.jsxs(be,{variant:"secondary",className:"font-normal",children:[N.length," / ",o]})]})}),e.jsx(ee,{className:"space-y-3",children:U?y?e.jsx(Za,{rows:4}):e.jsxs(e.Fragment,{children:[g.map((b,M)=>{const X=j==null?void 0:j.get(b.id),W=!!X,r=X?X.status==="running"?"ÐдÑÑ Ð¼Ð¾Ð½Ð¸ÑоÑинг â ÑедакÑиÑование и Ñдаление недоÑÑÑпнÑ.":`ÐÑÐ¾Ñ ÑÐ¾Ð²Ð°Ñ Ð½ÐµÐ´Ð°Ð²Ð½Ð¾ пÑоÑ
одил мониÑоÑинг. РазблокиÑовка Ð´Ð»Ñ ÑедакÑиÑÐ¾Ð²Ð°Ð½Ð¸Ñ Ð¸ ÑÐ´Ð°Ð»ÐµÐ½Ð¸Ñ Ð¿ÑÐ¾Ð¸Ð·Ð¾Ð¹Ð´ÐµÑ ${Va(X.earliestFreeAt)}.`:"",i=l&&!W;return e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsxs("span",{className:"w-6 text-sm text-muted-foreground font-medium",children:[M+1,"."]}
1),x===b.id&&i?e.jsxs(e.Fragment,{children:[e.jsx(Y,{value:E,onChange:k=>S(k.target.value),className:"flex-1",onKeyDown:k=>{k.key==="Enter"&&ie(b.id),k.key==="Escape"&&ae()},autoFocus:!0}),E.trim()&&E.trim()!==b.name&&e.jsx(te,{size:"icon",variant:"outline",onClick:()=>ie(b.id),disabled:v,children:e.jsx(Ne,{className:"h-4 w-4"})}),e.jsx(te,{size:"icon",variant:"ghost",onClick:ae,disabled:v,children:e.jsx(Ve,{className:"h-4 w-4"})})]}):e.jsxs(e.Fragment,{children:[W?e.jsxs(Ye,{children:[e.jsx(Je,{asChild:!0,children:e.jsx(Y,{value:a(b),readOnly:!0,className:"flex-1 cursor-not-allowed opacity-70"})}),e.jsx(We,{children:r})]}):e.jsx(Y,{value:a(b),readOnly:!0,onClick:()=>i&&J(b),className:`flex-1 ${i?"cursor-pointer hover:bg-muted/50":"cursor-default"} transition-colors`}),X&&e.jsx(Wt,{aggregate:X}),l&&(W?e.jsxs(Ye,{children:[e.jsx(Je,{asChild:!0,children:e.jsx("span",{children:e.jsx(te,{size:"icon",variant:"ghost",disabled:!0,className:"text-muted-foreground",children:e.jsx(Ve,{className:"h-4 w-4"})})})}),e.jsx(We,{children:r})]}):e.jsx(te,{size:"icon",variant:"ghost",onClick:()=>$(b.id),disabled:v,className:"text-muted-foreground hover:text-destructive",children:e.jsx(Ve,{className:"h-4 w-4"})}))]})]},b.id)}),w&&l&&e.jsxs("div",{className:"flex items-center gap-2 pt-2 border-t border-border",children:[e.jsxs("span",{className:"w-6 text-sm text-muted-foreground font-medium",children:[N.length+1,"."]}),e.jsx(Y,{value:L,onChange:b=>P(b.target.value),placeholder:p("enterProductName"),className:"flex-1",onKeyDown:b=>{b.key==="Enter"&&R()}}),L.trim()&&e.jsx(te,{size:"icon",variant:"outline",onClick:R,disabled:v,children:e.jsx(Ne,{className:"h-4 w-4"})})]}),N.length>5&&e.jsx(te,{variant:"ghost",className:"w-full text-muted-foreground",onClick:()=>A(!T),children:T?e.jsxs(e.Fragment,{children:[e.jsx(Xa,{className:"h-4 w-4 mr-2"}),p("collapse")]}):e.jsxs(e.Fragment,{children:[e.jsx(Ga,{className:"h-4 w-4 mr-2"}),p("expand")," (",V,")"]})}),F&&l&&e.jsxs("div",{className:"flex items-center gap-2 pt-2 border-t border-border",children:[e.jsxs("span",{className:"w-6 text-sm text-muted-foreground font-medium",children:[N.length+1,"."]}),e.jsx(Y,{value:L,onChange:b=>P(b.target.value),placeholder:p("enterProductName"),className:"flex-1",onKeyDown:b=>{b.key==="Enter"&&R()}}),L.trim()&&e.jsx(te,{size:"icon",variant:"outline",onClick:R,disabled:v,children:e.jsx(Ne,{className:"h-4 w-4"})})]}),!l&&N.length>0&&e.jsxs("div",{className:"flex items-center gap-2 pt-2 border-t border-border text-muted-foreground",children:[e.jsx(Qa,{className:"h-4 w-4"}),e.jsx("span",{className:"text-sm",children:p("productEditingNotAllowed")})]}),N.length>=o&&e.jsx("p",{className:"text-sm text-muted-foreground pt-2 border-t border-border",children:p("productLimitReachedContact")})]}):e.jsx("p",{className:"text-sm text-muted-foreground",children:p("selectTrademark")})})]})]})},Xt=({companyId:t,employees:n,onEmployeesChange:c})=>{const{isOwner:o}=Ba(),{t:m}=oe(),[l,p]=h.useState(!1),[_,a]=h.useState(""),[C,j]=h.useState(""),[N,d]=h.useState(!1),[T,A]=h.useState(null),L=10,P=async f=>{if(f.preventDefault(),n.length>=L){H.error(`${m("employeeLimitReached")} (${L})`);return}if(!_.trim()||!C.trim()){H.error(m("fillAllFieldsError"));return}if(C.length<6){H.error(m("passwordMinLength"));return}p(!0);try{const{data:{session:E}}=await B.auth.getSession(),S=await fetch(Ze("create-company-employee"),{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${E==null?void 0:E.access_token}`},body:JSON.stringify({email:_.trim(),password:C,companyId:t,permissions:{}})}),y=await S.json();if(!S.ok)throw new Error(y.error||m("employeeCreationError"));H.success(m("employeeAdded")),a(""),j(""),c()}catch(E){console.error("Error creating employee:",E),H.error(E.message||m("employeeCreationError"))}finally{p(!1)}},x=async()=>{if(T)try{const{error:f}=await B.from("company_employees").delete().eq("id",T.id);if(f)throw f;H.success(m("employeeDeleted")),A(null),c()}catch(f){console.error("Error deleting employee:",f),H.error(m("employeeDeletionError"))}};return e.jsxs("div",{className:"grid grid-cols-1 lg:grid-cols-2 gap-6",children:[e.jsxs(G,{className:"border-0 shadow-soft",children:[e.jsx(Q,{children:e.jsxs(se,{className:"text-lg flex items-center gap-2",children:[e.jsx(qt,{className:"h-5 w-5"}),m("employees"),e.jsxs(be,{variant:"secondary",className:"ml-auto font-normal",children:[n.length," / ",L]})]})}),e.jsx(ee,{children:n.length===0?e.jsx("p",{className:"text-sm text-muted-foreground text-center py-8",children:m("noEmployees")}):e.jsx("div",{className:"space-y-3",children:n.map((f,E)=>e.jsxs("div",{className:"flex items-center justify-between p-3 rounded-lg bg-muted/50 border border-border hover:bg-muted/70 transition-colors",children:[e.jsxs("div",{className:"flex items-center gap-3",children:[e.jsxs("span",{className:"text-sm text-muted-foreground font-medium w-6",children:[E+1,"."]}),e.jsx("p",{className:"text-sm font-medium",children:f.email})]}),o&&e.jsx(te,{size:"icon",variant:"ghost",onClick:()=>A(f),className:"text-muted-foreground hover:text-destructive",children:e.jsx(et,{className:"h-4 w-4"})})]},f.id))})})]}),e.jsxs(G,{className:"border-0 shadow-soft",children:[e.jsx(Q,{children:e.jsxs(se,{className:"text-lg flex items-center gap-2",children:[e.jsx(Pa,{className:"h-5 w-5"}),m("addEmployee")]})}),e.jsx(ee,{children:e.jsxs("form",{onSubmit:P,className:"space-y-4",children:[e.jsxs("div",{className:"space-y-2",children:[e.jsx(D,{htmlFor:"employee-email",children:"Email"}
1),e.jsx(Y,{id:"employee-email",type:"email",value:_,onChange:f=>a(f.target.value),placeholder:"[email protected]"})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(D,{htmlFor:"employee-password",children:m("password")}),e.jsxs("div",{className:"relative",children:[e.jsx(Y,{id:"employee-password",type:N?"text":"password",value:C,onChange:f=>j(f.target.value),placeholder:m("passwordPlaceholder"),className:"pr-10"}),e.jsx(te,{type:"button",variant:"ghost",size:"icon",className:"absolute right-0 top-0 h-full px-3 hover:bg-transparent",onClick:()=>d(!N),children:N?e.jsx(at,{className:"h-4 w-4 text-muted-foreground"}):e.jsx(tt,{className:"h-4 w-4 text-muted-foreground"})})]})]}),e.jsx(te,{type:"submit",className:"w-full",disabled:l,children:l?e.jsxs(e.Fragment,{children:[e.jsx(ue,{className:"h-4 w-4 mr-2 animate-spin"}),m("creating")]}):e.jsxs(e.Fragment,{children:[e.jsx(Pa,{className:"h-4 w-4 mr-2"}),m("addEmployee")]})})]})})]}),e.jsx(Ue,{open:!!T,onOpenChange:()=>A(null),children:e.jsxs(Pe,{children:[e.jsxs(Fe,{children:[e.jsx(Le,{children:m("deleteEmployee")}),e.jsx(Ae,{children:m("deleteEmployeeConfirm").replace("{email}",(T==null?void 0:T.email)||"")})]}),e.jsxs(Re,{children:[e.jsx(Oe,{children:m("cancel")}),e.jsx(Ie,{onClick:x,className:"bg-destructive text-destructive-foreground hover:bg-destructive/90",children:m("delete")})]})]})})]})};async function sa(t,n){let c=t.from("complaint_text_presets").select("text, lk_message").eq("marketplace",n.marketplace);const o=[["complaint_type",n.complaintType],["complaint_essence",n.complaintEssence],["applicant_type",n.applicantType],["applicant_basis",n.applicantBasis]];for(const[_,a]of o)a==null||a===""?c=c.is(_,null):c=c.eq(_,a);const{data:m,error:l}=await c.maybeSingle();if(l)return console.warn("[complaintTextPresets] fetch error:",l),null;if(!m)return null;const p=m;return{text:p.text?String(p.text):null,lkMessage:p.lk_message?String(p.lk_message):null}}const He=({trademarks:t,selectedIds:n,onChange:c,errorKey:o})=>{const{t:m}=oe(),[l,p]=h.useState(""),_=h.useMemo(()=>{const x=l.trim().toLowerCase();return x?t.filter(f=>f.name.toLowerCase().includes(x)||(f.certificate_number||"").toLowerCase().includes(x)):t},[t,l]),a=t.length>10,C=new Set(_.map(x=>x.id)),j=n.filter(x=>C.has(x)).length,N=h.useRef(null),[d,T]=h.useState();h.useEffect(()=>{N.current&&T(N.current.getBoundingClientRect().height)},[t.length]);const A=(x,f)=>{c(f?[...n,x]:n.filter(E=>E!==x))},L=()=>{c(Array.from(new Set([...n,..._.map(x=>x.id)])))},P=()=>{c(n.filter(x=>!C.has(x)))};return e.jsxs(G,{children:[e.jsxs(Q,{children:[e.jsxs(se,{className:le("text-base",o&&"text-destructive"),children:[m("trademarksForComplaintsSection"),e.jsx(z,{})]}),e.jsx(ce,{children:m("trademarksForComplaintsHint")}),e.jsx(pe,{errorKey:o})]}),e.jsx(ee,{children:t.length===0?e.jsx("p",{className:"text-sm text-muted-foreground italic",children:m("noTrademarksForComplaints")}):e.jsxs(e.Fragment,{children:[a&&e.jsxs("div",{className:"relative mb-3 max-w-xs",children:[e.jsx(st,{className:"absolute left-2.5 top-1/2 -translate-y-1/2 h-4 w-4 text-muted-foreground pointer-events-none"}),e.jsx(Y,{value:l,onChange:x=>p(x.target.value),placeholder:m("searchPlaceholder"),className:"pl-8 pr-8 h-8 text-sm"}),l&&e.jsx("button",{type:"button",onMouseDown:x=>x.preventDefault(),onClick:()=>p(""),"aria-label":m("clearSearch"),title:m("clearSearch"),className:"absolute right-2 top-1/2 -translate-y-1/2 p-0.5 rounded text-muted-foreground hover:text-foreground hover:bg-muted transition-colors",children:e.jsx(Ve,{className:"h-3.5 w-3.5"})})]}),e.jsxs("div",{className:"flex items-center justify-between mb-3 gap-3 flex-wrap",children:[e.jsxs("span",{className:"text-sm text-muted-foreground",children:[m("selectedCount")," ",n.length," / ",t.length,l.trim()&&e.jsxs("span",{className:"ml-2 text-xs",children:["(",j," / ",_.length,")"]})]}),e.jsxs("div",{className:"flex gap-1",children:[e.jsx(te,{type:"button",variant:"ghost",size:"sm",disabled:_.length===0||j===_.length,onClick:L,children:m("selectAll")}),e.jsx(te,{type:"button",variant:"ghost",size:"sm",disabled:j===0,onClick:P,children:m("unselectAll")})]})]}),e.jsx("div",{style:d?{minHeight:d}:void 0,children:e.jsx("div",{ref:N,className:"flex flex-wrap gap-2",children:_.length===0?e.jsx("p",{className:"text-sm text-muted-foreground italic",children:m("noResults")}):_.map(x=>{const f=n.includes(x.id);return e.jsxs("button",{type:"button",onClick:()=>A(x.id,!f),className:le("inline-flex items-center gap-1.5 rounded-full border px-3 py-1.5 text-sm transition-colors",f?"bg-primary text-primary-foreground border-primary hover:bg-primary/90":"bg-background hover:bg-muted/60 border-border"),children:[f&&e.jsx(Ne,{className:"h-3.5 w-3.5 shrink-0"}),e.jsx("span",{className:"font-medium",children:x.name}),x.certificate_number&&e.jsxs("span",{className:le("text-xs",f?"text-primary-foreground
1/80":"text-muted-foreground"),children:["â ",x.certificate_number]})]},x.id)})})})]})})]})},Gt=[{value:"right_holder",label:"ÐÑавообладаÑелÑ",description:"ÐÐ¾Ð¼Ð¿Ð°Ð½Ð¸Ñ Ñама Ð²Ð»Ð°Ð´ÐµÐµÑ ÑоваÑнÑм знаком"},{value:"representative",label:"ÐÑедÑÑавиÑелÑ",description:"ÐÐ¾Ð¼Ð¿Ð°Ð½Ð¸Ñ Ð´ÐµÐ¹ÑÑвÑÐµÑ Ð¿Ð¾ довеÑенноÑÑи Ð¾Ñ Ð¿ÑавообладаÑелÑ"}],ze=({value:t,onChange:n,title:c="Ð Ð¾Ð»Ñ Ð·Ð°ÑвиÑелÑ",description:o="ÐÑ ÑÑего лиÑа подаÑÑÑÑ Ð¶Ð°Ð»Ð¾Ð±Ð°. ÐлиÑÐµÑ Ð½Ð° Ð½Ð°Ð±Ð¾Ñ Ð¾Ð±ÑзаÑелÑнÑÑ
докÑменÑов."})=>e.jsxs(G,{children:[e.jsxs(Q,{children:[e.jsx(se,{className:"text-base",children:c}),e.jsx(ce,{children:o})]}),e.jsx(ee,{children:e.jsx("div",{className:"grid gap-2 sm:grid-cols-2",children:Gt.map(m=>{const l=t===m.value;return e.jsxs("button",{type:"button",onClick:()=>n(m.value),className:le("flex items-start gap-2 rounded-md border px-3 py-2.5 text-left transition-colors",l?"border-primary bg-primary/5":"border-border hover:bg-muted/50"),children:[e.jsx("span",{className:le("mt-0.5 inline-flex h-4 w-4 shrink-0 items-center justify-center rounded-full border",l?"border-primary bg-primary text-primary-foreground":"border-muted-foreground/40"),children:l&&e.jsx(Ne,{className:"h-3 w-3"})}),e.jsxs("span",{className:"flex flex-col",children:[e.jsx("span",{className:"text-sm font-medium",children:m.label}),e.jsx("span",{className:"text-xs text-muted-foreground",children:m.description})]})]},m.value)})})})]});function ra({companyId:t,marketplace:n,trademarkId:c,emptyState:o,mapRow:m,buildInitial:l}){const[p,_]=h.useState(o),[a,C]=h.useState(o),[j,N]=h.useState(!0),[d,T]=
1h.useState(null),A=h.useRef(m),L=h.useRef(l);return A.current=m,L.current=l,h.useEffect(()=>{if(!t)return;let P=!1;return N(!0),(async()=>{const{data:f,error:E}=await B.rpc("get_complaint_template_variant",{p_company_id:t,p_marketplace:n,p_trademark_id:c});if(P)return;E&&console.error(`Load template (${n}) failed:`,E);const S=Array.isArray(f)&&f.length>0?f[0]:null;if(S){const y=rt.safeParse(S);y.success||console.warn(`[complaint-template] row shape drift (${n}):`,y.error.issues);const s=A.current(S);_(s),C(s)}else{const y=L.current();_(y),C(y)}T(t),N(!1)})(),()=>{P=!0}},[t,n,c]),{state:p,setState:_,pristine:a,setPristine:C,loading:j||d!==t}}function ia(t,n,c){const o=h.useMemo(()=>JSON.stringify(t)!==JSON.stringify(n),[t,n]);return h.useEffect(()=>{c==null||c(o)},[o,c]),o}async function qe({payload:t,trademarkId:n,applicantRole:c}){const o=it.safeParse(t);o.success||console.warn("[upsertComplaintTemplate] payload mismatch â ÑÑо-Ñо оÑпÑавлÑеÑÑÑ Ð½Ðµ Ñак:",o.error.issues);const{company_id:m,user_id:l,marketplace:p,..._}=t,{data:a,error:C}=await B.rpc("upsert_complaint_template_variant",{p_company_id:m,p_marketplace:p,p_trademark_id:n,p_applicant_role:c,p_user_id:l,p_template:_});if(C)throw C;return a}async function Qt(t,n){var d;const c=nt.safeParse(t);c.success||console.warn("[previewComplaintPdf] payload mismatch â ÑÑо-Ñо оÑпÑавлÑеÑÑÑ Ð½Ðµ Ñак:",c.error.issues);const{data:o}=await B.auth.getSession(),m=(d=o.session)==null?void 0:d.access_token;if(!m)throw new Error("СеÑÑÐ¸Ñ Ð¸ÑÑекла, войдиÑе Ñнова");const l=await fetch(Ze("preview-complaint-pdf"),{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${m}`,apikey:"eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJpc3MiOiJzdXBhYmFzZSIsInJlZiI6Im5mY3pjdXhzYm1nb2V5enJsaGdiIiwicm9sZSI6ImFub24iLCJpYXQiOjE3NjA0Mzk5ODcsImV4cCI6MjA3NjAxNTk4N30.AopM22r4hrSboZGAczM2rAVSla4hsdyoTMLF5zwxpCw"},body:JSON.stringify(t),cache:"no-store"});if(!l.ok){const T=await l.text();try{const A=JSON.parse(T);throw new Error(A.error||"PDF не бÑл ÑгенеÑиÑован")}catch{throw new Error(T||"PDF не бÑл ÑгенеÑиÑован")}}const p=(n||"preview").replace(/[^a-zA-Zа-ÑÐ-Я0-9]/g,"_"),_=new Date,a=String(_.getDate()).padStart(2,"0"),C=String(_.getMonth()+1).padStart(2,"0"),j=`ÐÑевÑÑ_жалобÑ_${p}_${a}.${C}.${_.getFullYear()}.pdf`;if((l.headers.get("content-type")||"").includes("application/json")){const T=await l.json();if(!(T!=null&&T.downloadUrl))throw new Error((T==null?void 0:T.error)||"Ðе ÑдалоÑÑ Ð¿Ð¾Ð»ÑÑиÑÑ ÑÑÑÐ»ÐºÑ Ð½Ð° PDF");await es(T.downloadUrl,j)}else{const T=await l.blob();if(!T.size)throw new Error("PDF пÑиÑÑл пÑÑÑÑм");Ka(T,j)}}function Ka(t,n){const c=URL.createObjectURL(t),o=document.createElement("a");o.href=c,o.download=n,o.style.display="none",document.body.appendChild(o),o.click(),document.body.removeChild(o),window.setTimeout(()=>URL.revokeObjectURL(c),6e5)}async function es(t,n){let c=null;for(let o=0;o<wa.length;o+=1){const m=wa[o];m>0&&await new Promise(l=>window.setTimeout(l,m));try{const l=await fetch(t,{method:"GET",cache:"no-store",credentials:"omit"});if(!l.ok)throw new Error(`Ðе ÑдалоÑÑ ÑкаÑаÑÑ PDF (${l.status})`);const p=await l.blob();if(!p.size)throw new Error("PDF по signed URL пÑиÑÑл пÑÑÑÑм");Ka(p,n);return}catch(l){c=l instanceof Error?l:new Error(String(l)),console.error(`[previewComplaintPdf] download attempt ${o+1} failed`,c)}}throw c??new Error("Ðе ÑдалоÑÑ ÑкаÑаÑÑ PDF по signed URL")}function ba(){const[t,n]=h.useState(!1),{toast:c}=_e(),{t:o}=oe(),m=h.useCallback(async(l,p)=>{n(!0);try{await Qt(l,p)}catch(_){console.error(`Preview PDF (${l.marketplace}) failed:`,_),c({title:o("error"),description:(_==null?void 0:_.message)||o("error"),variant:"destructive"})}finally{n(!1)}},[c,o]);return{generating:t,run:m}}function Na({rows:t,uploading:n,getDisplayUrl:c,onUpload:o,onRemove:m,fieldByUpload:l,isInvalid:p,errorFor:_}){const{t:a}=oe();return e.jsxs(G,{children:[e.jsxs(Q,{children:[e.jsx(se,{className:"text-base",children:a("documentsSection")}),e.jsx(ce,{children:a("documentsSectionHint")})]}),e.jsx(ee,{className:"space-y-4",children:t.filter(C=>C.show!==!1).map(C=>{const j=l==null?void 0:l[C.type],N=C.isImage?String(C.type).toLowerCase().includes("stamp")?"stamp":String(C.type).toLowerCase().includes("signature")?"signature":void 0:void 0;return e.jsx(ve,{label:C.label,accept:C.accept,url:c(C.url),uploading:n===C.type,onUpload:d=>o(d,C.type),onRemove:()=>
1m(C.type),isImage:C.isImage,required:C.required,hint:C.hint,cropKind:N,invalid:j?p==null?void 0:p(j):!1,errorKey:j?_==null?void 0:_(j):void 0},C.type)})})]})}const na=()=>e.jsx("div",{className:"flex items-center justify-center min-h-[300px]",children:e.jsx(ue,{className:"h-6 w-6 animate-spin text-muted-foreground"})}),_a=({title:t,description:n,titleSuffix:c,headerAction:o,children:m})=>e.jsx("div",{className:"relative",children:e.jsxs(G,{className:"absolute inset-0 flex flex-col",children:[e.jsx(Q,{children:e.jsxs("div",{className:"flex items-start justify-between gap-2",children:[e.jsxs("div",{className:"min-w-0",children:[e.jsxs(se,{className:"text-base",children:[t,c]}),n&&e.jsx(ce,{children:n})]}),o&&e.jsx("div",{className:"shrink-0",children:o})]})}),e.jsx(ee,{className:"flex-1 min-h-0 flex flex-col",children:m})]})}),Ta=({onClick:t,generating:n,disabled:c})=>{const{t:o}=oe();return e.jsxs(te,{type:"button",variant:"outline",size:"sm",onClick:t,disabled:n||c,children:[n?e.jsx(ue,{className:"h-4 w-4 mr-2 animate-spin"}):e.jsx(lt,{className:"h-4 w-4 mr-2"}),o("pdfPreview")]})},we="wildberries",as=({companyId:t,companyName:n,trademarks:c,userEmail:o,userId:m,companyEmail:l,trademarkId:p,onDirtyChange:_})=>{const{t:a,language:C}=oe(),j=ha(a,C),{toast:N}=_e(),[d,T]=h.useState(!1),{isInvalid:A,errorFor:L,setFromZod:P,clear:x,clearField:f}=Ge(),{generating:E,run:S}=ba(),y=De(),{state:s,setState:v,pristine:u,setPristine:U,loading:q}=ra({companyId:t,marketplace:we,trademarkId:p,emptyState:Se,mapRow:i=>({applicantRole:i.applicant_role==="representative"?"representative":"right_holder",complaintType:Ee(i.complaint_type,dt,""),complaintEssence:Ee(i.complaint_essence,mt,""),copyrightHolderName:i.copyright_holder_name||n,brandName:i.brand_name||"",applicantFullName:i.applicant_full_name||"",email:l??"",emailVisible:!0,phone:i.phone||"",phoneVisible:i.phone_visible??!0,ipRegistrationNumber:i.ip_registration_number||"",signatureUrl:i.signature_url||"",stampUrl:i.stamp_url||"",rightConfirmationUrl:i.right_confirmation_url||"",violationConfirmationUrl:i.violation_confirmation_url||"",authorityConfirmationUrl:i.authority_confirmation_url||"",selectedTrademarkIds:i.selected_trademark_ids||[],templateText:i.template_text||fa}),buildInitial:()=>({...Se,copyrightHolderName:n,email:l??"",emailVisible:!0})});h.useEffect(()=>{const i=l??"";v(k=>k.email===i?k:{...k,email:i}),U(k=>k.email===i?k:{...k,email:i})},[l]);const I=Ha(a),re=s.complaintType?za(a)[s.complaintType]||[]:[],R=(i,k)=>{v(O=>({...O,[i]:k})),f(i)},[ie,$]=h.useState(!1),[J,ae]=h.useState(null),g=async(i,k)=>{let O=s.complaintType,K=s.complaintEssence;if(i==="complaintType"?(O=k,K="",v(Z=>({...Z,complaintType:k,complaintEssence:""})),f("complaintType"),f("complaintEssence")):(K=k,R("complaintEssence",k)),O&&K){const Z=await sa(B,{marketplace:"wildberries",complaintType:O,complaintEssence:K});Z!=null&&Z.text&&R("templateText",Z.text)}},V=(i,k)=>{const O=i==="complaintType"?k:s.complaintType,K=i==="complaintType"?"":i==="complaintEssence"?k:s.complaintEssence,Z=!!(O&&K),Te=s.templateText.trim().length>0;if(Z&&Te){ae({field:i,value:k}),$(!0);return}g(i,k)},{uploading:ne,handleUpload:w,getDisplayUrl:F}=Qe({companyId:t,marketplace:we,fieldByUpload:Ke,onFieldUpdate:(i,k)=>R(i,k),watchedUrls:[s.signatureUrl,s.stampUrl,s.rightConfirmationUrl,s.violationConfirmationUrl,s.authorityConfirmationUrl]}),b=async()=>{if(!t||!m)return;const i=ot.safeParse(s),k=ct(s),O=[...i.success?[]:i.error.issues,...k];if(O.length>0){P(O),N({title:a("validationError"),description:aa(O,a),variant:"destructive"});return}const K=ta(s.phone);T(!0);try{const Z=s.complaintType==="trademark",Te={company_id:t,user_id:m,marketplace:we,complaint_type:s.complaintType,complaint_essence:s.complaintEssence,has_international_trademark:!0,copyright_holder_name:s.copyrightHolderName,brand_name:s.brandName,applicant_full_name:s.applicantFullName,email:s.email,email_visible:s.emailVisible,phone:K,phone_visible:s.phoneVisible,ip_registration_number:Z?s.ipRegistrationNumber:"",signature_url:s.signatureUrl,stamp_url:s.stampUrl,right_confirmation_url:s.right
1ConfirmationUrl,violation_confirmation_url:s.violationConfirmationUrl,authority_confirmation_url:s.authorityConfirmationUrl,selected_trademark_ids:s.selectedTrademarkIds,template_text:s.templateText};await qe({payload:Te,trademarkId:p,applicantRole:s.applicantRole}),U(s),x(),y.invalidateQueries({queryKey:Me(t,we)}),N({title:a("saveSuccess"),duration:2e3})}catch(Z){console.error("Save template failed:",Z),N({title:a("error"),description:(Z==null?void 0:Z.message)||a("saveFailed"),variant:"destructive"})}finally{T(!1)}},M=ia(s,u,_),X=()=>S({marketplace:we,companyId:t,products:ya.wildberries.map(i=>({...i})),template:{complaintType:s.complaintType,complaintEssence:s.complaintEssence,copyrightHolderName:s.copyrightHolderName,brandName:s.brandName,applicantFullName:s.applicantFullName,email:s.email,phone:s.phone,ipRegistrationNumber:s.ipRegistrationNumber,hasInternationalTrademark:!0,signatureUrl:s.signatureUrl,stampUrl:s.stampUrl,rightConfirmationUrl:s.rightConfirmationUrl,violationConfirmationUrl:s.violationConfirmationUrl,authorityConfirmationUrl:s.authorityConfirmationUrl,templateText:s.templateText,selectedTrademarkIds:s.selectedTrademarkIds}},s.brandName||s.copyrightHolderName||n);if(q)return e.jsx(na,{});const W=s.complaintType==="trademark",r=[{type:"signature",label:a("signature"),accept:"image/png,image/jpeg",url:s.signatureUrl,isImage:!0,required:!0},{type:"stamp",label:a("stamp"),accept:"image/png,image/jpeg",url:s.stampUrl,isImage:!0,required:!1},{type:"rightConfirmation",label:a("rightConfirmation"),hint:a("rightConfirmationHint"),accept:"application/pdf",url:s.rightConfirmationUrl,isImage:!1,required:!0},{type:"violationConfirmation",label:a("violationConfirmation"),hint:a("violationConfirmationDescription"),accept:"application/pdf",url:s.violationConfirmationUrl,isImage:!1,required:!1},{type:"authorityConfirmation",label:a("authorityDoc"),hint:a("authorityDocHint"),accept:"application/pdf",url:s.authorityConfirmationUrl,isImage:!1,required:!0}];return e.jsxs("div",{className:"space-y-6",children:[e.jsxs("div",{className:"grid grid-cols-1 lg:grid-cols-[2fr_3fr] gap-6",children:[e.jsxs("div",{className:"space-y-6",children:[e.jsx(ze,{value:s.applicantRole,onChange:i=>R("applicantRole",i)}),e.jsxs(G,{children:[e.jsx(Q,{children:e.jsx(se,{className:"text-base",children:a("complaintParametersSection")})}),e.jsxs(ee,{className:"grid grid-cols-1 md:grid-cols-2 gap-4",children:[e.jsxs("div",{className:"space-y-2",children:[e.jsxs(D,{children:[a("complaintType"),e.jsx(z,{})]}),e.jsxs(he,{value:s.complaintType,onValueChange:i=>{i!==s.complaintType&&V("complaintType",i)},children:[e.jsx(xe,{"aria-invalid":A("complaintType"),className:le("[&>span]:!block [&>span]:flex-1 [&>span]:text-left [&>span]:truncate",A("complaintType")&&"border-destructive focus-visible:ring-destructive"),children:e.jsx(ge,{placeholder:a("selectComplaintType")})}),e.jsx(fe,{children:I.map(i=>e.jsx(ye,{value:i.value,children:i.label},i.value))})]}),e.jsx(pe,{errorKey:L("complaintType")})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsxs(D,{children:[a("complaintEssence"),e.jsx(z,{})]}),e.jsxs(he,{value:s.complaintEssence,onValueChange:i=>{i!==s.complaintEssence&&V("complaintEssence",i)},disabled:!s.complaintType,children:[e.jsx(xe,{"aria-invalid":A("complaintEssence"),className:le("[&>span]:!block [&>span]:flex-1 [&>span]:text-left [&>span]:truncate",A("complaintEssence")&&"border-destructive focus-visible:ring-destructive"),children:e.jsx(ge,{placeholder:a("selectComplaintEssence")})}),e.jsx(fe,{children:re.map(i=>e.jsx(ye,{value:i.value,children:i.label},i.value))})]}),e.jsx(pe,{errorKey:L("complaintEssence")})]})]})]}),e.jsx(xa,{copyrightHolderName:s.copyrightHolderName,onCopyrightHolderNameChange:i=>R("copyrightHolderName",i),copyrightHolderNamePlaceholder:n,applicantFullName:s.applicantFullName,onApplicantFullNameChange:i=>R("applicantFullName",i),applicantFullNameLabel:a("applicantFullNameWB"),email:s.email,onEmailChange:i=>R("email",i),emailLocked:!0,phone:s.phone,onPhoneChange:i=>R("phone",i),brandName:s.brandName,onBrandNameChange:i=>R("brandName",i),phoneVisible:s.phoneVisible,onPhoneVisibleChange:i=>R("phoneVisible",i),isInvalid:A,errorFor:L,footer:W&&e.jsx("div",{className:"space-y-4 pt-4 border-t",children:e.jsxs("div",{className:"space-y-2 max-w-sm",children:[e.jsxs(D,{children:[a("ipRegistrationNumberLabel"),e.jsx(z,{})]}),e.jsx(Y,{value:s.ipRegistrationNumber,onChange:i=>R("ipRegistrationNumber",i.target.value),placeholder:"â 123456",className:le(A("ipRegistrationNumber")&&"border-destructive focus-visible:ring-destructive"),"aria-invalid":A("ipRegistrationNumber")}),e.jsx(pe,{errorKey:L("ipRegistrationNumber")})]})})}),e.jsx(Na,{rows:r,uploading:ne,getDisplayUrl:F,onUpload:w,onRemove:i=>R(Ke[i],""),fieldByUpload:Ke,isInvalid:A,errorFor:L})]}),e.jsx(_a,{title:a("complaintTemplateText"),description:a("complaintTemplateTextHint"),headerAction:e.jsx(Ta,{onClick:X,generating:E}),children:(()=>{const i=!s.complaintType||!s.complaintEssence;return e.jsxs("div",{className:"relative h-full",children:[e.jsx("div",{className:le("h-full",i&&"pointer-events-none"),children:e.jsx(ea,{value:s.templateText,onChange:k=>R("templateText",k),variables:j})}),i&&e.jsx("div",{className:"absolute inset-0 z-10 flex items-center justify-center bg-background/80 rounded-md cursor-not-allowed",children:e.jsxs("div",{className:"flex flex-col items-center gap-3 text-center px-6 pointer-events-none",children:[e.jsx(ga,{className:"h-12 w-12 text-warning"}),e.jsx("p",{className:"text-lg font-medium text-foreground",children:a("selectTypeAndEssenceFirst")})]})})]})})()})]}),e.jsx(He,{trademarks:c,selectedIds:s.selectedTrademarkIds,onChange:i=>R("selectedTrademarkIds",i),errorKey:L("selectedTrademarkIds")}),M&&e.jsx(Be,{saving:d,onSave:b,onDiscard:()=>{v(u),x()}}),e.jsx(Ue,{open:ie,onOpenChange:i=>{$(i),i||ae(null)},children:e.jsxs(Pe,{children:[e.jsxs(Fe,{children:[e.jsx(Le,{children:a("presetSwitchTitle")}),e.jsx(Ae,{children:a("presetSwitchDescription")})]}),e.jsxs(Re,{children:[e.jsx(Oe,{children:a("stayHere")}),e.jsx(Ie,{onClick:()=>{J&&g(J.field,J.value),ae(null),$(!1)},children:a("presetSwitchConfirm")})]})]})})]})},Ce="ozon",ts=({companyId:t,companyName:n,trademarks:c,userEmail:o,userId:m,companyEmail:l,trademarkId:p,onDirtyChange:_})=>{const{t:a,language:C}=oe(),{toast:j}
1=_e(),N=ha(a,C),[d,T]=h.useState(!1),{isInvalid:A,errorFor:L,setFromZod:P,clear:x,clearField:f}=Ge(),{generating:E,run:S}=ba(),y=De(),{state:s,setState:v,pristine:u,setPristine:U,loading:q}=ra({companyId:t,marketplace:Ce,trademarkId:p,emptyState:Ca,mapRow:w=>({applicantRole:w.applicant_role==="representative"?"representative":"right_holder",lkMessage:w.lk_message||"",copyrightHolderName:w.copyright_holder_name||n,applicantFullName:w.applicant_full_name||"",email:l??"",phone:w.phone||"",rightConfirmationUrl:w.right_confirmation_url||"",authorityConfirmationUrl:w.authority_confirmation_url||"",signatureUrl:w.signature_url||"",stampUrl:w.stamp_url||"",selectedTrademarkIds:w.selected_trademark_ids||[],templateText:w.template_text||fa}),buildInitial:()=>({...Ca,copyrightHolderName:n,email:l??""})});h.useEffect(()=>{const w=l??"";v(F=>F.email===w?F:{...F,email:w}),U(F=>F.email===w?F:{...F,email:w})},[l]);const I=(w,F)=>{v(b=>({...b,[w]:F})),f(w)};h.useEffect(()=>{if(q||s.lkMessage.trim()||s.templateText.trim())return;let w=!1;return(async()=>{const F=s.applicantRole==="right_holder"?"rightholder":"representative",b=await sa(B,{marketplace:"ozon",applicantBasis:F});w||!b||(b.lkMessage&&I("lkMessage",b.lkMessage),b.text&&I("templateText",b.text))})(),()=>{w=!0}},[q,s.applicantRole]);const{uploading:re,handleUpload:R,getDisplayUrl:ie}=Qe({companyId:t,marketplace:Ce,fieldByUpload:la,onFieldUpdate:(w,F)=>I(w,F),watchedUrls:[s.signatureUrl,s.stampUrl,s.rightConfirmationUrl,s.authorityConfirmationUrl]}),$=async()=>{if(!t||!m)return;const w=pt.safeParse(s);if(!w.success){P(w.error.issues),j({title:a("validationError"),description:aa(w.error.issues,a),variant:"destructive"});return}const F=ta(s.phone);T(!0);try{const b={...va,company_id:t,user_id:m,marketplace:Ce,copyright_objects_names:"",lk_message:s.lkMessage,copyright_holder_name:s.copyrightHolderName,applicant_full_name:s.applicantFullName,email:s.email,phone:F,right_confirmation_url:s.rightConfirmationUrl,authority_confirmation_url:s.authorityConfirmationUrl,signature_url:s.signatureUrl,stamp_url:s.stampUrl,selected_trademark_ids:s.selectedTrademarkIds,template_text:s.templateText};await qe({payload:b,trademarkId:p,applicantRole:s.applicantRole}),U(s),x(),y.invalidateQueries({queryKey:Me(t,Ce)}),j({title:a("saveSuccess"),duration:2e3})}catch(b){console.error("Save Ozon template failed:",b),j({title:a("error"),description:(b==null?void 0:b.message)||a("saveFailed"),variant:"destructive"})}finally{T(!1)}},J=ia(s,u,_),ae=()=>S({marketplace:Ce,companyId:t,products:ya.ozon.map(w=>({...w})),template:{complaintType:"",complaintEssence:"",copyrightHolderName:s.copyrightHolderName,brandName:"",applicantFullName:s.applicantFullName,email:s.email,phone:s.phone,ipRegistrationNumber:"",hasInternationalTrademark:!1,signatureUrl:s.signatureUrl,stampUrl:s.stampUrl,rightConfirmationUrl:s.rightConfirmationUrl,authorityConfirmationUrl:s.authorityConfirmationUrl,templateText:s.templateText,selectedTrademarkIds:s.selectedTrademarkIds}},s.copyrightHolderName||n);if(q)return e.jsx(na,{});const g=s.lkMessage.length,V=g>oa,ne=[{type:"signature",label:a("signature"),accept:"image/png,image/jpeg",url:s.signatureUrl,isImage:!0,required:!0},{type:"stamp",label:a("stamp"),accept:"image/png,image/jpeg",url:s.stampUrl,isImage:!0,required:!1}];return e.jsxs("div",{className:"space-y-6",children:[e.jsxs("div",{className:"grid grid-cols-1 lg:grid-cols-[2fr_3fr] gap-6",children:[e.jsxs("div",{className:"space-y-6",children:[e.jsx(ze,{value:s.applicantRole,onChange:w=>I("applicantRole",w)}),e.jsxs(G,{children:[e.jsxs(Q,{children:[e.jsx(se,{className:"text-base",children:a("ozonLkMessageSection")}),e.jsx(ce,{children:a("ozonLkMessageHint")})]}),e.jsx(ee,{className:"space-y-4",children:e.jsxs("div",{className:"space-y-2",children:[e.jsxs(D,{children:[a("ozonLkMessageLabel"),e.jsx(z,{})]}),e.jsx(ja,{value:s.lkMessage,onChange:w=>I("lkMessage",w.target.value),placeholder:a("ozonLkMessagePlaceholder"),rows:10,maxLength:oa,className:le(A("lkMessage")&&"border-destructive focus-visible:ring-destructive"),"aria-invalid":A("lkMessage")}),e.jsxs("p",{className:le("text-xs",V?"text-destructive":"text-muted-foreground"),children:[g," / ",oa]}),e.jsx(pe,{errorKey:L("lkMessage")})]})})]}
1),e.jsx(xa,{copyrightHolderName:s.copyrightHolderName,onCopyrightHolderNameChange:w=>I("copyrightHolderName",w),copyrightHolderNamePlaceholder:n,applicantFullName:s.applicantFullName,onApplicantFullNameChange:w=>I("applicantFullName",w),email:s.email,onEmailChange:w=>I("email",w),emailLocked:!0,phone:s.phone,onPhoneChange:w=>I("phone",w),isInvalid:A,errorFor:L}),e.jsx(Na,{rows:ne,uploading:re,getDisplayUrl:ie,onUpload:R,onRemove:w=>I(la[w],""),fieldByUpload:la,isInvalid:A,errorFor:L})]}),e.jsx(_a,{title:a("complaintTemplateText"),description:a("complaintTemplateTextHint"),headerAction:e.jsx(Ta,{onClick:ae,generating:E}),children:e.jsx("div",{className:"h-full",children:e.jsx(ea,{value:s.templateText,onChange:w=>I("templateText",w),variables:N})})})]}),e.jsx(He,{trademarks:c,selectedIds:s.selectedTrademarkIds,onChange:w=>I("selectedTrademarkIds",w),errorKey:L("selectedTrademarkIds")}),J&&e.jsx(Be,{saving:d,onSave:$,onDiscard:()=>{v(u),x()}})]})},Fa="megamarket",ss=({companyId:t,companyName:n,trademarks:c,userEmail:o,userId:m,trademarkId:l,onDirtyChange:p})=>{const _=Fa,{t:a,language:C}=oe(),j=ha(a,C),{toast:N}=_e(),[d,T]=h.useState(Se),[A,L]=h.useState(Se),[P,x]=h.useState(null),[f,E]=h.useState(!0),[S,y]=h.useState(!1),s=De(),v=Ha(a),u=d.complaintType?za(a)[d.complaintType]||[]:[];h.useEffect(()=>{if(!t)return;let g=!1;return E(!0),(async()=>{const{data:ne}=await B.rpc("get_complaint_template_variant",{p_company_id:t,p_marketplace:_,p_trademark_id:l});if(g)return;const w=Array.isArray(ne)&&ne.length>0?ne[0]:null;if(w){const F=w;x(F.id);const b={applicantRole:F.applicant_role==="representative"?"representative":"right_holder",complaintType:F.complaint_type||"",complaintEssence:F.complaint_essence||"",copyrightHolderName:F.copyright_holder_name||n,brandName:F.brand_name||"",applicantFullName:F.applicant_full_name||"",email:F.email||o,emailVisible:F.email_visible??!0,phone:F.phone||"",phoneVisible:F.phone_visible??!0,ipRegistrationNumber:F.ip_registration_number||"",signatureUrl:F.signature_url||"",stampUrl:F.stamp_url||"",rightConfirmationUrl:F.right_confirmation_url||"",violationConfirmationUrl:F.violation_confirmation_url||"",authorityConfirmationUrl:F.authority_confirmation_url||"",selectedTrademarkIds:F.selected_trademark_ids||[],templateText:F.template_text||fa,applicantInn:F.partner_legal_address||""};T(b),L(b)}else{const F={...Se,copyrightHolderName:n,email:o};
1T(F),L(F)}E(!1)})(),()=>{g=!0}},[t,_,n,o,l]);const U=(g,V)=>{T(ne=>({...ne,[g]:V}))},{uploading:q,handleUpload:I,getDisplayUrl:re}=Qe({companyId:t,marketplace:_,fieldByUpload:Ke,onFieldUpdate:(g,V)=>U(g,V),watchedUrls:[d.signatureUrl,d.stampUrl,d.rightConfirmationUrl,d.violationConfirmationUrl,d.authorityConfirmationUrl]}),R=d.applicantRole==="representative",ie=()=>{const g=[];return d.complaintType||g.push(a("complaintType")),d.complaintEssence||g.push(a("complaintEssence")),d.copyrightHolderName.trim()||g.push(a("copyrightHolderCompanyName")),d.brandName.trim()||g.push(a("brandNameLabel")),d.applicantFullName.trim()||g.push(a("applicantFullName")),d.email.trim()||g.push(a("emailLabel")),d.phone.trim()||g.push(a("phoneLabel")),d.signatureUrl||g.push(a("signature")),d.stampUrl||g.push(a("stamp")),d.rightConfirmationUrl||g.push(a("rightConfirmation")),d.violationConfirmationUrl||g.push(a("violationConfirmation")),d.selectedTrademarkIds.length===0&&g.push(a("trademarksForComplaintsSection")),d.complaintType==="trademark"&&!d.ipRegistrationNumber.trim()&&g.push(a("ipRegistrationNumberLabel")),R&&!d.authorityConfirmationUrl&&g.push(a("authorityDoc")),g},$=async()=>{if(!t||!m)return;const g=ie();if(g.length>0){N({title:a("validationError"),description:`${a("requiredFieldsMissing")}: ${g.join(", ")}`,variant:"destructive"});return}if(!ut(d.email)){N({title:a("validationError"),description:a("emailInvalidFormat"),variant:"destructive"});return}const V=ht(d.phone);if(!V.ok&&V.errorKey){N({title:a("validationError"),description:a(V.errorKey),variant:"destructive"});return}if(!/^[а-ÑÐ-ЯÑÐa-zA-Z\s]+$/.test(d.applicantFullName)){N({title:a("validationError"),description:a("nameLettersOnly"),variant:"destructive"});return}const ne=ta(d.phone);y(!0);try{const w=d.complaintType==="trademark",F={company_id:t,user_id:m,marketplace:_,complaint_type:d.complaintType,complaint_essence:d.complaintEssence,has_international_trademark:!0,copyright_holder_name:d.copyrightHolderName,brand_name:d.brandName,applicant_full_name:d.applicantFullName,email:d.email,email_visible:d.emailVisible,phone:ne,phone_visible:d.phoneVisible,ip_registration_number:w?d.ipRegistrationNumber:"",signature_url:d.signatureUrl,stamp_url:d.stampUrl,right_confirmation_url:d.rightConfirmationUrl,violation_confirmation_url:d.violationConfirmationUrl,authority_confirmation_url:R?d.authorityConfirmationUrl:"",selected_trademark_ids:d.selectedTrademarkIds,template_text:d.templateText,partner_legal_address:(d.applicantInn??"").trim()},b=await qe({payload:F,trademarkId:l,applicantRole:d.applicantRole});P||x(b),L(d),s.invalidateQueries({queryKey:Me(t,Fa)}),N({title:a("saveSuccess"),duration:2e3})}catch(w){console.error("Save template failed:",w),N({title:a("error"),description:(w==null?void 0:w.message)||a("saveFailed"),variant:"destructive"})}finally{y(!1)}},J=JSON.stringify(d)!==JSON.stringify(A);if(h.useEffect(()=>{p==null||p(J)},[J,p]),f)return e.jsx("div",{className:"flex items-center justify-center min-h-[300px]",children:e.jsx(ue,{className:"h-6 w-6 animate-spin text-muted-foreground"})});const ae=d.complaintType==="trademark";return e.jsxs("div",{className:"space-y-6",children:[e.jsxs("div",{className:"grid grid-cols-1 lg:grid-cols-[2fr_3fr] gap-6",children:[e.jsxs("div",{className:"space-y-6",children:[e.jsx(ze,{value:d.applicantRole,onChange:g=>U("applicantRole",g)}),e.jsxs(G,{children:[e.jsx(Q,{children:e.jsx(se,{className:"text-base",children:a("complaintParametersSection")})}),e.jsxs(ee,{className:"grid grid-cols-1 md:grid-cols-2 gap-4",children:[e.jsxs("div",{className:"space-y-2",children:[e.jsxs(D,{children:[a("complaintType"),e.jsx(z,{})]}),e.jsxs(he,{value:d.complaintType,onValueChange:g=>{U("complaintType",g),U("complaintEssence","")},children:[e.jsx(xe,{className:"[&>span]:!block [&>span]:flex-1 [&>span]:text-left [&>span]:truncate",children:e.jsx(ge,{placeholder:a("selectComplaintType")})}),e.jsx(fe,{children:v.map(g=>e.jsx(ye,{value:g.value,children:g.label},g.value))})]})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsxs(D,{children:[a("complaintEssence"),e.jsx(z,{})]}),e.jsxs(he,{value:d.complaintEssence,onValueChange:g=>
1U("complaintEssence",g),disabled:!d.complaintType,children:[e.jsx(xe,{className:"[&>span]:!block [&>span]:flex-1 [&>span]:text-left [&>span]:truncate",children:e.jsx(ge,{placeholder:a("selectComplaintEssence")})}),e.jsx(fe,{children:u.map(g=>e.jsx(ye,{value:g.value,children:g.label},g.value))})]})]})]})]}),e.jsxs(G,{children:[e.jsx(Q,{children:e.jsx(se,{className:"text-base",children:a("contactInformation")})}),e.jsxs(ee,{className:"space-y-6",children:[e.jsxs("div",{className:"space-y-2",children:[e.jsxs(D,{children:[a("copyrightHolderCompanyName"),e.jsx(z,{})]}),e.jsx(Y,{value:d.copyrightHolderName,onChange:g=>U("copyrightHolderName",g.target.value),placeholder:n})]}),e.jsxs("div",{className:"space-y-2 max-w-md",children:[e.jsx(D,{children:a("inn")}),e.jsx(Y,{value:d.applicantInn??"",onChange:g=>U("applicantInn",g.target.value.replace(/\D/g,"")),placeholder:"7700000000",maxLength:12,inputMode:"numeric"}),e.jsx("p",{className:"text-xs text-muted-foreground",children:C==="ru"?"10 ÑиÑÑ Ð´Ð»Ñ ÑÑидиÑеÑкого лиÑа, 12 ÑиÑÑ Ð´Ð»Ñ ÐÐ. ÐодÑÑавлÑеÑÑÑ Ð² ÑоÑÐ¼Ñ Ð¶Ð°Ð»Ð¾Ð±Ñ ÐегаÐаÑкеÑ.":"10 digits for legal entity, 12 digits for sole proprietor. Used in MegaMarket complaint form."})]}),e.jsxs("div",{className:"grid grid-cols-1 md:grid-cols-2 gap-4",children:[e.jsxs("div",{className:"space-y-2",children:[e.jsxs(D,{children:[a("brandNameLabel"),e.jsx(z,{})]}),e.jsx(Y,{value:d.brandName,onChange:g=>U("brandName",g.target.value)})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsxs(D,{children:[a("applicantFullName"),e.jsx(z,{})]}),e.jsx(Y,{value:d.applicantFullName,onChange:g=>U("applicantFullName",g.target.value),placeholder:a("applicantFullNamePlaceholder")})]})]}),e.jsxs("div",{className:"grid grid-cols-1 md:grid-cols-2 gap-4",children:[e.jsxs("div",{className:"space-y-2",children:[e.jsxs(D,{children:[a("emailLabel"),e.jsx(z,{})]}),e.jsx(Y,{type:"email",value:d.email,onChange:g=>U("email",g.target.value)}),e.jsxs("div",{className:"flex items-center justify-between pt-1",children:[e.jsx(D,{htmlFor:"email-visible",className:"font-normal text-sm text-muted-foreground cursor-pointer",children:a("makeVisibleToSeller")}),e.jsx(ca,{id:"email-visible",checked:d.emailVisible,onCheckedChange:g=>U("emailVisible",g)})]})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsxs(D,{children:[a("phoneLabel"),e.jsx(z,{})]}),e.jsx(Y,{value:d.phone,onChange:g=>U("phone",g.target.value),placeholder:"79991234567"}),e.jsxs("div",{className:"flex items-center justify-between pt-1",children:[e.jsx(D,{htmlFor:"phone-visible",className:"font-normal text-sm text-muted-foreground cursor-pointer",children:a("makeVisibleToSeller")}),e.jsx(ca,{id:"phone-visible",checked:d.phoneVisible,onCheckedChange:g=>U("phoneVisible",g)})]})]})]}),ae&&e.jsxs("div",{className:"space-y-4 pt-4 border-t",children:[e.jsxs("div",{className:"space-y-2 max-w-sm",children:[e.jsxs(D,{children:[a("ipRegistrationNumberLabel"),e.jsx(z,{})]}),e.jsx(Y,{value:d.ipRegistrationNumber,onChange:g=>U("ipRegistrationNumber",g.target.value),placeholder:"â 123456"})]}),e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(ca,{id:"intl-tm",checked:!0,disabled:!0}),e.jsx(D,{htmlFor:"intl-tm",className:"font-normal",children:a("hasInternationalTrademark")})]})]})]})]}),e.jsxs(G,{children:[e.jsxs(Q,{children:[e.jsx(se,{className:"text-base",children:a("documentsSection")}),e.jsx(ce,{children:a("documentsSectionHint")})]}),e.jsxs(ee,{className:"space-y-4",children:[e.jsx(ve,{label:a("signature"),accept:"image/png",url:re(d.signatureUrl),uploading:q==="signature",onUpload:g=>I(g,"signature"),onRemove:()=>U("signatureUrl",""),isImage:!0,required:!0}),e.jsx(ve,{label:a("stamp"),accept:"image/png",url:re(d.stampUrl),uploading:q==="stamp",onUpload:g=>I(g,"stamp"),onRemove:()=>U("stampUrl",""),isImage:!0,required:!0}),e.jsx(ve,{label:a("rightConfirmation"),accept:"application/pdf",url:re(d.rightConfirmationUrl),uploading:q==="rightConfirmation",onUpload:g=>I(g,"rightConfirmation"),onRemove:()=>U("rightConfirmationUrl",""),isImage:!1,required:!0}),e.jsx(ve,{label:a("violationConfirmation"),accept:"application/pdf",url:re(d.violationConfirmationUrl),uploading:q==="violationConfirmation",onUpload:g=>I(g,"violationConfirmation"),onRemove:()=>U("violationConfirmationUrl",""),isImage:!1,required:!0}),R&&e.jsx(ve,{label:a("authorityDoc"),accept:"application/pdf",url:re(d.authorityConfirmationUrl),uploading:q==="authorityConfirmation",onUpload:g=>I(g,"authorityConfirmation"),onRemove:()=>U("authorityConfirmationUrl",""),isImage:!1,required:!0})]})]})]}),e.jsx("div",{className:"relative",children:e.jsxs(G,{className:"absolute inset-0 flex flex-col",children:[e.jsxs(Q,{children:[e.jsx(se,{className:"text-base",children:a("complaintTemplateText")}),e.jsx(ce,{children:a("complaintTemplateTextHint")})]}),e.jsx(ee,{className:"flex-1 min-h-0 flex flex-col",children:e.jsx(ea,{value:d.templateText,onChange:g=>U("templateText",g),variables:j})})]})})]}),e.jsx(He,{trademarks:c,selectedIds:d.selectedTrademarkIds,onChange:g=>U("selectedTrademarkIds",g)}),J&&e.jsx(Be,{saving:S,onSave:$,onDiscard:()=>T(A)})]})}
1,ke="yandex_market",rs=({companyId:t,companyName:n,trademarks:c,userEmail:o,userId:m,companyEmail:l,trademarkId:p,onDirtyChange:_})=>{const{t:a,language:C}=oe(),{toast:j}=_e(),N=xt(a,C),d=gt(a),T=ft(a),[A,L]=h.useState(!1),{isInvalid:P,errorFor:x,setFromZod:f,clear:E,clearField:S}=Ge(),{generating:y,run:s}=ba(),v=De(),{state:u,setState:U,pristine:q,setPristine:I,loading:re}=ra({companyId:t,marketplace:ke,trademarkId:p,emptyState:ka,mapRow:r=>({applicantRole:r.applicant_role==="representative"?"representative":"right_holder",complaintType:Ee(r.complaint_type,vt,""),applicantBasis:Ee(r.applicant_basis,bt,""),copyrightHolderName:r.copyright_holder_name||n,applicantFullName:r.applicant_full_name||"",email:l??"",phone:r.phone||"",rightConfirmationUrl:r.right_confirmation_url||"",authorityConfirmationUrl:r.authority_confirmation_url||"",signatureUrl:r.signature_url||"",stampUrl:r.stamp_url||"",selectedTrademarkIds:r.selected_trademark_ids||[],templateText:r.template_text||yt}),buildInitial:()=>({...ka,copyrightHolderName:n,email:l??""})});h.useEffect(()=>{const r=l??"";U(i=>i.email===r?i:{...i,email:r}),I(i=>i.email===r?i:{...i,email:r})},[l]);const R=(r,i)=>{U(k=>({...k,[r]:i})),S(r)},[ie,$]=h.useState(!1),[J,ae]=h.useState(null),g=async(r,i)=>{const k=r==="complaintType"?i:u.complaintType,O=r==="applicantBasis"?i:u.applicantBasis;if(R(r,i),k&&O){const K=await sa(B,{marketplace:"yandex_market",complaintType:k,applicantBasis:O});K!=null&&K.text&&R("templateText",K.text)}},V=(r,i)=>{const k=r==="complaintType"?i:u.complaintType,O=r==="applicantBasis"?i:u.applicantBasis,K=!!(k&&O),Z=u.templateText.trim().length>0;if(K&&Z){ae({field:r,value:i}),$(!0);return}g(r,i)},{uploading:ne,handleUpload:w,getDisplayUrl:F}=Qe({companyId:t,marketplace:ke,fieldByUpload:da,onFieldUpdate:(r,i)=>R(r,i),watchedUrls:[u.signatureUrl,u.stampUrl,u.rightConfirmationUrl,u.authorityConfirmationUrl]}),b=async()=>{if(!t||!m)return;const r=jt.safeParse(u);if(!r.success){f(r.error.issues),j({title:a("validationError"),description:aa(r.error.issues,a),variant:"destructive"});return}const i=ta(u.phone);L(!0);try{const k={...va,company_id:t,user_id:m,marketplace:ke,complaint_type:u.complaintType,copyright_holder_name:u.copyrightHolderName,applicant_full_name:u.applicantFullName,email:u.email,phone:i,right_confirmation_url:u.rightConfirmationUrl,authority_confirmation_url:u.authorityConfirmationUrl,signature_url:u.signatureUrl,stamp_url:u.stampUrl,selected_trademark_ids:u.selectedTrademarkIds,template_text:u.templateText};await qe({payload:k,trademarkId:p,applicantRole:u.applicantRole}),I(u),E(),v.invalidateQueries({queryKey:Me(t,ke)}),j({title:a("saveSuccess"),duration:2e3})}catch(k){console.error("Save Yandex template failed:",k),j({title:a("error"),description:(k==null?void 0:k.message)||a("saveFailed"),variant:"destructive"})}finally{L(!1)}},M=ia(u,q,_),X=()=>s({marketplace:ke,companyId:t,products:ya.yandex_market.map(r=>({...r})),template:{complaintType:u.complaintType,complaintEssence:"",copyrightHolderName:u.copyrightHolderName,brandName:"",applicantFullName:u.applicantFullName,email:u.email,phone:u.phone,ipRegistrationNumber:"",hasInternationalTrademark:!1,signatureUrl:u.signatureUrl,stampUrl:u.stampUrl,rightConfirmationUrl:u.rightConfirmationUrl,authorityConfirmationUrl:u.authorityConfirmationUrl,templateText:u.templateText,selectedTrademarkIds:u.selectedTrademarkIds}},u.copyrightHolderName||n);if(re)return e.jsx(na,{});const W=[{type:"signature",label:a("signature"),accept:"image/png,image/jpeg",url:u.signatureUrl,isImage:!0,required:!0},{type:"stamp",label:a("stamp"),accept:"image/png,image/jpeg",url:u.stampUrl,isImage:!0,required:!1},{type:"rightConfirmation",label:a("rightConfirmation"),hint:a("rightConfirmationHint"),accept:"application/pdf",url:u.rightConfirmationUrl,isImage:!1,required:!0},{type:"authorityConfirmation",label:a("authorityDoc"),hint:a("authorityDocHint"),accept:"application/pdf",url:u.authorityConfirmationUrl,isImage:!1,required:!0}];return e.jsxs("div",{className:"space-y-6",children:[e.jsxs("div",{className:"grid grid-cols-1 lg:grid-cols-[2fr_3fr] gap-6",children:[e.jsxs("div",{className:"space-y-6",children:[e.jsx(ze,{value:u.applicantRole,onChange:r=>R("applicantRole",r)}),e.jsxs(G,{children:[e.jsx(Q,{children:e.jsx(se,{className:"text-base",children:a("complaintParametersSection")})}),e.jsxs(ee,{className:"grid grid-cols-1 md:grid-cols-2 gap-4",children:[e.jsxs("div",{className:"space-y-2",children:[e.jsxs(D,{children:[a("yandexComplaintCategoryLabel"),e.jsx(z,{})]}),e.jsxs(he,{value:u.complaintType,onValueChange:r=>{r!==u.complaintType&&V("complaintType",r)},children:[e.jsx(xe,{"aria-invalid":P("complaintType"),className:le("[&>span]:!block [&>span]:flex-1 [&>span]:text-left [&>span]:truncate",P("complaintType")&&"border-destructive focus-visible:ring-destructive"),children:e.jsx(ge,{placeholder:a("selectComplaintType")})}),e.jsx(fe,{children:d.map(r=>e.jsx(ye,{value:r.value,children:r.label},r.value))})]}),e.jsx(pe,{errorKey:x("complaintType")})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsxs(D,{children:[a("applicantBasisLabel"),e.jsx(z,{})]}),e.jsxs(he,{value:u.applicantBasis,onValueChange:r=>{r!==u.applicantBasis&&V("applicantBasis",r)},children:[e.jsx(xe,{"aria-invalid":P("applicantBasis"),className:le("[&>span]:!block [&>span]:flex-1 [&>span]:text-left [&>span]:truncate",P("applicantBasis")&&"border-destructive focus-visible:ring-destructive"),children:e.jsx(ge,{placeholder:a("applicantBasisPlaceholder")})}),e.jsx(fe,{children:T.map(r=>e.jsx(ye,{value:r.value,children:r.label},r.value))})]}),e.jsx(pe,{errorKey:x("applicantBasis")})]})]})]}
1),e.jsx(xa,{copyrightHolderName:u.copyrightHolderName,onCopyrightHolderNameChange:r=>R("copyrightHolderName",r),copyrightHolderNamePlaceholder:n,applicantFullName:u.applicantFullName,onApplicantFullNameChange:r=>R("applicantFullName",r),email:u.email,onEmailChange:r=>R("email",r),emailLocked:!0,phone:u.phone,onPhoneChange:r=>R("phone",r),isInvalid:P,errorFor:x}),e.jsx(Na,{rows:W,uploading:ne,getDisplayUrl:F,onUpload:w,onRemove:r=>R(da[r],""),fieldByUpload:da,isInvalid:P,errorFor:x})]}),e.jsx(_a,{title:a("complaintTemplateText"),description:a("complaintTemplateTextHint"),headerAction:e.jsx(Ta,{onClick:X,generating:y}),children:(()=>{const r=!u.complaintType||!u.applicantBasis;return e.jsxs("div",{className:"relative h-full",children:[e.jsx("div",{className:le("h-full",r&&"pointer-events-none"),children:e.jsx(ea,{value:u.templateText,onChange:i=>R("templateText",i),variables:N})}),r&&e.jsx("div",{className:"absolute inset-0 z-10 flex items-center justify-center bg-background/80 rounded-md cursor-not-allowed",children:e.jsxs("div",{className:"flex flex-col items-center gap-3 text-center px-6 pointer-events-none",children:[e.jsx(ga,{className:"h-12 w-12 text-warning"}),e.jsx("p",{className:"text-lg font-medium text-foreground",children:a("selectComplaintTypeAndBasisFirst")})]})})]})})()})]}),e.jsx(He,{trademarks:c,selectedIds:u.selectedTrademarkIds,onChange:r=>R("selectedTrademarkIds",r),errorKey:x("selectedTrademarkIds")}),M&&e.jsx(Be,{saving:A,onSave:b,onDiscard:()=>{U(q),E()}}),e.jsx(Ue,{open:ie,onOpenChange:r=>{$(r),r||ae(null)},children:e.jsxs(Pe,{children:[e.jsxs(Fe,{children:[e.jsx(Le,{children:a("presetSwitchTitle")}),e.jsx(Ae,{children:a("presetSwitchDescription")})]}),e.jsxs(Re,{children:[e.jsx(Oe,{children:a("stayHere")}),e.jsx(Ie,{onClick:()=>{J&&g(J.field,J.value),ae(null),$(!1)},children:a("presetSwitchConfirm")})]})]})})]})},pa="avito",La=t=>({complaintType:t.complaintType,applicantType:t.applicantType,applicantPersonType:t.applicantPersonType,applicantCompanyName:t.applicantCompanyName,representativeFIO:t.representativeFIO,ownerName:t.ownerName,ownerEmail:t.ownerEmail,proofOfOwnershipUrl:t.proofOfOwnershipUrl,proofOfAuthorityUrl:t.proofOfAuthorityUrl,powerOfAttorneyUrl:t.powerOfAttorneyUrl,passportUrl:t.passportUrl}),is=({companyId:t,companyName:n,trademarks:c,userEmail:o,userId:m,companyEmail:l,trademarkId:p,onDirtyChange:_})=>{const{t:a,language:C}=oe(),{toast:j}=_e(),N=Nt(a),[d,T]=h.useState(!1),{isInvalid:A,errorFor:L,setFromZod:P,clear:x,clearField:f}=Ge(),E=h.useRef(null),S=De(),{state:y,setState:s,pristine:v,setPristine:u,loading:U}=ra({companyId:t,marketplace:pa,trademarkId:p,emptyState:Ea,mapRow:r=>{const i=r.applicant_role==="representative"?"representative":"right_holder";return{applicantRole:i,complaintType:Ee(r.complaint_type,kt,""),applicantType:i==="right_holder"?"rightowner":"representative",applicantPersonType:r.applicant_person_type==="natural"?"natural":"legal",applicantCompanyName:r.applicant_company_name||"",representativeFIO:r.applicant_full_name||"",ownerName:r.copyright_holder_name||n,ownerEmail:l??"",proofOfOwnershipUrl:r.right_confirmation_url||"",proofOfAuthorityUrl:r.authority_confirmation_url||"",powerOfAttorneyUrl:r.power_of_attorney_url||"",passportUrl:r.passport_url||"",selectedTrademarkIds:r.selected_trademark_ids||[],templateText:r.lk_message||r.template_text||wt}},buildInitial:()=>({...Ea,ownerName:n,ownerEmail:l??""})});h.useEffect(()=>{const r=l??"";s(i=>i.ownerEmail===r?i:{...i,ownerEmail:r}),u(i=>i.ownerEmail===r?i:{...i,ownerEmail:r})},[l]);const q=y.applicantRole==="right_holder"?"rightowner":"representative";h.useEffect(()=>{s(r=>r.applicantType===q?r:{...r,applicantType:q})},[q]);const I=(r,i)=>{s(k=>({...k,[r]:i})),f(r)},re=r=>{s(i=>{const k=La(i),O=typeof r=="function"?r(k):r;return{...i,...O}});for(const i of["complaintType","applicantType","applicantPersonType","applicantCompanyName","representativeFIO","ownerName","ownerEmail","proofOfOwnershipUrl","proofOfAuthorityUrl","powerOfAttorneyUrl","passportUrl"])f(i)},[R,ie]=h.useState(!1),[$,J]=h.useState(null),ae=async(r,i)=>{const k=r==="applicantType"?i:y.applicantType,O=r==="complaintType"?i:y.complaintType;if(I(r,i),k&&O){const K=await sa(B,{marketplace:"avito",complaintType:O,applicantType:k});K!=null&&K.text&&I("templateText",K.text)}},g=(r,i)=>{const k=r==="applicantType"?i:y.applicantType,O=r==="complaintType"?i:y.complaintType,K=!!(k&&O),Z=y.templateText.trim().length>0;if(K&&Z){J({field:r,value:i}),ie(!0);return}ae(r,i)},V=h.useRef(null);h.useLayoutEffect(()=>{if(V.current===null||!E.current)return;const r=V.current;V.current=null,E.current.focus(),E.current.setSelectionRange(r,r)},[y.templateText]);const ne=r=>{const i=`{{${r}}}`,k=E.current;s(O=>{if(O.templateText.length+i.length>$e)return O;if(!k)return{...O,templateText:O.templateText+i};const Z=k.selectionStart??O.templateText.length,Te=k.selectionEnd??O.templateText.length,Ya=O.templateText.slice(0,Z)+i+O.templateText.slice(Te);return V.current=Z+i.length,{...O,templateText:Ya}})},w=async()=>
1{if(!t||!m)return;const r=Ct.safeParse(y);if(!r.success){P(r.error.issues),j({title:a("validationError"),description:aa(r.error.issues,a),variant:"destructive"});return}if(y.complaintType==="trademark"){const k=c.filter(O=>y.selectedTrademarkIds.includes(O.id)).filter(O=>!(O.certificate_number||"").trim());if(k.length>0){j({title:a("validationError"),description:`${a("avitoTrademarkMissingCertificate")}: ${k.map(O=>O.name).join(", ")}`,variant:"destructive"});return}}T(!0);try{const i={...va,company_id:t,user_id:m,marketplace:pa,complaint_type:y.complaintType,applicant_person_type:y.applicantPersonType,applicant_company_name:y.applicantCompanyName,applicant_full_name:y.representativeFIO,copyright_holder_name:y.ownerName,email:y.ownerEmail,lk_message:y.templateText,template_text:y.templateText,right_confirmation_url:y.proofOfOwnershipUrl,authority_confirmation_url:y.proofOfAuthorityUrl,power_of_attorney_url:y.powerOfAttorneyUrl,passport_url:y.passportUrl,selected_trademark_ids:y.selectedTrademarkIds};await qe({payload:i,trademarkId:p,applicantRole:y.applicantRole}),u(y),x(),S.invalidateQueries({queryKey:Me(t,pa)}),j({title:a("saveSuccess"),duration:2e3})}catch(i){console.error("Save Avito template failed:",i),j({title:a("error"),description:(i==null?void 0:i.message)||a("saveFailed"),variant:"destructive"})}finally{T(!1)}},F=ia(y,v,_);if(U)return e.jsx(na,{});const b=y.templateText.length,M=b>$e,X=b<Sa,W=M||X?"text-destructive":"text-muted-foreground";return e.jsxs("div",{className:"space-y-6",children:[e.jsx(ze,{value:y.applicantRole,onChange:r=>I("applicantRole",r)}),e.jsxs("div",{className:"grid grid-cols-1 lg:grid-cols-[2fr_3fr] gap-6",children:[e.jsx(_t,{formData:La(y),setFormData:re,emailLocked:!0,onApplicantTypeChange:r=>{r!==y.applicantType&&g("applicantType",r)},onComplaintTypeChange:r=>{r!==y.complaintType&&g("complaintType",r)}}),e.jsx("div",{className:"relative",children:e.jsxs(G,{className:"absolute inset-0 flex flex-col",children:[e.jsxs(Q,{children:[e.jsxs(se,{className:"text-base",children:[a("avitoLkMessageLabel"),e.jsx(z,{})]}),e.jsx(ce,{children:a("avitoTextareaHint")})]}),e.jsxs(ee,{className:"flex-1 min-h-0 flex flex-col space-y-3",children:[(()=>{const r=!y.applicantType||!y.complaintType;return e.jsxs("div",{className:"relative flex-1 flex flex-col min-h-0",children:[e.jsx(ja,{ref:E,value:y.templateText,onChange:i=>I("templateText",i.target.value),maxLength:$e,disabled:r,"aria-invalid":A("templateText"),className:le("font-mono text-sm min-h-[300px] flex-1 resize-none",A("templateText")&&"border-destructive focus-visible:ring-destructive",r&&"cursor-not-allowed")}),r&&e.jsx("div",{className:"absolute inset-0 z-10 flex items-center justify-center bg-background/80 rounded-md cursor-not-allowed",children:e.jsxs("div",{className:"flex flex-col items-center gap-3 text-center px-6 pointer-events-none",children:[e.jsx(ga,{className:"h-12 w-12 text-warning"}),e.jsx("p",{className:"text-lg font-medium text-foreground",children:a("selectApplicantAndComplaintTypeFirst")})]})})]})})(),e.jsxs("div",{className:`text-xs ${W} text-right`,children:[b," / ",$e,X&&` (мин. ${Sa})`]}),e.jsx(pe,{errorKey:L("templateText")}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(D,{className:"text-xs text-muted-foreground",children:a("avitoVariablesHeading")}),e.jsx(Tt,{delayDuration:300,children:e.jsx("div",{className:"flex flex-wrap gap-2",children:N.map(r=>e.jsxs(Ye,{children:[e.jsx(Je,{asChild:!0,children:e.jsx(te,{type:"button",variant:"outline",size:"sm",className:"h-7 text-xs",onClick:()=>ne(r.key),children:r.label})}),e.jsx(We,{className:"font-mono",children:`{{${r.key}}}`})]},r.key))})})]})]})]})})]}),e.jsx(He,{trademarks:c,selectedIds:y.selectedTrademarkIds,onChange:r=>I("selectedTrademarkIds",r),errorKey:L("selectedTrademarkIds")}),F&&e.jsx(Be,{saving:d,onSave:w,onDiscard:()=>{s(v),x()}}),e.jsx(Ue,{open:R,onOpenChange:r=>{ie(r),r||J(null)},children:e.jsxs(Pe,{children:[e.jsxs(Fe,{children:[e.jsx(Le,{children:a("presetSwitchTitle")}),e.jsx(Ae,{children:a("presetSwitchDescription")})]}),e.jsxs(Re,{children:[e.jsx(Oe,{children:a("stayHere")}),e.jsx(Ie,{onClick:()=>{$&&ae($.field,$.value),J(null),ie(!1)},children:a("presetSwitchConfirm")})]})]})})]})},Aa="web",ns="right_holder",Ra="ÐаÑÑÑение пÑав на ÑоваÑнÑй знак",Oa=`<p>ÐдÑавÑÑвÑйÑе!</p> 2<p>ÐбÑаÑаемÑÑ Ðº вам Ð¾Ñ Ð¸Ð¼ÐµÐ½Ð¸ пÑавообладаÑÐµÐ»Ñ ÑоваÑного знака. ÐÑи мониÑоÑинге ÑеÑи ÐнÑеÑÐ½ÐµÑ Ð¼Ñ Ð·Ð°ÑикÑиÑовали на ваÑем ÑеÑÑÑÑе ÑазмеÑение маÑеÑиалов, наÑÑÑаÑÑÐ¸Ñ Ð¸ÑклÑÑиÑелÑнÑе пÑава.</p> 3<p>ÐÑоÑим ÑдалиÑÑ Ð½Ð°ÑÑÑаÑÑий конÑÐµÐ½Ñ Ð² ÑазÑмнÑй ÑÑок и ÑообÑиÑÑ Ð¾ пÑинÑÑÑÑ Ð¼ÐµÑÐ°Ñ .</p> 4<p>С Ñважением,<br/>ÐÑавообладаÑелÑ.</p>`,ls=({companyId:t,userId:n,trademarkId:c,trademarkName:o,onDirtyChange:m})=>{const{language:l}=oe(),[p,_]=h.useState(""),[a,C]=h.useState(""),[j,N]=h.useState(!0),[d,T]=
4h.useState(!1),[A,L]=h.useState(null),P=h.useRef({subject:"",body:""});h.useEffect(()=>{if(!t)return;let S=!1;return N(!0),(async()=>{let y=B.from("complaint_templates").select("id, email_subject, template_text").eq("company_id",t).eq("marketplace",Aa);y=c?y.eq("trademark_id",c):y.is("trademark_id",null);const{data:s}=await y.maybeSingle();if(S)return;const v=(s==null?void 0:s.email_subject)??Ra,u=(s==null?void 0:s.template_text)??Oa;_(v),C(u),L((s==null?void 0:s.id)??null),P.current={subject:v,body:u},N(!1)})(),()=>{S=!0}},[t,c]);const x=h.useMemo(()=>p!==P.current.subject||a!==P.current.body,[p,a]);h.useEffect(()=>{m==null||m(x)},[x,m]);const f=p.trim().length>0&&a.trim().length>0&&!d&&!j&&x,E=h.useCallback(async()=>{if(f){T(!0);try{const S={company_id:t,user_id:n,marketplace:Aa,trademark_id:c,applicant_role:ns,email_subject:p.trim(),template_text:a,has_international_trademark:!1};if(A){const{error:y}=await B.from("complaint_templates").update(S).eq("id",A);if(y)throw y}else{const{data:y,error:s}=await B.from("complaint_templates").insert(S).select("id").single();if(s)throw s;L(y==null?void 0:y.id)}P.current={subject:p,body:a},m==null||m(!1),H.success(l==="ru"?"Шаблон ÑоÑ
ÑанÑн":"Template saved")}catch(S){console.error("[DomainTemplateEditor] save failed",S),H.error(l==="ru"?"Ðе ÑдалоÑÑ ÑоÑ
ÑаниÑÑ":"Save failed")}finally{T(!1)}}},[f,t,n,c,p,a,A,l,m]);return e.jsx("div",{className:"space-y-4",children:e.jsxs(G,{children:[e.jsxs(Q,{children:[e.jsxs(se,{className:"text-base flex items-center gap-2",children:[l==="ru"?"Шаблон Ð¶Ð°Ð»Ð¾Ð±Ñ Ð´Ð»Ñ Ð²ÐµÐ±-ÑайÑов":"Web complaint template",c?e.jsx(be,{variant:"outline",className:"text-xs",children:o||(l==="ru"?"ÐÐ»Ñ ÐºÐ¾Ð½ÐºÑеÑного ТÐ":"Per trademark")}):e.jsx(be,{variant:"secondary",className:"text-xs",children:l==="ru"?"УнивеÑÑалÑнÑй (вÑе ТÐ)":"Universal (all TMs)"})]}),e.jsx(ce,{children:l==="ru"?"Тема и Ñело пиÑÑма, коÑоÑое пойдÑÑ Ð½Ð° abuse-конÑакÑÑ Ð´Ð¾Ð¼ÐµÐ½Ð¾Ð². ÐÑпÑавлÑеÑÑÑ Ð±ÐµÐ· подÑÑановок â пиÑиÑе гоÑовÑй ÑекÑÑ.":"Subject and body of the email sent to domain abuse contacts. Sent as-is â write final text."})]}),e.jsx(ee,{className:"space-y-4",children:j?e.jsx("div",{className:"flex items-center justify-center py-8",children:e.jsx(ue,{className:"h-5 w-5 animate-spin text-muted-foreground"})}):e.jsxs(e.Fragment,{children:[e.jsxs("div",{className:"space-y-2",children:[e.jsxs(D,{htmlFor:"web-subject",children:[l==="ru"?"Тема пиÑÑма":"Email subject",e.jsx(z,{})]}),e.jsx(Y,{id:"web-subject",value:p,onChange:S=>_(S.target.value),disabled:d,maxLength:200,placeholder:Ra})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsxs(D,{htmlFor:"web-body",children:[l==="ru"?"Тело пиÑÑма (HTML)":"Email body (HTML)",e.jsx(z,{})]}),e.jsx(ja,{id:"web-body",value:a,onChange:S=>C(S.target.value),disabled:d,rows:16,className:"font-mono text-xs",placeholder:Oa}),e.jsx("p",{className:"text-xs text-muted-foreground",children:l==="ru"?"ÐоддеÑживаÑÑÑÑ HTML-Ñеги. ÐикакиÑ
placeholder'ов ({{name}} и Ñ.п.) пока не подÑÑавлÑеÑÑÑ â ÑÑо напиÑеÑе, Ñо и ÑйдÑÑ.":"HTML tags supported. No placeholders substituted yet â the text is sent as-is."})]}),e.jsx("div",{className:"flex justify-end pt-2",children:e.jsxs(te,{onClick:()=>void E(),disabled:!f,children:[d&&e.jsx(ue,{className:"h-4 w-4 mr-2 animate-spin"}),!d&&e.jsx($t,{className:"h-4 w-4 mr-2"}),l==="ru"?"СоÑ
ÑаниÑÑ":"Save"]})})]})})]})})},os=({trademarks:t,value:n,onChange:c,existingTrademarkIds:o,hasUniversalTemplate:m})=>{const l=t.length>=2;return e.jsxs(G,{children:[e.jsxs(Q,{children:[e.jsx(se,{className:"text-base",children:"Шаг 1. ТоваÑнÑй знак"}),e.jsx(ce,{children:"ÐÑбеÑиÑе ÑоваÑнÑй знак, Ð´Ð»Ñ ÐºÐ¾ÑоÑого ÑоздаÑÑÑÑ Ñаблон. Ðдин ÑоваÑнÑй знак = один Ñаблон. ÐалоÑкой оÑмеÑÐµÐ½Ñ Ð¢Ð, Ð´Ð»Ñ ÐºÐ¾ÑоÑÑÑ
Ñже еÑÑÑ ÑоÑ
ÑаненнÑй Ñаблон."})]}),e.jsx(ee,{children:t.length===0?e.jsx("p",{className:"text-sm text-muted-foreground italic",children:"У компании Ð
4½ÐµÑ ÑоваÑнÑÑ
знаков. ÐобавÑÑе Ñ
оÑÑ Ð±Ñ Ð¾Ð´Ð¸Ð½, ÑÑÐ¾Ð±Ñ ÑоздаÑÑ Ñаблон жалобÑ."}):e.jsxs("div",{className:"flex flex-wrap gap-2",children:[l&&e.jsx(Ia,{selected:n===null,onClick:()=>c(null),icon:e.jsx(Vt,{className:"h-3.5 w-3.5 shrink-0"}),label:"ÐÑе ÑоваÑнÑе знаки",sublabel:"обÑий Ñаблон",hasTemplate:!!m}),t.map(p=>e.jsx(Ia,{selected:n===p.id,onClick:()=>c(p.id),label:p.name,sublabel:p.certificate_number?`â ${p.certificate_number}`:void 0,hasTemplate:!!(o!=null&&o.has(p.id))},p.id))]})})]})},Ia=({selected:t,onClick:n,label:c,sublabel:o,icon:m,hasTemplate:l})=>e.jsxs("button",{type:"button",onClick:n,className:le("inline-flex items-center gap-1.5 rounded-full border px-3 py-1.5 text-sm transition-colors",t?"bg-primary text-primary-foreground border-primary hover:bg-primary/90":"bg-background hover:bg-muted/60 border-border"),title:l?"Уже еÑÑÑ ÑоÑ
ÑаненнÑй Ñаблон":void 0,children:[t?e.jsx(Ne,{className:"h-3.5 w-3.5 shrink-0"}):m,e.jsx("span",{className:"font-medium",children:c}),o&&e.jsx("span",{className:le("text-xs",t?"text-primary-foreground/80":"text-muted-foreground"),children:o}),l&&!t&&e.jsx(St,{className:"h-3.5 w-3.5 shrink-0 text-emerald-600","aria-label":"Уже еÑÑÑ ÑоÑ
ÑаненнÑй Ñаблон"})]}),je=({trademarks:t,children:n,value:c,onChange:o,companyId:m,marketplace:l})=>{var j;const{data:p}=Et(m,l),_=h.useMemo(()=>t.length===1?t[0].id:void 0,[t]);h.useEffect(()=>{_!==void 0&&c.trademarkId===void 0&&o({trademarkId:_})},[_,c.trademarkId,o]);const a=c.trademarkId!==void 0,C=()=>{o({trademarkId:_})};return e.jsx("div",{className:"space-y-4",children:a?e.jsxs("div",{className:"space-y-3",children:[e.jsxs("div",{className:"flex items-center justify-between rounded-md border border-primary/30 bg-primary/5 px-3 py-2",children:[e.jsxs("div",{className:"text-xs text-muted-foreground",children:["Шаблон:"," ",e.jsx("span",{className:"font-medium text-foreground",children:c.trademarkId===null?"ÐÑе ÑоваÑнÑе знаки":((j=t.find(N=>N.id===c.trademarkId))==null?void 0:j.name)??"â"})]}),t.length>1&&e.jsxs(te,{type:"button",variant:"ghost",size:"sm",onClick:C,className:"gap-1.5 h-7",children:[e.jsx(Ut,{className:"h-3.5 w-3.5"}),"ÐзмениÑÑ"]})]}),n({trademarkId:c.trademarkId??null})]}):e.jsx(os,{trademarks:t,value:c.trademarkId,onChange:N=>o({trademarkId:N}),existingTrademarkIds:p==null?void 0:p.trademarkIds,hasUniversalTemplate:p==null?void 0:p.hasUniversal})})},cs=({companyId:t,companyName:n,trademarks:c})=>{const{user:o}=Pt(),{t:m}=oe(),[l,p]=h.useState("wildberries"),[_,a]=h.useState(null),[C,j]=h.useState(null),[N,d]=h.useState({});h.useEffect(()=>{if(!t)return;let x=!1;return(async()=>{const{data:f,error:E}=await B.from("companies").select("email_address").eq("id",t).maybeSingle();if(!x){if(E){console.error("[ComplaintTemplateTab] failed to load company email:",E),j(null);return}j((f==null?void 0:f.email_address)??null)}})(),()=>{x=!0}},[t]);const T=h.useRef({});h.useEffect(()=>{const x=f=>{Object.values(T.current).some(Boolean)&&(f.preventDefault(),f.returnValue="")};return window.addEventListener("beforeunload",x),()=>window.removeEventListener("beforeunload",x)},[]),h.useEffect(()=>{d({})},[t]);const A=x=>{if(x!==l){if(T.current[l]){a(x);return}p(x)}},L=()=>{_&&(T.current[l]=!1,p(_)),a(null)},P=x=>({value:N[x]??{},onChange:f=>d(E=>({...E,[x]:f}))});return e.jsxs(e.Fragment,{children:[e.jsxs(qa,{value:l,onValueChange:A,className:"w-full",children:[e.jsxs($a,{className:"grid w-full grid-cols-5 max-w-3xl",children:[e.jsx(me,{value:"wildberries",children:"Wildberries"}),e.jsx(me,{value:"ozon",children:"Ozon"}),e.jsx(me,{value:"yandex_market",children:"ЯндекÑ"}),e.jsx(me,{value:"avito",children:"ÐвиÑо"}),e.jsx(me,{value:"domains",children:m("domainsTabLabel")})]}),e.jsx(de,{value:"wildberries",className:"mt-6",children:e.jsx(je,{trademarks:c,companyId:t,marketplace:"wildberries",...P("wildberries"),children:x=>e.jsx(as,{companyId:t,companyName:n,trademarks:c,userEmail:(o==null?void 0:o.email)||"",userId:(o==null?void 0:o.id)||"",companyEmail:C,trademarkId:x.trademarkId,onDirtyChange:f=>{T.current.wildberries=f}})})}),e.jsx(de,{value:"ozon",className:"mt-6",children:e.jsx(je,{trademarks:c,companyId:t,marketplace:"ozon",...P("ozon"),children:x=>e.jsx(ts,{companyId:t,companyName:n,trademarks:c,userEmail:(o==null?void 0:o.email)||"",userId:(o==null?void 0:o.id)||"",companyEmail:C,trademarkId:x.trademarkId,onDirtyChange:f=>{T.current.ozon=f}})})}),e.jsx(de,{value:"megamarket",className:"mt-6",children:e.jsx(je,{trademarks:c,companyId:t,marketplace:"megamarket",...P("megamarket"),children:x=>e.jsx(ss,{companyId:t,companyName:n,trademarks:c,userEmail:(o==null?void 0:o.email)||"",userId:(o==null?void 0:o.id)||"",companyEmail:C,trademarkId:x.trademarkId,onDirtyChange:f=>{T.current.megamarket=f}})})}),e.jsx(de,{value:"yandex_market",className:"mt-6",children:e.jsx(je,{trademarks:c,companyId:t,marketplace:"yandex_market",...P("yandex_market"),children:x=>e.jsx(rs,{companyId:t,companyName:n,trademarks:c,userEmail:(o==null?void 0:o.email)||"",userId:(o==null?void 0:o.id)||"",companyEmail:C,trademarkId:x.trademarkId,onDirtyChange:f=>{T.current.yandex_market=f}})})}),e.jsx(de,{value:"avito",className:"mt-6",children:e.jsx(je,{trademarks:c,companyId:t,marketplace:"avito",...P("avito"),children:x=>e.jsx(is,{companyId:t,companyName:n,trademarks:c,userEmail:(o==null?void 0:o.email)||"",userId:(o==null?void 0:o.id)||"",companyEmail:C,trademarkId:x.trademarkId,onDirtyChange:f=>{T.current.avito=f}}
4)})}),e.jsx(de,{value:"domains",className:"mt-6",children:e.jsx(je,{trademarks:c,companyId:t,marketplace:"web",...P("domains"),children:x=>{var f;return e.jsx(ls,{companyId:t,userId:(o==null?void 0:o.id)||"",trademarkId:x.trademarkId,trademarkName:x.trademarkId?((f=c.find(E=>E.id===x.trademarkId))==null?void 0:f.name)??null:null,onDirtyChange:E=>{T.current.domains=E}})}})})]}),e.jsx(Ue,{open:_!==null,onOpenChange:x=>{x||a(null)},children:e.jsxs(Pe,{children:[e.jsxs(Fe,{children:[e.jsx(Le,{children:m("unsavedSwitchTitle")}),e.jsx(Ae,{children:m("unsavedSwitchDescription")})]}),e.jsxs(Re,{children:[e.jsx(Oe,{children:m("stayHere")}),e.jsx(Ie,{onClick:L,children:m("discardAndSwitch")})]})]})})]})},ds=[{code:"RUB",symbol:"â½"},{code:"USD",symbol:"$"}],ms=({value:t,onChange:n,disabled:c})=>{const{t:o}=oe();return e.jsxs("div",{className:"space-y-1.5",children:[e.jsx(D,{htmlFor:"currency-switcher",className:"text-xs text-muted-foreground uppercase tracking-wide",children:o("currencySwitcherLabel")}),e.jsxs(he,{value:t,onValueChange:m=>n(m),disabled:c,children:[e.jsx(xe,{id:"currency-switcher",className:"w-[125px] h-10",children:e.jsx(ge,{})}),e.jsx(fe,{children:ds.map(m=>e.jsx(ye,{value:m.code,className:"cursor-pointer",children:e.jsxs("span",{className:"flex items-center gap-2",children:[e.jsx("span",{className:"font-mono text-sm",children:m.symbol}),e.jsx("span",{className:"text-sm font-medium",children:m.code})]})},m.code))})]})]})},ps={currency:"RUB",payer_type:"individual",payer_name:"",tax_id:"",kpp:"",email:"",phone:"",billing_address:""},us=({companyId:t})=>{const{t:n}=oe(),{data:c,isLoading:o}=Kt(t),m=Yt(t),[l,p]=h.useState(ps),[_,a]=h.useState("edit"),C=!!(c!=null&&c.profile),j=_==="edit",N=()=>{c!=null&&c.profile&&p({currency:c.profile.currency,payer_type:c.profile.payer_type,payer_name:c.profile.payer_name??"",tax_id:c.profile.tax_id??"",kpp:c.profile.kpp??"",email:c.profile.email??"",phone:c.profile.phone??"",billing_address:c.profile.billing_address??""})};h.useEffect(()=>{c!=null&&c.profile&&(N(),a("view"))},[c]);const d=l.payer_type==="legal_entity",T=(v,u)=>p(U=>({...U,[v]:u})),A=v=>{p(u=>({...u,payer_type:v,kpp:v==="individual"?"":u.kpp}))},L=d&&l.currency==="RUB",P=!m.isPending&&l.payer_name.trim().length>0&&l.tax_id.trim().length>0&&l.email.trim().length>0&&l.phone.trim().length>0&&l.billing_address.trim().length>0&&(!L||l.kpp.trim().length>0),x=v=>v.map(u=>{const U={payer_type:"paymentBillingType",payer_name:d?"paymentPayerNameCompanyLabel":"paymentPayerNameIndividualLabel",tax_id:"billingTaxIdLabel",kpp:"paymentKppLabel",email:"paymentEmailLabel",phone:"paymentPhoneLabel",billing_address:"paymentAddressLabel",currency:"currencySwitcherLabel"};return U[u]?n(U[u]):u}).join(", "),f=()=>{N(),a("view")},E=()=>
4{if(!P){H.error(n("billingSettingsRequiredFields"));return}m.mutate({form:l,hasProfile:C},{onSuccess:()=>{H.success(n("billingSettingsSaved")),a("view")},onError:v=>{if(v instanceof Jt){if(v.code==="BILLING_PROFILE_INCOMPLETE"&&v.missingFields.length){H.error(`${n("billingSettingsSaveFailed")}: ${n("billingSettingsMissingFields")} â ${x(v.missingFields)}`);return}if(v.code==="BILLING_PROFILE_INVALID"&&v.invalidFields.length){H.error(`${n("billingSettingsSaveFailed")}: ${n("billingSettingsInvalidFields")} â ${x(v.invalidFields)}`);return}if(v.code==="COMPANY_COUNTRY_CODE_REQUIRED"){H.error(n("billingSettingsCountryCodeRequired"));return}H.error(`${n("billingSettingsSaveFailed")}: ${v.code}`);return}const u=v instanceof Error?v.message:"";H.error(u?`${n("billingSettingsSaveFailed")}: ${u}`:n("billingSettingsSaveFailed"))}})};if(o)return e.jsxs(G,{children:[e.jsxs(Q,{children:[e.jsx(ma,{className:"h-6 w-64"}),e.jsx(ma,{className:"h-4 w-96 mt-2"})]}),e.jsx(ee,{className:"space-y-4",children:Array.from({length:6}).map((v,u)=>e.jsx(ma,{className:"h-10 w-full"},u))})]});const S=v=>e.jsx("div",{className:"text-base font-medium text-foreground min-h-[24px]",children:v!=null&&v.trim()?v:e.jsx("span",{className:"text-muted-foreground font-normal",children:"â"})}),y="text-[11px] text-muted-foreground uppercase tracking-wider font-medium",s=j?"space-y-1.5":"space-y-1.5 pb-4 border-b border-border/50 last:border-b-0";return e.jsxs(G,{children:[e.jsxs(Q,{children:[e.jsx(se,{children:n("billingSettingsTitle")}),e.jsx(ce,{children:n("billingSettingsDescription")})]}),e.jsxs(ee,{className:"space-y-5",children:[e.jsx("div",{children:j?e.jsx(ms,{value:l.currency,onChange:v=>T("currency",v)}):e.jsxs("div",{className:s,children:[e.jsx(D,{className:y,children:n("currencySwitcherLabel")}),S(l.currency)]})}),e.jsxs("div",{className:s,children:[e.jsx(D,{className:j?void 0:y,children:n("paymentBillingType")}),j?e.jsxs(Ft,{value:l.payer_type,onValueChange:v=>A(v),className:"grid grid-cols-2 gap-2 max-w-md",children:[e.jsxs("label",{className:"flex items-center gap-2 rounded-lg border border-border p-2.5 cursor-pointer hover:bg-accent transition-colors",children:[e.jsx(Ua,{value:"individual"}),e.jsx("span",{className:"text-sm",children:n("paymentIndividual")})]}),e.jsxs("label",{className:"flex items-center gap-2 rounded-lg border border-border p-2.5 cursor-pointer hover:bg-accent transition-colors",children:[e.jsx(Ua,{value:"legal_entity"}),e.jsx("span",{className:"text-sm",children:n("paymentCompany")})]})]}):S(n(d?"paymentCompany":"paymentIndividual"))]}),e.jsxs("div",{className:s,children:[e.jsxs(D,{htmlFor:"billing-payer-name",className:j?void 0:y,children:[n(d?"paymentPayerNameCompanyLabel":"paymentPayerNameIndividualLabel"),j&&e.jsx(z,{})]}),j?e.jsx(Y,{id:"billing-payer-name",value:l.payer_name,onChange:v=>T("payer_name",v.target.value),placeholder:n(d?"paymentPayerNamePlaceholderCompany":"paymentPayerNamePlaceholderIndividual")}):S(l.payer_name)]}),e.jsxs("div",{className:`${d?"grid grid-cols-2 gap-3":""} ${j?"":"pb-4 border-b border-border/50"}`,children:[e.jsxs("div",{className:"space-y-1.5",children:[e.jsxs(D,{htmlFor:"billing-tax-id",className:j?void 0:y,children:[n("billingTaxIdLabel"),j&&e.jsx(z,{})]}),j?e.jsx(Y,{id:"billing-tax-id",value:l.tax_id,onChange:v=>T("tax_id",v.target.value),placeholder:n(d?"paymentTaxIdPlaceholderCompany":"paymentTaxIdPlaceholderIndividual")}):S(l.tax_id)]}),d&&e.jsxs("div",{className:"space-y-1.5",children:[e.jsxs(D,{htmlFor:"billing-kpp",className:j?void 0:y,children:[n("paymentKppLabel"),j&&l.currency==="RUB"&&e.jsx(z,{})]}),j?e.jsx(Y,{id:"billing-kpp",value:l.kpp,onChange:v=>T("kpp",v.target.value),placeholder:n("paymentKppPlaceholder")}):S(l.kpp)]})]}),e.jsxs("div",{className:`grid grid-cols-1 md:grid-cols-2 gap-3 ${j?"":"pb-4 border-b border-border/50"}`,children:[e.jsxs("div",{className:"space-y-1.5",children:[e.jsxs(D,{htmlFor:"billing-email",className:j?void 0:y,children:[n("paymentEmailLabel"),j&&e.jsx(z,{})]}),j?e.jsx(Y,{id:"billing-email",type:"email",value:l.email,onChange:v=>T("email",v.target.value),placeholder:"[email protected]"}):S(l.email)]}),e.jsxs("div",{className:"space-y-1.5",children:[e.jsxs(D,{htmlFor:"billing-phone",className:j?void 0:y,children:[n("paymentPhoneLabel"),j&&e.jsx(z,{})]}),j?e.jsx(Y,{id:"billing-phone",type:"tel",value:l.phone,onChange:v=>T("phone",v.target.value),placeholder:"+7 (999) 000-00-00"}):S(l.phone)]})]}),e.jsxs("div",{className:s,children:[e.jsxs(D,{htmlFor:"billing-address",className:j?void 0:y,children:[n("paymentAddressLabel"),j&&e.jsx(z,{})]}),j?e.jsx(Y,{id:"billing-address",value:l.billing_address,onChange:v=>T("billing_address",v.target.value)}):S(l.billing_address)]}),e.jsx("div",{className:"flex justify-end gap-2 pt-2",children:j?e.jsxs(e.Fragment,{children:[C&&e.jsx(te,{type:"button",variant:"outline",onClick:f,disabled:m.isPending,children:n("cancel")}),e.jsx(te,{type:"button",onClick:E,disabled:!P,children:m.isPending?e.jsx(ue,{className:"h-4 w-4 animate-spin"}):e.jsx("div",{children:n("billingSettingsSave")}
4)})]}):e.jsx(te,{type:"button",onClick:()=>a("edit"),children:n("edit")})})]})]})};async function Da(t,n,c=3){let o=null;for(let m=0;m<c;m++){try{const l=await fetch(t,n);if(l.status!==503)return l;o=l}catch(l){if(m===c-1)throw l}await new Promise(l=>setTimeout(l,400*Math.pow(2,m)))}return o}const Xe={},hs=3e4,xs=t=>{const n=Xe[t];return n&&Date.now()-n.timestamp<hs?n.data:null},gs=(t,n)=>{Xe[t]={data:n,timestamp:Date.now()}},ua=t=>{Object.keys(Xe).forEach(n=>{n.startsWith(t)&&delete Xe[n]})},Ma={view_monitoring:!1,edit_monitoring_products:!1,create_monitoring_requests:!1,interact_monitoring_results:!1,view_sellers:!1,edit_sellers:!1,view_complaints:!1,create_complaint_requests:!1,add_employees:!1},fs=t=>{const[n,c]=h.useState([]),[o,m]=h.useState({maxTrademarks:1,maxProducts:5}),[l,p]=h.useState([]),[_,a]=h.useState(!0),[C,j]=h.useState(null),N=h.useRef(!1),d=h.useCallback(async(P=!1)=>{var f,E;if(!t||N.current)return;N.current=!0,a(!0),j(null);const x=`company-profile-${t}`;if(!P){const S=xs(x);if(S){c(S.trademarks),m(S.limits),p(S.employees),a(!1),N.current=!1;return}}try{const[S,y,s]=await Promise.all([B.from("companies").select("max_trademarks, max_products").eq("id",t).single(),B.from("company_trademarks").select("id, name, transliteration, certificate_number, mktu_classes, fips_url, image_url, is_international").eq("company_id",t),B.from("company_employees").select("id, user_id, permissions, created_at").eq("company_id",t).order("created_at",{ascending:!0})]),v={maxTrademarks:((f=S.data)==null?void 0:f.max_trademarks)||1,maxProducts:((E=S.data)==null?void 0:E.max_products)||5},u=y.data||[];let U=[];if(s.data&&s.data.length>0){const q=s.data.map($=>$.user_id),{data:{session:I}}=await B.auth.getSession(),re=await Da(Ze("company-employee-emails"),{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${I==null?void 0:I.access_token}`},body:JSON.stringify({companyId:t,userIds:q})}),R=await re.json().catch(()=>({})),ie=re.ok?R==null?void 0:R.profiles:null;U=s.data.map($=>{var J;return{...$,email:((J=ie==null?void 0:ie.find(ae=>ae.id===$.user_id))==null?void 0:J.email)||"ÐеизвеÑÑно",permissions:{...Ma,...$.permissions}}})}c(u),m(v),p(U),gs(x,{trademarks:u,limits:v,employees:U})}catch(S){console.error("Error loading company profile data:",S),j("ÐÑибка загÑÑзки даннÑÑ
")}finally{a(!1),N.current=!1}},[t]),T=h.useCallback(async()=>{if(t)try{const{data:P}=await B.from("company_trademarks").select("id, name, transliteration, certificate_number, mktu_classes, fips_url, image_url, is_international").eq("company_id",t);c(P||[]),ua(`company-profile-${t}`)}catch(P){console.error("Error refetching trademarks:",P)}},[t]),A=h.useCallback(async()=>{if(t)try{const{data:P}=await B.from("company_employees").select("id, user_id, permissions, created_at").eq("company_id",t).order("created_at",{ascending:!0});if(P&&P.length>0){const x=P.map(v=>v.user_id),{data:{session:f}}=await B.auth.getSession(),E=await Da(Ze("company-employee-emails"),{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${f==null?void 0:f.access_token}`},body:JSON.stringify({companyId:t,userIds:x})}),S=await E.json().catch(()=>({})),y=E.ok?S==null?void 0:S.profiles:null,s=P.map(v=>{var u;return{...v,email:((u=y==null?void 0:y.find(U=>U.id===v.user_id))==null?void 0:u.email)||"ÐеизвеÑÑно",permissions:{...Ma,...v.permissions}}});p(s)}else p([]);ua(`company-profile-${t}`)}catch(P){console.error("Error refetching employees:",P)}},[t]),L=h.useCallback(async()=>{ua(`company-profile-${t}`),await d(!0)},[t,d]);return h.useEffect(()=>{d()},[d]),{trademarks:n,limits:o,employees:l,isLoading:_,error:C,refetchTrademarks:T,refetchEmployees:A,refetchAll:L}},Cs=()=>{const{selectedCompany:t}=Lt(),[n,c]=h.useState("products"),{t:o}=oe(),{isAdmin:m}=At(),l=m,{trademarks:p,limits:_,employees:a,isLoading:C,refetchTrademarks:j,refetchEmployees:N}=fs(t==null?void 0:t.id);return t!=null&&t.id?C?e.jsx(Rt,{}):e.jsxs("div",{className:"space-y-8",children:[e.jsxs("div",{className:"flex flex-col items-center text-center space-y-4",children:[e.jsxs(Ot,{className:"h-24 w-24 border-4 border-background shadow-lg",children:[e.jsx(It,{src:(t==null?void 0:t.logo_url)||"",alt:t==null?void 0:t.name}),e.jsx(Dt,{className:"bg-primary/10 text-primary text-2xl",children:e.jsx(Mt,{className:"h-10 w-10"})})]}),e.jsx("h1",{className:"text-2xl font-bold text-foreground",children:(t==null?void 0:t.name)||o("company")})]}),e.jsxs(qa,{value:n,onValueChange:c,className:"w-full",children:[e.jsxs($a,{className:"grid w-full max-w-3xl mx-auto "+(l?"grid-cols-4":"grid-cols-3"),children:[e.jsx(me,{value:"products",children:o("productSettings")}),e.jsx(me,{value:"complaint-template",children:o("complaintTemplateMy")}),l&&e.jsx(me,{value:"billing-settings",children:o("companySettingsTab")}),e.jsx(me,{value:"employees",children:o("employeesTab")})]}),e.jsx(de,{value:"products",className:"mt-6",children:e.jsx(Zt,{companyId:t.id,trademarks:p,maxTrademarks:_.maxTrademarks,maxProducts:_.maxProducts,onTrademarksChange:j})}),e.jsx(de,{value:"complaint-template",className:"mt-6",children:e.jsx(cs,{companyId:t.id,companyName:t.name,trademarks:p})}),l&&e.jsx(de,{value:"billing-settings",className:"mt-6",children:e.jsx(us,{companyId:t.id})}),e.jsx(de,{value:"employees",className:"mt-6",children:e.jsx(Xt,{companyId:t.id,employees:a,onEmployeesChange:N})})]})]}):e.jsx("div",{className:"flex items-center justify-center min-h-[400px]",children:e.jsx("p",{className:"text-muted-foreground",children:o("companyNotSelected")})})};export{Cs 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.