1import{c as gs,r as t,s as g,a2 as ts,t as Re,a as Ks,j as e,m as fe,B as b,w as ee,K as ye,N as be,O as Le,x as ae,y as q,I as se,T as is,M as Bs,o as Ht,u as Zs,$ as as,G as Ke,H as Ze,J as He,F as at,n as js,a3 as ka,a4 as Ca,z as Kn,a5 as Zn,X as Wt,Z as ws,Y as ds,a6 as tt,a7 as Es,a8 as It,a9 as Tt,aa as Ot,ab as Ft,ac as Mt,ad as Lt,ae as Rt,af as Vt,ag as sa,ah as nt,L as bn,q as Hn,p as Wn}from"./index-MoAbC8_9.js";import{L as ta}from"./Layout-jB2m3rBw.js";import{M as Gn,P as Nn,C as xt,a as ht,b as pt,A as _n,V as Jn,S as Yn,c as Qn,d as Xn}from"./collapsible-BIxz44zB.js";import{B as rt,a as er,b as sr,c as aa,d as Sa,e as za,f as Da}from"./breadcrumb-CmKLwRya.js";import{M as Pa,A as Aa}from"./AdminSidebar-B1OFksO6.js";import{T as ks,a as Cs,c as We,b as es}from"./tabs-5EVsfllK.js";import{C as ms}from"./confirm-dialog-DHYtbMdr.js";import{T as $e,a as Be,b as Ne,c as D,d as Ue,e as _}from"./table-BNHSYido.js";import{P as Xe}from"./plus-CkJQv7GY.js";import{S as ha}from"./sparkles-OdPvYVOS.js";import{P as Ns}from"./pencil-C_0Cp3wi.js";import{T as qe}from"./trash-2-DRJ_nWSl.js";import{S as ss}from"./switch-BHj3-8MN.js";import{S as gt}from"./separator-CQ84aZ0V.js";import{B as Q}from"./badge-BHbYeRgi.js";import{R as wn,d as tr,g as ar,_ as kn,u as ns,a as Cn,b as Sn,c as nr,e as rr,f as ir,W as na,S as zn,h as Dn}from"./useCostCategories-Cao1SRG4.js";import{S as Ds}from"./save-DWdLHugL.js";import{B as Dt}from"./bell-CKHJStUz.js";import{U as Fs}from"./users-xui-UtA1.js";import{b as pa}from"./avatar-Bl5f64JA.js";import{F as lr,a as or,C as cr,b as Ea}from"./ForumCategoryRow-od0t3MBP.js";import{S as De,a as Pe,b as Ae,c as Ee,d as me}from"./select-ChAxOmxm.js";import{A as ut}from"./arrow-left-CZKmX_Y-.js";import{S as fs}from"./search-_fcwEKN-.js";import{F as _s}from"./file-text-Bif0RP8Y.js";import{S as Gt}from"./settings-BUFFH3UG.js";import{C as xs}from"./checkbox-D2A7tWS7.js";import{D as Ge,a as Je,b as Ye,c as Qe,d as us,f as yt,e as ls}from"./dialog-DrI7Oddz.js";import{S as bt}from"./scroll-area-CoT3wSM0.js";import{I as Us}from"./info-CZr0REZX.js";import{A as Gs}from"./arrow-right-QNKB-9eH.js";import{S as As,C as Ts,d as jt,M as $t,D as dr,a as mr,b as ur,c as Ia,e as xr}from"./Header-CnJGZ8vQ.js";import{U as ba}from"./user-Cvsz7Lm_.js";import{f as hs}from"./format-Beid_ZIk.js";import{c as ys}from"./cs-DzBP63t1.js";import{L as Vs,U as ga}from"./unlink-CxCPpy3W.js";import{E as bs}from"./eye-DKrvAixa.js";import{A as Is}from"./arrow-up-down-D7o6PKMM.js";import{T as vs}from"./textarea-4z16PwID.js";import{D as vt}from"./download-DXQgHLv7.js";import{T as hr}from"./thermometer-CsW4-4zi.js";import{C as Pn}from"./clipboard-list-CzdQdj9P.js";import{R as An}from"./receipt-DnGXta2k.js";import{F as En}from"./folder-open-CYrqGGwY.js";import{P as Bt}from"./progress-CIau9pND.js";import{P as pr,C as gr,M as jr,S as Na,r as vr,u as fr,U as yr}from"./xlsx-CdLBLU9U.js";import{f as Ta}from"./pollQuorum-DtU2ni5k.js";import{i as In}from"./pollDates-DP2VfLei.js";import{C as Tn}from"./chart-column-Bo5i9GGE.js";import{S as $s}from"./send-DIVN8qsp.js";import{C as ps}from"./circle-check-7w5_oQMu.js";import{T as br}from"./TransferOwnershipDialog-DJ-o6_JR.js";import{B as Jt}from"./building-crte1H4H.js";import{A as Nr}from"./arrow-right-left-Yai1ia-T.js";import{C as qs}from"./circle-check-big-_JLEBINb.js";import{I as _r}from"./InvitePreviewDialog-DT7jKBqI.js";import{U as Ut}from"./user-check-CArzXJ3-.js";import{C as Os}from"./copy-BJvw7_4P.js";import{C as Js}from"./chevron-down-BDe4YKQW.js";import{U as Ps}from"./upload-BH1HltYO.js";import{H as On}from"./house-DjS1WMqx.js";import{C as wr}from"./calculator-GhS8BFwe.js";import{u as kr,a as Cr,b as Sr}from"./useReserveFundData-CaCbmV8U.js";import{E as Yt}from"./euro-Cc6O9qjZ.js";import{T as zr}from"./trending-up-Cg9WFJWB.js";import{T as Dr}from"./trending-down-EHPUNHPt.js";import{C as Qt}from"./calendar-CnsXUgOr.js";import{A as Pr,a as Ar,b as Er,c as Ir}from"./accordion-CatLYK39.js";import{P as Tr,a as Or,b as Fr}from"./popover-BsQ559UC.js";import{C as _a}from"./circle-alert-CI-iPm0z.js";import{F as Pt}from"./file-down-D9u4xV4V.js";import{P as Oa}from"./pen-line-3TShWx6o.js";import{E as Ys}from"./external-link-Bd1Ktkpe.js";import{D as Mr}from"./droplets-Cp2l0Gq2.js";import{R as Lr}from"./route-CzrZqZen.js";import{P as Rr}from"./piggy-bank-DP-A2O0m.js";import{F as ft}from"./flame-wMx8KIS8.js";import{W as Fn}from"./wrench-B4A_f5hE.js";import{Z as Mn}from"./zap-D5DuRxrj.js";import{A as it,b as qt,a as lt}from"./alert-B1M6s1_G.js";import{W as At}from"./wallet-e9E2tgeo.js";import{G as wa}from"./globe-DTZBS0aY.js";import{F as Fa}from"./filter-DtRxSZ25.js";import{L as Xt}from"./languages-DJ80weRR.js";import{a as Ma,A as Vr}from"./arrow-up-D486G_0n.js";import{D as mt}from"./database-yc2noHJi.js";import{P as $r}from"./play-Dv41UmTM.js";import{E as ja}from"./eye-off-D1RUMkPr.js";import{C as Br}from"./circle-minus-C6Bv3LRu.js";import{C as Ur}from"./circle-help-BFmb_2uk.js";import{H as qr}from"./history-GAI9mcQt.js";import{I as Kr}from"./image-zcTlJhLM.js";import{S as Zr}from"./snowflake-DxjZHYUy.js";import{S as Hr}from"./sun-DQzfPl1A.js";import{S as Hs}from"./skeleton-ClxqB572.js";import{S as Ln}from"./shield-check-DViJUJ8V.js";import{F as Wr}from"./fingerprint-tahGlWAG.js";import{M as Gr}from"./monitor-BfzJ2sMA.js";import{m as Jr}from"./en-US-CQ3IMwMG.js";import{L as La}
1from"./log-in-CT_3hHd4.js";import{C as Yr}from"./chevron-left-BrISfdwW.js";import{U as Qr}from"./user-plus-BJ2nTN1d.js";import{T as Xr}from"./table-pagination-DgaWMZqT.js";import{p as Ra}from"./hausverwaltungComparison-BTWUXTnR.js";import"./file-search-B2CpYcS_.js";import"./index-D9-GACGG.js";import"./endOfMonth-D_4h-ZFk.js";import"./purify.es-dhnUglUx.js";import"./index-Dh4i1-J3.js";import"./video-DFpZvpEd.js";import"./minus-Dry52jGc.js";import"./table-BYzMA2MF.js";import"./printer-Bb7W1Pva.js";import"./ellipsis-BEOtFA2b.js";import"./thumbs-up-jDPlFMTx.js";import"./paperclip-I8ctU5eK.js";import"./index-BdQq_4o_.js";import"./chevron-up-JyGCcpt9.js";import"./mountain-BHfTfCFy.js";/** 2 * @license lucide-react v0.462.0 - ISC 3 * 4 * This source code is licensed under the ISC license. 5 * See the LICENSE file in the root directory of this source tree. 6 */const ei=gs("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"}]]);/** 7 * @license lucide-react v0.462.0 - ISC 8 * 9 * This source code is licensed under the ISC license. 10 * See the LICENSE file in the root directory of this source tree. 11 */const Va=gs("Ban",[["circle",{cx:"12",cy:"12",r:"10",key:"1mglay"}],["path",{d:"m4.9 4.9 14.2 14.2",key:"1m5liu"}]]);/** 12 * @license lucide-react v0.462.0 - ISC 13 * 14 * This source code is licensed under the ISC license. 15 * See the LICENSE file in the root directory of this source tree. 16 */const si=gs("Bot",[["path",{d:"M12 8V4H8",key:"hb8ula"}],["rect",{width:"16",height:"12",x:"4",y:"8",rx:"2",key:"enze0r"}],["path",{d:"M2 14h2",key:"vft8re"}],["path",{d:"M20 14h2",key:"4cs60a"}],["path",{d:"M15 13v2",key:"1xurst"}],["path",{d:"M9 13v2",key:"rq6x2g"}]]);/** 17 * @license lucide-react v0.462.0 - ISC 18 * 19 * This source code is licensed under the ISC license. 20 * See the LICENSE file in the root directory of this source tree. 21 */const va=gs("Folder",[["path",{d:"M20 20a2 2 0 0 0 2-2V8a2 2 0 0 0-2-2h-7.9a2 2 0 0 1-1.69-.9L9.6 3.9A2 2 0 0 0 7.93 3H4a2 2 0 0 0-2 2v13a2 2 0 0 0 2 2Z",key:"1kt360"}]]);/** 22 * @license lucide-react v0.462.0 - ISC 23 * 24 * This source code is licensed under the ISC license. 25 * See the LICENSE file in the root directory of this source tree. 26 */const Rn=gs("GripVertical",[["circle",{cx:"9",cy:"12",r:"1",key:"1vctgf"}],["circle",{cx:"9",cy:"5",r:"1",key:"hp0tcf"}],["circle",{cx:"9",cy:"19",r:"1",key:"fkjjf6"}],["circle",{cx:"15",cy:"12",r:"1",key:"1tmaij"}],["circle",{cx:"15",cy:"5",r:"1",key:"19l28e"}],["circle",{cx:"15",cy:"19",r:"1",key:"f4zoj3"}]]);/** 27 * @license lucide-react v0.462.0 - ISC 28 * 29 * This source code is licensed under the ISC license. 30 * See the LICENSE file in the root directory of this source tree. 31 */const ti=gs("MailWarning",[["path",{d:"M22 10.5V6a2 2 0 0 0-2-2H4a2 2 0 0 0-2 2v12c0 1.1.9 2 2 2h12.5",key:"e61zoh"}],["path",{d:"m22 7-8.97 5.7a1.94 1.94 0 0 1-2.06 0L2 7",key:"1ocrg3"}],["path",{d:"M20 14v4",key:"1hm744"}],["path",{d:"M20 22v.01",key:"12bgn6"}]]);/** 32 * @license lucide-react v0.462.0 - ISC 33 * 34 * This source code is licensed under the ISC license. 35 * See the LICENSE file in the root directory of this source tree. 36 */const ai=gs("Maximize2",[["polyline",{points:"15 3 21 3 21 9",key:"mznyad"}],["polyline",{points:"9 21 3 21 3 15",key:"1avn1i"}],["line",{x1:"21",x2:"14",y1:"3",y2:"10",key:"ota7mn"}],["line",{x1:"3",x2:"10",y1:"21",y2:"14",key:"1atl0r"}]]);/** 37 * @license lucide-react v0.462.0 - ISC 38 * 39 * This source code is licensed under the ISC license. 40 * See the LICENSE file in the root directory of this source tree. 41 */const Kt=gs("Pen",[["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"}]]);/** 42 * @license lucide-react v0.462.0 - ISC 43 * 44 * This source code is licensed under the ISC license. 45 * See the LICENSE file in the root directory of this source tree. 46 */const ni=gs("RotateCw",[["path",{d:"M21 12a9 9 0 1 1-9-9c2.52 0 4.93 1 6.74 2.74L21 8",key:"1p45f6"}],["path",{d:"M21 3v5h-5",key:"1q7to0"}]]);/** 47 * @license lucide-react v0.462.0 - ISC 48 * 49 * This source code is licensed under the ISC license. 50 * See the LICENSE file in the root directory of this source tree. 51 */const ri=gs("Settings2",[["path",{d:"M20 7h-9",key:"3s1dr2"}],["path",{d:"M14 17H5",key:"gfn3mx"}],["circle",{cx:"17",cy:"17",r:"3",key:"18b49y"}],["circle",{cx:"7",cy:"7",r:"3",key:"dfmy0x"}]]);/** 52 * @license lucide-react v0.462.0 - ISC 53 * 54 * This source code is licensed under the ISC license. 55 * See the LICENSE file in the root directory of this source tree. 56 */const ii=gs("Timer",[["line",{x1:"10",x2:"14",y1:"2",y2:"2",key:"14vaq8"}],["line",{x1:"12",x2:"15",y1:"14",y2:"11",key:"17fdiu"}],["circle",{cx:"12",cy:"14",r:"8",key:"1e1u0o"}]]);/** 57 * @license lucide-react v0.462.0 - ISC 58 * 59 * This source code is licensed under the ISC license. 60 * See the LICENSE file in the root directory of this source tree. 61 */const li=gs("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"}]]);/** 62 * @license lucide-react v0.462.0 - ISC 63 * 64 * This source code is licensed under the ISC license. 65 * See the LICENSE file in the root directory of this source tree. 66 */const oi=gs("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"}]]);/** 67 * @license lucide-react v0.462.0 - ISC 68 * 69 * This source code is licensed under the ISC license. 70 * See the LICENSE file in the root directory of this source tree. 71 */const ci=gs("Trees",[["path",{d:"M10 10v.2A3 3 0 0 1 8.9 16H5a3 3 0 0 1-1-5.8V10a3 3 0 0 1 6 0Z",key:"1l6gj6"}],["path",{d:"M7 16v6",key:"1a82de"}],["path",{d:"M13 19v3",key:"13sx9i"}],["path",{d:"M12 19h8.3a1 1 0 0 0 .7-1.7L18 14h.3a1 1 0 0 0 .7-1.7L16 9h.2a1 1 0 0 0 .8-1.7L13 3l-1.4 1.5",key:"1sj9kv"}]]);/** 72 * @license lucide-react v0.462.0 - ISC 73 * 74 * This source code is licensed under the ISC license. 75 * See the LICENSE file in the root directory of this source tree. 76 */const di=gs("UserCog",[["circle",{cx:"18",cy:"15",r:"3",key:"gjjjvw"}],["circle",{cx:"9",cy:"7",r:"4",key:"nufk8"}],["path",{d:"M10 15H6a4 4 0 0 0-4 4v2",key:"1nfge6"}],["path",{d:"m21.7 16.4-.9-.3",key:"12j9ji"}],["path",{d:"m15.2 13.9-.9-.3",key:"1fdjdi"}],["path",{d:"m16.6 18.7.3-.9",key:"heedtr"}],["path",{d:"m19.1 12.2.3-.9",key:"1af3ki"}],["path",{d:"m19.6 18.7-.4-1",key:"1x9vze"}],["path",{d:"m16.8 12.3-.4-1",key:"vqeiwj"}],["path",{d:"m14.3 16.6 1-.4",key:"1qlj63"}],["path",{d:"m20.7 13.8 1-.4",key:"1v5t8k"}]]);/** 77 * @license lucide-react v0.462.0 - ISC 78 * 79 * This source code is licensed under the ISC license. 80 * See the LICENSE file in the root directory of this source tree. 81 */const mi=gs("Waves",[["path",{d:"M2 6c.6.5 1.2 1 2.5 1C7 7 7 5 9.5 5c2.6 0 2.4 2 5 2 2.5 0 2.5-2 5-2 1.3 0 1.9.5 2.5 1",key:"knzxuh"}],["path",{d:"M2 12c.6.5 1.2 1 2.5 1 2.5 0 2.5-2 5-2 2.6 0 2.4 2 5 2 2.5 0 2.5-2 5-2 1.3 0 1.9.5 2.5 1",key:"2jd2cc"}],["path",{d:"M2 18c.6.5 1.2 1 2.5 1 2.5 0 2.5-2 5-2 2.6 0 2.4 2 5 2 2.5 0 2.5-2 5-2 1.3 0 1.9.5 2.5 1",key:"rd2r6e"}]]),ui=5e3,$a="ai_analysis_notified_jobs";function xi(){const s=t.useRef(null);t.useEffect(()=>{const a=()=>{try{return JSON.parse(localStorage.getItem($a)||"[]")}catch{return[]}},i=E=>{const P=a();if(!P.includes(E)){P.push(E);const x=P.slice(-50);localStorage.setItem($a,JSON.stringify(x))}},y=async()=>{try{const{data:E,error:P}=await g.from("ai_analysis_jobs").select("id, status, document_ids, total_items, processed_items, error_message").in("status",["completed","failed"]).gte("completed_at",new Date(Date.now()-864e5).toISOString()).order("completed_at",{ascending:!1}).limit(10);if(P){console.error("Error checking AI analysis jobs:",P);return}const x=a();for(const O of E||[])x.includes(O.id)||(O.status==="completed"?ts.success("AI analýza dokonÄena â",{description:`Zpracováno ${O.processed_items||0} z ${O.total_items||0} položek`}):O.status==="failed"&&ts.error("AI analýza selhala",{description:O.error_message||"Neznámá chyba"}),i(O.id))}catch(E){console.error("Error in AI analysis notification check:",E)}};return y(),s.current=setInterval(y,ui),()=>{s.current&&clearInterval(s.current)}},[])}const hi=()=>{const{toast:s}=Re(),a=Ks(),[i,y]=t.useState([]),[E,P]=t.useState(!0),[x,O]=t.useState(!1),[S,N]=t.useState(null),[j,w]=t.useState(null),M=async p=>{w(p.id);try{const{data:m,error:$}=await g.functions.invoke("generate-category-image",{body:{categoryId:p.id}});if($||!(m!=null&&m.imageUrl))throw new Error((m==null?void 0:m.error)||($==null?void 0:$.message)||"Generovánà selhalo");y(H=>H.map(J=>J.id===p.id?{...J,image_url:m.imageUrl}:J)),s({title:"Hotovo",description:`IlustraÄnà obrázek pro â${p.name}â byl vygenerován.`})}catch(m){s({variant:"destructive",title:"Chyba",description:m instanceof Error?m.message:"Obrázek se nepodaÅilo vygenerovat."})}finally{w(null)}};t.useEffect(()=>{o()},[]);const o=async()=>{const{data:p,error:m}=await g.from("forum_categories").select("*").order("sort_order");if(m){s({variant:"destructive",title:"Chyba",description:"NepodaÅilo se naÄÃst kategorie."});return}y(p||[]),P(!1)},v=p=>{N(p),O(!0)},u=async()=>
81{if(!S)return;const{error:p}=await g.from("forum_categories").delete().eq("id",S);p?s({variant:"destructive",title:"Chyba",description:"NepodaÅilo se smazat kategorii."}):(s({title:"ÃspÄch",description:"Kategorie byla smazána."}),o()),O(!1),N(null)};return E?e.jsx("div",{className:"flex justify-center py-12",children:e.jsx(fe,{className:"h-8 w-8 animate-spin text-primary"})}):e.jsxs("div",{className:"space-y-4",children:[e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsx("h2",{className:"font-serif text-2xl font-bold text-foreground",children:"Správa kategorià fóra"}),e.jsxs(b,{onClick:()=>a("/admin/forum-category/new"),children:[e.jsx(Xe,{className:"mr-2 h-4 w-4"}),"PÅidat kategorii"]})]}),e.jsx("div",{className:"rounded-md border",children:e.jsxs($e,{children:[e.jsx(Be,{children:e.jsxs(Ne,{className:"bg-muted/50 h-9",children:[e.jsx(D,{className:"w-[50px] text-xs",children:"#"}),e.jsx(D,{className:"w-[56px] text-xs",children:"Obr."}),e.jsx(D,{className:"text-xs",children:"Název"}),e.jsx(D,{className:"text-xs",children:"Slug"}),e.jsx(D,{className:"text-xs",children:"Popis"}),e.jsx(D,{className:"w-[100px] text-right text-xs",children:"Akce"})]})}),e.jsx(Ue,{children:i.map(p=>e.jsxs(Ne,{className:"h-8 cursor-pointer hover:bg-muted/30",onClick:()=>a(`/admin/forum-category/${p.id}`),children:[e.jsx(_,{className:"text-xs text-muted-foreground",children:e.jsxs("div",{className:"flex items-center gap-1",children:[e.jsx(Rn,{className:"h-3 w-3 text-muted-foreground/40"}),p.sort_order??"â"]})}),e.jsx(_,{children:p.image_url?e.jsx("img",{src:p.image_url,alt:"",className:"h-7 w-7 rounded object-cover"}):e.jsx("div",{className:"h-7 w-7 rounded bg-muted"})}),e.jsx(_,{className:"text-sm font-medium",children:p.name}),e.jsx(_,{className:"text-xs text-muted-foreground font-mono",children:p.slug}),e.jsx(_,{className:"text-xs text-muted-foreground max-w-[300px] truncate",children:p.description||"â"}),e.jsx(_,{className:"text-right",onClick:m=>m.stopPropagation(),children:e.jsxs("div",{className:"flex justify-end gap-1",children:[e.jsx(b,{size:"icon",variant:"ghost",className:"h-7 w-7",title:"Vygenerovat AI obrázek",disabled:j!==null,onClick:()=>M(p),children:j===p.id?e.jsx(fe,{className:"h-3.5 w-3.5 animate-spin"}):e.jsx(ha,{className:"h-3.5 w-3.5"})}),e.jsx(b,{size:"icon",variant:"ghost",className:"h-7 w-7",onClick:()=>a(`/admin/forum-category/${p.id}`),children:e.jsx(Ns,{className:"h-3.5 w-3.5"})}),e.jsx(b,{size:"icon",variant:"ghost",className:"h-7 w-7 text-destructive hover:text-destructive",onClick:()=>v(p.id),children:e.jsx(qe,{className:"h-3.5 w-3.5"})})]})})]},p.id))})]})}),e.jsx(ms,{open:x,onOpenChange:O,title:"Smazat kategorii",description:"Opravdu chcete smazat tuto kategorii? Tato akce je nevratná.",confirmText:"Smazat",onConfirm:u})]})},Ba={max_post_length:1e4,max_thread_title_length:200,min_post_length:3,posts_per_page:20,threads_per_page:25,formatting:{bold:!0,italic:!0,underline:!0,strikethrough:!0,links:!0,images:!0,code:!0,quotes:!0},editing:{enabled:!0,time_limit_minutes:60},attachments:{enabled:!0,max_size_mb:5}},pi=()=>{const{toast:s}=Re(),[a,i]=t.useState(!0),[y,E]=t.useState(!1),[P,x]=t.useState(Ba),[O,S]=t.useState([]);t.useEffect(()=>{N()},[]);const N=async()=>{i(!0);const{data:o,error:v}=await g.from("forum_settings").select("*");if(v){s({variant:"destructive",title:"Chyba",description:"NepodaÅilo se naÄÃst nastavenà fóra."}),i(!1);return}o&&(S(o),j(o)),i(!1)},j=o=>{const v={...Ba};o.forEach(u=>{switch(u.key){case"max_post_length":v.max_post_length=u.value.value;break;case"max_thread_title_length":v.max_thread_title_length=u.value.value;break;case"min_post_length":v.min_post_length=u.value.value;break;case"posts_per_page":v.posts_per_page=u.value.value;break;case"threads_per_page":v.threads_per_page=u.value.value;break;case"allowed_formatting":v.formatting=u.value;break;case"allow_editing":v.editing=u.value;break;case"allow_attachments":v.attachments={enabled:u.value.enabled,max_size_mb:u.value.max_size_mb};break}}),x(v)},w=async()=>{E(!0);const o=[{key:"max_post_length",value:{value:P.max_post_length}},{key:"max_thread_title_length",value:{value:P.max_thread_title_length}},{key:"min_post_length",value:{value:P.min_post_length}},{key:"posts_per_page",value:{value:P.posts_per_page}},{key:"threads_per_page",value:{value:P.threads_per_page}},{key:"allowed_formatting",value:P.formatting},{key:"allow_editing",value:P.editing},{key:"allow_attachments",value:{enabled:P.attachments.enabled,max_size_mb:P.attachments.max_size_mb,allowed_types:["image/jpeg","image/png","image/gif","application/pdf"]}}];let v=!1;for(const u of o){const{error:p}=await g.from("forum_settings").update({value:u.value}).eq("key",u.key);if(p){v=!0;break}}s(v?{variant:"destructive",title:"Chyba",description:"NepodaÅilo se uložit nastavenÃ."}:{title:"Uloženo",description:"Nastavenà fóra bylo úspÄÅ¡nÄ uloženo."}),E(!1)},M=()=>{j(O),s({title:"Obnoveno",description:"Nastavenà bylo obnoveno na poslednà uložené hodnoty."})};return a?e.jsx("div",{className:"flex items-center justify-center py-12",children:e.jsx(fe,{className:"h-8 w-8 animate-spin text-primary"})}):e.jsxs("div",{className:"space-y-6",children:[e.jsxs(ee,{children:[e.jsxs(ye,{children:[e.jsx(be,{children:"Limity délek textů"}),e.jsx(Le,{children:"Nastavte minimálnà a maximálnà délky pÅÃspÄvků a názvů vláken"})]}),e.jsx(ae,{className:"space-y-4",children:e.jsxs("div",{className:"grid grid-cols-1 md:grid-cols-3 gap-4",children:[e.jsxs("div",{className:"space-y-2",children:[e.jsx(q,{htmlFor:"min_post_length",children:"Minimálnà délka pÅÃspÄvku (znaků)"}),e.jsx(se,{id:"min_post_length",type:"number",min:1,max:100,value:P.min_post_length,onChange:o=>x({...P,min_post_length:parseInt(o.target.value)||1})})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(q,{htmlFor:"max_post_length",children:"Maximálnà délka pÅÃspÄvku (znaků)"}),e.jsx(se,{id:"max_post_length",type:"number",min:100,max:1e5,value:P.max_post_length,onChange:o=>x({...P,max_post_length:parseInt(o.target.value)||1e4})})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(q,{htmlFor:"max_thread_title_length",children:"Maximálnà délka názvu vlákna (znaků)"}),e.jsx(se,{id:"max_thread_title_length",type:"number",min:10,max:500,value:P.max_thread_title_length,onChange:o=>x({...P,max_thread_title_length:parseInt(o.target.value)||200}
81)})]})]})})]}),e.jsxs(ee,{children:[e.jsxs(ye,{children:[e.jsx(be,{children:"StránkovánÃ"}),e.jsx(Le,{children:"PoÄet položek zobrazených na jedné stránce"})]}),e.jsx(ae,{className:"space-y-4",children:e.jsxs("div",{className:"grid grid-cols-1 md:grid-cols-2 gap-4",children:[e.jsxs("div",{className:"space-y-2",children:[e.jsx(q,{htmlFor:"threads_per_page",children:"PoÄet vláken na stránku"}),e.jsx(se,{id:"threads_per_page",type:"number",min:5,max:100,value:P.threads_per_page,onChange:o=>x({...P,threads_per_page:parseInt(o.target.value)||25})})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(q,{htmlFor:"posts_per_page",children:"PoÄet pÅÃspÄvků na stránku"}),e.jsx(se,{id:"posts_per_page",type:"number",min:5,max:100,value:P.posts_per_page,onChange:o=>x({...P,posts_per_page:parseInt(o.target.value)||20})})]})]})})]}),e.jsxs(ee,{children:[e.jsxs(ye,{children:[e.jsx(be,{children:"Povolené formátovánÃ"}),e.jsx(Le,{children:"Vyberte, které formátovacà možnosti budou uživatelům k dispozici"})]}),e.jsx(ae,{children:e.jsx("div",{className:"grid grid-cols-2 md:grid-cols-4 gap-4",children:Object.entries(P.formatting).map(([o,v])=>e.jsxs("div",{className:"flex items-center justify-between space-x-2 p-3 rounded-lg border",children:[e.jsxs(q,{htmlFor:`format_${o}`,className:"capitalize",children:[o==="bold"&&"TuÄné",o==="italic"&&"KurzÃva",o==="underline"&&"PodtrženÃ",o==="strikethrough"&&"PÅeÅ¡krtnutÃ",o==="links"&&"Odkazy",o==="images"&&"Obrázky",o==="code"&&"Kód",o==="quotes"&&"Citace"]}),e.jsx(ss,{id:`format_${o}`,checked:v,onCheckedChange:u=>x({...P,formatting:{...P.formatting,[o]:u}})})]},o))})})]}),e.jsxs(ee,{children:[e.jsxs(ye,{children:[e.jsx(be,{children:"Ãpravy pÅÃspÄvků"}),e.jsx(Le,{children:"Nastavenà možnosti úprav pÅÃspÄvků uživateli"})]}),e.jsxs(ae,{className:"space-y-4",children:[e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsxs("div",{className:"space-y-0.5",children:[e.jsx(q,{htmlFor:"editing_enabled",children:"Povolit úpravy pÅÃspÄvků"}),e.jsx("p",{className:"text-sm text-muted-foreground",children:"Uživatelé mohou upravovat své pÅÃspÄvky po jejich odeslánÃ"})]}),e.jsx(ss,{id:"editing_enabled",checked:P.editing.enabled,onCheckedChange:o=>x({...P,editing:{...P.editing,enabled:o}})})]}),P.editing.enabled&&e.jsxs(e.Fragment,{children:[e.jsx(gt,{}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(q,{htmlFor:"time_limit",children:"Äasový limit pro úpravy (minuty)"}),e.jsx("p",{className:"text-sm text-muted-foreground",children:"0 = bez limitu, jinak poÄet minut po odeslánÃ, kdy je úprava možná"}),e.jsx(se,{id:"time_limit",type:"number",min:0,max:10080,value:P.editing.time_limit_minutes,onChange:o=>x({...P,editing:{...P.editing,time_limit_minutes:parseInt(o.target.value)||0}}),className:"max-w-xs"})]})]})]})]}),e.jsxs(ee,{children:[e.jsxs(ye,{children:[e.jsx(be,{children:"PÅÃlohy"}),e.jsx(Le,{children:"Nastavenà pÅÃloh v pÅÃspÄvcÃch"})]}),e.jsxs(ae,{className:"space-y-4",children:[e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsxs("div",{className:"space-y-0.5",children:[e.jsx(q,{htmlFor:"attachments_enabled",children:"Povolit pÅÃlohy"}),e.jsx("p",{className:"text-sm text-muted-foreground",children:"Uživatelé mohou pÅikládat soubory k pÅÃspÄvkům"})]}),e.jsx(ss,{id:"attachments_enabled",checked:P.attachments.enabled,onCheckedChange:o=>x({...P,attachments:{...P.attachments,enabled:o}})})]}),P.attachments.enabled&&e.jsxs(e.Fragment,{children:[e.jsx(gt,{}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(q,{htmlFor:"max_size",children:"Maximálnà velikost souboru (MB)"}),e.jsx(se,{id:"max_size",type:"number",min:1,max:50,value:P.attachments.max_size_mb,onChange:o=>x({...P,attachments:{...P.attachments,max_size_mb:parseInt(o.target.value)||5}}),className:"max-w-xs"})]}),e.jsx("div",{className:"text-sm text-muted-foreground",children:"Povolené typy souborů: JPEG, PNG, GIF, PDF"})]})]})]}),e.jsx(gi,{}),e.jsxs("div",{className:"flex justify-end gap-3",children:[e.jsxs(b,{variant:"outline",onClick:M,disabled:y,children:[e.jsx(wn,{className:"h-4 w-4 mr-2"}),"Obnovit"]}),e.jsxs(b,{onClick:w,disabled:y,children:[y?e.jsx(fe,{className:"h-4 w-4 mr-2 animate-spin"}):e.jsx(Ds,{className:"h-4 w-4 mr-2"}),"Uložit nastavenÃ"]})]})]})},gi=()=>{const{toast:s}=Re(),[a,i]=t.useState({total:0,enabled:0,disabled:0}),[y,E]=t.useState(!0),[P,x]=t.useState(!1);t.useEffect(()=>{O()},[]);const O=async()=>{E(!0);const{data:N,error:j}=await g.from("forum_thread_subscriptions").select("id, notify_comments");if(!j&&N){const w=N.filter(M=>M.notify_comments).length;i({total:N.length,enabled:w,disabled:N.length-w})}E(!1)},S=async N=>{x(!0);const{error:j}=await g.from("forum_thread_subscriptions").update({notify_comments:N}).neq("notify_comments",N);j?s({variant:"destructive",title:"Chyba",description:"NepodaÅilo se aktualizovat notifikace."}):(s({title:"Hotovo",description:N?"Notifikace komentáÅů byly zapnuty pro vÅ¡echny odbÄry.":"Notifikace komentáÅů byly vypnuty pro vÅ¡echny odbÄry."}),O()),x(!1)};return e.jsxs(ee,{children:[e.jsxs(ye,{children:[e.jsxs(be,{className:"flex items-center gap-2",children:[e.jsx(Dt,{className:"h-5 w-5 text-primary"}),"Notifikace komentáÅů"]}),e.jsx(Le,{children:"Hromadná správa e-mailových notifikacà pro komentáÅe ve vláknech. StandardnÄ jsou notifikace vypnuté â zde je můžete hromadnÄ zapnout pro výjimeÄné pÅÃpady."})]}),e.jsx(ae,{className:"space-y-4",children:y?e.jsx("div",{className:"flex justify-center py-4",children:e.jsx(fe,{className:"h-5 w-5 animate-spin text-muted-foreground"})}):e.jsxs(e.Fragment,{children:[e.jsxs("div",{className:"flex items-center gap-4 flex-wrap",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(Fs,{className:"h-4 w-4 text-muted-foreground"}),e.jsx("span",{className:"text-sm text-muted-foreground",children:"Celkem odbÄrů:"}),e.jsx(Q,{variant:"outline",children:a.total})]}),e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(Dt,{className:"h-4 w-4 text-green-600"}),e.jsx("span",{className:"text-sm text-muted-foreground",children:"Zapnuto:"}),e.jsx(Q,{className:"bg-green-100 text-green-800 border-green-200",children:a.enabled})]}),e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(pa,{className:"h-4 w-4 text-amber-600"}),e.jsx("span",{className:"text-sm text-muted-foreground",children:"Vypnuto:"}),e.jsx(Q,{className:"bg-amber-100 text-amber-800 border-amber-200",children:a.disabled})]})]}),e.jsx(gt,{}),e.jsxs("div",{className:"flex gap-3 flex-wrap",children:[e.jsxs(b,{variant:"default",size:"sm",disabled:P||a.disabled===0,onClick:()=>S(!0),children:[P?e.jsx(fe,{className:"h-4 w-4 mr-2 animate-spin"}):e.jsx(Dt,{className:"h-4 w-4 mr-2"}),"Zapnout vÅ¡em notifikace"]}),e.jsxs(b,{variant:"outline",size:"sm",disabled:P||a.enabled===0,onClick:()=>S(!1),children:[P?e.jsx(fe,{className:"h-4 w-4 mr-2 animate-spin"}):e.jsx(pa,{className:"h-4 w-4 mr-2"}),"Vypnout vÅ¡em notifikace"]})]})]})})]})},ji=()=>{const{toast:s}=Re(),[a,i]=t.useState([]),[y,E]=t.useState([]),[P,x]=t.useState(!0),[O,S]=t.useState(""),[N,j]=t.useState("all"),[w,M]=t.useState("all"),[o,v]=t.useState("all"),[u,p]=t.useState(null),[m,$]=t.useState(null),[H,J]=t.useState(!1),[z,h]=t.useState(new Map),[I,k]=t.useState(null);t.useEffect(()=>{c()},[]);const c=async()=>{var ke;x(!0);const[W,Z]=await Promise.all([g.from("forum_threads").select("id, title, title_translated, translation_source, translation_outdated, created_at, updated_at, is_pinned, is_draft, user_id, category_id, language, forum_categories(name, description)").order("updated_at",{ascending:!1}),g.from("forum_categories").select("id, name, description").order("sort_order")]);if(W.error||!W.data){W.error&&s({variant:"destructive",title:"Chyba",description:"NepodaÅilo se naÄÃst vlákna."}),i([]),x(!1);return}E((Z.data||[]).map(je=>({id:je.id,name:je.name,description:je.description})));const K=W.data,l=K.map(je=>je.id),[U,n,G,Y,pe]=await Promise.all([g.from("forum_posts").select("id, thread_id, content, content_translated, translation_source, created_at, attachments, user_id, parent_id, language").in("thread_id",l).order("created_at",{ascending:!0}),g.from("forum_thread_views").select("thread_id").in("thread_id",l),g.from("forum_post_reactions").select("post_id, forum_posts!inner(thread_id)").eq("emoji","ð").in("forum_posts.thread_id",l),g.from("email_history").select("related_entity_id").eq("related_entity_type","forum_thread").in("related_entity_id",l).eq("status","sent"),g.from("forum_thread_subscriptions").select("thread_id, notify_comments").in("thread_id",l)]),B=[...new Set([...K.map(je=>je.user_id),...(U.data||[]).map(je=>je.user_id)])],te=await g.rpc("admin_get_profiles_by_ids",{_user_ids:B}),xe=new Map((te.data||[]).map(je=>
81[je.user_id,je.full_name||[je.first_name,je.last_name].filter(Boolean).join(" ")||je.email||"â"])),de=new Map;for(const je of U.data||[])de.has(je.thread_id)||de.set(je.thread_id,[]),de.get(je.thread_id).push(je);const L=new Map;for(const je of n.data||[])L.set(je.thread_id,(L.get(je.thread_id)||0)+1);const re=new Map;for(const je of G.data||[]){const ue=(ke=je.forum_posts)==null?void 0:ke.thread_id;ue&&re.set(ue,(re.get(ue)||0)+1)}const A=new Set((Y.data||[]).map(je=>je.related_entity_id)),ne=new Map;for(const je of pe.data||[])je.notify_comments?ne.set(je.thread_id,!0):ne.has(je.thread_id)||ne.set(je.thread_id,!1);h(ne);const le=je=>{const ue=je.match(/<img[^>]+src="([^"]+)"/);return(ue==null?void 0:ue[1])||null},oe=K.map(je=>{var ze;const ue=de.get(je.id)||[],ve=ue[0]||null,X=(ve==null?void 0:ve.content)||"",Ce=ue.filter(Me=>Me.id!==(ve==null?void 0:ve.id));return{id:je.id,title:je.title,title_translated:je.title_translated||null,translation_source:je.translation_source||null,translation_outdated:je.translation_outdated||!1,created_at:je.created_at,updated_at:je.updated_at,is_pinned:je.is_pinned||!1,is_draft:je.is_draft||!1,user_id:je.user_id,category_id:je.category_id,category_name:((ze=je.forum_categories)==null?void 0:ze.name)||"â",author_name:xe.get(je.user_id)||"â",post_count:ue.length,view_count:L.get(je.id)||0,like_count:re.get(je.id)||0,first_post_id:(ve==null?void 0:ve.id)||null,first_post_content:X,first_post_content_translated:(ve==null?void 0:ve.content_translated)||null,first_post_translation_source:(ve==null?void 0:ve.translation_source)||null,first_post_attachments:(ve==null?void 0:ve.attachments)||[],first_post_image:le(X),first_post_comments:Ce.map(Me=>({id:Me.id,content:Me.content,content_translated:Me.content_translated||null,translation_source:Me.translation_source||null,created_at:Me.created_at,authorName:xe.get(Me.user_id)||"â",language:Me.language||"de",user_id:Me.user_id,parent_id:Me.parent_id||null})),notification_sent:A.has(je.id),language:je.language||"cs"}});i(oe),x(!1)},d=t.useCallback(async W=>{k(W);const K=!(z.get(W)??!1),{error:l}=await g.from("forum_thread_subscriptions").update({notify_comments:K}).eq("thread_id",W);l?s({variant:"destructive",title:"Chyba",description:"NepodaÅilo se zmÄnit notifikace."}):(h(U=>new Map(U).set(W,K)),s({title:K?"Notifikace komentáÅů zapnuty":"Notifikace komentáÅů vypnuty"})),k(null)},[z,s]),T=W=>new DOMParser().parseFromString(W,"text/html").body.textContent||"",r=t.useMemo(()=>[...new Set(a.map(Z=>new Date(Z.created_at).getFullYear()))].sort((Z,K)=>K-Z),[a]),f=t.useMemo(()=>[...new Set(a.map(Z=>Z.author_name))].sort(),[a]),R=t.useMemo(()=>{let W=a;if(N!=="all"&&(W=W.filter(Z=>new Date(Z.created_at).getFullYear().toString()===N)),w!=="all"&&(W=W.filter(Z=>Z.category_id===w)),o!=="all"&&(W=W.filter(Z=>Z.author_name===o)),O){const Z=O.toLowerCase();W=W.filter(K=>K.title.toLowerCase().includes(Z)||K.author_name.toLowerCase().includes(Z)||K.category_name.toLowerCase().includes(Z)||T(K.first_post_content).toLowerCase().includes(Z))}return W},[a,O,N,w,o]),F=async(W,Z,K)=>{const l=u;if(!l)return;let U=!1;if(l.first_post_id){const{error:n}=await g.from("forum_posts").update({content:Z,updated_at:new Date().toISOString()}).eq("id",l.first_post_id);n&&(s({variant:"destructive",title:"Chyba",description:"NepodaÅilo se uložit obsah."}),U=!0)}if(K&&K!==l.title){const{error:n}=await g.from("forum_threads").update({title:K,updated_at:new Date().toISOString()}).eq("id",l.id);n&&(s({variant:"destructive",title:"Chyba",description:"NepodaÅilo se uložit název."}),U=!0)}U||s({title:"Uloženo"}),p(null),c()},ce=async()=>{m&&(await g.from("forum_posts").delete().eq("thread_id",m),await g.from("forum_threads").delete().eq("id",m),s({title:"Smazáno"}),i(W=>W.filter(Z=>Z.id!==m)),J(!1),$(null))},ie=async W=>{if(!u)return;const{error:Z}=await g.from("forum_threads").update({category_id:W,updated_at:new Date().toISOString()}).eq("id",u.id);Z?s({variant:"destructive",title:"Chyba",description:"NepodaÅilo se pÅesunout vlákno."}):(s({title:"PÅesunuto"}),p(null),c())};return u?e.jsxs("div",{className:"space-y-4",children:[e.jsxs(b,{variant:"ghost",size:"sm",onClick:()=>p(null),children:[e.jsx(ut,{className:"h-4 w-4 mr-1"})," ZpÄt na seznam"]}),e.jsx(lr,{id:u.first_post_id||u.id,threadId:u.id,authorName:u.author_name,createdAt:u.created_at,userId:u.user_id,title:u.title,titleTranslated:u.title_translated,content:u.first_post_content,contentTranslated:u.first_post_content_translated,translationSource:u.first_post_translation_source||u.translation_source,translationOutdated:u.translation_outdated,language:u.language,attachments:u.first_post_attachments,isFirstPost:!0,isPreview:!1,replyCount:u.post_count,viewCount:u.view_count,isPinned:u.is_pinned,isDraft:u.is_draft,isAdmin:!0,categoryName:u.category_name,currentCategoryId:u.category_id,availableCategories:y,disableReactions:!0,comments:u.first_post_comments,onEdit:F,onDelete:async()=>{await g.from("forum_posts").delete().eq("thread_id",u.id),await g.from("forum_threads").delete().eq("id",u.id),s({title:"Smazáno"}),p(null),c()},onEditComment:async(W,Z)=>{const{error:K}=await g.from("forum_posts").update({content:Z,updated_at:new Date().toISOString()}).eq("id",W);if(K)s({variant:"destructive",title:"Chyba",description:"NepodaÅilo se uložit komentáÅ."});else{s({title:"KomentáŠuložen"});const l={...u,first_post_comments:u.first_post_comments.map(U=>U.id===W?{...U,content:Z}:U)};p(l),c()}},onDeleteComment:async W=>{const{error:Z}=await g.from("forum_posts").delete().eq("id",W);if(Z)s({variant:"destructive",title:"Chyba",description:"NepodaÅilo se smazat komentáÅ."});else{s({title:"KomentáŠsmazán"});const K={...u,first_post_comments:u.first_post_comments.filter(l=>l.id!==W),post_count:Math.max(0,u.post_count-1)};p(K),c()}},onSendCommentNotification:async W=>{var U;
81const Z=u.first_post_comments.find(n=>n.id===W);if(!Z){s({variant:"destructive",title:"Chyba",description:"KomentáŠnenalezen."});return}const{data:K}=await g.auth.getUser(),{error:l}=await g.functions.invoke("notify-forum-post",{body:{thread_title:u.title,category_name:u.category_name,post_content:Z.content,author_user_id:Z.user_id,thread_id:u.id,is_comment:!0,force_all_recipients:!0,sent_by:(U=K.user)==null?void 0:U.id}});s(l?{variant:"destructive",title:"Chyba",description:l.message||"NepodaÅilo se odeslat."}:{title:"Notifikace odeslána"})},onMoveThread:ie})]}):e.jsxs("div",{className:"space-y-4",children:[e.jsxs("div",{className:"flex flex-wrap items-center justify-between gap-3",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx("h2",{className:"font-serif text-2xl font-bold text-foreground",children:"VÅ¡echny pÅÃspÄvky"}),e.jsxs("span",{className:"text-sm text-muted-foreground",children:["(",R.length,")"]})]}),e.jsxs("div",{className:"relative w-64",children:[e.jsx(fs,{className:"absolute left-2.5 top-2.5 h-4 w-4 text-muted-foreground"}),e.jsx(se,{placeholder:"Hledatâ¦",value:O,onChange:W=>S(W.target.value),className:"pl-9 h-9"})]})]}),e.jsxs("div",{className:"flex flex-wrap items-center gap-3",children:[e.jsxs(De,{value:N,onValueChange:j,children:[e.jsx(Pe,{className:"w-[130px] h-9",children:e.jsx(Ae,{placeholder:"Rok"})}),e.jsxs(Ee,{children:[e.jsx(me,{value:"all",children:"VÅ¡echny roky"}),r.map(W=>e.jsx(me,{value:W.toString(),children:W},W))]})]}),e.jsxs(De,{value:w,onValueChange:M,children:[e.jsx(Pe,{className:"w-[200px] h-9",children:e.jsx(Ae,{placeholder:"Kategorie"})}),e.jsxs(Ee,{children:[e.jsx(me,{value:"all",children:"VÅ¡echny kategorie"}),y.map(W=>e.jsx(me,{value:W.id,children:W.name},W.id))]})]}),e.jsxs(De,{value:o,onValueChange:v,children:[e.jsx(Pe,{className:"w-[200px] h-9",children:e.jsx(Ae,{placeholder:"Autor"})}),e.jsxs(Ee,{children:[e.jsx(me,{value:"all",children:"VÅ¡ichni autoÅi"}),f.map(W=>e.jsx(me,{value:W,children:W},W))]})]})]}),P?e.jsx("div",{className:"flex justify-center py-12",children:e.jsx(fe,{className:"h-8 w-8 animate-spin text-primary"})}):R.length===0?e.jsx("p",{className:"text-center text-muted-foreground py-8",children:"Žádné pÅÃspÄvky"}):e.jsx("div",{className:"space-y-3",children:R.map(W=>e.jsx(or,{id:W.id,name:W.title,nameTranslated:W.title_translated,descriptionTranslated:W.first_post_content_translated?T(W.first_post_content_translated).substring(0,200):null,originalLanguage:W.language,translationSource:W.first_post_translation_source||W.translation_source,authorName:W.author_name,categoryName:W.category_name,createdAt:W.created_at,description:T(W.first_post_content).substring(0,200),imageUrl:W.first_post_image,threadCount:Math.max(0,W.post_count-1),viewCount:W.view_count,likeCount:W.like_count,onClick:()=>p(W),onCommentClick:()=>p(W),notificationStats:W.notification_sent?{sent:1,failed:0,total:1}:null,commentNotify:z.get(W.id)??!1,isTogglingNotify:I===W.id,onToggleCommentNotify:()=>d(W.id)},W.id))}),e.jsx(ms,{open:H,onOpenChange:J,title:"Smazat pÅÃspÄvek",description:"Opravdu chcete smazat tento pÅÃspÄvek a celé vlákno? Tato akce je nevratná.",confirmText:"Smazat",onConfirm:ce})]})},vi=()=>e.jsxs(ks,{defaultValue:"posts",className:"space-y-4",children:[e.jsxs(Cs,{children:[e.jsxs(We,{value:"posts",className:"gap-1.5",children:[e.jsx(_s,{className:"h-3.5 w-3.5"}),"PÅÃspÄvky"]}),e.jsxs(We,{value:"groups",className:"gap-1.5",children:[e.jsx(Gn,{className:"h-3.5 w-3.5"}),"Správa skupin"]}),e.jsxs(We,{value:"settings",className:"gap-1.5",children:[e.jsx(Gt,{className:"h-3.5 w-3.5"}),"NastavenÃ"]})]}),e.jsx(es,{value:"posts",children:e.jsx(ji,{})}),e.jsx(es,{value:"groups",children:e.jsx(hi,{})}),e.jsx(es,{value:"settings",children:e.jsx(pi,{})})]});function fi(s,a,i){const y=tr(s,a)/Jr;return ar(i==null?void 0:i.roundingMethod)(y)}const Vn=({scope:s,onSwitch:a})=>{const i=s==="users";return e.jsxs("div",{className:"rounded-lg border border-blue-200 bg-blue-50/60 p-3 flex items-start gap-3 text-sm",children:[e.jsx(Us,{className:"h-4 w-4 text-blue-600 mt-0.5 shrink-0"}),e.jsx("div",{className:"flex-1 space-y-1",children:i?e.jsxs(e.Fragment,{children:[e.jsx("p",{className:"font-medium text-blue-900",children:"PÅÃstupy do portálu â kdo se může pÅihlásit"}),e.jsxs("p",{className:"text-blue-800/80 text-xs",children:["Tento seznam spravuje ",e.jsx("strong",{children:"uživatelské úÄty"})," (pÅihlášenÃ, role, schvalovánà registracÃ). Vlastnická evidence (TOP, podÃly WEG, hlasovacà práva) je v jiném seznamu."]})]}):e.jsxs(e.Fragment,{children:[e.jsx("p",{className:"font-medium text-blue-900",children:"VlastnÃci & jednotky (WEG) â právnà evidence vlastnictvÃ"}),e.jsxs("p",{className:"text-blue-800/80 text-xs",children:["Tento seznam je ",e.jsx("strong",{children:"autoritativnà zdroj"})," pro vlastnictvà bytů, podÃly a hlasovánÃ. PÅihlaÅ¡ovacà úÄty (e-mail, heslo, role) se spravujà v sekci âPÅÃstupy do portáluâ."]})]})}),e.jsxs(b,{variant:"outline",size:"sm",className:"gap-1 shrink-0",onClick:a,children:[i?"OtevÅÃt vlastnÃky":"OtevÅÃt pÅÃstupy",e.
81jsx(Gs,{className:"h-3.5 w-3.5"})]})]})},yi=()=>{const{toast:s}=Re(),a=Ks(),[i,y]=t.useState([]),[E,P]=t.useState(!0),[x,O]=t.useState(""),[S,N]=t.useState("apartments"),[j,w]=t.useState("asc"),[M,o]=t.useState("all"),[v,u]=t.useState({}),[p,m]=t.useState(!1),[$,H]=t.useState(new Set),[J,z]=t.useState(!0),[h,I]=t.useState(!1);t.useEffect(()=>{k()},[]);const k=async()=>{const[Z,K,l,U,n]=await Promise.all([g.rpc("admin_list_profiles"),g.from("user_roles").select("*"),g.from("apartment_owners").select("user_id, owner_contact_id, apartment_id, is_current, apartments(code)").eq("is_current",!0),g.from("owner_contacts").select("id, user_id"),g.from("owner_contact_persons").select("id, owner_contact_id, user_id")]);if(Z.error){s({variant:"destructive",title:"Chyba",description:"NepodaÅilo se naÄÃst uživatele."}),P(!1);return}const G=K.data||[],Y=l.data||[],pe=U.data||[],B=n.data||[],te=new Map;pe.forEach(de=>{de.user_id&&(te.has(de.user_id)||te.set(de.user_id,new Set),te.get(de.user_id).add(de.id))}),B.forEach(de=>{!de.user_id||!de.owner_contact_id||(te.has(de.user_id)||te.set(de.user_id,new Set),te.get(de.user_id).add(de.owner_contact_id))});const xe=(Z.data||[]).map(de=>{var A,ne;const L=te.get(de.user_id)||new Set,re=new Set;return Y.forEach(le=>{var ke;const oe=(ke=le.apartments)==null?void 0:ke.code;oe&&(le.user_id===de.user_id||le.owner_contact_id&&L.has(le.owner_contact_id))&&re.add(oe)}),{id:de.id,user_id:de.user_id,full_name:de.full_name,first_name:de.first_name,last_name:de.last_name,email:de.email,language:de.language,roles:G.filter(le=>le.user_id===de.user_id).map(le=>le.role),apartments:Array.from(re),owner_contact_id:((A=pe.find(le=>le.user_id===de.user_id))==null?void 0:A.id)||((ne=B.find(le=>le.user_id===de.user_id))==null?void 0:ne.owner_contact_id)||null,approval_status:de.approval_status||"pending",created_at:de.created_at}});y(xe),P(!1),c(xe)},c=async Z=>{const K=Z.filter(te=>te.approval_status==="pending"&&te.email);if(K.length===0)return;K.map(te=>te.email.toLowerCase());const[l,U,n]=await Promise.all([g.from("owner_contacts").select("id, first_name, last_name, company_name, email, user_id, is_active, language"),g.from("apartment_owners").select("owner_contact_id, apartments(code)").eq("is_current",!0),g.from("owner_contact_persons").select("id, email")]),G=l.data||[],Y=U.data||[],pe=n.data||[],B={};for(const te of K){const xe=te.email.toLowerCase(),de=G.filter(A=>A.email&&A.email.toLowerCase()===xe),L=de.filter(A=>A.user_id&&A.is_active),re=pe.filter(A=>A.email&&A.email.toLowerCase()===xe);if(L.length===1&&re.length===0){const A=L[0],ne=Y.filter(le=>le.owner_contact_id===A.id).map(le=>{var oe;return((oe=le.apartments)==null?void 0:oe.code)||"?"});B[te.user_id]={type:"strong",ownerName:A.company_name||`${A.first_name||""} ${A.last_name||""}`.trim()||"Neuvedeno",ownerContactId:A.id,ownerEmail:A.email,ownerLanguage:A.language,apartments:ne}}else if(L.length>0||re.length>0){const A=L[0]||de[0];if(A){const ne=Y.filter(le=>le.owner_contact_id===A.id).map(le=>{var oe;return((oe=le.apartments)==null?void 0:oe.code)||"?"});B[te.user_id]={type:"weak",ownerName:A.company_name||`${A.first_name||""} ${A.last_name||""}`.trim()||"Neuvedeno",ownerContactId:A.id,ownerEmail:A.email,ownerLanguage:A.language,apartments:ne}}}}u(B)},d=t.useMemo(()=>Object.entries(v).filter(([Z,K])=>K.type==="strong"),[v]),T=t.useMemo(()=>i.filter(Z=>Z.approval_status==="pending").length,[i]),r=Z=>{S===Z?w(K=>K==="asc"?"desc":"asc"):(N(Z),w("asc"))},f=Z=>Z.full_name||`${Z.first_name||""} ${Z.last_name||""}`.trim()||"",R=t.useMemo(()=>{const Z=x.toLowerCase();let K=i.filter(l=>{var U;return f(l).toLowerCase().includes(Z)||((U=l.email)==null?void 0:U.toLowerCase().includes(Z))||l.apartments.some(n=>n.toLowerCase().includes(Z))});return M!=="all"&&(K=K.filter(l=>l.approval_status===M)),K.sort((l,U)=>{let n=0;switch(S){case"apartments":n=(l.apartments[0]||"zzz").localeCompare(U.apartments[0]||"zzz",void 0,{numeric:!0});break;case"name":n=f(l).localeCompare(f(U));break;case"email":n=(l.email||"").localeCompare(U.email||"");break;case"language":n=(l.language||"").localeCompare(U.language||"");break;case"role":n=(l.roles[0]||"zzz").localeCompare(U.roles[0]||"zzz");break;case"status":n=l.approval_status.localeCompare(U.approval_status);break;case"created_at":n=l.created_at.localeCompare(U.created_at);break}return j==="desc"?-n:n})},[i,x,S,j,M]),F=()=>{const Z=new Set(d.map(([K])=>K));H(Z),z(!0),m(!0)},ce=async()=>
81{if($.size===0)return;I(!0);const{data:{session:Z}}=await g.auth.getSession();if(!Z){s({variant:"destructive",title:"Chyba",description:"Nenà pÅihlášen."}),I(!1);return}let K=0,l=0;const U=window.location.origin;for(const n of $){const G=v[n],Y=i.find(pe=>pe.user_id===n);if(!(!G||!Y))try{J&&G.ownerEmail&&await g.functions.invoke("send-notification-email",{body:{template_type:"duplicate_registration",language:G.ownerLanguage||"en",recipient_email:G.ownerEmail,variables:{"{userName}":G.ownerName?` ${G.ownerName}`:"","{loginLink}":`${U}/auth`,"{resetPasswordUrl}":`${U}/reset-password`,"{emailSignature}":""}}});const{error:pe}=await g.functions.invoke("admin-user-actions",{body:{userId:n,action:"delete_user",audit:{action:"duplicate_registration_deleted",target_email:Y.email,reason:"existing_active_account_found",details:{notification_sent:J,matched_owner_contact_id:G.ownerContactId,matched_owner_name:G.ownerName,duplicate_type:G.type,bulk_processed:!0}}}});if(pe)throw pe;K++}catch{l++}}m(!1),s({title:"Zpracováno",description:`${K} duplicit smazáno${l>0?`, ${l} chyb`:""}.`}),k(),I(!1)},ie=({label:Z,k:K})=>e.jsxs(b,{variant:"ghost",size:"sm",className:"h-auto p-0 font-medium text-muted-foreground hover:text-foreground gap-1",onClick:()=>r(K),children:[Z,e.jsx(Is,{className:"h-3 w-3"})]}),W=(Z,K,l,U)=>{const n=K?v[K]:null;return e.jsxs("div",{className:"flex items-center gap-1 flex-wrap",children:[Z==="approved"&&e.jsx(Q,{className:"bg-green-100 text-green-800 border-green-200 text-xs",children:"Schváleno"}),Z==="pending"&&e.jsx(Q,{className:"bg-amber-100 text-amber-800 border-amber-200 text-xs",children:"Äeká"}),Z==="rejected"&&e.jsx(Q,{variant:"destructive",className:"text-xs",children:"ZamÃtnuto"}),!["approved","pending","rejected"].includes(Z)&&e.jsx("span",{className:"text-muted-foreground",children:"â"}),Z==="approved"&&U&&l===!1&&e.jsxs(Q,{className:"bg-orange-100 text-orange-700 border-orange-200 text-[10px] gap-0.5",children:[e.jsx(Vs,{className:"h-2.5 w-2.5"}),"Bez WEG vazby"]}),n&&e.jsx(Q,{className:`text-[10px] ${n.type==="strong"?"bg-amber-100 text-amber-800 border-amber-200":"bg-orange-100 text-orange-700 border-orange-200"}`,children:"Duplicita"})]})};return E?e.jsx("div",{className:"flex justify-center py-12",children:e.jsx(fe,{className:"h-8 w-8 animate-spin text-primary"})}):e.jsxs("div",{className:"space-y-4",children:[e.jsx(Vn,{scope:"users",onSwitch:()=>a("/admin?section=property&sub=owners")}),e.jsxs("div",{className:"rounded-xl border border-border bg-card shadow-soft p-6 space-y-5",children:[e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsxs("h3",{className:"font-serif text-base font-semibold text-foreground",children:["PÅÃstupy do portálu (",i.length,")",T>0&&e.jsxs(Q,{className:"ml-2 bg-amber-100 text-amber-800 border-amber-200 text-xs",children:[T," Äeká na schválenÃ"]})]}),d.length>0&&e.jsxs(b,{variant:"outline",size:"sm",onClick:F,className:"gap-1.5",children:[e.jsx(is,{className:"h-4 w-4 text-amber-600"}),"Zpracovat duplicity (",d.length,")"]})]}),e.jsx(ks,{value:M,onValueChange:Z=>o(Z),children:e.jsxs(Cs,{children:[e.jsx(We,{value:"all",children:"VÅ¡ichni"}),e.jsxs(We,{value:"pending",className:"gap-1",children:["ÄekajÃcÃ",T>0&&e.jsx(Q,{className:"ml-1 h-5 min-w-5 bg-amber-500 text-white text-xs",children:T})]}),e.jsx(We,{value:"approved",children:"SchválenÃ"}),e.jsx(We,{value:"rejected",children:"ZamÃtnutÃ"})]})}),e.jsxs("div",{className:"relative",children:[e.jsx(fs,{className:"absolute left-3 top-1/2 -translate-y-1/2 h-4 w-4 text-muted-foreground"}),e.jsx(se,{placeholder:"Hledat...",value:x,onChange:Z=>O(Z.target.value),className:"pl-9 h-10 border-border"})]}),e.jsx("div",{children:e.jsxs($e,{className:"[&_th]:px-3 [&_td]:px-3",children:[e.jsx(Be,{children:e.jsxs(Ne,{className:"bg-muted/50 hover:bg-muted/50 border-b border-border",children:[e.jsx(D,{className:"w-[140px] h-11",children:e.jsx(ie,{label:"TOP",k:"apartments"})}),e.jsx(D,{className:"h-11",children:e.jsx(ie,{label:"Jméno",k:"name"})}),e.jsx(D,{className:"h-11",children:e.jsx(ie,{label:"E-mail",k:"email"})}),e.jsx(D,{className:"w-[90px] h-11",children:e.jsx(ie,{label:"Jazyk",k:"language"})}),e.jsx(D,{className:"w-[110px] h-11",children:e.jsx(ie,{label:"Role",k:"role"})}),e.jsx(D,{className:"w-[150px] h-11",children:e.jsx(ie,{label:"Status",k:"status"})}),e.jsx(D,{className:"w-[120px] h-11",children:e.jsx(ie,{label:"Registrace",k:"created_at"})}),e.jsx(D,{className:"w-[70px] h-11 text-right font-medium text-muted-foreground",children:"Akce"})]})}),e.jsx(Ue,{children:R.length===0?e.jsx(Ne,{children:e.jsx(_,{colSpan:8,className:"text-center py-10 text-muted-foreground",children:x?"Žádnà uživatelé neodpovÃdajà hledánÃ":"Žádnà uživatelé"})}):R.map(Z=>{var K;return e.jsxs(Ne,{className:"cursor-pointer hover:bg-muted/40 border-b border-border/50 last:border-0",onClick:()=>a(`/admin/user/${Z.user_id}`),children:[e.jsx(_,{className:"font-semibold text-sm py-3.5",children:Z.apartments.length>
810?Z.apartments.map(l=>`TOP ${l.replace(/^TOP\s*/i,"")}`).join(", "):e.jsx("span",{className:"text-muted-foreground",children:"â"})}),e.jsx(_,{className:"text-sm py-3.5",children:f(Z)||e.jsx("span",{className:"text-muted-foreground italic",children:"Neuvedeno"})}),e.jsx(_,{className:"text-sm text-muted-foreground py-3.5",children:Z.email||"â"}),e.jsx(_,{className:"text-sm py-3.5",children:((K=Z.language)==null?void 0:K.toUpperCase())||"â"}),e.jsx(_,{className:"py-3.5",children:Z.roles.length>0?e.jsx(Q,{variant:Z.roles.includes("admin")?"default":"outline",className:"gap-1 text-xs font-medium",children:Z.roles.includes("admin")?e.jsxs(e.Fragment,{children:[e.jsx(As,{className:"h-3 w-3"})," Admin"]}):e.jsxs(e.Fragment,{children:[e.jsx(ba,{className:"h-3 w-3"})," User"]})}):e.jsx("span",{className:"text-muted-foreground",children:"â"})}),e.jsx(_,{className:"py-3.5",children:W(Z.approval_status,Z.user_id,Z.apartments.length>0,Z.roles.includes("owner"))}),e.jsx(_,{className:"text-sm text-muted-foreground py-3.5",children:hs(new Date(Z.created_at),"dd.MM.yyyy",{locale:ys})}),e.jsx(_,{className:"text-right py-3.5",onClick:l=>l.stopPropagation(),children:e.jsxs("div",{className:"flex items-center justify-end gap-1",children:[Z.owner_contact_id&&e.jsx(b,{size:"icon",variant:"ghost",className:"h-7 w-7",title:"OtevÅÃt vlastnickou kartu",onClick:()=>a(`/admin/owner/${Z.owner_contact_id}`),children:e.jsx(Vs,{className:"h-3.5 w-3.5 text-emerald-600"})}),e.jsx(b,{size:"icon",variant:"ghost",className:"h-7 w-7",title:"OtevÅÃt detail úÄtu",onClick:()=>a(`/admin/user/${Z.user_id}`),children:e.jsx(bs,{className:"h-3.5 w-3.5 text-muted-foreground"})})]})})]},Z.id)})})]})}),e.jsx(Ge,{open:p,onOpenChange:m,children:e.jsxs(Je,{className:"max-w-lg",children:[e.jsxs(Ye,{children:[e.jsx(Qe,{className:"font-serif",children:"Zpracovat vybrané duplicity"}),e.jsxs(us,{children:["Nalezeno ",d.length," silných duplicit. Vyberte, které chcete smazat."]})]}),e.jsx(bt,{className:"max-h-[300px]",children:e.jsx("div",{className:"space-y-2",children:d.map(([Z,K])=>{const l=i.find(U=>U.user_id===Z);return l?e.jsxs("label",{className:`flex items-start gap-3 p-3 rounded-lg border cursor-pointer transition-colors ${$.has(Z)?"border-primary bg-primary/5":"border-border hover:bg-muted/50"}`,children:[e.jsx(xs,{checked:$.has(Z),onCheckedChange:U=>{const n=new Set($);U?n.add(Z):n.delete(Z),H(n)},className:"mt-0.5"}),e.jsxs("div",{className:"flex-1 min-w-0",children:[e.jsx("div",{className:"font-medium text-sm",children:f(l)||"Neuvedeno"}),e.jsxs("div",{className:"text-xs text-muted-foreground",children:[l.email," â ",K.ownerName,K.apartments.length>0&&e.jsxs(e.Fragment,{children:[" (",K.apartments.map(U=>`TOP ${U.replace(/^TOP\s*/i,"")}`).join(", "),")"]})]})]})]},Z):null})})}),e.jsxs("label",{className:"flex items-center gap-3 p-3 rounded-lg border border-border bg-muted/20 cursor-pointer",children:[e.jsx(xs,{checked:J,onCheckedChange:Z=>z(Z===!0)}),e.jsxs("div",{className:"flex items-center gap-2 text-sm",children:[e.jsx(Bs,{className:"h-4 w-4"}),e.jsx("span",{children:"Informovat uživatele e-mailem"})]})]}),e.jsxs("div",{className:"flex justify-between pt-2",children:[e.jsx(b,{variant:"outline",onClick:()=>m(!1),children:"ZruÅ¡it"}),e.jsxs(b,{variant:"destructive",disabled:$.size===0||h,onClick:ce,children:[h?e.jsx(fe,{className:"h-4 w-4 animate-spin mr-1"}):e.jsx(qe,{className:"h-4 w-4 mr-1"}),"Zpracovat vybrané (",$.size,")"]})]})]})})]})]})},Zt=[{value:"techem",label:"Techem Report",icon:hr},{value:"protokol",label:"Protokol â zápis ze zasedánÃ",icon:Pn},{value:"vyuctovani",label:"RoÄnà vyúÄtovánÃ",icon:An},{value:"ostatni",label:"Ostatnà dokumenty",icon:En}],bi=s=>Zt.find(a=>a.value===s)||Zt[3],Ni=new Date().getFullYear(),_i=Array.from({length:10},(s,a)=>Ni-a),wi=()=>{const{user:s}=Ht(),{toast:a}=Re(),[i,y]=t.useState([]),[E,P]=t.useState(!0),[x,O]=t.useState(!1),[S,N]=t.useState({title:"",description:"",category:"",year:""}),[j,w]=t.useState(null),[M,o]=t.useState(!1),[v,u]=t.useState(!1),[p,m]=t.useState(null),[$,H]=t.useState("all");t.useEffect(()=>{J()},[]);const J=async()=>{const{data:T,error:r}=await g.from("owner_documents").select("*").order("year",{ascending:!1,nullsFirst:!1}).order("created_at",{ascending:!1});if(r){a({variant:"destructive",title:"Chyba",description:"NepodaÅilo se naÄÃst dokumenty."});return}y(T||[]),P(!1)},z=async T=>
81{if(T.preventDefault(),!j){a({variant:"destructive",title:"Chyba",description:"Vyberte soubor."});return}o(!0);const r=j.name.split(".").pop(),f=`${Date.now()}.${r}`,{error:R}=await g.storage.from("documents").upload(f,j);if(R){a({variant:"destructive",title:"Chyba",description:"NepodaÅilo se nahrát soubor."}),o(!1);return}const{data:F}=g.storage.from("documents").getPublicUrl(f),{error:ce}=await g.from("owner_documents").insert([{title:S.title,description:S.description||null,category:S.category||null,year:S.year?parseInt(S.year):null,file_url:F.publicUrl,file_name:j.name,uploaded_by:s==null?void 0:s.id}]);ce?a({variant:"destructive",title:"Chyba",description:"NepodaÅilo se uložit dokument."}):(a({title:"ÃspÄch",description:"Dokument byl nahrán."}),N({title:"",description:"",category:"",year:""}),w(null),O(!1),J()),o(!1)},h=T=>{m(T),u(!0)},I=async()=>{if(!p)return;const{error:T}=await g.from("owner_documents").delete().eq("id",p);T?a({variant:"destructive",title:"Chyba",description:"NepodaÅilo se smazat dokument."}):(a({title:"ÃspÄch",description:"Dokument byl smazán."}),J()),u(!1),m(null)},c=($==="all"?i:i.filter(T=>T.category===$)).reduce((T,r)=>{const f=r.year?String(r.year):"Bez roku";return T[f]||(T[f]=[]),T[f].push(r),T},{}),d=Object.keys(c).sort((T,r)=>T==="Bez roku"?1:r==="Bez roku"?-1:Number(r)-Number(T));return E?e.jsx("div",{className:"flex justify-center py-12",children:e.jsx(fe,{className:"h-8 w-8 animate-spin text-primary"})}):e.jsxs("div",{className:"space-y-6",children:[e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsxs("h2",{className:"font-serif text-2xl font-bold text-foreground",children:["Správa dokumentů",e.jsxs("span",{className:"text-base font-normal text-muted-foreground ml-2",children:["(",i.length,")"]})]}),e.jsxs(Ge,{open:x,onOpenChange:O,children:[e.jsx(yt,{asChild:!0,children:e.jsxs(b,{children:[e.jsx(Xe,{className:"mr-2 h-4 w-4"}),"Nahrát dokument"]})}),e.jsxs(Je,{className:"max-w-md",children:[e.jsx(Ye,{children:e.jsx(Qe,{className:"font-serif",children:"Nový dokument"})}),e.jsxs("form",{onSubmit:z,className:"space-y-4",children:[e.jsxs("div",{className:"space-y-2",children:[e.jsx(q,{htmlFor:"title",children:"Název"}),e.jsx(se,{id:"title",value:S.title,onChange:T=>N({...S,title:T.target.value}),required:!0})]}),e.jsxs("div",{className:"grid grid-cols-2 gap-3",children:[e.jsxs("div",{className:"space-y-2",children:[e.jsx(q,{children:"Kategorie"}),e.jsxs(De,{value:S.category,onValueChange:T=>N({...S,category:T}),children:[e.jsx(Pe,{children:e.jsx(Ae,{placeholder:"Vyberte"})}),e.jsx(Ee,{children:Zt.map(T=>e.jsx(me,{value:T.value,children:e.jsxs("span",{className:"flex items-center gap-2",children:[e.jsx(T.icon,{className:"h-3.5 w-3.5"}),T.label]})},T.value))})]})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(q,{children:"Rok"}),e.jsxs(De,{value:S.year,onValueChange:T=>N({...S,year:T}),children:[e.jsx(Pe,{children:e.jsx(Ae,{placeholder:"Rok"})}),e.jsx(Ee,{children:_i.map(T=>e.jsx(me,{value:String(T),children:T},T))})]})]})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(q,{htmlFor:"description",children:"Popis"}),e.jsx(vs,{id:"description",value:S.description,onChange:T=>N({...S,description:T.target.value}),rows:3})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(q,{htmlFor:"file",children:"Soubor"}),e.jsx(se,{id:"file",type:"file",onChange:T=>{var r;return w(((r=T.target.files)==null?void 0:r[0])||null)},required:!0})]}),e.jsx(b,{type:"submit",className:"w-full",disabled:M,children:M?e.jsxs(e.Fragment,{children:[e.jsx(fe,{className:"mr-2 h-4 w-4 animate-spin"}),"Nahrávám..."]}):"Nahrát dokument"})]})]})]})]}),e.jsx(ks,{value:$,onValueChange:H,children:e.jsxs(Cs,{children:[e.jsx(We,{value:"all",children:"VÅ¡e"}),Zt.map(T=>{const r=i.filter(f=>f.category===T.value).length;return e.jsxs(We,{value:T.value,className:"gap-1.5",children:[e.jsx(T.icon,{className:"h-3.5 w-3.5"}),T.label.split(" â ")[0].split(" ")[0],r>0&&e.jsx(Q,{variant:"secondary",className:"ml-1 h-5 min-w-5 text-xs",children:r})]},T.value)})]})}),d.length===0?e.jsx(ee,{children:e.jsx(ae,{className:"p-8 text-center text-muted-foreground",children:"Žádné dokumenty v této kategorii"})}):d.map(T=>e.jsxs("div",{className:"space-y-3",children:[e.jsx("h3",{className:"text-sm font-semibold text-muted-foreground uppercase tracking-wide border-b border-border pb-1",children:T}),e.jsx("div",{className:"grid gap-3 md:grid-cols-2 lg:grid-cols-3",children:c[T].map(r=>
81{const f=bi(r.category),R=f.icon;return e.jsxs(ee,{className:"group hover:shadow-md transition-shadow",children:[e.jsx(ye,{className:"pb-2",children:e.jsxs("div",{className:"flex items-start gap-3",children:[e.jsx("div",{className:"p-2 rounded-lg bg-primary/10 text-primary shrink-0",children:e.jsx(R,{className:"h-4 w-4"})}),e.jsxs("div",{className:"flex-1 min-w-0",children:[e.jsx(be,{className:"text-sm font-medium truncate",children:r.title}),e.jsxs("div",{className:"flex items-center gap-2 mt-0.5",children:[e.jsx(Q,{variant:"outline",className:"text-[10px] px-1.5 py-0",children:f.label.split(" â ")[0]}),e.jsx("span",{className:"text-[10px] text-muted-foreground",children:new Date(r.created_at).toLocaleDateString("cs-CZ")})]})]})]})}),e.jsxs(ae,{className:"pt-0",children:[r.description&&e.jsx("p",{className:"text-xs text-muted-foreground mb-3 line-clamp-2",children:r.description}),e.jsxs("div",{className:"flex gap-2",children:[e.jsx(b,{asChild:!0,variant:"outline",size:"sm",className:"h-7 text-xs",children:e.jsxs("a",{href:r.file_url,target:"_blank",rel:"noopener noreferrer",children:[e.jsx(vt,{className:"mr-1 h-3 w-3"}),"Stáhnout"]})}),e.jsxs(b,{variant:"ghost",size:"sm",className:"h-7 text-xs text-destructive hover:text-destructive opacity-0 group-hover:opacity-100 transition-opacity",onClick:()=>h(r.id),children:[e.jsx(qe,{className:"mr-1 h-3 w-3"}),"Smazat"]})]})]})]},r.id)})})]},T)),e.jsx(ms,{open:v,onOpenChange:u,title:"Smazat dokument",description:"Opravdu chcete smazat tento dokument? Tato akce je nevratná.",confirmText:"Smazat",onConfirm:I})]})},ki=()=>{const{user:s}=Ht(),{toast:a}=Re(),[i,y]=t.useState([]),[E,P]=t.useState(!0),[x,O]=t.useState(!1),[S,N]=t.useState(null),[j,w]=t.useState({title:"",content:"",is_important:!1,expires_at:""}),[M,o]=t.useState(!1),[v,u]=t.useState(!1),[p,m]=t.useState(null);t.useEffect(()=>{$()},[]);const $=async()=>{const{data:I,error:k}=await g.from("announcements").select("*").order("created_at",{ascending:!1});if(k){a({variant:"destructive",title:"Chyba",description:"NepodaÅilo se naÄÃst oznámenÃ."});return}y(I||[]),P(!1)},H=I=>{I?(N(I),w({title:I.title,content:I.content,is_important:I.is_important,expires_at:I.expires_at?new Date(I.expires_at).toISOString().split("T")[0]:""})):(N(null),w({title:"",content:"",is_important:!1,expires_at:""})),O(!0)},J=async I=>{I.preventDefault(),o(!0);const k={title:j.title,content:j.content,is_important:j.is_important,expires_at:j.expires_at?new Date(j.expires_at).toISOString():null,created_by:s==null?void 0:s.id};if(S){const{error:c}=await g.from("announcements").update(k).eq("id",S.id);a(c?{variant:"destructive",title:"Chyba",description:"NepodaÅilo se aktualizovat oznámenÃ."}:{title:"ÃspÄch",description:"Oznámenà bylo aktualizováno."})}else{const{error:c}=await g.from("announcements").insert([k]);a(c?{variant:"destructive",title:"Chyba",description:"NepodaÅilo se vytvoÅit oznámenÃ."}:{title:"ÃspÄch",description:"Oznámenà bylo vytvoÅeno."})}o(!1),O(!1),$()},z=I=>{m(I),u(!0)},h=async()=>{if(!p)return;const{error:I}=await g.from("announcements").delete().eq("id",p);I?a({variant:"destructive",title:"Chyba",description:"NepodaÅilo se smazat oznámenÃ."}):(a({title:"ÃspÄch",description:"Oznámenà bylo smazáno."}),$()),u(!1),m(null)};return E?e.jsx("div",{className:"flex justify-center py-12",children:e.jsx(fe,{className:"h-8 w-8 animate-spin text-primary"})}):e.jsxs("div",{className:"space-y-6",children:[e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsx("h2",{className:"font-serif text-2xl font-bold text-foreground",children:"Správa oznámenÃ"}),e.jsxs(Ge,{open:x,onOpenChange:O,children:[e.jsx(yt,{asChild:!0,children:e.jsxs(b,{onClick:()=>H(),children:[e.jsx(Xe,{className:"mr-2 h-4 w-4"}),"Nové oznámenÃ"]})}),e.jsxs(Je,{className:"max-w-md",children:[e.jsx(Ye,{children:e.jsx(Qe,{className:"font-serif",children:S?"Upravit oznámenÃ":"Nové oznámenÃ"})}),e.jsxs("form",{onSubmit:J,className:"space-y-4",children:[e.jsxs("div",{className:"space-y-2",children:[e.jsx(q,{htmlFor:"title",children:"Titulek"}),e.jsx(se,{id:"title",value:j.title,onChange:I=>w({...j,title:I.target.value}),required:!0})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(q,{htmlFor:"content",children:"Obsah"}),e.jsx(vs,{id:"content",value:j.content,onChange:I=>w({...j,content:I.target.value}),rows:5,required:!0})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(q,{htmlFor:"expires_at",children:"Platné do"}),e.jsx(se,{id:"expires_at",type:"date",value:j.expires_at,onChange:I=>w({...j,expires_at:I.target.value})})]}),e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsxs(q,{htmlFor:"is_important",className:"flex items-center gap-2",children:[e.jsx(is,{className:"h-4 w-4 text-destructive"}),"Důležité oznámenÃ"]}),e.jsx(ss,{id:"is_important",checked:j.is_important,onCheckedChange:I=>w({...j,is_important:I})})]}),e.jsx(b,{type:"submit",className:"w-full",disabled:M,children:M?e.jsxs(e.Fragment,{children:[e.jsx(fe,{className:"mr-2 h-4 w-4 animate-spin"}),"Ukládám..."]}):S?"Uložit zmÄny":"VytvoÅit oznámenÃ"})]})]})]})]}),e.jsx("div",{className:"space-y-4",children:i.map(I=>e.jsxs(ee,{className:I.is_important?"border-destructive/50":"",children:[e.jsxs(ye,{className:"pb-2",children:[e.jsxs("div",{className:"flex items-start justify-between gap-4",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(Dt,{className:"h-5 w-5 text-primary"}),e.jsx(be,{className:"font-serif text-lg",children:I.title}),I.is_important&&e.jsxs(Q,{variant:"destructive",className:"gap-1",children:[e.jsx(is,{className:"h-3 w-3"}),"Důležité"]})]}),e.jsxs("div",{className:"flex gap-2",children:[e.jsx(b,{variant:"outline",size:"sm",onClick:()=>H(I),children:e.jsx(Ns,{className:"h-3 w-3"})}),e.jsx(b,{variant:"destructive",size:"sm",onClick:()=>z(I.id),children:e.jsx(qe,{className:"h-3 w-3"})})]})]}),e.jsxs(Le,{children:[new Date(I.created_at).toLocaleDateString("cs-CZ"),I.expires_at&&e.jsxs(e.Fragment,{children:[" · Platné do: ",new Date(I.expires_at).toLocaleDateString("cs-CZ")]})]})]}),e.jsx(ae,{children:e.jsx("p",{className:"text-sm text-muted-foreground whitespace-pre-wrap line-clamp-3",children:I.content})})]},I.id))}),e.jsx(ms,{open:v,onOpenChange:u,title:"Smazat oznámenÃ",description:"Opravdu chcete smazat toto oznámenÃ? Tato akce je nevratná.",confirmText:"Smazat",onConfirm:h})]})},fa=s=>{const a=new Date;return!s.is_active||In(s.ends_at,a)?"closed":new Date(s.starts_at)>a?"not_started":"active"},Ci=({poll:s})=>{const a=fa(s);return a==="not_started"?e.jsxs(Q,{className:"bg-amber-100 text-amber-800 border-amber-300",children:[e.jsx(at,{className:"h-3 w-3 mr-1"}),"Plánované"]}):a==="active"?e.jsxs(Q,{className:"bg-green-100 text-green-800 border-green-300",children:[e.jsx(ps,{className:"h-3 w-3 mr-1"}),"ProbÃhá"]}):e.jsx(Q,{variant:"secondary",children:"UkonÄené"})},Si=({resolution:s,votingType:a})=>s==="accepted"?e.jsxs(Q,{className:"bg-green-100 text-green-800 border-green-300",children:[e.jsx(ps,{className:"h-3 w-3 mr-1"}),"PÅijato"]}):s==="rejected"?e.jsxs(Q,{className:"bg-red-100 text-red-800 border-red-300",children:[e.jsx(js,{className:"h-3 w-3 mr-1"}),"ZamÃtnuto"]}):a==="automatic"?e.jsxs(Q,{variant:"outline",children:[e.jsx(Us,{className:"h-3 w-3 mr-1"}),"Bez oficiálnÃho výsledku"]}):e.jsx("span",{className:"text-muted-foreground",children:"â"}),zi=()=>{var ve;const s=Ks(),{toast:a}=Re(),{language:i}=Zs(),[y,E]=t.useState([]),[P,x]=t.useState([]),[O,S]=t.useState([]),[N,j]=t.useState(!0),[w,M]=t.useState(!1),[o,v]=t.useState(null),[u,p]=t.useState(!1),[m,$]=t.useState(null),[H,J]=t.useState(!1),[z,h]=t.useState(null),[I,k]=t.useState(!1),[c,d]=t.useState(!1),[T,r]=t.useState(null),[f,R]=t.useState(!1),[F,ce]=t.useState(null),[ie,W]=t.useState(""),[Z,K]=t.useState(!1),[l,U]=t.useState(!1);t.useEffect(()=>{n()},[]);const n=async()=>{const[X,Ce,ze]=await Promise.all([g.from("polls").select("*").order("created_at",{ascending:!1}),g.from("poll_votes").select("poll_id, apartment_code"),g.from("apartments").select("code, excluded_from_voting, weg_anteil_rv")]);if(X.error){a({variant:"destructive",title:"Chyba",description:"NepodaÅilo se naÄÃst hlasovánÃ."});return}const Me=(X.data||[]).map(_e=>({..._e,options:Array.isArray(_e.options)?_e.options:[],resolution:_e.resolution??null,voting_type:_e.voting_type||"automatic",auto_close:_e.auto_close??!0,results_visibility:_e.results_visibility||"always",title_cs:_e.title_cs||null,title_en:_e.title_en||null,auto_send_results:_e.auto_send_results??!1,results_sent_at:_e.results_sent_at??null})),V=new Date;Me.forEach(_e=>{_e.auto_close&&In(_e.ends_at,V)&&_e.is_active&&(g.from("polls").update({is_active:!1}).eq("id",_e.id).then(()=>{}),_e.is_active=!1)}),E(Me),x(Ce.data||[]),S(ze.data||[]),j(!1)},G=O.filter(X=>!X.excluded_from_voting),Y=G.reduce((X,Ce)=>X+(Ce.weg_anteil_rv||0),0),pe=G.length,B=X=>{const Ce=P.filter(ze=>ze.poll_id===X&&ze.apartment_code).map(ze=>ze.apartment_code);return[...new Set(Ce)]},te=X=>B(X).reduce((ze,Me)=>{const V=O.find(_e=>_e.code===Me);return ze+((V==null?void 0:V.weg_anteil_rv)||0)},0),xe=async()=>
81{if(!o)return;const{error:X}=await g.from("polls").delete().eq("id",o);X?a({variant:"destructive",title:"Chyba",description:"NepodaÅilo se smazat hlasovánÃ."}):(a({title:"Hlasovánà smazáno"}),n()),M(!1),v(null)},de=async()=>{if(!m)return;const X=new Date().toISOString(),{error:Ce}=await g.from("polls").update({is_active:!1,ends_at:X}).eq("id",m);Ce||await g.from("polls").update({posted_on_board_at:X}).eq("id",m).is("posted_on_board_at",null),Ce?a({variant:"destructive",title:"Chyba",description:"NepodaÅilo se ukonÄit hlasovánÃ."}):(a({title:"Hlasovánà ukonÄeno"}),n()),p(!1),$(null)},L=X=>{const Ce=X.ends_at?new Date(X.ends_at):new Date,ze=Ce.getTime()>Date.now()?Ce:new Date;ze.setDate(ze.getDate()+7);const Me=V=>String(V).padStart(2,"0");W(`${ze.getFullYear()}-${Me(ze.getMonth()+1)}-${Me(ze.getDate())}T${Me(ze.getHours())}:${Me(ze.getMinutes())}`),ce(X.id),U(!1),R(!0)},re=async()=>{if(!(!F||!ie)){K(!0);try{const X=new Date(ie);if(isNaN(X.getTime()))throw new Error("Neplatné datum.");const{error:Ce}=await g.from("polls").update({ends_at:X.toISOString(),is_active:!0}).eq("id",F);if(Ce)throw Ce;if(l){const{error:ze}=await g.functions.invoke("send-poll-reminder",{body:{poll_id:F,kind:"reminder"}});ze&&a({variant:"destructive",title:"TermÃn prodloužen, e-mail se nepodaÅilo odeslat",description:ze.message})}a({title:"Hlasovánà prodlouženo",description:`Nový termÃn: ${X.toLocaleString("cs-CZ")}. Již odevzdané hlasy zůstávajà platné.`}),R(!1),ce(null),n()}catch(X){a({variant:"destructive",title:"Chyba",description:(X==null?void 0:X.message)||"NepodaÅilo se prodloužit hlasovánÃ."})}finally{K(!1)}}},A=async()=>{if(z){k(!0);try{const{data:X,error:Ce}=await g.functions.invoke("send-poll-results",{body:{poll_id:z}});if(Ce)throw Ce;a({title:"Výsledek odeslán",description:`Odesláno: ${(X==null?void 0:X.sent)??0}, chyby: ${(X==null?void 0:X.failed)??0} (pÅÃjemců: ${(X==null?void 0:X.total_recipients)??0}).`}),n()}catch(X){a({variant:"destructive",title:"Chyba",description:(X==null?void 0:X.message)||"NepodaÅilo se odeslat výsledek."})}finally{k(!1),J(!1),h(null)}}},ne=X=>X?new Date(X).toLocaleDateString("cs-CZ"):"â",le=y.reduce((X,Ce)=>{const ze=fa(Ce);return ze==="active"?X.active.push(Ce):ze==="not_started"?X.planned.push(Ce):X.closed.push(Ce),X},{active:[],planned:[],closed:[]}),oe=[...le.active.sort((X,Ce)=>new Date(X.starts_at).getTime()-new Date(Ce.starts_at).getTime()),...le.planned.sort((X,Ce)=>new Date(X.starts_at).getTime()-new Date(Ce.starts_at).getTime())],ke=le.closed.sort((X,Ce)=>{const ze=X.ends_at?new Date(X.ends_at).getTime():0;return(Ce.ends_at?new Date(Ce.ends_at).getTime():0)-ze}),je=(()=>{if(le.active.length===0)return null;const X=le.active.map(Ce=>{const ze=te(Ce.id);return Y>0?ze/Y*100:0});return X.reduce((Ce,ze)=>Ce+ze,0)/X.length})(),ue=({poll:X,showResolution:Ce})=>{const ze=fa(X),Me=ze==="active"||ze==="not_started",V=B(X.id),_e=te(X.id),Ie=Y>0?_e/Y*100:0,Ve=pe>0?V.length/pe*100:0,Fe=Ie>=33.33,C=i==="cs"?X.title_cs||X.title:i==="en"&&X.title_en||X.title;return e.jsxs(Ne,{className:"cursor-pointer h-8",onClick:()=>s(`/admin/poll/${X.id}/results`),children:[e.jsx(_,{className:"max-w-[300px] py-1.5",children:e.jsx("span",{className:"block truncate font-medium text-sm",title:C,children:C})}),e.jsx(_,{className:"py-1.5",children:e.jsx(Ci,{poll:X})}),e.jsxs(_,{className:"text-muted-foreground whitespace-nowrap text-sm py-1.5",children:[ne(X.starts_at)," â ",ne(X.ends_at)]}),e.jsx(_,{className:"py-1.5",children:e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsxs("span",{className:"whitespace-nowrap",children:[V.length," / ",pe]}),e.jsx(Bt,{value:Ve,className:"h-1.5 w-16"})]})}),e.jsx(_,{className:"py-1.5",children:e.jsx(as,{children:e.jsxs(Ke,{children:[e.jsx(Ze,{asChild:!0,children:e.jsxs("span",{className:`font-bold ${Fe?"text-green-700":"text-muted-foreground"}`,children:[Ie.toFixed(1)," %"]})}),e.jsxs(He,{children:[e.jsx("p",{children:Fe?"SplÅuje kvórum (⥠33,33 %)":"NesplÅuje kvórum (< 33,33 %)"}),e.jsxs("p",{className:"text-xs text-muted-foreground",children:[Ta(_e)," / ",Ta(Y)]})]})]})})}),Ce&&e.jsx(_,{className:"py-1.5",children:e.jsx(Si,{resolution:X.resolution,votingType:X.voting_type})}),e.jsx(_,{className:"text-right py-1.5",onClick:ge=>ge.stopPropagation(),children:e.jsxs("div",{className:"flex gap-1 justify-end",children:[e.jsx(as,{children:e.jsxs(Ke,{children:[e.jsx(Ze,{asChild:!0,children:e.jsx(b,{variant:"ghost",size:"sm",onClick:()=>s(`/admin/poll/${X.id}/results`),children:e.jsx(Tn,{className:"h-3.5 w-3.5"})})}),e.jsx(He,{children:"Výsledky"})]})}),e.jsx(as,{children:e.jsxs(Ke,{children:[e.jsx(Ze,{asChild:!0,children:e.jsx(b,{variant:"ghost",size:"sm",onClick:()=>s(`/admin/poll/${X.id}`),children:e.jsx(Ns,{className:"h-3.5 w-3.5"})})}),e.jsx(He,{children:"Upravit"})]})}),Me&&e.jsx(as,{children:e.jsxs(Ke,{children:[e.jsx(Ze,{asChild:!0,children:e.jsx(b,{variant:"ghost",size:"sm",onClick:()=>{$(X.id),p(!0)},children:e.jsx(gr,{className:"h-3.5 w-3.5 text-amber-600"})})}),e.jsx(He,{children:"UkonÄit hlasovánÃ"})]})}),e.jsx(as,{children:e.jsxs(Ke,{children:[e.jsx(Ze,{asChild:!0,children:e.jsx(b,{variant:"ghost",size:"sm",onClick:()=>L(X),children:e.jsx(cr,{className:"h-3.5 w-3.5 text-blue-600"})})}),e.jsx(He,{children:ze==="closed"?"Znovu otevÅÃt / prodloužit hlasovánÃ":"Prodloužit termÃn hlasovánÃ"})]})}),e.jsx(as,{children:e.jsxs(Ke,{children:[e.jsx(Ze,{asChild:!0,children:e.jsx(b,{variant:"ghost",size:"sm",onClick:()=>{r(X.id),d(!0)},children:e.jsx(bs,{className:"h-3.5 w-3.5 text-blue-600"})})}),e.jsx(He,{children:"Náhled e-mailu s výsledkem"})]})}),e.jsx(as,{children:e.jsxs(Ke,{children:[e.jsx(Ze,{asChild:!0,children:e.jsx(b,{variant:"ghost",size:"sm",onClick:()=>{h(X.id),J(!0)},children:e.jsx($s,{className:`h-3.5 w-3.5 ${X.results_sent_at?"text-muted-foreground":"text-green-600"}`})})}),e.jsx(He,{children:X.results_sent_at?`Znovu odeslat výsledek (naposledy ${new Date(X.results_sent_at).toLocaleStr
81ing("cs-CZ")})`:"Odeslat výsledek e-mailem vÅ¡em vlastnÃkům"})]})}),e.jsx(as,{children:e.jsxs(Ke,{children:[e.jsx(Ze,{asChild:!0,children:e.jsx(b,{variant:"ghost",size:"sm",onClick:()=>{v(X.id),M(!0)},children:e.jsx(qe,{className:"h-3.5 w-3.5 text-destructive"})})}),e.jsx(He,{children:"Smazat"})]})})]})})]})};return N?e.jsx("div",{className:"flex justify-center py-12",children:e.jsx(fe,{className:"h-8 w-8 animate-spin text-primary"})}):e.jsxs("div",{className:"space-y-6",children:[e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsx("h2",{className:"font-serif text-2xl font-bold text-foreground",children:"Správa hlasovánÃ"}),e.jsxs(b,{onClick:()=>s("/admin/poll/new"),children:[e.jsx(Xe,{className:"mr-2 h-4 w-4"}),"Nové hlasovánÃ"]})]}),e.jsxs("div",{className:"grid grid-cols-2 md:grid-cols-4 gap-3",children:[e.jsx(ee,{children:e.jsxs(ae,{className:"py-3 px-4",children:[e.jsx("div",{className:"text-2xl font-bold text-foreground",children:le.active.length}),e.jsx("div",{className:"text-xs text-muted-foreground",children:"ProbÃhá"})]})}),e.jsx(ee,{children:e.jsxs(ae,{className:"py-3 px-4",children:[e.jsx("div",{className:"text-2xl font-bold text-foreground",children:le.planned.length}),e.jsx("div",{className:"text-xs text-muted-foreground",children:"Plánované"})]})}),e.jsx(ee,{children:e.jsxs(ae,{className:"py-3 px-4",children:[e.jsx("div",{className:"text-2xl font-bold text-foreground",children:le.closed.length}),e.jsx("div",{className:"text-xs text-muted-foreground",children:"UkonÄené"})]})}),e.jsx(ee,{children:e.jsxs(ae,{className:"py-3 px-4",children:[e.jsx("div",{className:"text-2xl font-bold text-foreground",children:je!==null?`${je.toFixed(1)} %`:"â"}),e.jsx("div",{className:"text-xs text-muted-foreground",children:"à úÄast (aktivnÃ)"})]})})]}),e.jsxs(ks,{defaultValue:"current",children:[e.jsxs(Cs,{children:[e.jsxs(We,{value:"current",children:["Aktuálnà (",oe.length,")"]}),e.jsxs(We,{value:"history",children:["Historie (",ke.length,")"]})]}),e.jsx(es,{value:"current",children:e.jsxs(ee,{children:[e.jsx(ye,{className:"flex flex-row items-center justify-between",children:e.jsxs(be,{className:"text-base",children:["Aktuálnà hlasovánà (",oe.length,")"]})}),e.jsx(ae,{children:oe.length===0?e.jsx("p",{className:"text-muted-foreground py-8 text-center",children:"Žádné aktuálnà hlasovánÃ."}):e.jsxs($e,{children:[e.jsx(Be,{children:e.jsxs(Ne,{className:"bg-muted/50 hover:bg-muted/50",children:[e.jsx(D,{className:"h-9 text-xs",children:"Název"}),e.jsx(D,{className:"h-9 text-xs",children:"Stav"}),e.jsx(D,{className:"h-9 text-xs",children:"ObdobÃ"}),e.jsx(D,{className:"h-9 text-xs",children:"ÃÄast"}),e.jsx(D,{className:"h-9 text-xs",children:"WEG %"}),e.jsx(D,{className:"text-right h-9 text-xs",children:"Akce"})]})}),e.jsx(Ue,{children:oe.map(X=>e.jsx(ue,{poll:X,showResolution:!1},X.id))})]})})]})}),e.jsx(es,{value:"history",children:e.jsxs(ee,{children:[e.jsx(ye,{className:"flex flex-row items-center justify-between",children:e.jsxs(be,{className:"text-base",children:["Historie hlasovánà (",ke.length,")"]})}),e.jsx(ae,{children:ke.length===0?e.jsx("p",{className:"text-muted-foreground py-8 text-center",children:"Žádné ukonÄené hlasovánÃ."}):e.jsxs($e,{children:[e.jsx(Be,{children:e.jsxs(Ne,{className:"bg-muted/50 hover:bg-muted/50",children:[e.jsx(D,{className:"h-9 text-xs",children:"Název"}),e.jsx(D,{className:"h-9 text-xs",children:"Stav"}),e.jsx(D,{className:"h-9 text-xs",children:"ObdobÃ"}),e.jsx(D,{className:"h-9 text-xs",children:"ÃÄast"}),e.jsx(D,{className:"h-9 text-xs",children:"WEG %"}),e.jsx(D,{className:"h-9 text-xs",children:"Výsledek"}),e.jsx(D,{className:"text-right h-9 text-xs",children:"Akce"})]})}),e.jsx(Ue,{children:ke.map(X=>e.jsx(ue,{poll:X,showResolution:!0},X.id))})]})})]})})]}),e.jsx(ms,{open:w,onOpenChange:M,title:"Smazat hlasovánÃ",description:"Opravdu chcete smazat toto hlasovánÃ? Tato akce je nevratná.",confirmText:"Smazat",onConfirm:xe}),e.jsx(ms,{open:u,onOpenChange:p,title:"UkonÄit hlasovánÃ",description:"Opravdu chcete ukonÄit toto hlasovánÃ? Äas ukonÄenà bude nastaven na aktuálnà Äas.",confirmText:"UkonÄit",onConfirm:de}),e.jsx(ms,{open:H,onOpenChange:J,title:"Odeslat výsledek hlasovánÃ",description:(ve=y.find(X=>X.id===z))!=null&&ve.results_sent_at?"Výsledek už byl jednou rozeslán. Chcete jej odeslat znovu vÅ¡em vlastnÃkům?":"Odeslat e-mail s výsledkem hlasovánà vÅ¡em oprávnÄným vlastnÃkům? E-mail obsahuje právnà upozornÄnà dle § 24 odst. 6 WEG 2002 (lhůta 1 mÄsÃc pro napadenÃ).",confirmText:I?"OdesÃlámâ¦":"Odeslat",onConfirm:A}),e.jsx(Ge,{open:f,onOpenChange:X=>{R(X),X||ce(null)},children:e.jsxs(Je,{className:"sm:max-w-md",children:[e.jsxs(Ye,{children:[e.jsx(Qe,{children:"Prodloužit hlasovánÃ"}),e.jsx(us,{children:"Nastavte nový termÃn ukonÄenÃ. Hlasovánà se znovu otevÅe, již odevzdané hlasy zůstávajà platné a vlastnÃci, kteÅà jeÅ¡tÄ nehlasovali, mohou hlasovat do nového termÃnu."})]}),e.jsxs("div",{className:"space-y-4",children:[e.jsxs("div",{className:"space-y-2",children:[e.jsx(q,{htmlFor:"extend-date",children:"Nový termÃn ukonÄenÃ"}),e.jsx(se,{id:"extend-date",type:"datetime-local",value:ie,onChange:X=>W(X.target.value)})]}),e.jsxs("div",{className:"flex items-center gap-3",children:[e.jsx(ss,{id:"notify-extend",checked:l,onCheckedChange:U}),e.jsx(q,{htmlFor:"notify-extend",className:"cursor-pointer text-sm font-normal",children:"Informovat e-mailem vlastnÃky, kteÅà jeÅ¡tÄ nehlasovali"})]})]}),e.jsxs(ls,{children:[e.jsx(b,{variant:"outline",onClick:()=>R(!1),children:"ZruÅ¡it"}),e.jsx(b,{onClick:re,disabled:Z||!ie,children:Z?"Ukládámâ¦":"Prodloužit"})]})]})}),e.jsx(pr,{open:c,onOpenChange:X=>{d(X),X||r(null)},pollId:T})]})},Di=s=>s?s.company_name?s.company_name:[s.first_name,s.last_name].filter(
81Boolean).join(" ")||s.email||"â":"â",Pi=({open:s,onOpenChange:a,onCompleted:i})=>{const{toast:y}=Re(),[E,P]=t.useState(!1),[x,O]=t.useState([]),[S,N]=t.useState(""),[j,w]=t.useState(null),[M,o]=t.useState(""),[v,u]=t.useState([]),[p,m]=t.useState(!1),[$,H]=t.useState(!1);t.useEffect(()=>{if(!s){N(""),w(null),o(""),u([]),m(!1);return}J()},[s]);const J=async()=>{P(!0);const{data:k,error:c}=await g.from("apartments").select("id, code, sort_order").order("sort_order",{ascending:!0});if(c||!k){y({variant:"destructive",title:"Chyba",description:"NepodaÅilo se naÄÃst apartmány."}),P(!1);return}const{data:d}=await g.from("apartment_owners").select("apartment_id, owner_contact:owner_contacts(first_name, last_name, company_name, email)").eq("is_current",!0),T=k.map(r=>{const f=d==null?void 0:d.find(R=>R.apartment_id===r.id);return{id:r.id,code:r.code,ownerName:Di(f==null?void 0:f.owner_contact)}});O(T),P(!1)},z=t.useMemo(()=>{const k=S.trim().toLowerCase();return k?x.filter(c=>c.code.toLowerCase().includes(k)||c.ownerName.toLowerCase().includes(k)):x},[x,S]),h=async k=>{H(!0);const{data:c,error:d}=await g.from("apartment_owners").select("*, owner_contact:owner_contacts(*)").eq("apartment_id",k.id).eq("is_current",!0);if(d){y({variant:"destructive",title:"Chyba",description:"NepodaÅilo se naÄÃst majitele."}),H(!1);return}w(k.id),o(k.code),u(c||[]),H(!1),m(!0)},I=()=>{m(!1),a(!1),i==null||i()};return e.jsxs(e.Fragment,{children:[e.jsx(Ge,{open:s&&!p,onOpenChange:a,children:e.jsxs(Je,{className:"max-w-2xl",children:[e.jsxs(Ye,{children:[e.jsx(Qe,{children:"PÅevod vlastnictvà â výbÄr bytu"}),e.jsx(us,{children:"Vyberte byt, jehož vlastnictvà chcete pÅevést na nového majitele."})]}),e.jsxs("div",{className:"space-y-4",children:[e.jsxs("div",{className:"relative",children:[e.jsx(fs,{className:"absolute left-3 top-1/2 h-4 w-4 -translate-y-1/2 text-muted-foreground"}),e.jsx(se,{autoFocus:!0,placeholder:"Hledat TOP nebo majiteleâ¦",value:S,onChange:k=>N(k.target.value),className:"pl-9"})]}),e.jsx("div",{className:"max-h-[420px] overflow-y-auto rounded-md border",children:E?e.jsx("div",{className:"flex items-center justify-center py-12",children:e.jsx(fe,{className:"h-6 w-6 animate-spin text-muted-foreground"})}):z.length===0?e.jsx("div",{className:"py-10 text-center text-sm text-muted-foreground",children:"Žádné apartmány neodpovÃdajà hledánÃ."}):e.jsx("ul",{className:"divide-y",children:z.map(k=>e.jsx("li",{children:e.jsxs("button",{type:"button",onClick:()=>h(k),disabled:$,className:"flex w-full items-center justify-between gap-3 px-4 py-3 text-left transition-colors hover:bg-muted/60 disabled:opacity-50",children:[e.jsxs("div",{className:"flex items-center gap-3 min-w-0",children:[e.jsx(Jt,{className:"h-4 w-4 text-muted-foreground shrink-0"}),e.jsxs("div",{className:"min-w-0",children:[e.jsx("div",{className:"font-medium text-sm",children:k.code}),e.jsx("div",{className:"text-xs text-muted-foreground truncate",children:k.ownerName})]})]}),e.jsx(Gs,{className:"h-4 w-4 text-muted-foreground shrink-0"})]})},k.id))})}),e.jsx("div",{className:"flex justify-end",children:e.jsx(b,{variant:"outline",onClick:()=>a(!1),children:"ZruÅ¡it"})})]})]})}),j&&e.jsx(br,{open:p,onOpenChange:k=>{m(k),k||(w(null),u([]))},apartmentId:j,apartmentCode:M,currentOwners:v,onCompleted:I})]})},Ai=()=>{const s=Ks(),{toast:a}=Re(),[i,y]=t.useState([]),[E,P]=t.useState(!0),[x,O]=t.useState(""),[S,N]=t.useState(""),[j,w]=t.useState(!1),[M,o]=t.useState(!1),[v,u]=t.useState(""),[p,m]=t.useState("code"),[$,H]=t.useState("asc"),[J,z]=t.useState(null),[h,I]=t.useState(""),[k,c]=t.useState(""),[d,T]=t.useState("");t.useState(!1);const[r,f]=t.useState(!1),[R,F]=t.useState(null),[ce,ie]=t.useState(!1);t.useEffect(()=>{W()},[]);const W=async()=>{const{data:L,error:re}=await g.from("apartments").select("*").order("sort_order",{ascending:!0});if(re){a({variant:"destructive",title:"Chyba",description:"NepodaÅilo se naÄÃst apartmány."}),P(!1);return}const{data:A}=await g.from("apartment_owners").select(` 82 apartment_id, 83 is_current,
84 owner_contact:owner_contacts(first_name, last_name, company_name) 85 `).eq("is_current",!0),ne=(L||[]).map(le=>{const oe=A==null?void 0:A.find(ke=>ke.apartment_id===le.id);return{...le,currentOwner:(oe==null?void 0:oe.owner_contact)||null}});y(ne),P(!1)},Z=async()=>{if(!x.trim()){a({variant:"destructive",title:"Chyba",description:"Zadejte název apartmánu."});return}o(!0);const L=S?parseInt(S):i.length+1,{error:re}=await g.from("apartments").insert({code:x.trim(),sort_order:L});if(re){a({variant:"destructive",title:"Chyba",description:re.code==="23505"?"Apartmán s tÃmto názvem již existuje.":"NepodaÅilo se pÅidat apartmán."}),o(!1);return}a({title:"Apartmán pÅidán"}),O(""),N(""),w(!1),o(!1),W()},K=async()=>{if(!R)return;const{error:L}=await g.from("apartments").delete().eq("id",R.id);if(L){a({variant:"destructive",title:"Chyba",description:"NepodaÅilo se smazat apartmán."}),f(!1);return}a({title:"Apartmán smazán"}),f(!1),F(null),W()},l=L=>L?L.company_name?L.company_name:[L.first_name,L.last_name].filter(Boolean).join(" ")||"-":"-",U=L=>L==="active"?e.jsx(Q,{className:"bg-primary text-primary-foreground",children:"AktivnÃ"}):L==="inactive"?e.jsx(Q,{variant:"secondary",children:"Neakt."}):L==="archived"?e.jsx(Q,{variant:"outline",children:"Archiv"}):e.jsx(Q,{variant:"secondary",children:L}),n=L=>{p===L?H($==="asc"?"desc":"asc"):(m(L),H("asc"))},G=i.filter(L=>{const re=v.toLowerCase(),A=l(L.currentOwner).toLowerCase();return L.code.toLowerCase().includes(re)||A.includes(re)}).sort((L,re)=>{let A=0;if(p==="code")A=L.code.localeCompare(re.code,"cs",{numeric:!0});else if(p==="floor")A=(L.floor||0)-(re.floor||0);else if(p==="sqm")A=(Number(L.sqm)||0)-(Number(re.sqm)||0);else if(p==="weg_anteil_rv")A=(Number(L.weg_anteil_rv)||0)-(Number(re.weg_anteil_rv)||0);else if(p==="status"){const ne={active:0,inactive:1,archived:2},le=ne[L.status]??3,oe=ne[re.status]??3;A=le-oe}return $==="asc"?A:-A}),Y=i.filter(L=>L.status==="active").length,pe=i.filter(L=>L.status==="inactive").length,B=i.length>0?i.reduce((L,re)=>L+(Number(re.sqm)||0),0)/i.filter(L=>L.sqm).length:0,te=i.filter(L=>!L.excluded_from_voting).reduce((L,re)=>L+(Number(re.weg_anteil_rv)||0),0),xe=L=>L?L.toLocaleString("de-AT"):"-",de=L=>{const re=Number(L.weg_anteil_rv)||0;return!re||!te?"-":`${(re/te*100).toFixed(4)}%`};return E?e.jsx("div",{className:"flex items-center justify-center py-12",children:e.jsx(fe,{className:"h-8 w-8 animate-spin text-primary"})}):e.jsxs("div",{className:"space-y-6",children:[e.jsxs("div",{className:"flex flex-col sm:flex-row sm:items-center justify-between gap-4",children:[e.jsxs("div",{children:[e.jsx("h2",{className:"font-serif text-2xl font-bold text-foreground",children:"Apartmány"}),e.jsx("p",{className:"text-muted-foreground text-sm mt-1",children:"Správa vÅ¡ech apartmánů v komplexu"})]}),e.jsxs("div",{className:"flex flex-wrap items-center gap-2",children:[e.jsxs(b,{variant:"outline",onClick:()=>ie(!0),children:[e.jsx(Nr,{className:"h-4 w-4 mr-2"}),"PÅevod vlastnictvÃ"]}),e.jsxs(Ge,{open:j,onOpenChange:w,children:[e.jsx(yt,{asChild:!0,children:e.jsxs(b,{children:[e.jsx(Xe,{className:"h-4 w-4 mr-2"}),"PÅidat apartmán"]})}),e.jsxs(Je,{children:[e.jsx(Ye,{children:e.jsx(Qe,{children:"Nový apartmán"})}),e.jsxs("div",{className:"space-y-4 pt-4",children:[e.jsxs("div",{children:[e.jsx("label",{className:"text-sm font-medium",children:"Název"}),e.jsx(se,{value:x,onChange:L=>O(L.target.value),placeholder:"napÅ. TOP 53"})]}),e.jsxs("div",{children:[e.jsx("label",{className:"text-sm font-medium",children:"PoÅadà (volitelné)"}),e.jsx(se,{type:"number",value:S,onChange:L=>N(L.target.value),placeholder:"automaticky na konec"})]}),e.jsxs(b,{onClick:Z,disabled:M,className:"w-full",children:[M?e.jsx(fe,{className:"h-4 w-4 animate-spin mr-2"}):null,"PÅidat"]})]})]})]})]})]}),e.jsx(Pi,{open:ce,onOpenChange:ie,onCompleted:W}),e.jsxs("div",{className:"grid grid-cols-2 lg:grid-cols-4 gap-4",children:[e.jsx(ee,{children:e.jsx(ae,{className:"p-4",children:e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsxs("div",{children:[e.jsx("p",{className:"text-sm text-muted-foreground",children:"Celkem"}),e.jsx("p",{className:"text-2xl font-bold",children:i.length})]}),e.jsx(Jt,{className:"h-5 w-5 text-muted-foreground"})]})})}),e.jsx(ee,{children:e.jsx(ae,{className:"p-4",children:e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsxs("div",{children:[e.jsx("p",{className:"text-sm text-muted-foreground",children:"AktivnÃ"}),e.jsx("p",{className:"text-2xl font-bold",children:Y})]}),e.jsx(qs,{className:"h-5 w-5 text-primary"})]})})}),e.jsx(ee,{children:e.jsx(ae,{className:"p-4",children:e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsxs("div",{children:[e.jsx("p",{className:"text-sm text-muted-foreground",children:"NeaktivnÃ"}),e.jsx("p",{className:"text-2xl font-bold",children:pe})]}),e.jsx(js,{className:"h-5 w-5 text-destructive"})]})})}),e.jsx(ee,{children:e.jsx(ae,{className:"p-4",children:e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsxs("div",{children:[e.jsx("p",{className:"text-sm text-muted-foreground",children:"Prům. velikost"}),e.jsx("p",{className:"text-2xl font-bold",children:B>0?`${B.toFixed(1)} m²`:"-"})]}),e.jsx(ai,{className:"h-5 w-5 text-muted-foreground"})]})})})]}),e.jsxs(ee,{children:[e.jsx(ye,{className:"flex flex-row items-center justify-between",children:e.jsxs(be,{className:"text-base",children:["Seznam apartmánů (",G.length,")"]})}),e.jsxs(ae,{children:[e.jsxs("div",{className:"relative mb-4",children:[e.jsx(fs,{className:"absolute left-3 top-1/2 h-4 w-4 -translate-y-1/2 text-muted-foreground"}),e.jsx(se,{placeholder:"Hledat TOP, vlastnÃka...",value:v,onCh
85ange:L=>u(L.target.value),className:"pl-9 bg-background"})]}),e.jsxs($e,{children:[e.jsx(Be,{children:e.jsxs(Ne,{className:"bg-muted/50 hover:bg-muted/50",children:[e.jsx(D,{className:"h-9 text-xs",children:e.jsxs(b,{variant:"ghost",size:"sm",className:"h-auto p-0 font-medium hover:bg-transparent text-xs",onClick:()=>n("code"),children:["TOP ",e.jsx(Is,{className:"ml-1 h-3 w-3"})]})}),e.jsx(D,{className:"h-9 text-xs",children:e.jsxs(b,{variant:"ghost",size:"sm",className:"h-auto p-0 font-medium hover:bg-transparent text-xs",onClick:()=>n("floor"),children:["Patro ",e.jsx(Is,{className:"ml-1 h-3 w-3"})]})}),e.jsx(D,{className:"h-9 text-xs",children:e.jsxs(b,{variant:"ghost",size:"sm",className:"h-auto p-0 font-medium hover:bg-transparent text-xs",onClick:()=>n("sqm"),children:["m² ",e.jsx(Is,{className:"ml-1 h-3 w-3"})]})}),e.jsx(D,{className:"h-9 text-xs",children:"Majitel"}),e.jsx(D,{className:"h-9 text-xs",children:e.jsxs(b,{variant:"ghost",size:"sm",className:"h-auto p-0 font-medium hover:bg-transparent text-xs",onClick:()=>n("weg_anteil_rv"),children:["WEG RV ",e.jsx(Is,{className:"ml-1 h-3 w-3"})]})}),e.jsx(D,{className:"h-9 text-xs",children:"WEG %"}),e.jsx(D,{className:"h-9 text-xs",children:"Excluded"}),e.jsx(D,{className:"h-9 text-xs",children:e.jsxs(b,{variant:"ghost",size:"sm",className:"h-auto p-0 font-medium hover:bg-transparent text-xs",onClick:()=>n("status"),children:["Status ",e.jsx(Is,{className:"ml-1 h-3 w-3"})]})}),e.jsx(D,{className:"text-right h-9 text-xs",children:"Akce"})]})}),e.jsx(Ue,{children:G.length===0?e.jsx(Ne,{children:e.jsx(_,{colSpan:9,className:"text-center text-muted-foreground py-8",children:v?"Žádné apartmány nenalezeny.":"ZatÃm nejsou žádné apartmány."})}):G.map(L=>e.jsxs(Ne,{className:"h-8 cursor-pointer",onClick:()=>!J&&s(`/admin/apartment/${L.id}`),children:[e.jsx(_,{className:"font-medium text-sm py-1.5",children:L.code}),e.jsx(_,{className:"py-1.5",children:J===L.id?e.jsx(se,{type:"number",value:h,onChange:re=>I(re.target.value),className:"w-16 h-8",placeholder:"-"}):e.jsx("span",{className:"text-sm text-muted-foreground",children:L.floor??"-"})}),e.jsx(_,{className:"py-1.5",children:J===L.id?e.jsx(se,{type:"number",step:"0.1",value:k,onChange:re=>c(re.target.value),className:"w-20 h-8",placeholder:"-"}):e.jsx("span",{className:"text-sm text-muted-foreground",children:L.sqm?`${L.sqm}`:"-"})}),e.jsx(_,{className:"text-sm py-1.5",children:l(L.currentOwner)}),e.jsx(_,{className:"text-sm text-muted-foreground py-1.5 tabular-nums",children:xe(Number(L.weg_anteil_rv))}),e.jsx(_,{className:"text-sm text-muted-foreground py-1.5 tabular-nums",children:de(L)}),e.jsx(_,{className:"py-1.5",children:L.excluded_from_voting?e.jsx(Q,{variant:"outline",className:"text-destructive border-destructive/30",children:"Ano"}):e.jsx(Q,{variant:"outline",className:"text-primary border-primary/30",children:"Ne"})}),e.jsx(_,{className:"py-1.5",children:J===L.id?e.jsxs(De,{value:d,onValueChange:T,children:[e.jsx(Pe,{className:"w-28 h-8",children:e.jsx(Ae,{})}),e.jsxs(Ee,{children:[e.jsx(me,{value:"active",children:"AktivnÃ"}),e.jsx(me,{value:"inactive",children:"NeaktivnÃ"}),e.jsx(me,{value:"archived",children:"Archiv"})]})]}):U(L.status)}),e.jsx(_,{className:"text-right py-1.5",onClick:re=>re.stopPropagation(),children:e.jsx(b,{size:"icon",variant:"ghost",className:"h-7 w-7",onClick:()=>s(`/admin/apartment/${L.id}`),children:e.jsx(bs,{className:"h-3.5 w-3.5"})})})]},L.id))})]})]})]}),e.jsx(ms,{open:r,onOpenChange:f,title:"Smazat apartmán",description:`Opravdu chcete smazat apartmán "${R==null?void 0:R.code}"? Tato akce je nevratná.`,confirmText:"Smazat",onConfirm:K})]})},Ei=/^[^\s@]+@[^\s@]+\.[^\s@]{2,}$/i,ot=s=>[s.first_name,s.last_name].filter(Boolean).join(" ").trim()||"â",Ii=({open:s,onOpenChange:a,candidates:i,onConfirm:y,loading:E=!1})=>{const[P,x]=t.useState({}),[O,S]=t.useState(!1),N=v=>x(u=>({...u,[v]:!u[v]})),j=t.useMemo(()=>{const v=[],u=[],p=[],m=[],$=[],H=new Map,J=new Map;for(const z of i){if(z.user_id){m.push(z);continue}const I=(z.email??"").trim().toLowerCase();if(!I){u.push(z);continue}if(!Ei.test(I)){p.push(z);continue}if(H.has(I)){$.push(z);const k=J.get(I)||[H.get(I)];k.push(z),J.set(I,k);continue}H.set(I,z),v.push(z)}return{toInvite:v,noEmail:u,invalidEmail:p,hasAccount:m,duplicateEmail:$,dupGroups:J}},[i]),w=i.length,M=j.invalidEmail.length+j.duplicateEmail.length,o=({icon:v,label:u,count:p,tone:m,expandable:$,expandKey:H,children:J})=>{const z=m==="success"?"text-emerald-700":m==="destructive"?"text-destructive":m==="warning"?"text-amber-700":"text-muted-foreground",h=H?!!P[H]:!1;return e.jsxs("div",{className:"rounded-md border",children:[e.jsxs("button",{type:"button",onClick:()=>$&&H&&p>0&&N(H),className:`w-full flex items-center justify-between p-3 text-sm ${$&&p>
850?"hover:bg-muted/50 cursor-pointer":"cursor-default"}`,children:[e.jsxs("span",{className:`flex items-center gap-2 ${z}`,children:[$&&p>0?h?e.jsx(Js,{className:"h-4 w-4"}):e.jsx(Ts,{className:"h-4 w-4"}):null,v,e.jsx("span",{children:u})]}),e.jsx("span",{className:`font-semibold ${z}`,children:p})]}),$&&h&&p>0&&e.jsx("div",{className:"border-t px-3 py-2 bg-muted/30 max-h-40 overflow-auto text-xs",children:J})]})};return e.jsxs(Ge,{open:s,onOpenChange:a,children:[e.jsxs(Je,{className:"sm:max-w-xl",children:[e.jsxs(Ye,{children:[e.jsx(Qe,{children:"Náhled hromadné pozvánky"}),e.jsx(us,{children:"Validujeme e-maily a hledáme duplicity jeÅ¡tÄ pÅed odeslánÃm. ÃÄet vznikne (nebo se znovu odeÅ¡le pozvánka) pouze pro Åádky oznaÄené zelenÄ. Žádné heslo se neposÃlá â uživatel si ho nastavà pÅes odkaz."})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsxs("div",{className:"flex items-center justify-between text-xs text-muted-foreground",children:[e.jsxs("span",{children:["Celkem osob: ",e.jsx("strong",{children:w})]}),M>0&&e.jsxs(Q,{variant:"destructive",className:"gap-1",children:[e.jsx(is,{className:"h-3 w-3"}),M," konfliktů blokuje odeslánà pro tyto Åádky"]})]}),e.jsx(o,{icon:e.jsx(Ut,{className:"h-4 w-4"}),label:"K pozvánà e-mailem",count:j.toInvite.length,tone:"success",expandable:!0,expandKey:"toInvite",children:e.jsx("ul",{className:"space-y-1",children:j.toInvite.map(v=>e.jsxs("li",{className:"flex justify-between gap-2",children:[e.jsx("span",{className:"truncate",children:ot(v)}),e.jsx("span",{className:"text-muted-foreground truncate",children:v.email})]},v.id))})}),e.jsx(o,{icon:e.jsx(jr,{className:"h-4 w-4"}),label:"PÅeskoÄeno â chybà e-mail",count:j.noEmail.length,tone:"muted",expandable:!0,expandKey:"noEmail",children:e.jsx("ul",{className:"space-y-1",children:j.noEmail.map(v=>e.jsx("li",{children:ot(v)},v.id))})}),e.jsx(o,{icon:e.jsx(ti,{className:"h-4 w-4"}),label:"Neplatný formát e-mailu",count:j.invalidEmail.length,tone:"destructive",expandable:!0,expandKey:"invalid",children:e.jsx("ul",{className:"space-y-1",children:j.invalidEmail.map(v=>e.jsxs("li",{className:"flex justify-between gap-2",children:[e.jsx("span",{className:"truncate",children:ot(v)}),e.jsx("span",{className:"text-destructive truncate font-mono",children:v.email})]},v.id))})}),e.jsx(o,{icon:e.jsx(Bs,{className:"h-4 w-4"}),label:"PÅeskoÄeno â už majà úÄet",count:j.hasAccount.length,tone:"muted",expandable:!0,expandKey:"hasAccount",children:e.jsx("ul",{className:"space-y-1",children:j.hasAccount.map(v=>e.jsxs("li",{className:"flex justify-between gap-2",children:[e.jsx("span",{className:"truncate",children:ot(v)}),e.jsx("span",{className:"text-muted-foreground truncate",children:v.email})]},v.id))})}),e.jsx(o,{icon:e.jsx(Os,{className:"h-4 w-4"}),label:"Duplicitnà e-mail (vÃce vlastnÃků sdÃlà stejný)",count:j.duplicateEmail.length,tone:"warning",expandable:!0,expandKey:"duplicate",children:e.jsx("ul",{className:"space-y-2",children:Array.from(j.dupGroups.entries()).map(([v,u])=>e.jsxs("li",{className:"border-l-2 border-amber-400 pl-2",children:[e.jsx("div",{className:"font-mono text-amber-700",children:v}),e.jsx("ul",{className:"ml-2 space-y-0.5",children:u.map((p,m)=>e.jsxs("li",{className:"text-muted-foreground",children:[m===0?"â pozve se: ":"â pÅeskoÄà se: ",ot(p)]},p.id))})]},v))})}),e.jsx("p",{className:"text-[11px] text-muted-foreground pt-2",children:"Konflikty identity (jiný e-mail v evidenci než na úÄtu) odhalà backend pÅi odesÃlánà a vrátà je v souhrnu."})]}),e.jsxs(ls,{children:[e.jsx(b,{variant:"outline",onClick:()=>a(!1),disabled:E,children:"ZruÅ¡it"}),j.toInvite.length>0&&e.jsxs(b,{variant:"outline",onClick:()=>S(!0),disabled:E,children:[e.jsx(bs,{className:"h-4 w-4 mr-2"}),"Náhled e-mailu"]}),e.jsxs(b,{onClick:()=>y(j.toInvite),disabled:E||j.toInvite.length===0,children:[E&&e.jsx(fe,{className:"h-4 w-4 animate-spin mr-2"}),e.jsx(Bs,{className:"h-4 w-4 mr-2"}),j.toInvite.length>0?`Odeslat ${j.toInvite.length} pozvánek`:"Nenà koho pozvat"]})]})]}),e.jsx(_r,{open:O,onOpenChange:S,params:j.toInvite[0]?{email:j.toInvite[0].email,first_name:j.toInvite[0].first_name,last_name:j.toInvite[0].last_name,language:j.toInvite[0].language,role:"owner",owner_contact_id:j.toInvite[0].owner_
85contact_id,contact_person_id:j.toInvite[0].contact_person_id}:null})]})},Ti={cs:"CS",en:"EN",de:"DE"},Oi=()=>{const s=Ks(),{toast:a}=Re(),[i,y]=t.useState([]),[E,P]=t.useState(!0),[x,O]=t.useState(""),[S,N]=t.useState("apartment"),[j,w]=t.useState("asc"),[M,o]=t.useState("active"),[v,u]=t.useState(!1),[p,m]=t.useState(!1),[$,H]=t.useState(new Set),[J,z]=t.useState(0),[h,I]=t.useState(0),[k,c]=t.useState(0),[d,T]=t.useState(0),[r,f]=t.useState(0),[R,F]=t.useState(0),[ce,ie]=t.useState({}),[W,Z]=t.useState(new Set),[K,l]=t.useState("all"),[U,n]=t.useState(new Map);t.useEffect(()=>{g.rpc("admin_list_legal_delivery").then(({data:A})=>{const ne=new Map;for(const le of A??[])ne.set(le.owner_id,le);n(ne)})},[]),t.useEffect(()=>{G()},[]);const G=async()=>{P(!0);const[A,ne,le,oe,ke,je]=await Promise.all([g.from("owner_contacts").select("*").order("last_name",{ascending:!0}),g.from("apartment_owners").select("owner_contact_id, is_current, share_percentage, apartment:apartments(*)"),g.from("apartments").select("id, weg_anteil_rv, excluded_from_voting"),g.from("user_roles").select("user_id, role"),g.from("owner_contact_persons").select("id, owner_contact_id, first_name, last_name, email, phone, role_type, role_label, is_primary, user_id, can_login"),g.from("forum_subscribers").select("user_id")]);if(A.error){a({variant:"destructive",title:"Chyba",description:"NepodaÅilo se naÄÃst kontakty vlastnÃků."}),P(!1);return}const ue=A.data||[],ve=ne.data||[],X=le.data||[],Ce=oe.data||[],ze=ke.data||[],Me=new Set((je.data||[]).map(Ie=>Ie.user_id));Z(Me),z(X.length),I(X.filter(Ie=>!Ie.excluded_from_voting).length),c(X.reduce((Ie,Ve)=>Ie+(Ve.weg_anteil_rv||0),0)),T(new Set(Ce.filter(Ie=>Ie.role==="admin").map(Ie=>Ie.user_id)).size),f(ue.filter(Ie=>Ie.user_id).length),F(ue.filter(Ie=>Ie.is_active).length);const V=ue.map(Ie=>{const Ve=ve.filter(we=>we.owner_contact_id===Ie.id&&we.apartment).map(we=>({apartment:we.apartment,is_current:we.is_current??!1,share_percentage:we.share_percentage??null})),Fe=Ie.user_id?Ce.filter(we=>we.user_id===Ie.user_id).map(we=>we.role):[],C=Ve.filter(we=>we.is_current).reduce((we,he)=>{const os=Number(he.apartment.weg_anteil_rv)||0,Ss=he.share_percentage!=null?he.share_percentage/100:1;return we+os*Ss},0),ge=ze.filter(we=>we.owner_contact_id===Ie.id),Te=ge.find(we=>we.is_primary),Oe=Te?`${Te.first_name} ${Te.last_name}`:ge[0]?`${ge[0].first_name} ${ge[0].last_name}`:null,Se=Math.max(0,ge.length-1);return{...Ie,apartments:Ve,roles:Fe,totalWegRv:C,primaryPerson:Oe,extraPersonsCount:Se,contactPersons:ge.map(we=>({id:we.id,first_name:we.first_name,last_name:we.last_name,email:we.email||null,phone:we.phone||null,role_type:we.role_type||"representative",role_label:we.role_label||null,is_primary:we.is_primary,user_id:we.user_id||null}))}}),_e={};(ve||[]).forEach(Ie=>{if(Ie.apartment&&Ie.is_current){const Ve=Ie.apartment.id;_e[Ve]||(_e[Ve]={total:0,ownerCount:0}),_e[Ve].total+=Number(Ie.share_percentage)||0,_e[Ve].ownerCount+=1}}),ie(_e),y(V),P(!1)},Y=A=>{var oe;const ne=((oe=A.apartments.find(ke=>ke.is_current))==null?void 0:oe.apartment.code)||"",le=parseInt(ne.replace(/\D/g,""));return isNaN(le)?1/0:le},pe=A=>{S===A?w(ne=>ne==="asc"?"desc":"asc"):(N(A),w("asc"))},B=i.filter(A=>!(M==="active"&&A.is_active===!1||M==="inactive"&&A.is_active!==!1)).filter(A=>{if(K==="all")return!0;const ne=U.get(A.id);return(ne?ka(ne):"not_selected")===K}).filter(A=>{var le,oe,ke,je,ue;if(!x)return!0;const ne=x.toLowerCase();return((le=A.first_name)==null?void 0:le.toLowerCase().includes(ne))||((oe=A.last_name)==null?void 0:oe.toLowerCase().includes(ne))||((ke=A.email)==null?void 0:ke.toLowerCase().includes(ne))||((je=A.company_name)==null?void 0:je.toLowerCase().includes(ne))||((ue=A.phone)==null?void 0:ue.includes(x))||A.apartments.some(ve=>ve.apartment.code.toLowerCase().includes(ne))||A.contactPersons.some(ve=>{var X,Ce,ze;return((X=ve.first_name)==null?void 0:X.toLowerCase().includes(ne))||((Ce=ve.last_name)==null?void 0:Ce.toLowerCase().includes(ne))||((ze=ve.email)==null?void 0:ze.toLowerCase().includes(ne))})}).sort((A,ne)=>{let le=0;switch(S){case"apartment":le=Y(A)-Y(ne);break;case"name":{const oe=`${A.last_name||""} ${A.first_name||""}`.trim().toLowerCase(),ke=`${ne.last_name||""} ${ne.first_name||""}`.trim().toLowerCase();le=oe.localeCompare(ke,"cs");break}case"email":le=(A.email||"").localeCompare(ne.email||"");break;case"language":le=(A.language||"").localeCompare(ne.language||"");break;case"role":{const oe=A.roles.includes("admin")?0:A.roles.length>0?1:2,ke=ne.roles.includes("admin")?0:ne.roles.length>0?1:2;le=oe-ke;break}}return j==="asc"?le:-le}),te=({field:A,children:ne,className:le})=>e.jsx(D,{className:le,children:e.jsxs(b,{variant:"ghost",size:"sm",className:"h-auto p-0 font-medium hover:bg-transparent",onClick:()=>pe(A),children:[ne," ",e.jsx(Is,{className:"ml-1 h-3 w-3 inline"})]})}),xe=A=>A.includes("admin")?e.jsxs(Q,{variant:"default",className:"gap-1",children:[e.jsx(As,{className:"h-3 w-3"}),"Admin"]}):A.includes("spravce")?e.jsxs(Q,{variant:"secondary",className:"gap-1 bg-amber-100 text-amber-800 border-amber-200",children:[e.jsx(As,{className:"h-3 w-3"}),"Správce"]}):A.length>0?e.jsxs(Q,{variant:"secondary",className:"gap-1",children:[e.jsx(ba,{className:"h-3 w-3"}),"User"]}):e.jsx("span",{className:"text-muted-foreground text-xs",children:"â"}),de=i.filter(A=>!A.user_id&&A.email),L=(()=>{const A=[];
85return i.forEach(ne=>{ne.user_id||A.push({id:ne.id,email:ne.email,first_name:ne.first_name,last_name:ne.last_name,language:ne.language,user_id:ne.user_id,owner_contact_id:ne.id}),ne.contactPersons.forEach(le=>{!le.user_id&&le.email!==void 0&&A.push({id:`cp-${le.id}`,email:le.email??null,first_name:le.first_name,last_name:le.last_name,language:ne.language,user_id:le.user_id,contact_person_id:le.id})})}),A})(),re=async A=>{if(m(!1),A.length!==0){u(!0);try{const ne=A.map(ke=>({email:ke.email,first_name:ke.first_name,last_name:ke.last_name,language:ke.language,role:"owner",owner_contact_id:ke.owner_contact_id??null,contact_person_id:ke.contact_person_id??null})),{data:le,error:oe}=await g.functions.invoke("invite-user",{body:{bulk:!0,recipients:ne}});if(oe)a({variant:"destructive",title:"Chyba",description:oe.message});else{const ke=(le==null?void 0:le.summary)||{};if(a({title:"Pozvánky odeslány",description:`Pozváno: ${ke.invited??0} · Re-invite: ${ke.reinvited??0} · AktivnÃ: ${ke.already_active??0} · PÅeskoÄeno: ${ke.skipped??0} · Chyby: ${ke.failed??0}`}),Array.isArray(le==null?void 0:le.results)){const je=le.results.filter(ue=>{var ve;return ue.status==="failed"||((ve=ue.status)==null?void 0:ve.startsWith("skipped_"))});je.length>0&&console.warn("Invite issues:",je)}G()}}catch(ne){a({variant:"destructive",title:"Chyba",description:ne.message})}u(!1)}};return E?e.jsx("div",{className:"flex justify-center py-12",children:e.jsx(fe,{className:"h-8 w-8 animate-spin text-primary"})}):e.jsxs("div",{className:"space-y-6",children:[e.jsx(Vn,{scope:"owners",onSwitch:()=>s("/admin?section=users")}),e.jsxs("div",{className:"flex flex-col sm:flex-row sm:items-center justify-between gap-4",children:[e.jsxs("div",{children:[e.jsx("h2",{className:"font-serif text-2xl font-bold text-foreground",children:"VlastnÃci & jednotky (WEG)"}),e.jsx("p",{className:"text-muted-foreground text-sm mt-1",children:"Autoritativnà evidence vlastnictvà bytů, podÃlů a hlasovacÃch práv"})]}),e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsxs(b,{variant:"outline",size:"sm",className:"gap-1.5",disabled:$.size===0,onClick:()=>{const A=[];i.forEach(le=>{$.has(le.id)&&le.email&&A.push(le.email),le.contactPersons.forEach(oe=>{$.has(`cp-${oe.id}`)&&oe.email&&A.push(oe.email)})});const ne=[...new Set(A)];navigator.clipboard.writeText(ne.join("; ")),a({title:"ZkopÃrováno",description:`${ne.length} e-mailů zkopÃrováno do schránky.`})},children:[e.jsx(Os,{className:"h-3.5 w-3.5"}),"KopÃrovat e-maily ",$.size>0&&`(${$.size})`]}),L.length>0&&e.jsxs(b,{variant:"outline",size:"sm",className:"gap-1.5",onClick:()=>m(!0),disabled:v,children:[v?e.jsx(fe,{className:"h-3.5 w-3.5 animate-spin"}):e.jsx(Bs,{className:"h-3.5 w-3.5"}),"Pozvat vÅ¡echny bez úÄtu (",L.length,")"]}),e.jsxs(b,{variant:"outline",size:"sm",className:"gap-1.5",children:[e.jsx(Ps,{className:"h-3.5 w-3.5"}),"Import"]}),e.jsxs(b,{onClick:()=>s("/admin/owner/new"),size:"sm",className:"gap-1.5",children:[e.jsx(Xe,{className:"h-3.5 w-3.5"}),"PÅidat vlastnÃka"]})]})]}),e.jsxs("div",{className:"grid grid-cols-2 lg:grid-cols-4 gap-4",children:[e.jsx(ee,{className:"border-l-4 border-l-primary",children:e.jsx(ae,{className:"p-4",children:e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsxs("div",{children:[e.jsx("p",{className:"text-xs font-medium uppercase tracking-wide text-muted-foreground",children:"VlastnÃci"}),e.jsx("p",{className:"text-3xl font-bold text-foreground mt-1",children:i.length}),e.jsxs("p",{className:"text-xs text-muted-foreground mt-1",children:[R," aktivnÃch · ",r," s úÄtem"]})]}),e.jsx("div",{className:"h-10 w-10 rounded-full bg-primary/10 flex items-center justify-center",children:e.jsx(Fs,{className:"h-5 w-5 text-primary"})})]})})}),e.jsx(ee,{className:"border-l-4 border-l-slate-400",children:e.jsx(ae,{className:"p-4",children:e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsxs("div",{children:[e.jsx("p",{className:"text-xs font-medium uppercase tracking-wide text-muted-foreground",children:"Apartmány"}),e.jsx("p",{className:"text-3xl font-bold text-foreground mt-1",children:J}),e.jsxs("p",{className:"text-xs text-muted-foreground mt-1",children:[h," hlasujÃcÃch · ",J-h," vylouÄených"]})]}),e.jsx("div",{className:"h-10 w-10 rounded-full bg-slate-100 flex items-center justify-center",children:e.jsx(Jt,{className:"h-5 w-5 text-slate-500"})})]})})}),e.jsx(ee,{className:"border-l-4 border-l-emerald-500",children:e.jsx(ae,{className:"p-4",children:e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsxs("div",{children:[e.jsx("p",{className:"text-xs font-medium uppercase tracking-wide text-muted-foreground",children:"WEG Share RV"}),e.jsx("p",{className:"text-3xl font-bold text-emerald-600 mt-1",children:k.toLocaleStr
85ing("cs-CZ")}),e.jsxs("p",{className:"text-xs text-muted-foreground mt-1",children:[h," hlasujÃcÃch jednotek"]})]}),e.jsx("div",{className:"h-10 w-10 rounded-full bg-emerald-500/10 flex items-center justify-center",children:e.jsx(Tn,{className:"h-5 w-5 text-emerald-600"})})]})})}),e.jsx(ee,{className:"border-l-4 border-l-amber-500",children:e.jsx(ae,{className:"p-4",children:e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsxs("div",{children:[e.jsx("p",{className:"text-xs font-medium uppercase tracking-wide text-muted-foreground",children:"Admini"}),e.jsx("p",{className:"text-3xl font-bold text-foreground mt-1",children:d}),e.jsxs("p",{className:"text-xs text-muted-foreground mt-1",children:[de.length," bez úÄtu"]})]}),e.jsx("div",{className:"h-10 w-10 rounded-full bg-amber-500/10 flex items-center justify-center",children:e.jsx(As,{className:"h-5 w-5 text-amber-600"})})]})})})]}),e.jsxs(ee,{children:[e.jsx(ye,{className:"flex flex-row items-center justify-between",children:e.jsxs(be,{className:"text-base",children:["Seznam vlastnÃků (",B.length,")"]})}),e.jsxs(ae,{children:[e.jsxs("div",{className:"flex flex-col sm:flex-row gap-2 mb-4",children:[e.jsxs("div",{className:"relative flex-1",children:[e.jsx(fs,{className:"absolute left-3 top-1/2 h-4 w-4 -translate-y-1/2 text-muted-foreground"}),e.jsx(se,{placeholder:"Hledat jméno, email, TOP...",value:x,onChange:A=>O(A.target.value),className:"pl-9 bg-background"})]}),e.jsx("div",{className:"flex items-center gap-1 rounded-md border bg-background p-1",children:[{v:"active",label:`Aktivnà (${i.filter(A=>A.is_active!==!1).length})`},{v:"inactive",label:`Deaktivovanà (${i.filter(A=>A.is_active===!1).length})`},{v:"all",label:`VÅ¡ichni (${i.length})`}].map(A=>e.jsx(b,{variant:M===A.v?"default":"ghost",size:"sm",className:"h-7 px-3 text-xs",onClick:()=>o(A.v),children:A.label},A.v))}),e.jsx("div",{className:"flex items-center gap-1 rounded-md border bg-background p-1",children:["all","electronic","postal","not_selected","reconfirmation_required"].map(A=>e.jsx(b,{variant:K===A?"default":"ghost",size:"sm",className:"h-7 px-2 text-xs",onClick:()=>l(A),children:A==="all"?"Komunikace: vÅ¡e":Ca.cs[A]},A))})]}),e.jsxs($e,{children:[e.jsx(Be,{children:e.jsxs(Ne,{className:"bg-muted/50 hover:bg-muted/50",children:[e.jsx(D,{className:"w-[40px] h-9",children:e.jsx(xs,{checked:B.filter(A=>A.email).length>0&&B.filter(A=>A.email).every(A=>$.has(A.id)),onCheckedChange:A=>{const ne=new Set($);B.filter(le=>le.email).forEach(le=>{A?ne.add(le.id):ne.delete(le.id)}),H(ne)}})}),e.jsx(te,{field:"apartment",className:"w-[120px] h-9 text-xs",children:"TOP"}),e.jsx(te,{field:"name",className:"h-9 text-xs",children:"Jméno"}),e.jsx(te,{field:"language",className:"w-[80px] h-9 text-xs",children:"Jazyk"}),e.jsx(te,{field:"email",className:"h-9 text-xs",children:"E-mail"}),e.jsx(D,{className:"w-[100px] text-right h-9 text-xs",children:"WEG RV"}),e.jsx(D,{className:"w-[90px] text-right h-9 text-xs",children:"PodÃl %"}),e.jsx(D,{className:"w-[60px] text-center h-9 text-xs",children:"PodÃl"}),e.jsx(D,{className:"w-[130px] h-9 text-xs",children:"Komunikace"}),e.jsx(te,{field:"role",className:"w-[120px] h-9 text-xs",children:"Role"}),e.jsx(D,{className:"w-[60px] text-right h-9 text-xs",children:"Akce"})]})}),e.jsx(Ue,{children:B.length===0?e.jsx(Ne,{children:e.jsx(_,{colSpan:11,className:"text-center text-muted-foreground py-8",children:x?"Žádnà vlastnÃci nebyli nalezeni.":"ZatÃm nejsou žádnà vlastnÃci."})}):B.map(A=>{const ne=A.apartments.filter(oe=>oe.is_current).map(oe=>oe.apartment.code),le=ne.length>0?ne.join(", "):"â";return e.jsxs(Kn.Fragment,{children:[e.jsxs(Ne,{className:"cursor-pointer h-8",onClick:()=>s(`/admin/owner/${A.id}`),children:[e.jsx(_,{className:"py-1.5",onClick:oe=>oe.stopPropagation(),children:A.email?e.jsx(xs,{checked:$.has(A.id),onCheckedChange:oe=>{const ke=new Set($);oe?ke.add(A.id):ke.delete(A.id),H(ke)}}):e.jsx("span",{className:"text-muted-foreground text-xs",children:"â"})}),e.jsx(_,{className:"font-medium text-sm py-1.5",children:le}),e.jsx(_,{className:"py-1.5",children:e.jsx("span",{className:"text-sm",children:A.user_type==="company"&&A.company_name?A.company_name:`${A.first_name||""} ${A.last_name||""}`.trim()||"â"})}),e.jsx(_,{className:"text-sm text-muted-foreground py-1.5",children:Ti[A.language||"cs"]}),e.jsx(_,{className:"text-sm text-muted-foreground py-1.5",children:e.jsxs("span",{className:"flex items-center gap-1 flex-wrap",children:[A.email||e.jsx("span",{className:"italic",children:"â bez e-mailu â"}),A.user_id?e.jsx(as,{delayDuration:200,children:e.jsxs(Ke,{children:[e.jsx(Ze,{children:e.jsxs(Q,{className:"bg-emerald-100 text-emerald-800 border-emerald-200 text-[10px] gap-0.5 h-4 px-1",children:[e.jsx(Vs,{className:"h-2.5 w-2.5"}),"ÃÄet"]})}),e.jsx(He,{className:"text-xs",children:"Propojeno s úÄtem"})]})}):A.email?e.jsx(as,{delayDuration:200,children:e.jsxs(Ke,{children:[e.jsx(Ze,{children:e.jsxs(Q,{className:"bg-amber-100 text-amber-800 border-amber-200 text-[10px] gap-0.5 h-4 px-1",children:[e.jsx(ga,{className:"h-2.5 w-2.5"}),"Bez úÄtu"]})}),e.jsx(He,{className:"text-xs",children:"Bez úÄtu (e-mail je k dispozici, úÄet lze vytvoÅit)"})]})}):e.jsx(as,{delayDuration:200,children:e.jsxs(Ke,{children:[e.jsx(Ze,{children:e.jsxs(Q,{variant:"outline",className:"text-[10px] gap-0.5 h-4 px-1 border-rose-300 text-rose-700",children:[e.jsx(is,{className:"h-2.5 w-2.5"}),"Chybà e-mail"]})}),e.jsx(He,{className:"text-xs",children:"Chybà e-mail pro vytvoÅenà úÄtu"})]})}),A.user_id&&W.has(A.user_id)&&e.jsx(as,{delayDuration:200,children:e.jsxs(Ke,{children:[e.jsx(Ze,{children:e.jsx(pa,{className:"h-3.5 w-3.5 text-destructive/70 inline-block"})}),e.jsx(He,{className:"text-xs",children:"Odhlášen z e-mailových notifikacà fóra"})]})})]})}),e.jsx(_,{className:"text-sm text-muted-foreground py-1.5 text-right tabular-nums",children:A.totalWegRv>
850?Math.round(A.totalWegRv).toLocaleString("cs-CZ"):"â"}),e.jsx(_,{className:"text-sm text-muted-foreground py-1.5 text-right tabular-nums",children:A.totalWegRv>0&&k>0?`${(A.totalWegRv/k*100).toFixed(2)}%`:"â"}),e.jsx(_,{className:"text-center py-1.5",children:e.jsx(as,{delayDuration:200,children:A.apartments.filter(oe=>oe.is_current).length>0?(()=>{const oe=[],ke=[];return A.apartments.filter(je=>je.is_current).forEach(je=>{const ue=ce[je.apartment.id];if(!ue)return;const{total:ve,ownerCount:X}=ue;X===1?je.share_percentage!=null&&Math.abs(je.share_percentage-100)>.01?oe.push({code:je.apartment.code,msg:`jediný vlastnÃk, podÃl = ${je.share_percentage}% (oÄekáváno 100%)`}):ke.push(`${je.apartment.code}: 100% (jediný vlastnÃk)`):Math.abs(ve-100)<=.01?ke.push(`${je.apartment.code}: podÃly = 100%`):ve>100?oe.push({code:je.apartment.code,msg:`souÄet podÃlů = ${ve.toFixed(1)}% (pÅekraÄuje 100%!)`}):oe.push({code:je.apartment.code,msg:`souÄet podÃlů = ${ve.toFixed(1)}% (chybà ${(100-ve).toFixed(1)}%)`})}),oe.length===0?e.jsxs(Ke,{children:[e.jsx(Ze,{children:e.jsx(ps,{className:"h-4 w-4 text-primary inline"})}),e.jsx(He,{className:"text-xs space-y-0.5",children:ke.map(je=>e.jsx("div",{children:je},je))})]}):e.jsxs(Ke,{children:[e.jsx(Ze,{children:e.jsx(is,{className:"h-4 w-4 text-destructive inline"})}),e.jsx(He,{className:"text-xs space-y-0.5",children:oe.map(je=>e.jsxs("div",{children:[je.code,": ",je.msg]},je.code))})]})})():e.jsx("span",{className:"text-muted-foreground text-xs",children:"â"})})}),e.jsx(_,{className:"py-1.5 text-xs whitespace-nowrap",children:(()=>{const oe=U.get(A.id),ke=oe?ka(oe):"not_selected";return e.jsxs("div",{title:ke==="not_selected"?Zn.cs:void 0,children:[e.jsx(Q,{variant:ke==="electronic"?"default":"outline",className:"text-[10px] whitespace-nowrap",children:Ca.cs[ke]}),(oe==null?void 0:oe.method)==="electronic"&&oe.confirmed_email&&e.jsx("div",{className:"text-[10px] text-muted-foreground",children:oe.confirmed_email}),(oe==null?void 0:oe.requested_at)&&e.jsx("div",{className:"text-[10px] text-muted-foreground",children:new Date(oe.requested_at).toLocaleDateString("cs-CZ")})]})})()}),e.jsx(_,{className:"py-1.5",children:xe(A.roles)}),e.jsx(_,{className:"text-right py-1.5",onClick:oe=>oe.stopPropagation(),children:e.jsxs("div",{className:"flex items-center justify-end gap-0.5",children:[A.user_id&&e.jsx(b,{size:"icon",variant:"ghost",className:"h-7 w-7",title:"OtevÅÃt úÄet",onClick:()=>s(`/admin/user/${A.user_id}`),children:e.jsx(Vs,{className:"h-3.5 w-3.5 text-emerald-600"})}),e.jsx(b,{size:"icon",variant:"ghost",className:"h-7 w-7",title:"OtevÅÃt vlastnickou kartu",onClick:()=>s(`/admin/owner/${A.id}`),children:e.jsx(bs,{className:"h-3.5 w-3.5"})})]})})]}),A.contactPersons.map(oe=>e.jsxs(Ne,{className:"cursor-pointer h-8 bg-muted/20 hover:bg-muted/40",onClick:()=>s(`/admin/owner/${A.id}`),children:[e.jsx(_,{className:"py-1.5",onClick:ke=>ke.stopPropagation(),children:oe.email?e.jsx(xs,{checked:$.has(`cp-${oe.id}`),onCheckedChange:ke=>{const je=new Set($);ke?je.add(`cp-${oe.id}`):je.delete(`cp-${oe.id}`),H(je)}}):e.jsx("span",{className:"text-muted-foreground text-xs",children:"â"})}),e.jsx(_,{className:"font-medium text-sm py-1.5 text-muted-foreground",children:le}),e.jsx(_,{className:"py-1.5",children:e.jsxs("div",{className:"flex items-center gap-1.5",children:[e.jsx("span",{className:"text-sm",children:`${oe.first_name} ${oe.last_name}`.trim()}),e.jsx(Q,{variant:"outline",className:"text-[10px] px-1 py-0 font-normal",children:oe.role_label||(oe.role_type==="representative"?"Zástupce":oe.role_type)})]})}),e.jsx(_,{className:"text-sm text-muted-foreground py-1.5",children:"â"}),e.jsx(_,{className:"text-sm text-muted-foreground py-1.5",children:e.jsxs("span",{className:"flex items-center gap-1 flex-wrap",children:[oe.email||e.jsx("span",{className:"italic",children:"â bez e-mailu â"}),oe.user_id?e.jsx(as,{delayDuration:200,children:e.jsxs(Ke,{children:[e.jsx(Ze,{children:e.jsxs(Q,{className:"bg-emerald-100 text-emerald-800 border-emerald-200 text-[10px] gap-0.5 h-4 px-1",children:[e.jsx(Vs,{className:"h-2.5 w-2.5"}),"ÃÄet"]})}),e.jsx(He,{className:"text-xs",children:"Zástupce je propojen s úÄtem"})]})}):oe.email?e.jsx(as,{delayDuration:200,children:e.jsxs(Ke,{children:[e.jsx(Ze,{children:e.jsxs(Q,{className:"bg-amber-100 text-amber-800 border-amber-200 text-[10px] gap-0.5 h-4 px-1",children:[e.jsx(ga,{className:"h-2.5 w-2.5"}),"Bez úÄtu"]})}),e.jsx(He,{className:"text-xs",children:"Bez úÄtu (e-mail je k dispozici, úÄet lze vytvoÅit)"})]})}):e.jsx(as,{delayDuration:200,children:e.jsxs(Ke,{children:[e.jsx(Ze,{children:e.jsxs(Q,{variant:"outline",className:"text-[10px] gap-0.5 h-4 px-1 border-rose-300 text-rose-700",children:[e.jsx(is,{className:"h-2.5 w-2.5"}),"Chybà e-mail"]})}),e.jsx(He,{className:"text-xs",children:"Chybà e-mail pro vytvoÅenà úÄtu"})]})}),oe.user_id&&e.jsx(as,{delayDuration:200,children:e.jsxs(Ke,{children:[e.jsx(Ze,{asChild:!0,children:e.jsx("button",{type:"button",onClick:ke=>{ke.stopPropagation(),s(`/admin/users?userId=${oe.user_id}`)},className:"inline-flex items-center text-emerald-700 hover:text-emerald-900",children:e.jsx(Vs,{className:"h-3 w-3"})})}),e.jsx(He,{className:"text-xs",children:"OtevÅÃt úÄet zástupce"})]})})]})}),e.jsx(_,{className:"text-sm text-muted-foreground py-1.5 text-right",children:"â"}),e.jsx(_,{className:"text-sm text-muted-foreground py-1.5 text-right",children:"â"}),e.jsx(_,{className:"py-1.5",children:"â"}),e.jsx(_,{className:"py-1.5",children:"â"}),e.jsx(_,{className:"text-right py-1.5",children:e.jsx(b,{size:"icon",variant:"ghost",className:"h-7 w-7",onClick:ke=>{ke.stopPropagation(),s(`/admin/owner/${A.id}`)},children:e.jsx(bs,{className:"h-3.5 w-3.5"})})})]},oe.id))]},A.id)})})]})]})]}),e.jsx(Ii,{open:p,onOpenChange:m,candidates:L,onConfirm:re,loading:v})]})},Fi=()=>{const{language:s}=Zs(),{toast:a}=Re(),[i,y]=t.useState([]),[E,P]=t.useState([]),[x,O]=t.useState(!0),[S,N]=t.useState(!1),[j,w]=t.useState({code:"",reason:""}),[M,o]=t.useState(null),[v,u]=t.useState("");t.useEffect(()=>{p()},[]);const p=async()=>{O(!0);const[r,f]=await Promise.all([g.from("reserve_fund_settings").select("*").order("apartment_code"),g.from("apartment_heating_costs").select("apartment_code, area_sqm").eq("year",2024)]);if(r.data&&y(r.data),f.data){const R=f.data.reduce((F,ce)=>(F.find(ie=>ie.apartment_code===ce.apartment_code)||F.push({apartment_code:ce.apartment_code,area_sqm:Number(ce.area_sqm)}),F),[]);P(R.sort((F,ce)=>F.apartment_code.localeCompare(ce.apartment_code)))}O(!1)},m=async(r,f)=>
85{const{error:R}=await g.from("reserve_fund_settings").update({excluded:!f}).eq("id",r);R?a({title:s==="de"?"Fehler":"Error",description:R.message,variant:"destructive"}):p()},$=async()=>{if(!j.code)return;const{error:r}=await g.from("reserve_fund_settings").insert({apartment_code:j.code,excluded:!0,reason:j.reason||null});r?a({title:s==="de"?"Fehler":"Error",description:r.message,variant:"destructive"}):(a({title:s==="de"?"Erfolgreich":"Success",description:s==="de"?"Ausschluss hinzugefügt":"Exclusion added"}),w({code:"",reason:""}),N(!1),p())},H=async r=>{const{error:f}=await g.from("reserve_fund_settings").delete().eq("id",r);f?a({title:s==="de"?"Fehler":"Error",description:f.message,variant:"destructive"}):p()},J=r=>{o(r.id),u(r.reason||"")},z=()=>{o(null),u("")},h=async r=>{const{error:f}=await g.from("reserve_fund_settings").update({reason:v||null}).eq("id",r);f?a({title:s==="de"?"Fehler":"Error",description:f.message,variant:"destructive"}):(a({title:s==="de"?"Gespeichert":"Saved",description:s==="de"?"Begründung aktualisiert":"Reason updated"}),o(null),u(""),p())},I=i.filter(r=>r.excluded).map(r=>r.apartment_code),k=E.reduce((r,f)=>r+f.area_sqm,0),c=E.filter(r=>I.includes(r.apartment_code)).reduce((r,f)=>r+f.area_sqm,0),d=k-c,T=E.filter(r=>!i.find(f=>f.apartment_code===r.apartment_code));return e.jsxs("div",{className:"space-y-6",children:[e.jsxs("div",{className:"grid gap-4 md:grid-cols-3",children:[e.jsxs(ee,{children:[e.jsx(ye,{className:"pb-2",children:e.jsxs(be,{className:"text-sm font-medium flex items-center gap-2",children:[e.jsx(On,{className:"h-4 w-4"}),s==="de"?"Gesamtfläche":"Total Area"]})}),e.jsxs(ae,{children:[e.jsxs("div",{className:"text-2xl font-bold",children:[k.toFixed(2)," m²"]}),e.jsxs("p",{className:"text-xs text-muted-foreground",children:[E.length," ",s==="de"?"Apartments":"apartments"]})]})]}),e.jsxs(ee,{className:"border-destructive/50",children:[e.jsx(ye,{className:"pb-2",children:e.jsxs(be,{className:"text-sm font-medium flex items-center gap-2 text-destructive",children:[e.jsx(qe,{className:"h-4 w-4"}),s==="de"?"Ausgeschlossen":"Excluded"]})}),e.jsxs(ae,{children:[e.jsxs("div",{className:"text-2xl font-bold text-destructive",children:[c.toFixed(2)," m²"]}),e.jsxs("p",{className:"text-xs text-muted-foreground",children:[I.length," ",s==="de"?"Apartments":"apartments"]})]})]}),e.jsxs(ee,{className:"border-primary",children:[e.jsx(ye,{className:"pb-2",children:e.jsxs(be,{className:"text-sm font-medium flex items-center gap-2 text-primary",children:[e.jsx(wr,{className:"h-4 w-4"}),s==="de"?"Für Berechnung":"For Calculation"]})}),e.jsxs(ae,{children:[e.jsxs("div",{className:"text-2xl font-bold text-primary",children:[d.toFixed(2)," m²"]}),e.jsxs("p",{className:"text-xs text-muted-foreground",children:[E.length-I.length," ",s==="de"?"Apartments":"apartments"]})]})]})]}),e.jsxs(ee,{children:[e.jsx(ye,{children:e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsxs("div",{children:[e.jsx(be,{className:"font-serif",children:s==="de"?"Ausgeschlossene Apartments":"Excluded Apartments"}),e.jsx(Le,{children:s==="de"?"Diese Apartments werden bei der Berechnung des Reparaturfonds pro m² nicht berücksichtigt":"These apartments are excluded from reserve fund per m² calculation"})]}),e.jsxs(Ge,{open:S,onOpenChange:N,children:[e.jsx(yt,{asChild:!0,children:e.jsxs(b,{children:[e.jsx(Xe,{className:"h-4 w-4 mr-2"}),s==="de"?"Hinzufügen":"Add"]})}),e.jsxs(Je,{children:[e.jsxs(Ye,{children:[e.jsx(Qe,{children:s==="de"?"Apartment ausschlieÃen":"Exclude Apartment"}),e.jsx(us,{children:s==="de"?"Wählen Sie ein Apartment aus, das von der Berechnung ausgeschlossen werden soll":"Select an apartment to exclude from calculation"})]}),e.jsxs("div",{className:"space-y-4",children:[e.jsxs("div",{className:"space-y-2",children:[e.jsx(q,{children:"Apartment"}),e.jsxs("select",{className:"w-full rounded-md border border-input bg-background px-3 py-2 text-sm",value:j.code,onChange:r=>w({...j,code:r.target.value}),children:[e.jsx("option",{value:"",children:s==="de"?"Auswählen...":"Select..."}),T.map(r=>e.jsxs("option",{value:r.apartment_code,children:[r.apartment_code," (",r.area_sqm.toFixed(2)," m²)"]},r.apartment_code))]})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(q,{children:s==="de"?"Begründung":"Reason"}),e.jsx(se,{value:j.reason,onChange:r=>w({...j,reason:r.target.value}),placeholder:"Optional..."})]})]}),e.jsxs(ls,{children:[e.jsx(b,{variant:"outline",onClick:()=>N(!1),children:s==="de"?"Abbrechen":"Cancel"}),e.jsx(b,{onClick:$,disabled:!j.code,children:s==="de"?"Hinzufügen":"Add"})]})]})]})]})}),e.jsx(ae,{children:i.length===0?e.jsx("p",{className:"text-muted-foreground text-center py-8",children:s==="de"?"Keine Ausschlüsse konfiguriert":"No exclusions configured"}):e.jsxs($e,{children:[e.jsx(Be,{children:e.jsxs(Ne,{children:[e.jsx(D,{children:"Apartment"}),e.jsx(D,{children:s==="de"?"Fläche":"Area"}),e.jsx(D,{children:s==="de"?"Begründung":"Reason"}),e.jsx(D,{children:s==="de"?"Ausgeschlossen":"Excluded"}),e.jsx(D,{})]})}),e.jsx(Ue,{children:i.map(r=>{const f=E.find(F=>F.apartment_code===r.apartment_code),R=M===r.id;return e.jsxs(Ne,{children:[e.jsx(_,{className:"font-medium",children:r.apartment_code}),e.jsx(_,{children:f?`${f.area_sqm.toFixed(2)} m²`:"-"}),e.jsx(_,{children:R?e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(se,{value:v,onCh
85ange:F=>u(F.target.value),placeholder:s==="de"?"Begründung...":"Reason...",className:"h-8"}),e.jsx(b,{variant:"ghost",size:"icon",className:"h-8 w-8",onClick:()=>h(r.id),children:e.jsx(jt,{className:"h-4 w-4 text-green-600"})}),e.jsx(b,{variant:"ghost",size:"icon",className:"h-8 w-8",onClick:z,children:e.jsx(Wt,{className:"h-4 w-4 text-muted-foreground"})})]}):e.jsxs("div",{className:"flex items-center gap-2 cursor-pointer hover:text-primary group",onClick:()=>J(r),children:[r.reason||e.jsx("span",{className:"text-muted-foreground italic",children:s==="de"?"Keine Angabe":"Not specified"}),e.jsx(Ns,{className:"h-3 w-3 opacity-0 group-hover:opacity-100 transition-opacity"})]})}),e.jsx(_,{children:e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(ss,{checked:r.excluded,onCheckedChange:()=>m(r.id,r.excluded)}),e.jsx(Q,{variant:r.excluded?"destructive":"secondary",children:r.excluded?s==="de"?"Ja":"Yes":s==="de"?"Nein":"No"})]})}),e.jsx(_,{children:e.jsx(b,{variant:"ghost",size:"icon",onClick:()=>H(r.id),children:e.jsx(qe,{className:"h-4 w-4 text-destructive"})})})]},r.id)})})]})})]})]})},Ua=[{value:"sonderumlage",labelDe:"Sonderumlage",labelCs:"MimoÅádný pÅÃspÄvek",labelEn:"Special contribution"},{value:"rental",labelDe:"Mieterlöse",labelCs:"Pronájem",labelEn:"Rental income"},{value:"laundry",labelDe:"Waschküche",labelCs:"Prádelna",labelEn:"Laundry"},{value:"interest",labelDe:"Zinsen",labelCs:"Ãroky",labelEn:"Interest"},{value:"other",labelDe:"Sonstige",labelCs:"OstatnÃ",labelEn:"Other"}],Mi=()=>{const{language:s}=Zs(),{toast:a}=Re(),i=ws(),{data:y=[],isLoading:E}=kr(),[P,x]=t.useState(!1),[O,S]=t.useState(!1),[N,j]=t.useState(null),[w,M]=t.useState(!1),[o,v]=t.useState(null),[u,p]=t.useState(!1),[m,$]=t.useState({year:new Date().getFullYear(),type:"other",description:"",descriptionEn:"",amount:0,notes:""}),H=()=>{$({year:new Date().getFullYear(),type:"other",description:"",descriptionEn:"",amount:0,notes:""}),S(!1),j(null)},J=f=>{f?($({year:f.year,type:f.type,description:f.description,descriptionEn:f.descriptionEn||"",amount:f.amount,notes:f.notes||""}),S(!0),j(f.id)):H(),x(!0)},z=async f=>{f.preventDefault(),p(!0);const R={year:m.year,type:m.type,description:m.description,description_en:m.descriptionEn||null,amount:m.amount,notes:m.notes||null};let F;if(O&&N){const{error:ce}=await g.from("reserve_fund_income").update(R).eq("id",N);F=ce}else{const{error:ce}=await g.from("reserve_fund_income").insert(R);F=ce}p(!1),F?a({variant:"destructive",title:s==="de"?"Fehler":"Chyba",description:F.message}):(a({title:s==="de"?"Gespeichert":"Uloženo",description:O?s==="de"?"Eintrag aktualisiert":"Položka aktualizována":s==="de"?"Eintrag hinzugefügt":"Položka pÅidána"}),i.invalidateQueries({queryKey:["reserve-fund-income"]}),x(!1),H())},h=f=>{v(f),M(!0)},I=async()=>{if(!o)return;const{error:f}=await g.from("reserve_fund_income").delete().eq("id",o);f?a({variant:"destructive",title:s==="de"?"Fehler":"Chyba",description:f.message}):(a({title:s==="de"?"Gelöscht":"Smazáno",description:s==="de"?"Eintrag gelöscht":"Položka smazána"}),i.invalidateQueries({queryKey:["reserve-fund-income"]})),M(!1),v(null)},k=f=>{const R=Ua.find(F=>F.value===f);return R?s==="de"?R.labelDe:s==="en"?R.labelEn:R.labelCs:f},c=f=>new Intl.NumberFormat("de-DE",{style:"currency",currency:"EUR"}).format(f),d=y.reduce((f,R)=>(f[R.year]||(f[R.year]=[]),f[R.year].push(R),f),{}),T=Object.keys(d).map(Number).sort((f,R)=>R-f),r=y.reduce((f,R)=>f+R.amount,0);return E?e.jsx("div",{className:"flex justify-center py-12",children:e.jsx(fe,{className:"h-8 w-8 animate-spin text-primary"})}):e.jsxs("div",{className:"space-y-6",children:[e.jsxs("div",{className:"grid gap-4 md:grid-cols-2",children:[e.jsxs(ee,{children:[e.jsx(ye,{className:"pb-2",children:e.jsxs(be,{className:"text-sm font-medium flex items-center gap-2",children:[e.jsx(Yt,{className:"h-4 w-4"}),s==="de"?"Gesamteinnahmen":"Celkové pÅÃjmy"]})}),e.jsxs(ae,{children:[e.jsx("div",{className:"text-2xl font-bold text-primary",children:c(r)}),e.jsxs("p",{className:"text-xs text-muted-foreground",children:[y.length," ",s==="de"?"Einträge":"položek"]})]})]}),e.jsxs(ee,{children:[e.jsx(ye,{className:"pb-2",children:e.jsxs(be,{className:"text-sm font-medium flex items-center gap-2",children:[e.jsx(zr,{className:"h-4 w-4"}),s==="de"?"Jahre":"Roky"]})}),e.jsxs(ae,{children:[e.jsx("div",{className:"text-2xl font-bold",children:T.length}),e.jsx("p",{className:"text-xs text-muted-foreground",children:T.length>0?`${T[T.length-1]} - ${T[0]}`:"-"})]})]})]}),e.jsxs(ee,{children:[e.jsx(ye,{children:e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsxs("div",{children:[e.jsx(be,{className:"font-serif",children:s==="de"?"Einnahmen":"PÅÃjmy"}),e.jsx(Le,{children:s==="de"?"Sonderumlagen, Mieterlöse und andere Einnahmen":"MimoÅádné pÅÃspÄvky, pÅÃjm
85y z pronájmu a dalšà pÅÃjmy"})]}),e.jsxs(b,{onClick:()=>J(),children:[e.jsx(Xe,{className:"h-4 w-4 mr-2"}),s==="de"?"Hinzufügen":"PÅidat"]})]})}),e.jsx(ae,{children:y.length===0?e.jsx("p",{className:"text-muted-foreground text-center py-8",children:s==="de"?"Keine Einnahmen erfasst":"Žádné pÅÃjmy"}):e.jsxs($e,{children:[e.jsx(Be,{children:e.jsxs(Ne,{children:[e.jsx(D,{children:s==="de"?"Jahr":"Rok"}),e.jsx(D,{children:"Typ"}),e.jsx(D,{children:s==="de"?"Beschreibung":"Popis"}),e.jsx(D,{className:"text-right",children:s==="de"?"Betrag":"Äástka"}),e.jsx(D,{})]})}),e.jsx(Ue,{children:y.map(f=>e.jsxs(Ne,{children:[e.jsx(_,{className:"font-medium",children:f.year}),e.jsx(_,{children:k(f.type)}),e.jsxs(_,{children:[e.jsx("div",{className:"max-w-xs truncate",children:f.description}),f.notes&&e.jsx("div",{className:"text-xs text-muted-foreground truncate",children:f.notes})]}),e.jsx(_,{className:"text-right font-medium text-primary",children:c(f.amount)}),e.jsx(_,{children:e.jsxs("div",{className:"flex gap-1",children:[e.jsx(b,{variant:"ghost",size:"icon",onClick:()=>J(f),children:e.jsx(Ns,{className:"h-4 w-4"})}),e.jsx(b,{variant:"ghost",size:"icon",onClick:()=>h(f.id),children:e.jsx(qe,{className:"h-4 w-4 text-destructive"})})]})})]},f.id))})]})})]}),e.jsx(Ge,{open:P,onOpenChange:x,children:e.jsxs(Je,{children:[e.jsxs(Ye,{children:[e.jsx(Qe,{className:"font-serif",children:O?s==="de"?"Eintrag bearbeiten":"Upravit položku":s==="de"?"Neue Einnahme":"Nový pÅÃjem"}),e.jsx(us,{children:s==="de"?"Geben Sie die Details der Einnahme ein":"Zadejte údaje o pÅÃjmu"})]}),e.jsxs("form",{onSubmit:z,className:"space-y-4",children:[e.jsxs("div",{className:"grid grid-cols-2 gap-4",children:[e.jsxs("div",{className:"space-y-2",children:[e.jsx(q,{children:s==="de"?"Jahr":"Rok"}),e.jsx(se,{type:"number",value:m.year,onChange:f=>$({...m,year:parseInt(f.target.value)}),required:!0})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(q,{children:"Typ"}),e.jsxs(De,{value:m.type,onValueChange:f=>$({...m,type:f}),children:[e.jsx(Pe,{children:e.jsx(Ae,{})}),e.jsx(Ee,{children:Ua.map(f=>e.jsx(me,{value:f.value,children:s==="de"?f.labelDe:f.labelCs},f.value))})]})]})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(q,{children:s==="de"?"Beschreibung (DE)":"Popis (DE)"}),e.jsx(se,{value:m.description,onChange:f=>$({...m,description:f.target.value}),required:!0})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(q,{children:s==="de"?"Beschreibung (EN)":"Popis (EN)"}),e.jsx(se,{value:m.descriptionEn,onChange:f=>$({...m,descriptionEn:f.target.value}),placeholder:s==="de"?"Optional":"Volitelné"})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(q,{children:s==="de"?"Betrag (EUR)":"Äástka (EUR)"}),e.jsx(se,{type:"number",step:"0.01",value:m.amount,onChange:f=>$({...m,amount:parseFloat(f.target.value)}),required:!0})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(q,{children:s==="de"?"Notizen":"Poznámky"}),e.jsx(vs,{value:m.notes,onChange:f=>$({...m,notes:f.target.value}),rows:2})]}),e.jsxs(ls,{children:[e.jsx(b,{type:"button",variant:"outline",onClick:()=>x(!1),children:s==="de"?"Abbrechen":"ZruÅ¡it"}),e.jsxs(b,{type:"submit",disabled:u,children:[u?e.jsx(fe,{className:"h-4 w-4 animate-spin mr-2"}):null,s==="de"?"Speichern":"Uložit"]})]})]})]})}),e.jsx(ms,{open:w,onOpenChange:M,title:s==="de"?"Eintrag löschen":"Smazat položku",description:s==="de"?"Sind Sie sicher, dass Sie diesen Eintrag löschen möchten?":"Opravdu chcete smazat tuto položku?",confirmText:s==="de"?"Löschen":"Smazat",onConfirm:I})]})},qa=[{value:"loan_repayment",labelDe:"Darlehensrückzahlung",labelCs:"Splátka úvÄru",labelEn:"Loan repayment"},{value:"maintenance",labelDe:"Instandhaltung",labelCs:"Ãdržba",labelEn:"Maintenance"},{value:"repair",labelDe:"Reparatur",labelCs:"Opravy",labelEn:"Repair"},{value:"insurance",labelDe:"Versicherung",labelCs:"PojiÅ¡tÄnÃ",labelEn:"Insurance"},{value:"other",labelDe:"Sonstige",labelCs:"OstatnÃ",labelEn:"Other"}],Li=()=>{const{language:s}=Zs(),{toast:a}=Re(),i=ws(),{data:y=[],isLoading:E}=Cr(),[P,x]=t.useState(!1),[O,S]=t.useState(!1),[N,j]=t.useState(null),[w,M]=t.useState(!1),[o,v]=t.useState(null),[u,p]=t.useState(!1),[m,$]=t.useState({year:new Date().getFullYear(),category:"other",description:"",descriptionEn:"",amount:0,vendor:"",itemDate:"",invoiceNumber:"",notes:""}),H=()=>{$({year:new Date().getFullYear(),category:"other",description:"",descriptionEn:"",amount:0,vendor:"",itemDate:"",invoiceNumber:"",notes:""}),S(!1),j(null)},J=r=>{r?($({year:r.year,category:r.category,description:r.description,descriptionEn:r.descriptionEn||"",amount:r.amount,vendor:r.vendor||"",itemDate:r.itemDate||"",invoiceNumber:r.invoiceNumber||"",notes:r.notes||""}),S(!0),j(r.id)):H(),x(!0)},z=async r=>{r.preventDefault(),p(!0);const f={year:m.year,category:m.category,description:m.description,description_en:m.descriptionEn||null,amount:m.amount,vendor:m.vendor||null,item_date:m.itemDate||null,invoice_number:m.invoiceNumber||null,notes:m.notes||null};let R;if(O&&N){const{error:F}=await g.from("reserve_fund_expenditures").update(f).eq("id",N);R=F}else{const{error:F}=await g.from("reserve_fund_expenditures").insert(f);R=F}p(!1),R?a({variant:"destructive",title:s==="de"?"Fehler":"Chyba",description:R.message}):(a({title:s==="de"?"Gespeichert":"Uloženo",description:O?s==="de"?"Eintrag aktualisiert":"Položka aktualizována":s==="de"?"Eintrag hinzugefügt":"Položka pÅidána"}),i.invalidateQueries({queryKey:["reserve-fund-expenditures"]}),x(!1),H())},h=r=>{v(r),M(!0)},I=async()=>
85{if(!o)return;const{error:r}=await g.from("reserve_fund_expenditures").delete().eq("id",o);r?a({variant:"destructive",title:s==="de"?"Fehler":"Chyba",description:r.message}):(a({title:s==="de"?"Gelöscht":"Smazáno",description:s==="de"?"Eintrag gelöscht":"Položka smazána"}),i.invalidateQueries({queryKey:["reserve-fund-expenditures"]})),M(!1),v(null)},k=r=>{const f=qa.find(R=>R.value===r);return f?s==="de"?f.labelDe:s==="en"?f.labelEn:f.labelCs:r},c=r=>new Intl.NumberFormat("de-DE",{style:"currency",currency:"EUR"}).format(r),d=y.reduce((r,f)=>r+f.amount,0),T=[...new Set(y.map(r=>r.year))].sort((r,f)=>f-r);return E?e.jsx("div",{className:"flex justify-center py-12",children:e.jsx(fe,{className:"h-8 w-8 animate-spin text-primary"})}):e.jsxs("div",{className:"space-y-6",children:[e.jsxs("div",{className:"grid gap-4 md:grid-cols-2",children:[e.jsxs(ee,{children:[e.jsx(ye,{className:"pb-2",children:e.jsxs(be,{className:"text-sm font-medium flex items-center gap-2",children:[e.jsx(Yt,{className:"h-4 w-4"}),s==="de"?"Gesamtausgaben":"Celkové výdaje"]})}),e.jsxs(ae,{children:[e.jsx("div",{className:"text-2xl font-bold text-destructive",children:c(d)}),e.jsxs("p",{className:"text-xs text-muted-foreground",children:[y.length," ",s==="de"?"Einträge":"položek"]})]})]}),e.jsxs(ee,{children:[e.jsx(ye,{className:"pb-2",children:e.jsxs(be,{className:"text-sm font-medium flex items-center gap-2",children:[e.jsx(Dr,{className:"h-4 w-4"}),s==="de"?"Jahre":"Roky"]})}),e.jsxs(ae,{children:[e.jsx("div",{className:"text-2xl font-bold",children:T.length}),e.jsx("p",{className:"text-xs text-muted-foreground",children:T.length>0?`${T[T.length-1]} - ${T[0]}`:"-"})]})]})]}),e.jsxs(ee,{children:[e.jsx(ye,{children:e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsxs("div",{children:[e.jsx(be,{className:"font-serif",children:s==="de"?"Ausgaben":"Výdaje"}),e.jsx(Le,{children:s==="de"?"Darlehensrückzahlungen, Instandhaltung und andere Ausgaben":"Splátky úvÄru, údržba a dalšà výdaje"})]}),e.jsxs(b,{onClick:()=>J(),children:[e.jsx(Xe,{className:"h-4 w-4 mr-2"}),s==="de"?"Hinzufügen":"PÅidat"]})]})}),e.jsx(ae,{children:y.length===0?e.jsx("p",{className:"text-muted-foreground text-center py-8",children:s==="de"?"Keine Ausgaben erfasst":"Žádné výdaje"}):e.jsxs($e,{children:[e.jsx(Be,{children:e.jsxs(Ne,{children:[e.jsx(D,{children:s==="de"?"Jahr":"Rok"}),e.jsx(D,{children:"Kategorie"}),e.jsx(D,{children:s==="de"?"Beschreibung":"Popis"}),e.jsx(D,{children:s==="de"?"Lieferant":"Dodavatel"}),e.jsx(D,{className:"text-right",children:s==="de"?"Betrag":"Äástka"}),e.jsx(D,{})]})}),e.jsx(Ue,{children:y.map(r=>e.jsxs(Ne,{children:[e.jsx(_,{className:"font-medium",children:r.year}),e.jsx(_,{children:k(r.category)}),e.jsxs(_,{children:[e.jsx("div",{className:"max-w-xs truncate",children:r.description}),r.invoiceNumber&&e.jsxs("div",{className:"text-xs text-muted-foreground",children:["#",r.invoiceNumber]})]}),e.jsx(_,{children:e.jsx("span",{className:"text-muted-foreground",children:r.vendor||"-"})}),e.jsx(_,{className:"text-right font-medium text-destructive",children:c(r.amount)}),e.jsx(_,{children:e.jsxs("div",{className:"flex gap-1",children:[e.jsx(b,{variant:"ghost",size:"icon",onClick:()=>J(r),children:e.jsx(Ns,{className:"h-4 w-4"})}),e.jsx(b,{variant:"ghost",size:"icon",onClick:()=>h(r.id),children:e.jsx(qe,{className:"h-4 w-4 text-destructive"})})]})})]},r.id))})]})})]}),e.jsx(Ge,{open:P,onOpenChange:x,children:e.jsxs(Je,{className:"max-w-lg",children:[e.jsxs(Ye,{children:[e.jsx(Qe,{className:"font-serif",children:O?s==="de"?"Eintrag bearbeiten":"Upravit položku":s==="de"?"Neue Ausgabe":"Nový výdaj"}),e.jsx(us,{children:s==="de"?"Geben Sie die Details der Ausgabe ein":"Zadejte údaje o výdaji"})]}),e.jsxs("form",{onSubmit:z,className:"space-y-4",children:[e.jsxs("div",{className:"grid grid-cols-2 gap-4",children:[e.jsxs("div",{className:"space-y-2",children:[e.jsx(q,{children:s==="de"?"Jahr":"Rok"}),e.jsx(se,{type:"number",value:m.year,onChange:r=>$({...m,year:parseInt(r.target.value)}),required:!0})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(q,{children:"Kategorie"}),e.jsxs(De,{value:m.category,onValueChange:r=>$({...m,category:r}),children:[e.jsx(Pe,{children:e.jsx(Ae,{})}),e.jsx(Ee,{children:qa.map(r=>e.jsx(me,{value:r.value,children:s==="de"?r.labelDe:r.labelCs}
85,r.value))})]})]})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(q,{children:s==="de"?"Beschreibung (DE)":"Popis (DE)"}),e.jsx(se,{value:m.description,onChange:r=>$({...m,description:r.target.value}),required:!0})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(q,{children:s==="de"?"Beschreibung (EN)":"Popis (EN)"}),e.jsx(se,{value:m.descriptionEn,onChange:r=>$({...m,descriptionEn:r.target.value}),placeholder:s==="de"?"Optional":"Volitelné"})]}),e.jsxs("div",{className:"grid grid-cols-2 gap-4",children:[e.jsxs("div",{className:"space-y-2",children:[e.jsx(q,{children:s==="de"?"Betrag (EUR)":"Äástka (EUR)"}),e.jsx(se,{type:"number",step:"0.01",value:m.amount,onChange:r=>$({...m,amount:parseFloat(r.target.value)}),required:!0})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(q,{children:"Datum"}),e.jsx(se,{type:"date",value:m.itemDate,onChange:r=>$({...m,itemDate:r.target.value})})]})]}),e.jsxs("div",{className:"grid grid-cols-2 gap-4",children:[e.jsxs("div",{className:"space-y-2",children:[e.jsx(q,{children:s==="de"?"Lieferant":"Dodavatel"}),e.jsx(se,{value:m.vendor,onChange:r=>$({...m,vendor:r.target.value})})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(q,{children:s==="de"?"Rechnungsnummer":"ÄÃslo faktury"}),e.jsx(se,{value:m.invoiceNumber,onChange:r=>
85$({...m,invoiceNumber:r.target.value})})]})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(q,{children:s==="de"?"Notizen":"Poznámky"}),e.jsx(vs,{value:m.notes,onChange:r=>$({...m,notes:r.target.value}),rows:2})]}),e.jsxs(ls,{children:[e.jsx(b,{type:"button",variant:"outline",onClick:()=>x(!1),children:s==="de"?"Abbrechen":"ZruÅ¡it"}),e.jsxs(b,{type:"submit",disabled:u,children:[u?e.jsx(fe,{className:"h-4 w-4 animate-spin mr-2"}):null,s==="de"?"Speichern":"Uložit"]})]})]})]})}),e.jsx(ms,{open:w,onOpenChange:M,title:s==="de"?"Eintrag löschen":"Smazat položku",description:s==="de"?"Sind Sie sicher, dass Sie diesen Eintrag löschen möchten?":"Opravdu chcete smazat tuto položku?",confirmText:s==="de"?"Löschen":"Smazat",onConfirm:I})]})},Ka=()=>{const{language:s}=Zs(),{toast:a}=Re(),i=ws(),{data:y=[],isLoading:E}=Sr(),[P,x]=t.useState(!1),[O,S]=t.useState(!1),[N,j]=t.useState(null),[w,M]=t.useState(!1),[o,v]=t.useState(null),[u,p]=t.useState(!1),[m,$]=t.useState({year:new Date().getFullYear(),startBalance:0,contributions:0,otherIncome:0,expenditures:0,loanRepayments:0,endBalance:0,notes:""}),H=()=>{$({year:new Date().getFullYear(),startBalance:0,contributions:0,otherIncome:0,expenditures:0,loanRepayments:0,endBalance:0,notes:""}),S(!1),j(null)},J=d=>{d?($({year:d.year,startBalance:d.startBalance,contributions:d.contributions,otherIncome:d.otherIncome,expenditures:d.expenditures,loanRepayments:d.loanRepayments,endBalance:d.endBalance,notes:d.notes||""}),S(!0),j(d.year)):H(),x(!0)},z=async d=>{d.preventDefault(),p(!0);const T={year:m.year,start_balance:m.startBalance,contributions:m.contributions,other_income:m.otherIncome,expenditures:m.expenditures,loan_repayments:m.loanRepayments,end_balance:m.endBalance,notes:m.notes||null};let r;if(O&&N!==null){const{error:f}=await g.from("reserve_fund_years").update(T).eq("year",N);r=f}else{const{error:f}=await g.from("reserve_fund_years").insert(T);r=f}p(!1),r?a({variant:"destructive",title:s==="de"?"Fehler":"Chyba",description:r.message}):(a({title:s==="de"?"Gespeichert":"Uloženo",description:O?s==="de"?"Jahr aktualisiert":"Rok aktualizován":s==="de"?"Jahr hinzugefügt":"Rok pÅidán"}),i.invalidateQueries({queryKey:["reserve-fund-years"]}),x(!1),H())},h=d=>{v(d),M(!0)},I=async()=>{if(o===null)return;const{error:d}=await g.from("reserve_fund_years").delete().eq("year",o);d?a({variant:"destructive",title:s==="de"?"Fehler":"Chyba",description:d.message}):(a({title:s==="de"?"Gelöscht":"Smazáno",description:s==="de"?"Jahr gelöscht":"Rok smazán"}),i.invalidateQueries({queryKey:["reserve-fund-years"]})),M(!1),v(null)},k=d=>new Intl.NumberFormat("de-DE",{style:"currency",currency:"EUR"}).format(d),c=y.length>0?y[y.length-1]:null;return E?e.jsx("div",{className:"flex justify-center py-12",children:e.jsx(fe,{className:"h-8 w-8 animate-spin text-primary"})}):e.jsxs("div",{className:"space-y-6",children:[e.jsxs("div",{className:"grid gap-4 md:grid-cols-2",children:[e.jsxs(ee,{children:[e.jsx(ye,{className:"pb-2",children:e.jsxs(be,{className:"text-sm font-medium flex items-center gap-2",children:[e.jsx(Yt,{className:"h-4 w-4"}),s==="de"?"Aktueller Stand":"Aktuálnà stav"]})}),e.jsxs(ae,{children:[e.jsx("div",{className:"text-2xl font-bold text-primary",children:c?k(c.endBalance):"-"}),e.jsx("p",{className:"text-xs text-muted-foreground",children:c?`${s==="de"?"Ende":"Konec"} ${c.year}`:"-"})]})]}),e.jsxs(ee,{children:[e.jsx(ye,{className:"pb-2",children:e.jsxs(be,{className:"text-sm font-medium flex items-center gap-2",children:[e.jsx(Qt,{className:"h-4 w-4"}),s==="de"?"Erfasste Jahre":"Evidované roky"]})}),e.jsxs(ae,{children:[e.jsx("div",{className:"text-2xl font-bold",children:y.length}),e.jsx("p",{className:"text-xs text-muted-foreground",children:y.length>0?`${y[0].year} - ${y[y.length-1].year}`:"-"})]})]})]}),e.jsxs(ee,{children:[e.jsx(ye,{children:e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsxs("div",{children:[e.jsx(be,{className:"font-serif",children:s==="de"?"Jahresübersichten":"RoÄnà pÅehledy"}),e.jsx(Le,{children:s==="de"?"Jährliche Zusammenfassung des Reparaturfonds":"RoÄnà pÅehledy fondu oprav"})]}),e.jsxs(b,{onClick:()=>J(),children:[e.jsx(Xe,{className:"h-4 w-4 mr-2"}),s==="de"?"Jahr hinzufügen":"PÅidat rok"]})]})}),e.jsx(ae,{children:y.length===0?e.jsx("p",{className:"text-muted-foreground text-center py-8",children:s==="de"?"Keine Jahre erfasst":"Žádné roky"}):e.jsxs($e,{children:[e.jsx(Be,{children:e.jsxs(Ne,{children:[e.jsx(D,{children:s==="de"?"Jahr":"Rok"}),e.jsx(D,{className:"text-right",children:s==="de"?"Anfangsstand":"PoÄáteÄnà stav"}),e.jsx(D,{className:"text-right",children:s==="de"?"Beiträge":"PÅÃspÄvky"}),e.jsx(D,{className:"text-right",children:s==="de"?"Sonstige":"OstatnÃ"}),e.jsx(D,{className:"text-right",children:s==="de"?"Ausgaben":"Výdaje"}),e.jsx(D,{className:"text-right",children:s==="de"?"Endstand":"KoneÄný stav"}),e.jsx(D,{})]})}),e.jsx(Ue,{children:y.map(d=>e.jsxs(Ne,{children:[e.jsx(_,{className:"font-medium",children:d.year}),e.jsx(_,{className:"text-right",children:k(d.startBalance)}),e.jsx(_,{className:"text-right text-primary",children:k(d.contributions)}),e.jsx(_,{className:"text-right text-primary",children:k(d.otherIncome)}),e.jsx(_,{className:"text-right text-destructive",children:k(d.expenditures+d.loanRepayments)}),e.jsx(_,{className:"text-right font-bold",children:k(d.endBalance)}),e.jsx(_,{children:e.jsxs("div",{className:"flex gap-1",children:[e.jsx(b,{variant:"ghost",size:"icon",onClick:()=>J(d),children:e.jsx(Ns,{className:"h-4 w-4"})}),e.jsx(b,{variant:"ghost",size:"icon",onClick:()=>h(d.year),children:e.jsx(qe,{className:"h-4 w-4 text-destructive"})})]})})]},d.year))})]})})]}),e.jsx(Ge,{open:P,onOpenChange:x,children:e.jsxs(Je,{className:"max-w-lg",children:[e.jsxs(Ye,{children:[e.jsx(Qe,{className:"font-serif",children:O?s==="de"?"Jahr bearbeiten":"Uprav
85it rok":s==="de"?"Neues Jahr":"Nový rok"}),e.jsx(us,{children:s==="de"?"Geben Sie die Jahresübersicht ein":"Zadejte roÄnà pÅehled"})]}),e.jsxs("form",{onSubmit:z,className:"space-y-4",children:[e.jsxs("div",{className:"space-y-2",children:[e.jsx(q,{children:s==="de"?"Jahr":"Rok"}),e.jsx(se,{type:"number",value:m.year,onChange:d=>$({...m,year:parseInt(d.target.value)}),required:!0,disabled:O})]}),e.jsxs("div",{className:"grid grid-cols-2 gap-4",children:[e.jsxs("div",{className:"space-y-2",children:[e.jsx(q,{children:s==="de"?"Anfangsstand (EUR)":"PoÄáteÄnà stav (EUR)"}),e.jsx(se,{type:"number",step:"0.01",value:m.startBalance,onChange:d=>$({...m,startBalance:parseFloat(d.target.value)}),required:!0})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(q,{children:s==="de"?"Endstand (EUR)":"KoneÄný stav (EUR)"}),e.jsx(se,{type:"number",step:"0.01",value:m.endBalance,onChange:d=>$({...m,endBalance:parseFloat(d.target.value)}),required:!0})]})]}),e.jsxs("div",{className:"grid grid-cols-2 gap-4",children:[e.jsxs("div",{className:"space-y-2",children:[e.jsx(q,{children:s==="de"?"Beiträge (EUR)":"PÅÃspÄvky (EUR)"}),e.jsx(se,{type:"number",step:"0.01",value:m.contributions,onChange:d=>$({...m,contributions:parseFloat(d.target.value)}),required:!0})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(q,{children:s==="de"?"Sonstige Einnahmen (EUR)":"Ostatnà pÅÃjmy (EUR)"}),e.jsx(se,{type:"number",step:"0.01",value:m.otherIncome,onChange:d=>$({...m,otherIncome:parseFloat(d.target.value)})})]})]}),e.jsxs("div",{className:"grid grid-cols-2 gap-4",children:[e.jsxs("div",{className:"space-y-2",children:[e.jsx(q,{children:s==="de"?"Ausgaben (EUR)":"Výdaje (EUR)"}),e.jsx(se,{type:"number",step:"0.01",value:m.expenditures,onChange:d=>$({...m,expenditures:parseFloat(d.target.value)})})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(q,{children:s==="de"?"Darlehensrückzahlung (EUR)":"Splátky úvÄru (EUR)"}),e.jsx(se,{type:"number",step:"0.01",value:m.loanRepayments,onChange:d=>$({...m,loanRepayments:parseFloat(d.target.value)})})]})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(q,{children:s==="de"?"Notizen":"Poznámky"}),e.jsx(vs,{value:m.notes,onChange:d=>$({...m,notes:d.target.value}),rows:2})]}),e.jsxs(ls,{children:[e.jsx(b,{type:"button",variant:"outline",onClick:()=>x(!1),children:s==="de"?"Abbrechen":"ZruÅ¡it"}),e.jsxs(b,{type:"submit",disabled:u,children:[u?e.jsx(fe,{className:"h-4 w-4 animate-spin mr-2"}):null,s==="de"?"Speichern":"Uložit"]})]})]})]})}),e.jsx(ms,{open:w,onOpenChange:M,title:s==="de"?"Jahr löschen":"Smazat rok",description:s==="de"?"Sind Sie sicher, dass Sie dieses Jahr löschen möchten?":"Opravdu chcete smazat tento rok?",confirmText:s==="de"?"Löschen":"Smazat",onConfirm:I})]})},Ri=()=>{Zs();const{toast:s}=Re(),[a,i]=t.useState([]),[y,E]=t.useState(null),[P,x]=t.useState([]),[O,S]=t.useState([]),[N,j]=t.useState(!0),[w,M]=t.useState(null),[o,v]=t.useState(!1),[u,p]=t.useState([]),[m,$]=t.useState(!1),[H,J]=t.useState(new Map),[z,h]=t.useState("all"),[I,k]=t.useState([]),[c,d]=t.useState({house_cost_id:"",description:"",amount:0,vendor:"",item_date:"",invoice_number:""});t.useEffect(()=>{T(),r()},[]),t.useEffect(()=>{y&&R(y)},[y]);const T=async()=>{j(!0);const{data:n}=await g.from("house_costs").select("year").order("year",{ascending:!1});if(n){const G=[...new Set(n.map(pe=>pe.year))];i(G);const Y=[];for(const pe of G){const{data:B}=await g.from("house_costs").select("id, subcategory, amount").eq("year",pe),{data:te}=await g.from("house_cost_items").select("id, house_cost_id, amount");if(B){const xe=new Set(B.map(re=>re.id)),de=(te==null?void 0:te.filter(re=>re.house_cost_id&&xe.has(re.house_cost_id)))||[],L=new Map;B.forEach(re=>{const A=re.subcategory||"Other",ne=L.get(A)||{amount:0,itemCount:0};L.set(A,{amount:ne.amount+Number(re.amount),itemCount:ne.itemCount})}),de.forEach(re=>{const A=B.find(ne=>ne.id===re.house_cost_id);if(A){const ne=A.subcategory||"Other",le=L.get(ne);le&&le.itemCount++}}),Y.push({year:pe,categoryCount:B.length,itemCount:de.length,totalAmount:B.reduce((re,A)=>re+Number(A.amount),0),categories:Array.from(L.entries()).map(([re,A])=>({subcategory:re,...A})).sort((re,A)=>A.amount-re.amount)})}}p(Y)}j(!1)},r=async()=>{const{data:n}=await g.from("category_mappings").select("source_category, target_category, target_subcategory").order("target_subcategory");n&&k(n)},f=async(n,G)=>{const{error:Y}=await g.from("house_costs").update({subcategory:G}).eq("id",n);if(Y){s({variant:"destructive",title:"Chyba",description:"NepodaÅilo se zmÄnit kategorii."});return}s({title:"Uloženo",description:"Kategorie byla zmÄnÄna."}),y&&R(y)},R=async n=>{j(!0);const{data:G}=await g.from("house_costs").select("*").eq("year",n).order("subcategory");if(G){x(G);const Y=G.map(te=>te.source_document_id).filter(te=>!!te);if(Y.length>0){const{data:te}=await g.from("pdf_documents").select("id, file_name, file_path").in("id",Y);if(te){const xe=new Map;te.forEach(de=>xe.set(de.id,de)),J(xe)}}const pe=G.map(te=>te.id),{data:B}=await g.from("house_cost_items").select("*").in("house_cost_id",pe).order("item_date",{ascending:!1});S(B||[])}j(!1)},F=n=>new Intl.NumberFormat("de-DE",{style:"currency",currency:"EUR",maximumFractionDigits:2}).format(n),ce=async n=>{try{const{data:G}=await g.storage.from("documents").createSignedUrl(n,3600);G!=null&&G.signedUrl?window.open(G.signedUrl,"_blank"):s({variant:"destructive",title:"Chyba",description:"NepodaÅilo se otevÅÃt PDF dokument."})}catch{s({variant:"destructive",title:"Chyba",description:"NepodaÅilo se otevÅÃt PDF dokument."})}},ie=n=>{M({...n}),v(!0)},W=async()=>
85{if(!w)return;const{error:n}=await g.from("house_cost_items").update({description:w.description,amount:w.amount,vendor:w.vendor,item_date:w.item_date,invoice_number:w.invoice_number}).eq("id",w.id);n?s({variant:"destructive",title:"Chyba",description:"NepodaÅilo se uložit zmÄny."}):(s({title:"Uloženo",description:"Položka byla aktualizována."}),v(!1),y&&R(y))},Z=async n=>{if(!confirm("Opravdu chcete smazat tuto položku?"))return;const{error:G}=await g.from("house_cost_items").delete().eq("id",n);G?s({variant:"destructive",title:"Chyba",description:"NepodaÅilo se smazat položku."}):(s({title:"Smazáno",description:"Položka byla odstranÄna."}),y&&R(y))},K=async()=>{if(!c.house_cost_id||!c.description||c.amount<=0){s({variant:"destructive",title:"Chyba",description:"VyplÅte povinné pole: kategorie, popis a Äástka."});return}const{error:n}=await g.from("house_cost_items").insert({house_cost_id:c.house_cost_id,description:c.description,amount:c.amount,vendor:c.vendor||null,item_date:c.item_date||null,invoice_number:c.invoice_number||null});n?s({variant:"destructive",title:"Chyba",description:"NepodaÅilo se vytvoÅit položku."}):(s({title:"VytvoÅeno",description:"Položka byla úspÄÅ¡nÄ pÅidána."}),$(!1),d({house_cost_id:"",description:"",amount:0,vendor:"",item_date:"",invoice_number:""}),y&&(R(y),T()))},l=t.useMemo(()=>{const n=P.filter(Y=>z==="all"?!0:z==="pdf_import"?Y.source==="pdf_import":z==="manual"?Y.source!=="pdf_import"||!Y.source:!0),G=new Map;return n.forEach(Y=>{const pe=Y.subcategory||"Other";G.has(pe)||G.set(pe,{cost:Y,items:[]})}),O.forEach(Y=>{const pe=n.find(B=>B.id===Y.house_cost_id);if(pe){const B=pe.subcategory||"Other",te=G.get(B);te&&te.items.push(Y)}}),Array.from(G.entries()).map(([Y,pe])=>({subcategory:Y,...pe,totalItems:pe.items.length,itemsTotal:pe.items.reduce((B,te)=>B+Number(te.amount),0)})).sort((Y,pe)=>pe.cost.amount-Y.cost.amount)},[P,O,z]),U=t.useMemo(()=>{const n=P.filter(Y=>Y.source==="pdf_import").length,G=P.filter(Y=>Y.source!=="pdf_import"||!Y.source).length;return{pdfCount:n,manualCount:G,total:P.length}},[P]);return N&&a.length===0?e.jsx("div",{className:"flex items-center justify-center py-12",children:e.jsx(fe,{className:"h-8 w-8 animate-spin text-primary"})}):e.jsxs("div",{className:"space-y-6",children:[e.jsx("div",{className:"flex items-center justify-between",children:e.jsxs("div",{children:[e.jsxs("h2",{className:"text-xl font-semibold flex items-center gap-2",children:[e.jsx(Yt,{className:"h-5 w-5 text-primary"}),"Správa domovnÃch nákladů"]}),e.jsx("p",{className:"text-sm text-muted-foreground",children:"PÅehled a úprava nákladových položek podle roků"})]})}),!y&&e.jsx("div",{className:"grid gap-4 md:grid-cols-2 lg:grid-cols-3",children:u.map(n=>e.jsxs(ee,{className:"cursor-pointer hover:border-primary transition-colors",onClick:()=>E(n.year),children:[e.jsx(ye,{className:"pb-2",children:e.jsxs(be,{className:"flex items-center justify-between",children:[e.jsxs("span",{className:"flex items-center gap-2",children:[e.jsx(Qt,{className:"h-5 w-5 text-primary"}),n.year]}),e.jsxs(Q,{variant:n.itemCount>0?"default":"secondary",children:[n.itemCount," položek"]})]})}),e.jsxs(ae,{className:"space-y-3",children:[e.jsxs("div",{className:"flex justify-between text-sm",children:[e.jsx("span",{className:"text-muted-foreground",children:"Celkem kategoriÃ:"}),e.jsx("span",{className:"font-medium",children:n.categoryCount})]}),e.jsxs("div",{className:"flex justify-between text-sm",children:[e.jsx("span",{className:"text-muted-foreground",children:"Celková Äástka:"}),e.jsx("span",{className:"font-semibold text-primary",children:F(n.totalAmount)})]}),e.jsxs("div",{className:"pt-2 border-t space-y-1",children:[n.categories.slice(0,5).map(G=>e.jsxs("div",{className:"flex justify-between text-xs",children:[e.jsx("span",{className:"text-muted-foreground truncate max-w-[150px]",children:G.subcategory}),e.jsxs("span",{className:"flex items-center gap-2",children:[G.itemCount>0?e.jsx(qs,{className:"h-3 w-3 text-green-500"}):e.jsx(_a,{className:"h-3 w-3 text-orange-500"}),e.jsx("span",{children:F(G.amount)})]})]},G.subcategory)),n.categories.length>5&&e.jsxs("div",{className:"text-xs text-muted-foreground text-center pt-1",children:["+",n.c
85ategories.length-5," dalÅ¡Ãch kategoriÃ"]})]})]})]},n.year))}),y&&e.jsxs("div",{className:"space-y-4",children:[e.jsxs("div",{className:"flex items-center justify-between flex-wrap gap-4",children:[e.jsxs("div",{className:"flex items-center gap-4",children:[e.jsx(b,{variant:"outline",onClick:()=>E(null),children:"â ZpÄt na pÅehled"}),e.jsxs("h3",{className:"text-lg font-semibold",children:["Rok ",y]}),e.jsxs(Q,{children:[O.length," položek"]})]}),e.jsxs("div",{className:"flex items-center gap-3",children:[e.jsxs("div",{className:"flex items-center gap-2 bg-muted rounded-lg p-1",children:[e.jsxs(b,{variant:z==="all"?"secondary":"ghost",size:"sm",className:"h-7 px-3",onClick:()=>h("all"),children:["VÅ¡e (",U.total,")"]}),e.jsxs(b,{variant:z==="pdf_import"?"secondary":"ghost",size:"sm",className:"h-7 px-3 gap-1",onClick:()=>h("pdf_import"),children:[e.jsx(Pt,{className:"h-3 w-3"}),"PDF (",U.pdfCount,")"]}),e.jsxs(b,{variant:z==="manual"?"secondary":"ghost",size:"sm",className:"h-7 px-3 gap-1",onClick:()=>h("manual"),children:[e.jsx(Oa,{className:"h-3 w-3"}),"Manuálnà (",U.manualCount,")"]})]}),e.jsxs(b,{onClick:()=>$(!0),children:[e.jsx(Xe,{className:"h-4 w-4 mr-2"}),"Nová položka"]})]})]}),N?e.jsx("div",{className:"flex items-center justify-center py-12",children:e.jsx(fe,{className:"h-8 w-8 animate-spin text-primary"})}):e.jsx(Pr,{type:"multiple",className:"space-y-2",children:l.map(n=>{const G=n.cost.source_document_id?H.get(n.cost.source_document_id):null;return e.jsxs(Ar,{value:n.subcategory,className:"border rounded-lg px-4",children:[e.jsx(Er,{className:"hover:no-underline",children:e.jsxs("div",{className:"flex items-center justify-between w-full pr-4",children:[e.jsxs("div",{className:"flex items-center gap-3",children:[e.jsx("span",{className:"font-medium",children:n.subcategory}),e.jsxs(Q,{variant:n.totalItems>0?"default":"outline",children:[n.totalItems," položek"]}),e.jsx(as,{children:e.jsxs(Ke,{children:[e.jsx(Ze,{asChild:!0,children:e.jsx("span",{className:"inline-flex items-center",children:n.cost.source==="pdf_import"?e.jsx(Pt,{className:"h-4 w-4 text-blue-500"}):e.jsx(Oa,{className:"h-4 w-4 text-muted-foreground"})})}),e.jsx(He,{children:n.cost.source==="pdf_import"?`Importováno z PDF${G?`: ${G.file_name}`:""}`:"Manuálnà zadánÃ"})]})})]}),e.jsxs("div",{className:"flex items-center gap-4 text-sm",children:[e.jsxs("span",{className:"text-muted-foreground",children:["RozpoÄet: ",e.jsx("span",{className:"font-semibold",children:F(n.cost.amount)})]}),n.totalItems>0&&e.jsxs("span",{className:n.itemsTotal===n.cost.amount?"text-green-600":"text-orange-500",children:["Položky: ",F(n.itemsTotal)]})]})]})}),e.jsxs(Ir,{children:[n.cost.source==="pdf_import"&&G&&n.items.length>0&&e.jsxs("div",{className:"mb-3 px-3 py-2 bg-blue-50 dark:bg-blue-950/30 rounded-md flex items-center justify-between text-sm text-blue-700 dark:text-blue-300",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(Pt,{className:"h-4 w-4"}),e.jsxs("span",{children:["Zdroj: ",G.file_name]})]}),e.jsxs(b,{variant:"ghost",size:"sm",className:"h-7 px-2 text-blue-700 dark:text-blue-300 hover:text-blue-900 dark:hover:text-blue-100 hover:bg-blue-100 dark:hover:bg-blue-900/50",onClick:()=>ce(G.file_path),children:[e.jsx(Ys,{className:"h-4 w-4 mr-1"}),"OtevÅÃt PDF"]})]}),e.jsx("div",{className:"mb-3 px-3 py-2 bg-muted/50 rounded-md text-sm",children:e.jsxs("div",{className:"flex items-center justify-between flex-wrap gap-2",children:[e.jsxs("div",{className:"flex items-center gap-4",children:[e.jsxs("span",{className:"text-muted-foreground",children:["PDF: ",e.jsx("span",{className:"font-medium text-foreground",children:n.cost.description||n.subcategory})]}),e.jsx("span",{className:"text-muted-foreground",children:"â"}),e.jsxs(Tr,{children:[e.jsx(Or,{asChild:!0,children:e.jsxs(b,{variant:"outline",size:"sm",className:"h-7 gap-1",children:[e.jsxs("span",{children:[n.cost.category,"/",n.subcategory]}),e.jsx(ri,{className:"h-3 w-3"})]})}),e.jsx(Fr,{className:"w-56 p-2",align:"start",children:e.jsxs("div",{className:"space-y-1",children:[e.jsx("p",{className:"text-xs text-muted-foreground mb-2",children:"ZmÄnit subkategorii:"}),[...new Set(I.map(Y=>
85Y.target_subcategory).filter(Boolean))].map(Y=>e.jsx(b,{variant:Y===n.subcategory?"secondary":"ghost",size:"sm",className:"w-full justify-start h-7 text-xs",onClick:()=>f(n.cost.id,Y),children:Y},Y))]})})]})]}),n.cost.source==="pdf_import"&&e.jsx(Q,{variant:"secondary",className:"text-xs",children:"PDF"})]})}),n.items.length===0?e.jsx("div",{className:"text-center py-4 text-muted-foreground",children:"Žádné detailnà položky"}):e.jsxs($e,{children:[e.jsx(Be,{children:e.jsxs(Ne,{children:[e.jsx(D,{children:"Datum"}),e.jsx(D,{children:"Popis"}),e.jsx(D,{children:"Dodavatel"}),e.jsx(D,{children:"Ä. faktury"}),e.jsx(D,{className:"text-right",children:"Äástka"}),e.jsx(D,{className:"w-20",children:"Akce"})]})}),e.jsx(Ue,{children:n.items.map(Y=>e.jsxs(Ne,{children:[e.jsx(_,{className:"font-mono text-sm",children:Y.item_date?hs(new Date(Y.item_date),"dd.MM.yyyy"):"-"}),e.jsx(_,{className:"max-w-[200px] truncate",title:Y.description,children:Y.description}),e.jsx(_,{children:Y.vendor||"-"}),e.jsx(_,{children:Y.invoice_number||"-"}),e.jsx(_,{className:"text-right font-semibold",children:F(Y.amount)}),e.jsx(_,{children:e.jsxs("div",{className:"flex gap-1",children:[e.jsx(b,{variant:"ghost",size:"icon",onClick:()=>ie(Y),children:e.jsx(Kt,{className:"h-4 w-4"})}),e.jsx(b,{variant:"ghost",size:"icon",onClick:()=>Z(Y.id),children:e.jsx(qe,{className:"h-4 w-4 text-destructive"})})]})})]},Y.id))})]})]})]},n.subcategory)})})]}),e.jsx(Ge,{open:o,onOpenChange:v,children:e.jsxs(Je,{children:[e.jsx(Ye,{children:e.jsx(Qe,{children:"Upravit položku"})}),w&&e.jsxs("div",{className:"space-y-4",children:[e.jsxs("div",{children:[e.jsx("label",{className:"text-sm font-medium",children:"Popis"}),e.jsx(se,{value:w.description,onChange:n=>M({...w,description:n.target.value})})]}),e.jsxs("div",{children:[e.jsx("label",{className:"text-sm font-medium",children:"Dodavatel"}),e.jsx(se,{value:w.vendor||"",onChange:n=>M({...w,vendor:n.target.value})})]}),e.jsxs("div",{className:"grid grid-cols-2 gap-4",children:[e.jsxs("div",{children:[e.jsx("label",{className:"text-sm font-medium",children:"Datum"}),e.jsx(se,{type:"date",value:w.item_date||"",onChange:n=>M({...w,item_date:n.target.value})})]}),e.jsxs("div",{children:[e.jsx("label",{className:"text-sm font-medium",children:"Äástka (â¬)"}),e.jsx(se,{type:"number",step:"0.01",value:w.amount,onChange:n=>M({...w,amount:parseFloat(n.target.value)})})]})]}),e.jsxs("div",{children:[e.jsx("label",{className:"text-sm font-medium",children:"Ä. faktury"}),e.jsx(se,{value:w.invoice_number||"",onChange:n=>M({...w,invoice_number:n.target.value})})]})]}),e.jsxs(ls,{children:[e.jsx(b,{variant:"outline",onClick:()=>v(!1),children:"ZruÅ¡it"}),e.jsxs(b,{onClick:W,children:[e.jsx(Ds,{className:"h-4 w-4 mr-2"}),"Uložit"]})]})]})}),e.jsx(Ge,{open:m,onOpenChange:$,children:e.jsxs(Je,{children:[e.jsx(Ye,{children:e.jsx(Qe,{children:"Nová položka nákladů"})}),e.jsxs("div",{className:"space-y-4",children:[e.jsxs("div",{children:[e.jsx("label",{className:"text-sm font-medium",children:"Kategorie *"}),e.jsxs(De,{value:c.house_cost_id,onValueChange:n=>d({...c,house_cost_id:n}),children:[e.jsx(Pe,{children:e.jsx(Ae,{placeholder:"Vyberte kategorii"})}),e.jsx(Ee,{children:P.map(n=>e.jsxs(me,{value:n.id,children:[n.subcategory||n.category," - ",n.description]},n.id))})]})]}),e.jsxs("div",{children:[e.jsx("label",{className:"text-sm font-medium",children:"Popis *"}),e.jsx(se,{value:c.description,onChange:n=>d({...c,description:n.target.value}),placeholder:"Zadejte popis položky"})]}),e.jsxs("div",{children:[e.jsx("label",{className:"text-sm font-medium",children:"Dodavatel"}),e.jsx(se,{value:c.vendor,onChange:n=>d({...c,vendor:n.target.value}),placeholder:"Název dodavatele"})]}),e.jsxs("div",{className:"grid grid-cols-2 gap-4",children:[e.jsxs("div",{children:[e.jsx("label",{className:"text-sm font-medium",children:"Datum"}),e.jsx(se,{type:"date",value:c.item_date,onChange:n=>d({...c,item_date:n.target.value})})]}),e.jsxs("div",{children:[e.jsx("label",{className:"text-sm font-medium",children:"Äástka (â¬) *"}),e.jsx(se,{type:"number",step:"0.01",value:c.amount||"",onChange:n=>d({...c,amount:parseFloat(n.target.value)||0}),placeholder:"0.00"})]})]}),e.jsxs("div",{children:[e.jsx("label",{className:"text-sm font-medium",children:"Ä. faktury"}),e.jsx(se,{value:c.invoice_number,onChange:n=>d({...c,invoice_number:n.target.value}),placeholder:"ÄÃslo faktury"})]})]}),e.jsxs(ls,{children:[e.jsx(b,{variant:"outline",onClick:()=>$(!1),children:"ZruÅ¡it"}),e.jsxs(b,{onClick:K,children:[e.jsx(Xe,{className:"h-4 w-4 mr-2"}),"VytvoÅit"]})]})]})})]})};kn.workerSrc="https://cdnjs.cloudflare.com/ajax/libs/pdf.js/4.4.168/pdf.worker.min.mjs";const Nt=[{value:"areas",label:"Oblasti"},{value:"subcategories",label:"Podkategorie"},{value:"descriptions",label:"Popisy"}],Vi=()=>{const{toast:s}=Re(),a=ws(),[i,y]=t.useState("upload"),[E,P]=t.useState("pending"),[x,O]=t.useState("all"),[S,N]=t.useState(new Set),[j,w]=t.useState(null),[M,o]=t.useState(!1),[v,u]=t.useState(!1),[p,m]=t.useState(!1),[$,H]=t.useState(0),[J,z]=t.useState(""),[h,I]=t.useState("descriptions"),{data:k,isLoading:c}=ds({queryKey:["translation-drafts",E,x],queryFn:async()=>{let l=g.from("translation_drafts").select("*").order("created_at",{ascending:!1});E!=="all"&&(l=l.eq("status",E)),x!=="all"&&(l=l.eq("section",x));const{data:U,error:n}=await l;if(n)throw n;return U}}),d=async l=>{const U=await l.arrayBuffer(),n=await Cn({data:U}).promise;let G="";const Y=n.numPages;for(let pe=1;pe<=Y;pe++){const xe=(await(await n.getPage(pe)).getTextContent()).items.map(de=>de.str).join(" ");G+=xe+` 86 87`,H(pe/Y*50)}return G},T=ns({mutationFn:async({text:l,fileName:U})=>{const{data:n,error:G}=await g.functions.invoke("extract-terms-dual",{body:{text:l,fileName:U,section:h}});if(G)throw G;return n.count},onSuccess:l=>{a.invalidateQueries({queryKey:["translation-drafts"]}),s({title:"Extrakce dokonÄena",description:`Extrahováno ${l} termÃnů k validaci.`}),y("review"),z(""),H(0)},onError:l=>{s({variant:"destructive",title:"Chyba",description:l.message||"NepodaÅilo se extrahovat termÃny."})}}),r=ns({mutationFn:async({id:l,data:U})=>{const{error:n}=await g.from("translation_drafts").update(U).eq("id",l);if(n)throw n},onSuccess:()=>{a.invalidateQueries({queryKey:["translation-drafts"]}),s({title:"PÅeklad aktualizován"}),o(!1),w(null)}}),f=ns({mutationFn:async l=>{const U=(k==null?void 0:k.filter(Y=>l.includes(Y.id)))||[],n=[];for(const Y of U)Y.czech_translation&&n.push({section:Y.section,language:"cs",key:Y.german_term,value:Y.czech_translation}),Y.english_translation&&n.push({section:Y.section,language:"en",key:Y.german_term,value:Y.english_translation});if(n.length>0){const{error:Y}=await g.from("translations").upsert(n,{onConflict:"section,language,key"});if(Y)throw Y}const{error:G}=await g.from("translation_drafts").update({status:"approved",approved_at:new Date().toISOString()}).in("id",l);if(G)throw G;return n.length},onSuccess:l=>{tt(),a.invalidateQueries({queryKey:["translation-drafts"]}),a.invalidateQueries({queryKey:["translations"]}),a.invalidateQueries({queryKey:["database-translations"]}),s({title:"PÅeklady schváleny",description:`PÅidáno ${l} pÅekladů do slovnÃku.`}),N(new Set)}}),R=ns({mutationFn:async l=>{const{error:U}=await g.from("translation_drafts").update({status:"rejected"}).in("id",l);if(U)throw U},onSuccess:()=>{a.invalidateQueries({queryKey:["translation-drafts"]}),s({title:"PÅeklady zamÃtnuty"}),N(new Set)}}),F=ns({mutationFn:async l=>{const{error:U}=await g.from("translation_drafts").delete().in("id",l);if(U)throw U},onSuccess:()=>{a.invalidateQueries({queryKey:["translation-drafts"]}),s({title:"Záznamy smazány"}),N(new Set)}}),ce=async l=>{var n;const U=(n=l.target.files)==null?void 0:n[0];if(U){if(U.type!=="application/pdf"){s({variant:"destructive",title:"Neplatný formát",description:"Nahrajte prosÃm PDF soubor."});return}u(!0),m(!1),H(0),z(U.name);try{const G=await d(U);u(!1),m(!0),H(50),await T.mutateAsync({text:G,fileName:U.name})}catch(G){console.error("PDF processing error:",G),s({variant:"destructive",title:"Chyba pÅi zpracovánà PDF",description:"NepodaÅilo se extrahovat text z PDF."})}finally{u(!1),m(!1)}}},ie=l=>{const U=new Set(S);U.has(l)?U.delete(l):U.add(l),N(U)},W=()=>{S.size===(k==null?void 0:k.length)?N(new Set):N(new Set((k==null?void 0:k.map(l=>l.id))||[]))},Z=l=>
87{switch(l){case"pending":return e.jsxs(Q,{variant:"outline",className:"gap-1",children:[e.jsx(at,{className:"h-3 w-3"})," Äeká"]});case"approved":return e.jsxs(Q,{variant:"default",className:"gap-1 bg-green-600",children:[e.jsx(ps,{className:"h-3 w-3"})," Schváleno"]});case"rejected":return e.jsxs(Q,{variant:"destructive",className:"gap-1",children:[e.jsx(js,{className:"h-3 w-3"})," ZamÃtnuto"]})}},K={total:(k==null?void 0:k.length)||0,pending:(k==null?void 0:k.filter(l=>l.status==="pending").length)||0,approved:(k==null?void 0:k.filter(l=>l.status==="approved").length)||0,rejected:(k==null?void 0:k.filter(l=>l.status==="rejected").length)||0};return e.jsxs("div",{className:"space-y-6",children:[e.jsxs("div",{className:"grid grid-cols-2 md:grid-cols-4 gap-4",children:[e.jsx(ee,{children:e.jsxs(ye,{className:"pb-2",children:[e.jsx(Le,{children:"Celkem"}),e.jsx(be,{className:"text-2xl",children:K.total})]})}),e.jsx(ee,{children:e.jsxs(ye,{className:"pb-2",children:[e.jsxs(Le,{className:"flex items-center gap-1",children:[e.jsx(at,{className:"h-3 w-3"})," K validaci"]}),e.jsx(be,{className:"text-2xl text-orange-600",children:K.pending})]})}),e.jsx(ee,{children:e.jsxs(ye,{className:"pb-2",children:[e.jsxs(Le,{className:"flex items-center gap-1",children:[e.jsx(ps,{className:"h-3 w-3"})," Schváleno"]}),e.jsx(be,{className:"text-2xl text-green-600",children:K.approved})]})}),e.jsx(ee,{children:e.jsxs(ye,{className:"pb-2",children:[e.jsxs(Le,{className:"flex items-center gap-1",children:[e.jsx(js,{className:"h-3 w-3"})," ZamÃtnuto"]}),e.jsx(be,{className:"text-2xl text-red-600",children:K.rejected})]})})]}),e.jsxs(ee,{children:[e.jsxs(ye,{children:[e.jsxs(be,{className:"flex items-center gap-2",children:[e.jsx(_s,{className:"h-5 w-5"}),"Extrakce pÅekladů z PDF"]}),e.jsx(Le,{children:"Nahrajte PDF výpisy, AI extrahuje nÄmecké termÃny a pÅeložà je. Pak je můžete zkontrolovat a schválit."})]}),e.jsx(ae,{children:e.jsxs(ks,{value:i,onValueChange:l=>y(l),children:[e.jsxs(Cs,{className:"grid w-full grid-cols-2 mb-6",children:[e.jsxs(We,{value:"upload",className:"gap-2",children:[e.jsx(Ps,{className:"h-4 w-4"}),"Nahrát PDF"]}),e.jsxs(We,{value:"review",className:"gap-2",children:[e.jsx(jt,{className:"h-4 w-4"}),"Validovat pÅeklady",K.pending>0&&e.jsx(Q,{variant:"secondary",className:"ml-1",children:K.pending})]})]}),e.jsx(es,{value:"upload",children:e.jsxs("div",{className:"space-y-4",children:[e.jsxs("div",{className:"space-y-2",children:[e.jsx(q,{children:"Výchozà sekce pro extrahované termÃny"}),e.jsxs(De,{value:h,onValueChange:l=>I(l),children:[e.jsx(Pe,{className:"w-[200px]",children:e.jsx(Ae,{})}),e.jsx(Ee,{children:Nt.map(l=>e.jsx(me,{value:l.value,children:l.label},l.value))})]})]}),e.jsx("input",{type:"file",accept:".pdf",onChange:ce,className:"hidden",id:"pdf-upload",disabled:v||p}),e.jsx("label",{htmlFor:"pdf-upload",className:`block border-2 border-dashed rounded-lg p-12 text-center cursor-pointer transition-colors ${v||p?"border-muted cursor-not-allowed opacity-50":"border-muted-foreground/25 hover:border-primary/50"}`,children:v||p?e.jsxs("div",{className:"space-y-4",children:[e.jsx(fe,{className:"h-12 w-12 mx-auto animate-spin text-primary"}),e.jsxs("div",{children:[e.jsx("p",{className:"font-medium",children:v?"NaÄÃtám text z PDF...":"AI extrahuje a pÅekládá termÃny..."}),e.jsx("p",{className:"text-sm text-muted-foreground",children:J})]}),e.jsx(Bt,{value:$,className:"max-w-xs mx-auto"})]}):e.jsxs(e.Fragment,{children:[e.jsx(Ps,{className:"h-12 w-12 mx-auto mb-4 text-muted-foreground"}),e.jsx("p",{className:"font-medium text-lg",children:"Nahrát PDF výpis"}),e.jsx("p",{className:"text-sm text-muted-foreground mt-1",children:"KliknÄte nebo pÅetáhnÄte PDF soubor"}),e.jsx("p",{className:"text-xs text-muted-foreground mt-4",children:"AI automaticky extrahuje nÄmecké termÃny a pÅeložà je do ÄeÅ¡tiny i angliÄtiny"})]})})]})}),e.jsx(es,{value:"review",children:e.jsxs("div",{className:"space-y-4",children:[e.jsxs("div",{className:"flex flex-wrap gap-4 justify-between items-center",children:[e.jsxs("div",{className:"flex gap-2",children:[e.jsxs(De,{value:E,onValueChange:l=>P(l),children:[e.jsx(Pe,{className:"w-[140px]",children:e.jsx(Ae,{placeholder:"Status"})}),e.jsxs(Ee,{children:[e.jsx(me,{value:"all",children:"VÅ¡echny"}),e.jsx(me,{value:"pending",children:"K validaci"}),e.jsx(me,{value:"approved",children:"Schválené"}),e.jsx(me,{value:"rejected",children:"ZamÃtnuté"})]})]}),e.jsxs(De,{value:x,onValueChange:l=>O(l),children:[e.jsx(Pe,{className:"w-[160px]",children:e.jsx(Ae,{placeholder:"Sekce"})}),e.jsxs(Ee,{children:[e.jsx(me,{value:"all",children:"VÅ¡echny sekce"}),Nt.map(l=>e.jsx(me,{value:l.value,children:l.label},l.value))]})]})]}),S.size>0&&e.jsxs("div",{className:"flex gap-2",children:[e.jsxs(b,{size:"sm",onClick:()=>f.mutate(Array.from(S)),disabled:f.isPending,className:"bg-green-600 hover:bg-green-700",children:[f.isPending?e.jsx(fe,{className:"h-4 w-4 mr-2 animate-spin"}):e.jsx(jt,{className:"h-4 w-4 mr-2"}),"Schválit (",S.size,")"]}),e.jsxs(b,{size:"sm",variant:"outline",onClick:()=>R.mutate(Array.from(S)),disabled:R.isPending,children:[e.jsx(Wt,{className:"h-4 w-4 mr-2"}),"ZamÃtnout"]}),e.jsxs(b,{size:"sm",variant:"destructive",onClick:()=>F.mutate(Array.from(S)),disabled:F.isPending,children:[e.jsx(qe,{className:"h-4 w-4 mr-2"}),"Smazat"]})]})]}),c?e.jsx("div",{className:"flex justify-center py-12",children:e.jsx(fe,{className:"h-8 w-8 animate-spin text-primary"})}):e.jsx(bt,{className:"h-[500px]",children:e.jsxs($e,{children:[e.jsx(Be,{children:e.jsxs(Ne,{children:[e.jsx(D,{className:"w-[40px]",children:e.jsx(xs,{checked:S.size===(k==null?void 0:k.length)&&k.length>0,onCheckedChange:W})}),e.jsx(D,{children:"NÄmecký termÃn"}),e.jsx(D,{children:"ð¨ð¿ ÄeÅ¡tina"}),e.jsx(D,{children:"ð¬ð§ AngliÄtina"}),e.jsx(D,{children:"Sekce"}),e.jsx(D,{children:"Status"}),e.jsx(D,{children:"Zdroj"}),e.jsx(D,{className:"w-[80px]",children:"Akce"})]})}),e.jsx(Ue,{children:(k==null?void 0:k.length)===0?e.jsx(Ne,{children:e.jsx(_,{colSpan:8,className:"text-center py-8 text-muted-foreground",children:"Žádné pÅeklady k zobrazenÃ. Nahrajte PDF pro extrakci termÃnů."})}):k==null?void 0:k.map(l=>{var U;return e.jsxs(Ne,{className:S.has(l.id)?"bg-muted/50":"",children:[e.jsx(_,{children:e.jsx(xs,{checked:S.has(l.id),onCheckedChange:()=>ie(l.id)})}),e.jsx(_,{className:"font-mono text-sm font-medium",children:l.german_term}),e.jsx(_,{className:"max-w-[200px]",children:e.jsx("span",{className:l.czech_translation?"":"text-muted-foreground italic",children:l.czech_translation||"ChybÃ"})}),e.jsx(_,{className:"max-w-[200px]",children:e.jsx("span",{className:l.english_translation?"":"text-muted-foreground italic",children:l.english_translation||"Missing"})}),e.jsx(_,{children:e.jsx(Q,{variant:"outline",className:"text-xs",children:((U=Nt.find(n=>n.value===l.section))==null?void 0:U.label)||l.section})}),e.jsx(_,{children:Z(l.status)}),e.jsx(_,{className:"text-xs text-muted-foreground truncate max-w-[100px]",children:l.source_file||"-"}),e.jsx(_,{children:e.jsx(b,{variant:"ghost",size:"icon",onClick:()=>{w(l),o(!0)},children:e.jsx(Kt,{className:"h-4 w-4"})})})]},l.id)})})]})})]})})]})})]}),e.jsx(Ge,{open:M,onOpenChange:o,children:e.jsxs(Je,{children:[e.jsxs(Ye,{children:[e.jsx(Qe,{children:"Upravit pÅeklad"}),e.jsxs(us,{children:['Upravte pÅeklady pro termÃn "',j==null?void 0:j.german_term,'"']})]}),j&&e.jsxs("div",{className:"space-y-4 py-4",children:[e.jsxs("div",{className:"space-y-2",children:[e.jsx(q,{children:"NÄmecký termÃn"}),e.jsx(se,{value:j.german_term,disabled:!0,className:"font-mono"})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(q,{children:"ð¨ð¿ Äeský pÅeklad"}),e.jsx(se,{value:j.czech_translation||"",onChange:l=>w({...j,czech_translation:l.target.value})})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(q,{children:"ð¬ð§ Anglický pÅeklad"}),e.jsx(se,{value:j.english_translation||"",onChange:l=>w({...j,english_translation:l.target.value})})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(q,{children:"Sekce"}),e.jsxs(De,{value:j.section,onValueChange:l=>w({...j,section:l}),children:[e.jsx(Pe,{children:e.jsx(Ae,{})}),e.jsx(Ee,{children:Nt.map(l=>e.jsx(me,{value:l.value,children:l.label},l.value))})]})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(q,{children:"Poznámky"}),e.jsx(vs,{value:j.notes||"",onChange:l=>w({...j,notes:l.target.value}),placeholder:"Volitelné poznámky..."})]})]}),e.jsxs(ls,{children:[e.jsx(b,{variant:"outline",onClick:()=>o(!1),children:"ZruÅ¡it"}),e.jsxs(b,{onClick:()=>j&&r.mutate({id:j.id,data:{czech_translation:j.czech_translation,english_translation:j.english_translation,section:j.section,notes:j.notes}}),disabled:r.isPending,children:[r.isPending&&e.jsx(fe,{className:"h-4 w-4 mr-2 animate-spin"}),"Uložit"]})]})]})})]})},ya=[{value:"folder",label:"Složka",Icon:va},{value:"users",label:"Uživatelé",Icon:Fs},{value:"droplets",label:"Kapky",Icon:Mr},{value:"route",label:"Cesta",Icon:Lr},{value:"piggy-bank",label:"Prasátko",Icon:Rr},{value:"flame",label:"Plamen",Icon:ft},{value:"building-2",label:"Budova",Icon:rt},{value:"trees",label:"Stromy",Icon:ci},{value:"waves",label:"Vlny",Icon:mi},{value:"wrench",label:"KlÃÄ",Icon:Fn},{value:"arrow-up-down",label:"Å ipky",Icon:Is},{value:"clipboard-list",label:"Seznam",Icon:Pn},{value:"zap",label:"Blesk",Icon:Mn},{value:"receipt",label:"ÃÄtenka",Icon:An},{value:"shield",label:"Å tÃt",Icon:As}],Za=[{value:"#3b82f6",label:"Modrá"},{value:"#22c55e",label:"Zelená"},{value:"#f59e0b",label:"Oranžová"},{value:"#10b981",label:"Smaragdová"},{value:"#ef4444",label:"Äervená"},{value:"#64748b",label:"Å edá"},{value:"#06b6d4",label:"Tyrkysová"},{value:"#82ca9d",label:"SvÄtle zelená"},{value:"#6366f1",label:"Indigo"},{value:"#ffc658",label:"Žlutá"},{value:"#f97316",label:"TmavÄ oranžová"},{value:"#8884d8",label:"Fialová"},{value:"#8b5cf6",label:"SvÄtle fialová"}],$n=s=>{if(!s)return va;const a=ya.find(i=>i.value===s);return(a==null?void 0:a.Icon)||va},Bn=({category:s,depth:a,onEdit:i,onDelete:y,onToggleActive:E,expandedIds:P,toggleExpanded:x})=>{const O=s.children&&s.children.length>0,S=P.has(s.id),N=$n(s.icon);return e.jsxs(e.Fragment,{children:[e.jsxs("div",{className:`flex items-center gap-2 py-3 px-4 border-b hover:bg-muted/50 transition-colors ${a>0?"bg-muted/20":""}`,style:{paddingLeft:`${16+a*24}px`},children:[e.jsx("div",{className:"w-6 flex-shrink-0",children:O?e.jsx(b,{variant:"ghost",size:"icon",className:"h-6 w-6",onClick:()=>x(s.id),children:S?e.jsx(Js,{className:"h-4 w-4"}):e.jsx(Ts,{className:"h-4 w-4"})}):e.jsx("div",{className:"h-6 w-6"})}
87),e.jsx(Rn,{className:"h-4 w-4 text-muted-foreground/50 cursor-grab"}),e.jsx("div",{className:"w-3 h-3 rounded-full flex-shrink-0",style:{backgroundColor:s.color||"#64748b"}}),e.jsx(N,{className:"h-4 w-4 text-muted-foreground"}),e.jsx("span",{className:`font-medium flex-1 ${s.is_active?"":"text-muted-foreground line-through"}`,children:s.name}),e.jsxs(Q,{variant:"outline",className:"text-xs",children:["L",s.level]}),s.is_link_only&&e.jsxs(Q,{variant:"secondary",className:"text-xs gap-1",children:[e.jsx(Ys,{className:"h-3 w-3"}),"Odkaz"]}),e.jsx(ss,{checked:s.is_active||!1,onCheckedChange:()=>E(s),className:"scale-75"}),e.jsxs("div",{className:"flex gap-1",children:[e.jsx(b,{variant:"ghost",size:"icon",className:"h-8 w-8",onClick:()=>i(s),children:e.jsx(Ns,{className:"h-4 w-4"})}),e.jsx(b,{variant:"ghost",size:"icon",className:"h-8 w-8 text-destructive hover:text-destructive",onClick:()=>y(s),children:e.jsx(qe,{className:"h-4 w-4"})})]})]}),O&&S&&s.children.map(j=>e.jsx(Bn,{category:j,depth:a+1,onEdit:i,onDelete:y,onToggleActive:E,expandedIds:P,toggleExpanded:x},j.id))]})},Ha={name:"",name_de:"",name_en:"",parent_id:"",color:"#64748b",icon:"folder",sort_order:0,is_active:!0,has_detail:!0,is_link_only:!1,link_url:""};function $i(){var r,f;const{data:s,flatData:a,isLoading:i}=Sn(),y=nr(),E=rr(),P=ir(),[x,O]=t.useState(new Set),[S,N]=t.useState(!1),[j,w]=t.useState(!1),[M,o]=t.useState(null),[v,u]=t.useState(null),[p,m]=t.useState(Ha),$=R=>{O(F=>{const ce=new Set(F);return ce.has(R)?ce.delete(R):ce.add(R),ce})},H=()=>{a&&O(new Set(a.map(R=>R.id)))},J=()=>{O(new Set)},z=()=>{o(null),m(Ha),N(!0)},h=R=>{o(R),m({name:R.name,name_de:R.name_de||"",name_en:R.name_en||"",parent_id:R.parent_id||"",color:R.color||"#64748b",icon:R.icon||"folder",sort_order:R.sort_order||0,is_active:R.is_active??!0,has_detail:R.has_detail??!0,is_link_only:R.is_link_only??!1,link_url:R.link_url||""}),N(!0)},I=R=>{u(R),w(!0)},k=async R=>{try{await E.mutateAsync({id:R.id,is_active:!R.is_active}),ts.success(`Kategorie "${R.name}" ${R.is_active?"deaktivována":"aktivována"}`)}catch{ts.error("Chyba pÅi zmÄnÄ stavu kategorie")}},c=async()=>{if(!p.name.trim()){ts.error("Název kategorie je povinný");return}const R={name:p.name.trim(),name_de:p.name_de.trim()||void 0,name_en:p.name_en.trim()||void 0,parent_id:p.parent_id||null,level:p.parent_id?2:1,color:p.color,icon:p.icon,sort_order:p.sort_order,is_active:p.is_active,has_detail:p.has_detail,is_link_only:p.is_link_only,link_url:p.is_link_only?p.link_url:void 0};try{M?(await E.mutateAsync({id:M.id,...R}),ts.success("Kategorie byla aktualizována")):(await y.mutateAsync(R),ts.success("Kategorie byla vytvoÅena")),N(!1)}catch{ts.error("Chyba pÅi ukládánà kategorie")}},d=async()=>{if(v)try{await P.mutateAsync(v.id),ts.success(`Kategorie "${v.name}" byla smazána`),w(!1),u(null)}catch{ts.error("Chyba pÅi mazánà kategorie. Možná obsahuje podkategorie.")}},T=(a==null?void 0:a.filter(R=>R.level===1&&!R.is_link_only))||[];return i?e.jsx("div",{className:"flex items-center justify-center h-64",children:e.jsx(fe,{className:"h-8 w-8 animate-spin text-muted-foreground"})}):e.jsxs("div",{className:"space-y-6",children:[e.jsxs(ee,{children:[e.jsxs(ye,{className:"flex flex-row items-center justify-between",children:[e.jsx(be,{children:"Správa kategorià nákladů"}),e.jsxs("div",{className:"flex gap-2",children:[e.jsx(b,{variant:"outline",size:"sm",onClick:H,children:"Rozbalit vÅ¡e"}),e.jsx(b,{variant:"outline",size:"sm",onClick:J,children:"Sbalit vÅ¡e"}),e.jsxs(b,{onClick:z,size:"sm",children:[e.jsx(Xe,{className:"h-4 w-4 mr-1"}),"PÅidat kategorii"]})]})]}),e.jsx(ae,{className:"p-0",children:e.jsxs("div",{className:"border rounded-lg overflow-hidden",children:[e.jsxs("div",{className:"flex items-center gap-2 py-2 px-4 bg-muted/50 border-b text-sm font-medium text-muted-foreground",children:[e.jsx("div",{className:"w-6"}),e.jsx("div",{className:"w-4"}),e.jsx("div",{className:"w-3"}),e.jsx("div",{className:"w-4"}),e.jsx("div",{className:"flex-1",children:"Název"}),e.jsx("div",{className:"w-12",children:"ÃroveÅ"}),e.jsx("div",{className:"w-16",children:"Typ"}),e.jsx("div",{className:"w-12",children:"AktivnÃ"}),e.jsx("div",{className:"w-20",children:"Akce"})]}),s==null?void 0:s.map(R=>e.jsx(Bn,{category:R,depth:0,onEdit:h,onDelete:I,onToggleActive:k,expandedIds:x,toggleExpanded:$},R.id)),(!s||s.length===0)&&e.jsx("div",{className:"py-8 text-center text-muted-foreground",children:'Žádné kategorie. KliknÄte na "PÅidat kategorii" pro vytvoÅenà prvnÃ.'})]})})]}),e.jsx(Ge,{open:S,onOpenChange:N,children:e.jsxs(Je,{className:"sm:max-w-[500px]",children:[e.jsx(Ye,{children:e.jsx(Qe,{children:M?"Upravit kategorii":"Nová kategorie"})}),e.jsxs("div",{className:"grid gap-4 py-4",children:[e.jsxs("div",{className:"grid gap-2",children:[e.jsx(q,{htmlFor:"name",children:"Název (CZ) *"}),e.jsx(se,{id:"name",value:p.name,onChange:R=>m(F=>({...F,name:R.target.value})),placeholder:"NapÅ. Bazén"})]}),e.jsxs("div",{className:"grid grid-cols-2 gap-4",children:[e.jsxs("div",{className:"grid gap-2",children:[e.jsx(q,{htmlFor:"name_de",children:"Název (DE)"}),e.jsx(se,{id:"name_de",value:p.name_de,onChange:R=>m(F=>({...F,name_de:R.target.value})),placeholder:"Schwimmbad"})]}),e.jsxs("div",{className:"grid gap-2",children:[e.jsx(q,{htmlFor:"name_en",children:"Název (EN)"}),e.jsx(se,{id:"name_en",value:p.name_en,onChange:R=>m(F=>({...F,name_en:R.target.value})),placeholder:"Swimming Pool"})]})]}),e.jsxs("div",{className:"grid gap-2",children:[e.jsx(q,{children:"NadÅazená kategorie"}),e.jsxs(De,{value:p.parent_id||"none",onValueChange:R=>m(F=>({...F,parent_id:R==="none"?"":R})),children:[e.jsx(Pe,{children:e.jsx(Ae,{placeholder:"Žádná (1. úroveÅ)"})}),e.jsxs(Ee,{children:[e.jsx(me,{value:"none",children:"Žádná (1. úroveÅ)"}),T.map(R=>e.jsx(me,{value:R.id,children:R.name},R.id))]})]})]}),e.jsxs("div",{className:"grid grid-cols-2 gap-4",children:[e.jsxs("div",{className:"grid gap-2",children:[e.jsx(q,{children:"Barva"}),e.jsxs(De,{value:p.color,onValueChange:R=>m(F=>({...F,color:R})),children:[e.jsx(Pe,{children:e.jsx(Ae,{children:e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx("div",{className:"w-4 h-4 rounded-full",style:{backgroundColor:p.color}}),((r=Za.find(R=>R.value===p.color))==null?void 0:r.label)||p.color]})})}),e.jsx(Ee,{children:Za.map(R=>e.jsx(me,{value:R.value,children:e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx("div",{className:"w-4 h-4 rounded-full",style:{backgroundColor:R.value}}),R.label]})},R.value))})]})]}),e.jsxs("div",{className:"grid gap-2",children:[e.jsx(q,{children:"Ikona"}),e.jsxs(De,{value:p.icon,onValueChange:R=>m(F=>({...F,icon:R})),children:[e.jsx(Pe,{children:e.jsx(Ae,{children:e.jsxs("div",{className:"flex items-center gap-2",children:[(()=>{const R=$n(p.icon);return e.jsx(R,{className:"h-4 w-4"})})(),((f=ya.find(R=>R.value===p.icon))==null?void 0:f.label)||p.icon]})})}),e.jsx(Ee,{children:ya.map(R=>e.jsx(me,{value:R.value,children:e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(R.Icon,{className:"h-4 w-4"}),R.label]})},R.value))})]})]})]}),e.jsxs("div",{className:"grid gap-2",children:[e.jsx(q,{htmlFor:"sort_order",children:"PoÅadà ÅazenÃ"}),e.jsx(se,{id:"sort_order",type:"number",value:p.sort_order,onChange:R=>m(F=>({...F,sort_order:parseInt(R.target.value)||0}))})]}),e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsx(q,{htmlFor:"is_active",children:"AktivnÃ"}),e.jsx(ss,{id:"is_active",checked:p.is_active,onCheckedChange:R=>m(F=>({...F,is_active:R}))})]}),e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsx(q,{htmlFor:"is_link_only",children:"Pouze odkaz (bez detailu)"}),e.jsx(ss,{id:"is_link_only",checked:p.is_link_only,onCheckedChange:R=>m(F=>
87({...F,is_link_only:R,has_detail:!R}))})]}),p.is_link_only&&e.jsxs("div",{className:"grid gap-2",children:[e.jsx(q,{htmlFor:"link_url",children:"URL odkazu"}),e.jsx(se,{id:"link_url",value:p.link_url,onChange:R=>m(F=>({...F,link_url:R.target.value})),placeholder:"/owners/costs/heating"})]})]}),e.jsxs(ls,{children:[e.jsx(b,{variant:"outline",onClick:()=>N(!1),children:"ZruÅ¡it"}),e.jsxs(b,{onClick:c,disabled:y.isPending||E.isPending,children:[(y.isPending||E.isPending)&&e.jsx(fe,{className:"h-4 w-4 mr-2 animate-spin"}),M?"Uložit zmÄny":"VytvoÅit"]})]})]})}),e.jsx(ms,{open:j,onOpenChange:w,title:"Smazat kategorii?",description:`Opravdu chcete smazat kategorii "${v==null?void 0:v.name}"? Pokud má podkategorie, musÃte je nejprve smazat.`,confirmText:"Smazat",onConfirm:d,variant:"destructive"})]})}const Wa={cs:{title:"Správa dat nákladů",subtitle:"PÅehled a správa importovaných dat podle roků",loading:"NaÄÃtánà dat...",refresh:"Obnovit",year:"Rok",houseCosts:"Domovnà náklady",houseCostItems:"Detailnà položky",apartmentHeating:"Topenà bytů",heatingCosts:"Agregované topenÃ",reserveFund:"Fond oprav",extractedItems:"Extrahované položky",pdfImported:"Z PDF",manualEntered:"ManuálnÃ",total:"Celkem",items:"položek",deleteYear:"Smazat rok",exportYear:"Exportovat CSV",confirmDelete:"Potvrdit smazánÃ",deleteWarning:"Tato akce je nevratná! Vyberte data ke smazánÃ:",selectAll:"Vybrat vÅ¡e",cancel:"ZruÅ¡it",delete:"Smazat vybraná data",deleting:"MazánÃ...",deleteSuccess:"Data byla úspÄÅ¡nÄ smazána",deleteError:"Chyba pÅi mazánà dat",noData:"Žádná data k zobrazenÃ",goToImport:"PÅejÃt na import",deleteAllYears:"Smazat vÅ¡echna data",deleteAllWarning:"Tato akce smaže VÅ ECHNA data za vÅ¡echny roky. Je to nevratné!",deleteAllConfirm:"Opravdu smazat vÅ¡echna data?",reimportAll:"Hromadný reimport",reimportDesc:"Smazat vÅ¡echna data a pÅejÃt na PDF Import",allYears:"vÅ¡echny roky",exportAll:"Exportovat vÅ¡e"},de:{title:"Datenverwaltung",subtitle:"Ãbersicht und Verwaltung der importierten Daten nach Jahr",loading:"Daten werden geladen...",refresh:"Aktualisieren",year:"Jahr",houseCosts:"Hauskosten",houseCostItems:"Detailpositionen",apartmentHeating:"Wohnungsheizung",heatingCosts:"Gesamtheizung",reserveFund:"Rücklagen",extractedItems:"Extrahierte Elemente",pdfImported:"Aus PDF",manualEntered:"Manuell",total:"Gesamt",items:"Elemente",deleteYear:"Jahr löschen",exportYear:"CSV exportieren",confirmDelete:"Löschen bestätigen",deleteWarning:"Diese Aktion kann nicht rückgängig gemacht werden! Wählen Sie zu löschende Daten:",selectAll:"Alle auswählen",cancel:"Abbrechen",delete:"Ausgewählte Daten löschen",deleting:"Wird gelöscht...",deleteSuccess:"Daten erfolgreich gelöscht",deleteError:"Fehler beim Löschen der Daten",noData:"Keine Daten verfügbar",goToImport:"Zum Import",deleteAllYears:"Alle Daten löschen",deleteAllWarning:"Diese Aktion löscht ALLE Daten für alle Jahre. Dies kann nicht rückgängig gemacht werden!",deleteAllConfirm:"Wirklic
87h alle Daten löschen?",reimportAll:"Massen-Reimport",reimportDesc:"Alle Daten löschen und zum PDF-Import wechseln",allYears:"alle Jahre",exportAll:"Alles exportieren"},en:{title:"Data Management",subtitle:"Overview and management of imported data by year",loading:"Loading data...",refresh:"Refresh",year:"Year",houseCosts:"House Costs",houseCostItems:"Detail Items",apartmentHeating:"Apartment Heating",heatingCosts:"Aggregate Heating",reserveFund:"Reserve Fund",extractedItems:"Extracted Items",pdfImported:"From PDF",manualEntered:"Manual",total:"Total",items:"items",deleteYear:"Delete Year",exportYear:"Export CSV",confirmDelete:"Confirm Delete",deleteWarning:"This action cannot be undone! Select data to delete:",selectAll:"Select all",cancel:"Cancel",delete:"Delete selected data",deleting:"Deleting...",deleteSuccess:"Data deleted successfully",deleteError:"Error deleting data",noData:"No data to display",goToImport:"Go to Import",deleteAllYears:"Delete all data",deleteAllWarning:"This action will delete ALL data for all years. This cannot be undone!",deleteAllConfirm:"Really delete all data?",reimportAll:"Mass Reimport",reimportDesc:"Delete all data and go to PDF Import",allYears:"all years",exportAll:"Export All"}},Bi=()=>{const{language:s}=Zs(),a=Ks(),i=Wa[s]||Wa.cs,[y,E]=t.useState([]),[P,x]=t.useState(!0),[O,S]=t.useState(!1),[N,j]=t.useState(!1),[w,M]=t.useState(null),[o,v]=t.useState(!1),[u,p]=t.useState({houseCosts:!0,houseCostItems:!0,apartmentHeating:!0,heatingCosts:!0,reserveFund:!0,extractedItems:!0}),m=async()=>{var r,f,R,F;x(!0);try{const[ce,ie,W,Z]=await Promise.all([g.from("house_costs").select("year, amount, source"),g.from("apartment_heating_costs").select("year, total_gross_eur"),g.from("reserve_fund_expenditures").select("year, amount"),g.from("extracted_cost_items").select("year")]),K=new Set;(r=ce.data)==null||r.forEach(n=>n.year&&K.add(n.year)),(f=ie.data)==null||f.forEach(n=>n.year&&K.add(n.year)),(R=W.data)==null||R.forEach(n=>n.year&&K.add(n.year)),(F=Z.data)==null||F.forEach(n=>n.year&&K.add(n.year));const l=Array.from(K).sort((n,G)=>G-n),U=await Promise.all(l.map(async n=>{var re,A,ne,le;const G=((re=ce.data)==null?void 0:re.filter(oe=>oe.year===n))||[],Y=G.filter(oe=>oe.source==="pdf_import").length,pe=G.filter(oe=>oe.source!=="pdf_import").length,{count:B}=await g.from("house_cost_items").select("id",{count:"exact",head:!0}).in("house_cost_id",G.map(oe=>oe.id).filter(Boolean)),te=((A=ie.data)==null?void 0:A.filter(oe=>oe.year===n))||[],{data:xe}=await g.from("heating_costs").select("id").eq("year",n).limit(1),de=((ne=W.data)==null?void 0:ne.filter(oe=>oe.year===n))||[],L=((le=Z.data)==null?void 0:le.filter(oe=>oe.year===n))||[];return{year:n,houseCostsCount:G.length,houseCostsTotal:G.reduce((oe,ke)=>oe+(ke.amount||0),0),houseCostItemsCount:B||0,apartmentHeatingCount:te.length,apartmentHeatingTotal:te.reduce((oe,ke)=>oe+(ke.total_gross_eur||0),0),heatingCostsExists:((xe==null?void 0:xe.length)||0)>0,reserveFundCount:de.length,reserveFundTotal:de.reduce((oe,ke)=>oe+(ke.amount||0),0),extractedItemsCount:L.length,pdfImported:Y,manualEntered:pe}}));E(U)}catch(ce){console.error("Error fetching year data:",ce),ts.error("Chyba pÅi naÄÃtánà dat")}finally{x(!1)}};t.useEffect(()=>{m()},[]);const $=r=>{M(r),p({houseCosts:!0,houseCostItems:!0,apartmentHeating:!0,heatingCosts:!0,reserveFund:!0,extractedItems:!0}),S(!0)},H=async()=>{if(w){v(!0);try{const r=[];if(u.houseCostItems||u.houseCosts){const{data:f}=await g.from("house_costs").select("id").eq("year",w);if(f&&f.length>0){const{error:R}=await g.from("house_cost_items").delete().in("house_cost_id",f.map(F=>F.id));R&&r.push(`house_cost_items: ${R.message}`)}}if(u.houseCosts){const{error:f}=await g.from("house_costs").delete().eq("year",w);f&&r.push(`house_costs: ${f.message}`)}if(u.apartmentHeating){const{error:f}=await g.from("apartment_heating_costs").delete().eq("year",w);f&&r.push(`apartment_heating_costs: ${f.message}`)}if(u.heatingCosts){const{error:f}=await g.from("heating_costs").delete().eq("year",w);f&&r.push(`heating_costs: ${f.message}`)}if(u.reserveFund){const{error:f}=await g.from("reserve_fund_expenditures").delete().eq("year",w);f&&r.push(`reserve_fund_expenditures: ${f.message}`)}if(u.extractedItems){const{error:f}=await g.from("extracted_cost_items").delete().eq("year",w);f&&r.push(`extracted_cost_items: ${f.message}`)}r.length>0?ts.error(`${i.deleteError}: ${r.join(", ")}`):(ts.success(i.deleteSuccess),S(!1),m())}catch(r){console.error("Delete error:",r),ts.error(i.deleteError)}finally{v(!1)}}},J=async r=>{try{const[f,R,F,ce]=await Promise.all([g.from("house_costs").select("*").eq("year",r),g.from("house_cost_items").select("*, house_costs!inner(year)").eq("house_costs.year",r),g.from("apartment_heating_costs").select("*").eq("year",r),g.from("reserve_fund_expenditures").select("*").eq("year",r)]),ie=new Date().toISOString().slice(0,10);if(f.data&&f.data.length>0){const W=k(f.data);c(W,`house_costs_${r}_${ie}.csv`)}if(F.data&&F.data.length>0){const W=k(F.data);
87c(W,`apartment_heating_${r}_${ie}.csv`)}if(ce.data&&ce.data.length>0){const W=k(ce.data);c(W,`reserve_fund_${r}_${ie}.csv`)}ts.success(`Export pro rok ${r} dokonÄen`)}catch(f){console.error("Export error:",f),ts.error("Chyba pÅi exportu")}},z=async()=>{for(const r of y)await J(r.year);ts.success("Export vÅ¡ech roků dokonÄen")},h=async()=>{v(!0);try{const r=[],{error:f}=await g.from("house_cost_items").delete().neq("id","00000000-0000-0000-0000-000000000000");f&&r.push(`house_cost_items: ${f.message}`);const{error:R}=await g.from("house_costs").delete().neq("id","00000000-0000-0000-0000-000000000000");R&&r.push(`house_costs: ${R.message}`);const{error:F}=await g.from("apartment_heating_costs").delete().neq("id","00000000-0000-0000-0000-000000000000");F&&r.push(`apartment_heating_costs: ${F.message}`);const{error:ce}=await g.from("heating_costs").delete().neq("id","00000000-0000-0000-0000-000000000000");ce&&r.push(`heating_costs: ${ce.message}`);const{error:ie}=await g.from("reserve_fund_expenditures").delete().neq("id","00000000-0000-0000-0000-000000000000");ie&&r.push(`reserve_fund_expenditures: ${ie.message}`);const{error:W}=await g.from("extracted_cost_items").delete().neq("id","00000000-0000-0000-0000-000000000000");W&&r.push(`extracted_cost_items: ${W.message}`);const{error:Z}=await g.from("pdf_documents").update({status:"extracted",imported_at:null,imported_by:null}).eq("status","imported");Z&&r.push(`pdf_documents: ${Z.message}`),r.length>0?ts.error(`${i.deleteError}: ${r.join(", ")}`):(ts.success(i.deleteSuccess),j(!1),m())}catch(r){console.error("Delete all error:",r),ts.error(i.deleteError)}finally{v(!1)}},I=async()=>{await h(),a("/admin/pdf-import")},k=r=>{if(r.length===0)return"";const f=Object.keys(r[0]),R=[f.join(";")];for(const F of r){const ce=f.map(ie=>{const W=F[ie];return W==null?"":typeof W=="string"?`"${W.replace(/"/g,'""')}"`:String(W)});R.push(ce.join(";"))}return"\uFEFF"+R.join(` 88`)},c=(r,f)=>{const R=new Blob([r],{type:"text/csv;charset=utf-8;"}),F=URL.createObjectURL(R),ce=document.createElement("a");ce.href=F,ce.download=f,document.body.appendChild(ce),ce.click(),document.body.removeChild(ce),URL.revokeObjectURL(F)},d=r=>new Intl.NumberFormat("de-DE",{style:"currency",currency:"EUR",maximumFractionDigits:0}).format(r),T=()=>{p({houseCosts:!0,houseCostItems:!0,apartmentHeating:!0,heatingCosts:!0,reserveFund:!0,extractedItems:!0})};return P?e.jsxs("div",{className:"flex items-center justify-center py-12",children:[e.jsx(fe,{className:"h-8 w-8 animate-spin text-primary"}),e.jsx("span",{className:"ml-2",children:i.loading})]}):e.jsxs("div",{className:"space-y-6",children:[e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsxs("div",{children:[e.jsx("h2",{className:"text-2xl font-bold",children:i.title}),e.jsx("p",{className:"text-muted-foreground",children:i.subtitle})]}),e.jsxs("div",{className:"flex gap-2",children:[e.jsxs(b,{variant:"outline",onClick:m,children:[e.jsx(Es,{className:"h-4 w-4 mr-2"}),i.refresh]}),y.length>0&&e.jsxs(e.Fragment,{children:[e.jsxs(b,{variant:"outline",onClick:z,children:[e.jsx(vt,{className:"h-4 w-4 mr-2"}),i.exportAll]}),e.jsxs(b,{variant:"destructive",onClick:()=>j(!0),children:[e.jsx(qe,{className:"h-4 w-4 mr-2"}),i.deleteAllYears]})]})]})]}),y.length>0&&e.jsx(ee,{className:"border-orange-200 bg-orange-50/50",children:e.jsx(ye,{className:"pb-3",children:e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsxs("div",{className:"flex items-center gap-3",children:[e.jsx(Es,{className:"h-5 w-5 text-orange-600"}),e.jsxs("div",{children:[e.jsx(be,{className:"text-lg text-orange-900",children:i.reimportAll}),e.jsx(Le,{className:"text-orange-700",children:i.reimportDesc})]})]}),e.jsxs(b,{variant:"outline",className:"border-orange-300 text-orange-700 hover:bg-orange-100",onClick:I,children:[e.jsx(Ps,{className:"h-4 w-4 mr-2"}),i.reimportAll]})]})})}),y.length===0?e.jsx(ee,{children:e.jsxs(ae,{className:"py-12 text-center",children:[e.jsx(_s,{className:"h-12 w-12 mx-auto text-muted-foreground mb-4"}),e.jsx("p",{className:"text-muted-foreground",children:i.noData})]})}):e.jsx("div",{className:"grid gap-4",children:y.map(r=>e.jsxs(ee,{children:[e.jsx(ye,{className:"pb-3",children:e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsxs("div",{className:"flex items-center gap-3",children:[e.jsx(Qt,{className:"h-5 w-5 text-primary"}),e.jsx(be,{className:"text-xl",children:r.year}),e.jsxs("div",{className:"flex gap-2",children:[r.pdfImported>0&&e.jsxs(Q,{variant:"secondary",className:"bg-blue-100 text-blue-700",children:[e.jsx(Ps,{className:"h-3 w-3 mr-1"}),r.pdfImported," ",i.pdfImported]}),r.manualEntered>0&&e.jsxs(Q,{variant:"outline",children:[r.manualEntered," ",i.manualEntered]})]})]}),e.jsxs("div",{className:"flex gap-2",children:[e.jsxs(b,{variant:"outline",size:"sm",onClick:()=>J(r.year),children:[e.jsx(vt,{className:"h-4 w-4 mr-1"}),i.exportYear]}),e.jsxs(b,{variant:"destructive",size:"sm",onClick:()=>$(r.year),children:[e.jsx(qe,{className:"h-4 w-4 mr-1"}),i.deleteYear]})]})]})}),e.jsx(ae,{children:e.jsxs("div",{className:"grid grid-cols-2 md:grid-cols-4 lg:grid-cols-6 gap-4",children:[e.jsxs("div",{className:"space-y-1",children:[e.jsxs("div",{className:"flex items-center gap-2 text-sm text-muted-foreground",children:[e.jsx(Jt,{className:"h-4 w-4"}),i.houseCosts]}),e.jsx("p",{className:"text-lg font-semibold",children:r.houseCostsCount}),e.jsx("p",{className:"text-sm text-muted-foreground",children:d(r.houseCostsTotal)})]}),e.jsxs("div",{className:"space-y-1",children:[e.jsxs("div",{className:"flex items-center gap-2 text-sm text-muted-foreground",children:[e.jsx(_s,{className:"h-4 w-4"}),i.houseCostItems]}),e.jsx("p",{className:"text-lg font-semibold",children:r.houseCostItemsCount})]}),e.jsxs("div",{className:"space-y-1",children:[e.jsxs("div",{className:"flex items-center gap-2 text-sm text-muted-foreground",children:[e.jsx(ft,{className:"h-4 w-4"}),i.apartmentHeating]}),e.jsx("p",{className:"text-lg font-semibold",children:r.apartmentHeatingCount}),e.jsx("p",{className:"text-sm text-muted-foreground",children:d(r.apartmentHeatingTotal)})]}),e.jsxs("div",{className:"space-y-1",children:[e.jsxs("div",{className:"flex items-center gap-2 text-sm text-muted-foreground",children:[e.jsx(ft,{className:"h-4 w-4"}),i.heatingCosts]}),e.jsx("p",{className:"text-lg font-semibold",children:r.heatingCostsExists?e.jsx(ps,{className:"h-5 w-5 text-green-500"}):"-"})]}),e.jsxs("div",{className:"space-y-1",children:[e.jsxs("div",{className:"flex items-center gap-2 text-sm text-muted-foreground",children:[e.jsx(At,{className:"h-4 w-4"}),i.reserveFund]}),e.jsx("p",{className:"text-lg font-semibold",children:r.reserveFundCount}),e.jsx("p",{className:"text-sm text-muted-foreground",children:d(r.reserveFundTotal)})]}),e.jsxs("div",{className:"space-y-1",children:[e.jsxs("div",{className:"flex items-center gap-2 text-sm text-muted-foreground",children:[e.jsx(_s,{className:"h-4 w-4"}),i.extractedItems]}),e.jsx("p",{className:"text-lg font-semibold",children:r.extractedItemsCount})]})]})})]},r.year))}),e.jsx(Ge,{open:O,onOpenChange:S,children:e.jsxs(Je,{children:[e.jsxs(Ye,{children:[e.jsxs(Qe,{className:"flex items-center gap-2",children:[e.jsx(is,{className:"h-5 w-5 text-destructive"}),i.confirmDelete," - ",w]}),e.jsx(us,{children:i.deleteWarning})]}),e.jsxs("div",{className:"space-y-4 py-4",children:[e.jsx(b,{variant:"outline",size:"sm",onClick:T,className:"mb-2",children:i.selectAll}),e.jsxs("div",{className:"space-y-3",children:[e.jsxs("div",{className:"flex items-center space-x-2",children:[e.jsx(xs,{id:"houseCosts",checked:u.houseCosts,onCheckedChange:r=>p(f=>({...f,houseCosts:!!r}))}),e.jsx(q,{htmlFor:"houseCosts",children:i.houseCosts})]}),e.jsxs("div",{className:"flex items-center space-x-2",children:[e.jsx(xs,{id:"houseCostItems",checked:u.houseCostItems,onCheckedChange:r=>p(f=>({...f,houseCostItems:!!r}))}),e.jsx(q,{htmlFor:"houseCostItems",children:i.houseCostItems})]}),e.jsxs("div",{className:"flex items-center space-x-2",children:[e.jsx(xs,{id:"apartmentHeating",checked:u.apartmentHeating,onCheckedChange:r=>p(f=>({...f,apartmentHeating:!!r}))}),e.jsx(q,{htmlFor:"apartmentHeating",children:i.apartmentHeating})]}),e.jsxs("div",{className:"flex items-center space-x-2",children:[e.jsx(xs,{id:"heatingCosts",checked:u.heatingCosts,onCheckedChange:r=>p(f=>({...f,heatingCosts:!!r}))}),e.jsx(q,{htmlFor:"heatingCosts",children:i.heatingCosts})]}),e.jsxs("div",{className:"flex items-center space-x-2",children:[e.jsx(xs,{id:"reserveFund",checked:u.reserveFund,onCheckedChange:r=>p(f=>({...f,reserveFund:!!r}))}),e.jsx(q,{htmlFor:"reserveFund",children:i.reserveFund})]}),e.jsxs("div",{className:"flex items-center space-x-2",children:[e.jsx(xs,{id:"extractedItems",checked:u.extractedItems,onCheckedChange:r=>p(f=>({...f,extractedItems:!!r}))}),e.jsx(q,{htmlFor:"extractedItems",children:i.extractedItems})]})]})]}),e.jsxs(it,{variant:"destructive",children:[e.jsx(is,{className:"h-4 w-4"}),e.jsx(qt,{children:"VarovánÃ"}),e.jsx(lt,{children:"Tato akce je nevratná. PÅed smazánÃm doporuÄujeme exportovat data jako zálohu."})]}),e.jsxs(ls,{children:[e.jsx(b,{variant:"outline",onClick:()=>S(!1),children:i.cancel}),e.jsx(b,{variant:"destructive",onClick:H,disabled:o||!Object.values(u).some(r=>r),children:o?e.jsxs(e.Fragment,{children:[e.jsx(fe,{className:"h-4 w-4 mr-2 animate-spin"}),i.deleting]}):e.jsxs(e.Fragment,{children:[e.jsx(qe,{className:"h-4 w-4 mr-2"}),i.delete]})})]})]})}),e.jsx(Ge,{open:N,onOpenChange:j,children:e.jsxs(Je,{children:[e.jsxs(Ye,{children:[e.jsxs(Qe,{className:"flex items-center gap-2",children:[e.jsx(is,{className:"h-5 w-5 text-destructive"}),i.deleteAllConfirm]}),e.jsx(us,{children:i.deleteAllWarning})]}),e.jsx("div",{className:"py-4",children:e.jsxs(it,{variant:"destructive",children:[e.jsx(is,{className:"h-4 w-4"}),e.jsx(qt,{children:i.confirmDelete}),e.jsxs(lt,{children:[y.length," ",i.allYears,": ",y.map(r=>
88r.year).join(", ")]})]})}),e.jsxs(ls,{children:[e.jsx(b,{variant:"outline",onClick:()=>j(!1),children:i.cancel}),e.jsx(b,{variant:"destructive",onClick:h,disabled:o,children:o?e.jsxs(e.Fragment,{children:[e.jsx(fe,{className:"h-4 w-4 mr-2 animate-spin"}),i.deleting]}):e.jsxs(e.Fragment,{children:[e.jsx(qe,{className:"h-4 w-4 mr-2"}),i.deleteAllYears]})})]})]})})]})},Ui=`You are extracting financial data from an Altmann & Partner document (Austrian property management). 89 90DOCUMENT STRUCTURE: 91- Hierarchical categories (e.g., "Betriebskosten > Wasser > Wassergebühren") 92- Usually has "Einnahmen" (income) and "Ausgaben" (expenses) sections 93- Categories can have subcategories with nested amounts 94- Total amounts at category level and document level 95 96EXTRACTION RULES: 971. Extract EVERY line item with an amount (positive or negative) 982. Preserve the EXACT German category names as source_category 993. Build source_hierarchy array showing full path (e.g., ["Betriebskosten", "Wasser", "Wassergebühren"]) 1004. Mark is_income = true for items in "Einnahmen" sections or with: 101 - "Erlöse", "Erträge", "Einnahmen", "Guthaben", "Miete", "Pacht" 102 - Positive amounts where convention shows income 1035. Mark is_income = false for expense items in "Ausgaben" sections 1046. DO NOT translate - keep original German text 105 106OUTPUT JSON: 107{ 108 "document_type": "betriebskosten", 109 "document_format": "altmann", 110 "year": 2021, 111 "items": [ 112 { 113 "source_category": "Wasser", 114 "source_text": "Wassergebühren Gemeinde", 115 "source_hierarchy": ["Betriebskosten", "Wasser"], 116 "amount": 1234.56, 117 "unit": null, 118 "vendor": null, 119 "item_date": null, 120 "is_income": false 121 } 122 ], 123 "validation": { 124 "items_total": 45000.00, 125 "document_total": 45000.00, 126 "match": true 127 } 128} 129 130CRITICAL: 131- Extract ALL items, even if you're unsure about the category 132- source_category = immediate parent category from document 133- items_total = sum of amounts where is_income=false MINUS sum where is_income=true 134- document_total = "Gesamtausgaben" or similar total from document 135- match = true if |items_total - document_total| < 1⬠136- Output ONLY valid JSON`,qi=`You are extracting financial data from a Black Point document (Austrian property management). 137 138DOCUMENT STRUCTURE: 139- Table format with columns: Datum | Beleg | Vertragspartner | Text | Betrag 140- "Vertragspartner" column contains vendor names 141- Dates in format like "06/24" meaning June 2024 142- Categories as section headers 143 144EXTRACTION RULES: 1451. Extract EVERY line item with an amount
1462. Preserve the EXACT German category/section names as source_category 1473. Extract vendor from "Vertragspartner" column 1484. Parse dates: "06/24" â "2024-06-01", "Jan 24" â "2024-01-01" 1495. Mark is_income = true for items in income sections or with income indicators 1506. DO NOT translate - keep original German text 151 152OUTPUT JSON: 153{ 154 "document_type": "betriebskosten", 155 "document_format": "blackpoint", 156 "year": 2024, 157 "items": [ 158 { 159 "source_category": "Versicherung", 160 "source_text": "Gebäudeversicherung Prämie", 161 "source_hierarchy": ["Betriebskosten", "Versicherung"], 162 "amount": 2500.00, 163 "unit": null, 164 "vendor": "Allianz Versicherung", 165 "item_date": "2024-01-15", 166 "is_income": false 167 } 168 ], 169 "validation": { 170 "items_total": 52000.00, 171 "document_total": 52000.00, 172 "match": true 173 } 174} 175 176CRITICAL: 177- ALWAYS extract vendor name from "Vertragspartner" column 178- ALWAYS parse dates to ISO format (YYYY-MM-DD) 179- source_category = section header from document 180- items_total = sum of expense amounts (is_income=false) 181- Output ONLY valid JSON`,Ki=`You are extracting heating cost data from a Techem document (German heating cost service). 182 183DOCUMENT STRUCTURE: 184- Individual apartment breakdowns (Top/Wohnung + Eigentümer) 185- Consumption data (Verbrauchseinheiten, kWh) 186- Heating and warm water costs separated 187- Cost per m² calculations 188 189EXTRACTION RULES: 1901. Extract data for EACH apartment separately 1912. apartment_code = "Top X" or similar apartment identifier 1923. owner_name = name from "Eigentümer" field 1934. Extract consumption_units (Verbrauchseinheiten) 1945. heating_eur = heating cost (Heizung Netto) 1956. warmwater_eur = warm water cost (Warmwasser Netto) 1967. amount = total cost for apartment 1978. All heating items are expenses (is_income = false) 198 199OUTPUT JSON: 200{ 201 "document_type": "heizkosten", 202 "document_format": "techem", 203 "year": 2021, 204 "items": [ 205 { 206 "source_category": "Heizkosten", 207 "source_text": "Wärmekosten Top 1 - Müller", 208 "source_hierarchy": ["Heizkosten", "Top 1"], 209 "amount": 850.00, 210 "unit": "EUR", 211 "vendor": "Techem", 212 "item_date": null, 213 "is_income": false, 214 "apartment_code": "Top 1", 215 "owner_name": "Müller", 216 "consumption_units": 1234.5, 217 "heating_eur": 650.00, 218 "warmwater_eur": 200.00 219 } 220 ], 221 "validation": { 222 "items_total": 12500.00, 223 "document_total": 12500.00, 224 "match": true 225 } 226} 227 228CRITICAL: 229- Extract EVERY apartment's heating data 230- Include consumption data when available 231- Split heating and warm water costs 232- Output ONLY valid JSON`,Ga=[{id:"altmann",name:"Altmann & Partner",description:"Staršà správce - hierarchická struktura kategoriÃ",prompt:Ui,badge:"betriebskosten"},{id:"blackpoint",name:"Black Point",description:"SouÄasný správce - tabulkový formát s dodavateli",prompt:qi,badge:"betriebskosten"},{id:"techem",name:"Techem",description:"VyúÄtovánà tepla - data jednotlivých apartmánů",prompt:Ki,badge:"heizkosten"}],Zi=[{step:1,title:"Krok 1: Äistá extrakce",description:"AI extrahuje surová data z PDF pÅesnÄ jak jsou v dokumentu"},{step:2,title:"Krok 2: Kategorizace",description:"Mapovánà source_category â cÃlové Äeské kategorie pomocà pravidel"},{step:3,title:"Krok 3: Validace",description:"Kontrola souÄtů a kompletnosti pÅed importem"}];function Hi(){const[s,a]=t.useState(null),{toast:i}=Re(),y=async(E,P)=>{try{await navigator.clipboard.writeText(P),a(E),i({title:"ZkopÃrováno",description:"Prompt byl zkopÃrován do schr
232ánky."}),setTimeout(()=>a(null),2e3)}catch{i({variant:"destructive",title:"Chyba",description:"NepodaÅilo se zkopÃrovat prompt."})}};return e.jsxs("div",{className:"space-y-6",children:[e.jsxs(it,{children:[e.jsx(Us,{className:"h-4 w-4"}),e.jsx(lt,{children:"Dvou-krokový pÅÃstup: AI nejprve extrahuje surová data (source_category), pak je párujeme s cÃlovými kategoriemi."})]}),e.jsxs(ee,{children:[e.jsx(ye,{className:"pb-3",children:e.jsx(be,{className:"text-lg",children:"Proces extrakce a kategorizace"})}),e.jsx(ae,{children:e.jsx("div",{className:"flex flex-col md:flex-row gap-4",children:Zi.map((E,P)=>e.jsxs("div",{className:"flex-1 flex items-start gap-3 p-4 rounded-lg border bg-card",children:[e.jsx("div",{className:"flex items-center justify-center h-8 w-8 rounded-full bg-primary text-primary-foreground font-bold text-sm shrink-0",children:E.step}),e.jsxs("div",{children:[e.jsx("div",{className:"font-medium",children:E.title}),e.jsx("p",{className:"text-sm text-muted-foreground mt-1",children:E.description})]})]},E.step))})})]}),e.jsxs(ks,{defaultValue:"altmann",className:"w-full",children:[e.jsx(Cs,{className:"grid w-full grid-cols-3",children:Ga.map(E=>e.jsxs(We,{value:E.id,className:"gap-2",children:[e.jsx(_s,{className:"h-4 w-4"}),E.name]},E.id))}),Ga.map(E=>e.jsx(es,{value:E.id,className:"space-y-4",children:e.jsxs(ee,{children:[e.jsx(ye,{className:"pb-3",children:e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsxs("div",{children:[e.jsxs(be,{className:"flex items-center gap-2 text-lg",children:[e.jsx(si,{className:"h-5 w-5"}),E.name]}),e.jsx(Le,{className:"mt-1",children:E.description})]}),e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(Q,{variant:"outline",children:E.badge}),e.jsx(Q,{variant:"secondary",children:"v3.0"}),e.jsx(b,{variant:"outline",size:"sm",onClick:()=>y(E.id,E.prompt),children:s===E.id?e.jsxs(e.Fragment,{children:[e.jsx(jt,{className:"h-4 w-4 mr-1"}),"ZkopÃrováno"]}):e.jsxs(e.Fragment,{children:[e.jsx(Os,{className:"h-4 w-4 mr-1"}),"KopÃrovat"]})})]})]})}),e.jsx(ae,{children:e.jsx(bt,{className:"h-[400px] rounded-md border bg-muted/30 p-4",children:e.jsx("pre",{className:"text-xs font-mono whitespace-pre-wrap text-foreground",children:E.prompt})})})]})},E.id))]}),e.jsxs(ee,{children:[e.jsx(ye,{className:"pb-3",children:e.jsx(be,{className:"text-lg",children:"Nová datová struktura"})}),e.jsx(ae,{children:e.jsxs("div",{className:"grid grid-cols-1 md:grid-cols-2 gap-4",children:[e.jsxs("div",{className:"p-4 rounded-lg border bg-card",children:[e.jsx("h4",{className:"font-medium mb-2",children:"Nové sloupce v extracted_cost_items"}),e.jsxs("ul",{className:"text-sm space-y-1 text-muted-foreground",children:[e.jsxs("li",{children:["⢠",e.jsx("code",{className:"text-foreground",children:"source_category"})," - původnà kategorie z PDF"]}),e.jsxs("li",{children:["⢠",e.jsx("code",{className:"text-foreground",children:"source_hierarchy"})," - hierarchie kategoriÃ"]}),e.jsxs("li",{children:["⢠",e.jsx("code",{className:"text-foreground",children:"is_income"})," - true pro pÅÃjmy, false pro náklady"]})]})]}),e.jsxs("div",{className:"p-4 rounded-lg border bg-card",children:[e.jsx("h4",{className:"font-medium mb-2",children:"Výhody dvou-krokového pÅÃstupu"}),e.jsxs("ul",{className:"text-sm space-y-1 text-muted-foreground",children:[e.jsx("li",{children:"⢠Originálnà data zachována pro audit"}),e.jsx("li",{children:"⢠Lepšà debugovánà - vidÃme co AI extrahoval"}),e.jsx("li",{children:"⢠FlexibilnÄjšà mapovánà kategoriÃ"}),e.jsx("li",{children:"⢠Automatické filtrovánà pÅÃjmů"})]})]})]})})]})]})}const ra={name:"",category:"",contact_email:"",contact_phone:"",address:"",website:"",notes:"",is_active:!0},Wi=["Ãdržba","Opravy","Energie","PojiÅ¡tÄnÃ","Ãklid","Zahrada","BezpeÄnost","Administrativa","Technické služby","OstatnÃ"],Gi=()=>{const{toast:s}=Re(),a=ws(),[i,y]=t.useState(""),[E,P]=t.useState(!1),[x,O]=t.useState(!1),[S,N]=t.useState(!1),[j,w]=t.useState(null),[M,o]=t.useState(ra),{data:v=[],isLoading:u}=ds({queryKey:["admin-vendors",E],queryFn:async()=>{let h=g.from("vendors").select("*").order("usage_count",{ascending:!1});E||(h=h.eq("is_active",!0));const{data:I,error:k}=await h;if(k)throw k;return I}}),p=ns({mutationFn:async h=>{const I={name:h.name,name_normalized:h.name.toLowerCase().trim(),category:h.category||null,contact_email:h.contact_email||null,contact_phone:h.contact_phone||null,address:h.address||null,website:h.website||null,notes:h.notes||null,is_active:h.is_active};if(h.id){const{error:k}=await g.from("vendors").update(I).eq("id",h.id);if(k)throw k}else{const{error:k}=await g.from("vendors").insert(I);if(k)throw k}},onSuccess:()=>{a.invalidateQueries({queryKey:["admin-vendors"]}
232),O(!1),w(null),o(ra),s({title:j?"Dodavatel upraven":"Dodavatel pÅidán",description:"ZmÄny byly úspÄÅ¡nÄ uloženy."})},onError:h=>{s({variant:"destructive",title:"Chyba",description:`NepodaÅilo se uložit dodavatele: ${h.message}`})}}),m=ns({mutationFn:async h=>{const{error:I}=await g.from("vendors").delete().eq("id",h);if(I)throw I},onSuccess:()=>{a.invalidateQueries({queryKey:["admin-vendors"]}),N(!1),w(null),s({title:"Dodavatel smazán",description:"Dodavatel byl úspÄÅ¡nÄ odstranÄn."})},onError:h=>{s({variant:"destructive",title:"Chyba",description:`NepodaÅilo se smazat dodavatele: ${h.message}`})}}),$=ns({mutationFn:async({id:h,is_active:I})=>{const{error:k}=await g.from("vendors").update({is_active:I}).eq("id",h);if(k)throw k},onSuccess:()=>{a.invalidateQueries({queryKey:["admin-vendors"]}),s({title:"Stav zmÄnÄn",description:"Stav dodavatele byl aktualizován."})},onError:h=>{s({variant:"destructive",title:"Chyba",description:`NepodaÅilo se zmÄnit stav: ${h.message}`})}}),H=h=>{h?(w(h),o({name:h.name,category:h.category||"",contact_email:h.contact_email||"",contact_phone:h.contact_phone||"",address:h.address||"",website:h.website||"",notes:h.notes||"",is_active:h.is_active})):(w(null),o(ra)),O(!0)},J=()=>{if(!M.name.trim()){s({variant:"destructive",title:"Chyba",description:"Název dodavatele je povinný."});return}p.mutate({...M,id:j==null?void 0:j.id})},z=v.filter(h=>{var I,k;return h.name.toLowerCase().includes(i.toLowerCase())||((I=h.category)==null?void 0:I.toLowerCase().includes(i.toLowerCase()))||((k=h.contact_email)==null?void 0:k.toLowerCase().includes(i.toLowerCase()))});return e.jsxs("div",{className:"space-y-6",children:[e.jsxs("div",{className:"flex flex-col sm:flex-row items-start sm:items-center justify-between gap-4",children:[e.jsxs("div",{children:[e.jsxs("h2",{className:"text-xl font-semibold flex items-center gap-2",children:[e.jsx(rt,{className:"h-5 w-5 text-primary"}),"Seznam dodavatelů"]}),e.jsxs("p",{className:"text-sm text-muted-foreground mt-1",children:["Celkem ",v.length," dodavatelů"]})]}),e.jsxs(b,{onClick:()=>H(),children:[e.jsx(Xe,{className:"h-4 w-4 mr-2"}),"PÅidat dodavatele"]})]}),e.jsx(ee,{children:e.jsx(ae,{className:"pt-4",children:e.jsxs("div",{className:"flex flex-col sm:flex-row gap-4",children:[e.jsxs("div",{className:"relative flex-1",children:[e.jsx(fs,{className:"absolute left-3 top-1/2 -translate-y-1/2 h-4 w-4 text-muted-foreground"}),e.jsx(se,{placeholder:"Hledat podle názvu, kategorie, emailu...",value:i,onChange:h=>y(h.target.value),className:"pl-9"})]}),e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(ss,{id:"show-inactive",checked:E,onCheckedChange:P}),e.jsx(q,{htmlFor:"show-inactive",className:"text-sm whitespace-nowrap",children:"Zobrazit neaktivnÃ"})]})]})})}),e.jsx(ee,{children:e.jsx(ae,{className:"p-0",children:u?e.jsx("div",{className:"flex items-center justify-center py-12",children:e.jsx(fe,{className:"h-8 w-8 animate-spin text-primary"})}):z.length===0?e.jsxs("div",{className:"text-center py-12 text-muted-foreground",children:[e.jsx(rt,{className:"h-12 w-12 mx-auto mb-4 opacity-50"}),e.jsx("p",{children:"Žádnà dodavatelé nenalezeni"})]}):e.jsx("div",{className:"overflow-x-auto",children:e.jsxs($e,{children:[e.jsx(Be,{children:e.jsxs(Ne,{children:[e.jsx(D,{children:"Název"}),e.jsx(D,{children:"Kategorie"}),e.jsx(D,{children:"Kontakt"}),e.jsx(D,{className:"text-center",children:"PoužitÃ"}),e.jsx(D,{className:"text-center",children:"Stav"}),e.jsx(D,{className:"text-right",children:"Akce"})]})}),e.jsx(Ue,{children:z.map(h=>e.jsxs(Ne,{className:h.is_active?"":"opacity-60",children:[e.jsxs(_,{children:[e.jsx("div",{className:"font-medium",children:h.name}),h.address&&e.jsxs("div",{className:"text-xs text-muted-foreground flex items-center gap-1 mt-1",children:[e.jsx($t,{className:"h-3 w-3"}),h.address]})]}),e.jsx(_,{children:h.category?e.jsx(Q,{variant:"secondary",children:h.category}):e.jsx("span",{className:"text-muted-foreground",children:"â"})}),e.jsx(_,{children:e.jsxs("div",{className:"space-y-1",children:[h.contact_email&&e.jsxs("div",{className:"text-xs flex items-center gap-1",children:[e.jsx(Bs,{className:"h-3 w-3 text-muted-foreground"}),e.jsx("a",{href:`mailto:${h.contact_email}`,className:"hover:underline",children:h.contact_email})]}),h.contact_phone&&e.jsxs("div",{className:"text-xs flex items-center gap-1",children:[e.jsx(Nn,{className:"h-3 w-3 text-muted-foreground"}),e.jsx("a",{href:`tel:${h.contact_phone}`,className:"hover:underline",children:h.contact_phone})]}),h.website&&e.jsxs("div",{className:"text-xs flex items-center gap-1",children:[e.jsx(wa,{className:"h-3 w-3 text-muted-foreground"}),e.jsx("a",{href:h.website,target:"_blank",rel:"noopener noreferrer",className:"hover:underline",children:"Web"})]}),!h.contact_email&&!h.contact_phone&&!h.website&&e.jsx("span",{className:"text-muted-foreground",children:"â"})]})}),e.jsx(_,{className:"text-center",children:e.jsxs(Q,{variant:"outline",className:"font-mono",children:[h.usage_count,"Ã"]})}),e.jsx(_,{className:"text-center",children:e.jsx(b,{variant:"ghost",size:"sm",onClick:()=>$.mutate({id:h.id,is_active:!h.is_active}),disabled:$.isPending,children:h.is_active?e.jsx(oi,{className:"h-5 w-5 text-green-600"}):e.jsx(li,{className:"h-5 w-5 text-muted-foreground"})})}),e.jsx(_,{className:"text-right",children:e.jsxs("div",{className:"flex items-center justify-end gap-2",children:[e.jsx(b,{variant:"ghost",size:"icon",onClick:()=>H(h),children:e.jsx(Ns,{className:"h-4 w-4"})}),e.jsx(b,{variant:"ghost",size:"icon",onClick:()=>{w(h),N(!0)},disabled:h.usage_count>0,children:e.jsx(qe,{className:"h-4 w-4 text-destructive"})})]})})]}
232,h.id))})]})})})}),e.jsx(Ge,{open:x,onOpenChange:O,children:e.jsxs(Je,{className:"max-w-lg",children:[e.jsxs(Ye,{children:[e.jsx(Qe,{children:j?"Upravit dodavatele":"Nový dodavatel"}),e.jsx(us,{children:j?"Upravte údaje o dodavateli.":"VyplÅte údaje o novém dodavateli."})]}),e.jsxs("div",{className:"space-y-4",children:[e.jsxs("div",{className:"space-y-2",children:[e.jsx(q,{htmlFor:"name",children:"Název *"}),e.jsx(se,{id:"name",value:M.name,onChange:h=>o({...M,name:h.target.value}),placeholder:"Název firmy nebo jméno"})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(q,{htmlFor:"category",children:"Kategorie"}),e.jsxs(De,{value:M.category,onValueChange:h=>o({...M,category:h}),children:[e.jsx(Pe,{children:e.jsx(Ae,{placeholder:"Vyberte kategorii"})}),e.jsx(Ee,{children:Wi.map(h=>e.jsx(me,{value:h,children:h},h))})]})]}),e.jsxs("div",{className:"grid grid-cols-2 gap-4",children:[e.jsxs("div",{className:"space-y-2",children:[e.jsx(q,{htmlFor:"contact_email",children:"Email"}),e.jsx(se,{id:"contact_email",type:"email",value:M.contact_email,onChange:h=>o({...M,contact_email:h.target.value}),placeholder:"[email protected]"})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(q,{htmlFor:"contact_phone",children:"Telefon"}),e.jsx(se,{id:"contact_phone",value:M.contact_phone,onChange:h=>o({...M,contact_phone:h.target.value}),placeholder:"+420 123 456 789"})]})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(q,{htmlFor:"address",children:"Adresa"}),e.jsx(se,{id:"address",value:M.address,onChange:h=>o({...M,address:h.target.value}),placeholder:"Ulice, MÄsto, PSÄ"})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(q,{htmlFor:"website",children:"Web"}),e.jsx(se,{id:"website",value:M.website,onChange:h=>o({...M,website:h.target.value}),placeholder:"https://www.firma.cz"})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(q,{htmlFor:"notes",children:"Poznámky"}),e.jsx(vs,{id:"notes",value:M.notes,onChange:h=>o({...M,notes:h.target.value}),placeholder:"Internà poznámky...",rows:3})]}),e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(ss,{id:"is_active",checked:M.is_active,onCheckedChange:h=>o({...M,is_active:h})}),e.jsx(q,{htmlFor:"is_active",children:"Aktivnà dodavatel"})]})]}),e.jsxs(ls,{children:[e.jsx(b,{variant:"outline",onClick:()=>O(!1),children:"ZruÅ¡it"}),e.jsxs(b,{onClick:J,disabled:p.isPending,children:[p.isPending&&e.jsx(fe,{className:"h-4 w-4 mr-2 animate-spin"}),j?"Uložit zmÄny":"PÅidat"]})]})]})}),e.jsx(It,{open:S,onOpenChange:N,children:e.jsxs(Tt,{children:[e.jsxs(Ot,{children:[e.jsx(Ft,{children:"Smazat dodavatele?"}),e.jsxs(Mt,{children:['Opravdu chcete smazat dodavatele "',j==null?void 0:j.name,'"? Tuto akci nelze vrátit zpÄt.']})]}),e.jsxs(Lt,{children:[e.jsx(Rt,{children:"ZruÅ¡it"}),e.jsxs(Vt,{onClick:()=>j&&m.mutate(j.id),className:"bg-destructive text-destructive-foreground hover:bg-destructive/90",children:[m.isPending&&e.jsx(fe,{className:"h-4 w-4 mr-2 animate-spin"}),"Smazat"]})]})]})})]})},Ji=["fakturierte nettobeträge","fakturierte umsatzsteuer","zwischensumme","abrechnungsergebnis","komprimierte darstellung","nachzahlung","vorauszahlung","saldo per","guthaben per","nettosumme positionen","ust von bemessungsgrundlage","umsatzsteuer von","bemessungsgrundlage","guthaben (brutto)","nachzahlung (brutto)","vorsteuerabzug","vorsteuer aus rücklagenentnahme","umsatzsteuerschuld","summe/differenz","umsatzsteuer 10%","umsatzsteuer 20%","wohnzweck","summe aufwände","summe aufwendungen"];function Yi(s){return(s||"").toLowerCase().normalize("NFD").replace(new RegExp("\\p{Diacritic}","gu"),"").replace(/\s+/g," ").trim()}Ji.map(Yi);const Ja=[{keywords:["lohn","löhne","lohne","gehalt","personal","hausmeister"],target:{targetCategory:"DomovnÃk",targetSubcategory:"Mzdy",itemType:"operating",isRepairFund:!1},confidence:"high"},{keywords:["sozial","lohnabgaben","arbeitgeber"],target:{targetCategory:"DomovnÃk",targetSubcategory:"Odvody",itemType:"operating",isRepairFund:!1},confidence:"high"},{keywords:["trinkwasser","wassergebühr","wasser"],target:{targetCategory:"Voda",targetSubcategory:"Pitná voda",itemType:"operating",isRepairFun
232d:!1},confidence:"high"},{keywords:["kanal","abwasser","kanalgebühr"],target:{targetCategory:"Voda",targetSubcategory:"Kanalizace",itemType:"operating",isRepairFund:!1},confidence:"high"},{keywords:["winterdienst","schnee","räum","winter"],target:{targetCategory:"Cesty",targetSubcategory:"Zimnà údržba",itemType:"operating",isRepairFund:!1},confidence:"high"},{keywords:["wegegemeinschaft","wege","straÃ"],target:{targetCategory:"Cesty",targetSubcategory:"Poplatky",itemType:"operating",isRepairFund:!1},confidence:"medium"},{keywords:["instandhaltung","reparatur","erhaltung","sanierung"],target:{targetCategory:"Fond Oprav",targetSubcategory:"Ãdržba",itemType:"reserve_fund_expense",isRepairFund:!0},confidence:"high"},{keywords:["sonderumlage","einmalzahlung"],target:{targetCategory:"Fond Oprav",targetSubcategory:"MimoÅádné",itemType:"reserve_fund_expense",isRepairFund:!0},confidence:"high"},{keywords:["heizkosten","heizung","wärme","warmwasser","heiztage"],target:{targetCategory:"VytápÄnà a TV",targetSubcategory:null,itemType:"heating_aggregate",isRepairFund:!1},confidence:"high"},{keywords:["auÃenanlagen","garten","grün","pflanz","rasen"],target:{targetCategory:"Provoznà náklady",targetSubcategory:"Venkovnà prostory",itemType:"operating",isRepairFund:!1},confidence:"high"},{keywords:["hallenbad","schwimmbad","pool","becken","sauna"],target:{targetCategory:"Provoznà náklady",targetSubcategory:"Bazén",itemType:"operating",isRepairFund:!1},confidence:"high"},{keywords:["diverser aufwand","reinigung","putz","pflege"],target:{targetCategory:"Provoznà náklady",targetSubcategory:"Ãdržba",itemType:"operating",isRepairFund:!1},confidence:"medium"},{keywords:["aufzug","lift","fahrstuhl"],target:{targetCategory:"Provoznà náklady",targetSubcategory:"Výtah",itemType:"operating",isRepairFund:!1},confidence:"high"},{keywords:["hausverwaltung","verwaltung","buchhalt","admin"],target:{targetCategory:"Provoznà náklady",targetSubcategory:"Správa domu",itemType:"operating",isRepairFund:!1},confidence:"high"},{keywords:["strom","elektr","stiegenhaus","energie"],target:{targetCategory:"Provoznà náklady",targetSubcategory:"Energie",itemType:"operating",isRepairFund:!1},confidence:"high"},{keywords:["müll","abfall","entsorg","gebühr"],target:{targetCategory:"Provoznà náklady",targetSubcategory:"Poplatky",itemType:"operating",isRepairFund:!1},confidence:"high"},{keywords:["versicherung","polizze","police","prämie"],target:{targetCategory:"Provoznà náklady",targetSubcategory:"PojiÅ¡tÄnÃ",itemType:"operating",isRepairFund:!1},confidence:"high"},{keywords:["sonstig","allgemein","divers"],target:{targetCategory:"Provoznà náklady",targetSubcategory:"OstatnÃ",itemType:"operating",isRepairFund:!1},confidence:"low"},{keywords:["betriebskosten gesamt","betriebskostenabrechnung"],target:{targetCategory:"Provoznà náklady",targetSubcategory:"OstatnÃ",itemType:"operating",isRepairFund:!1},confidence:"high",documentFormat:"altmann"},{keywords:["rücklagenvorschreibung","rücklagenzuführung"],target:{targetCategory:"Fond Oprav",targetSubcategory:"PÅÃspÄvky",itemType:"reserve_fund_contribution",isRepairFund:!0},confidence:"high",documentFormat:"altmann"},{keywords:["hausbetreuung","objektbetreuung"],target:{targetCategory:"DomovnÃk",targetSubcategory:"Mzdy",itemType:"operating",isRepairFund:!1},confidence:"high",documentFormat:"altmann"},{keywords:["allgemeine aufwendungen","gemeinsame kosten"],target:{targetCategory:"Provoznà náklady",targetSubcategory:"OstatnÃ",itemType:"operating",isRepairFund:!1},confidence:"medium",documentFormat:"altmann"},{keywords:["beleg","belegdatum","belegnr"],target:{targetCategory:"Provoznà náklady",targetSubcategory:"OstatnÃ",itemType:"operating",isRepairFund:!1},confidence:"low",documentFormat:"blackpoint"},{keywords:["reparaturrücklage","erhaltungsfonds"],target:{targetCategory:"Fond Oprav",targetSubcategory:"Ãdržba",itemType:"reserve_fund_expense",isRepairFund:!0},confidence:"high",documentFormat:"blackpoint"},{keywords:["ev-verwaltung","eigentumsverwaltung"],target:{targetCategory:"Provoznà náklady",targetSubcategory:"Správa domu",itemType:"operating",isRepairFun
232d:!1},confidence:"high",documentFormat:"blackpoint"},{keywords:["wärmekostenabrechnung","wärmekosten"],target:{targetCategory:"VytápÄnà a TV",targetSubcategory:"TopenÃ",itemType:"heating_aggregate",isRepairFund:!1},confidence:"high",documentFormat:"techem"},{keywords:["heizkostenabrechnung","heizkostenverteiler"],target:{targetCategory:"VytápÄnà a TV",targetSubcategory:"TopenÃ",itemType:"heating_apartment",isRepairFund:!1},confidence:"high",documentFormat:"techem"},{keywords:["warmwasserkosten","warmwasserabrechnung"],target:{targetCategory:"VytápÄnà a TV",targetSubcategory:"Teplá voda",itemType:"heating_aggregate",isRepairFund:!1},confidence:"high",documentFormat:"techem"},{keywords:["grundkosten","verbrauchskosten"],target:{targetCategory:"VytápÄnà a TV",targetSubcategory:null,itemType:"heating_aggregate",isRepairFund:!1},confidence:"medium",documentFormat:"techem"},{keywords:["ölkosten","brennstoff","heizöl"],target:{targetCategory:"VytápÄnà a TV",targetSubcategory:"TopenÃ",itemType:"heating_aggregate",isRepairFund:!1},confidence:"high",documentFormat:"techem"}],Qs=[{value:"operating",label:"Provoznà náklady",icon:At,color:"bg-blue-100 text-blue-700 dark:bg-blue-900/30 dark:text-blue-300"},{value:"heating_aggregate",label:"Topenà (agregát)",icon:ft,color:"bg-orange-100 text-orange-700 dark:bg-orange-900/30 dark:text-orange-300"},{value:"heating_apartment",label:"Topenà (per byt)",icon:ft,color:"bg-red-100 text-red-700 dark:bg-red-900/30 dark:text-red-300"},{value:"reserve_fund_contribution",label:"PÅÃspÄvek do RF",icon:At,color:"bg-green-100 text-green-700 dark:bg-green-900/30 dark:text-green-300"},{value:"reserve_fund_expense",label:"Výdaj z RF",icon:At,color:"bg-purple-100 text-purple-700 dark:bg-purple-900/30 dark:text-purple-300"},{value:"translation",label:"Pouze pÅeklad",icon:Xt,color:"bg-gray-100 text-gray-700 dark:bg-gray-900/30 dark:text-gray-300"}],Ya=[{value:"betriebskosten",label:"Provoznà náklady",short:"BK"},{value:"heizkosten",label:"Topné náklady",short:"HK"},{value:"ruecklage",label:"Rezervnà fond",short:"RF"},{value:"other",label:"OstatnÃ",short:"X"}],ct=[{value:"altmann",label:"Altmann & Partner",short:"ALT",color:"bg-blue-100 text-blue-700 dark:bg-blue-900/30 dark:text-blue-300"},{value:"blackpoint",label:"BlackPoint",short:"BP",color:"bg-gray-100 text-gray-700 dark:bg-gray-900/30 dark:text-gray-300"},{value:"techem",label:"Techem",short:"TEC",color:"bg-green-100 text-green-700 dark:bg-green-900/30 dark:text-green-300"}],Qi=()=>{var Fe;const{toast:s}=Re(),{data:a,flatData:i}=Sn(!0),[y,E]=t.useState([]),[P,x]=t.useState([]),[O,S]=t.useState([]),[N,j]=t.useState(!0),[w,M]=t.useState(""),[o,v]=t.useState("all"),[u,p]=t.useState("all"),[m,$]=t.useState(!1),[H,J]=t.useState(null),[z,h]=t.useState(["operating","heating_aggregate","reserve_fund_expense"]);t.useState(["altmann","blackpoint","techem","universal"]);const[I,k]=t.useState("created_at"),[c,d]=t.useState("desc"),[T,r]=t.useState("all"),[f,R]=t.useState(!1),[F,ce]=t.useState(null),[ie,W]=t.useState("all"),[Z,K]=t.useState("all"),[l,U]=t.useState("all"),[n,G]=t.useState(!1),[Y,pe]=t.useState(null),[B,te]=t.useState(!1),[xe,de]=t.useState({source_category:"",target_category:"Provozni_naklady",target_subcategory:"",target_category_id:"",is_repair_fund:!1,item_type:"operating",notes:"",skip_import:!1,skip_reason:"",source_document_type:"betriebskosten",document_format:"",source_aliases:""}),L=async()=>{if(!xe.source_category.trim()){s({variant:"destructive",title:"Chyba",description:"Zadejte nejprve nÄmecký text k pÅekladu."});return}te(!0);try{const{data:C,error:ge}=await g.functions.invoke("translate",{body:{text:xe.source_category,targetLanguage:"cs"}});if(ge)throw ge;C!=null&&C.translatedText&&(de(Te=>({...Te,target_subcategory:C.translatedText})),s({title:"PÅeloženo",description:`"${xe.source_category}" â "${C.translatedText}"`}))}catch(C){console.error("Translation error:",C),s({variant:"destructive",title:"Chyba pÅekladu",description:"NepodaÅilo se pÅeložit text."})}finally{te(!1)}};t.useEffect(()=>{re()},[]);const re=async()=>{j(!0);const[C,ge,Te]=await Promise.all([g.from("category_mappings").select("*").order("source_category"),g.from("cost_categories").select("id, name, level, parent_id").eq("is_active",!0).order("level").order("sort_order"),g.from("extracted_cost_items").select("category").not("category","is",null)]);if(C.error){s({variant:"destructive",title:"Chyba",description:"NepodaÅilo se naÄÃst mapovánÃ."}),j(!1);return}E(C.data||[]),x(ge.data||[]);const Oe=new Set((C.data||[]).map(Se=>Se.source_category.toLowerCase()));if(Te.data){const Se=[...new Set(Te.data.map(we=>we.category))].filter(we=>we&&!Oe.has(we.toLowerCase()));S(Se)}j(!1)},A=C=>{if(C.target_category_id){const Oe=P.find(Se=>Se.id===C.target_category_id);if(Oe){if(Oe.level===1)return{level1:Oe.name,level2:null};const Se=P.find(we=>we.id===Oe.parent_id);return{level1:(Se==null?void 0:Se.name)||null,level2:Oe.name}}}const ge=P.find(Oe=>{var Se;return Oe.level===1&&Oe.name.toLowerCase()===((Se=C.target_subcategory)==null?void 0:Se.toLowerCase())});if(ge)return{level1:ge.name,level2:null};const Te=P.find(Oe=>{var Se;return Oe.level===1&&Oe.name.toLowerCase()===((Se=C.target_category)==null?void 0:Se.toLowerCase())});if(Te){const Oe=C.target_subcategory,Se=Oe&&Oe.length<30&&!P.some(we=>we.name.toLowerCase()===Oe.toLowerCase());return{level1:Te.name,level2:Se?null:Oe}}return{level1:C.target_category,level2:C.target_subcategory}},ne=C=>{var Te;J(C);let ge=C.target_category_id||"";if(!ge&&i){if(C.target_subcategory){const Oe=i.find(Se=>{var we;return Se.name.toLowerCase()===((we=C.target_subcategory)==null?void 0:we.toLowerCase())});Oe&&(ge=Oe.id)}if(!ge&&C.target_category){const Oe=i.find(Se=>{var we;return Se.name.toLowerCase()===((we=C.target_category)==null?void 0:we.toLowerCase())});if(Oe&&(ge=Oe.id),!ge){const Se=i.find(we=>we.level===1&&we.name.toLowerCase().includes(C.target_category.toLowerCase()));Se&&(ge=Se.id)}}}de({source_category:C.source_category,target_category:C.target_category,target_subcategory:C.target_subcategory||"",target_category_id:ge,is_repair_fund:C.is_repair_fund,item_type:C.item_type,notes:C.notes||"",skip_import:C.skip_import||!1,skip_reason:C.skip_reason||"",source_document_type:C.source_document_type||"betriebskosten",document_format:C.document_format||"",source_aliases:((Te=C.source_aliases)==null?void 0:Te.join(", "))||""}),$(!0)},le=C=>{J(null),de({source_category:C||"",target_category:"Provozni_naklady",target_subcategory:C||"",target_category_id:"",is_repair_fund:!1,item_type:"operating",notes:"",skip_import:!1,skip_reason:"",source_document_type:"betriebskosten",document_format:"",source_aliases:""}),$(!0)},oe=(C,ge)=>{var Te,Oe;J(null),de({source_category:C.source_category,target_category:C.target_category,target_subcategory:C.target_subcategory||"",target_category_id:C.target_category_id||"",is_repair_fund:C.is_repair_fund,item_type:C.item_type,notes:`ZkopÃrováno z ${((Te=ct.find(Se=>Se.value===C.document_format))==null?void 0:Te.label)||"UniverzálnÃ"}`,skip_import:C.skip_import||!1,skip_reason:C.skip_reason||"",source_document_type:C.source_document_type||"betriebskosten",document_format:"",source_aliases:((Oe=C.source_aliases)==null?void 0:Oe.join(", "))||""}
232),$(!0),s({title:"KopÃrovánà pravidla",description:"Vyberte cÃlového zpracovatele a upravte pravidlo pÅed uloženÃm."})},ke=async()=>{if(!xe.source_category.trim()){s({variant:"destructive",title:"Chyba",description:"Zdrojová kategorie je povinná."});return}const C=xe.source_aliases.split(",").map(Te=>Te.trim()).filter(Te=>Te.length>0),ge={source_category:xe.source_category.trim(),target_category:xe.target_category,target_subcategory:xe.target_subcategory.trim()||null,target_category_id:xe.target_category_id||null,is_repair_fund:xe.is_repair_fund,item_type:xe.item_type,notes:xe.notes.trim()||null,skip_import:xe.skip_import,skip_reason:xe.skip_reason.trim()||null,source_document_type:xe.source_document_type,document_format:xe.document_format||null,source_aliases:C.length>0?C:null};if(H){const{error:Te}=await g.from("category_mappings").update(ge).eq("id",H.id);if(Te){s({variant:"destructive",title:"Chyba",description:Te.message});return}s({title:"Uloženo",description:"Mapovánà bylo aktualizováno."})}else{const{error:Te}=await g.from("category_mappings").insert(ge);if(Te){Te.code==="23505"?s({variant:"destructive",title:"Chyba",description:"Mapovánà pro tuto zdrojovou kategorii již existuje."}):s({variant:"destructive",title:"Chyba",description:Te.message});return}s({title:"VytvoÅeno",description:"Nové mapovánà bylo pÅidáno."})}$(!1),re()},je=async C=>{if(!confirm("Opravdu chcete smazat toto mapovánÃ?"))return;const{error:ge}=await g.from("category_mappings").delete().eq("id",C);if(ge){s({variant:"destructive",title:"Chyba",description:"NepodaÅilo se smazat mapovánÃ."});return}s({title:"Smazáno",description:"Mapovánà bylo odstranÄno."}),re()},ue=C=>{I===C?d(ge=>ge==="asc"?"desc":"asc"):(k(C),d("asc"))},ve=C=>I!==C?e.jsx(Is,{className:"h-3 w-3 ml-1 text-muted-foreground"}):c==="asc"?e.jsx(Vr,{className:"h-3 w-3 ml-1"}):e.jsx(Ma,{className:"h-3 w-3 ml-1"}),X=t.useMemo(()=>{let C=y;return w&&(C=C.filter(ge=>{var Te;return ge.source_category.toLowerCase().includes(w.toLowerCase())||((Te=ge.target_subcategory)==null?void 0:Te.toLowerCase().includes(w.toLowerCase()))||ge.target_category.toLowerCase().includes(w.toLowerCase())})),o!=="all"&&(C=C.filter(ge=>ge.item_type===o)),u!=="all"&&(C=C.filter(ge=>ge.target_category_id===u)),T!=="all"&&(T==="universal"?C=C.filter(ge=>!ge.document_format):C=C.filter(ge=>ge.document_format===T)),C},[y,w,o,u,T]);t.useMemo(()=>{const C=["altmann","blackpoint","techem","universal"],ge={};
232return C.forEach(Te=>{ge[Te]={},Qs.forEach(Oe=>{let Se=X.filter(we=>(Te==="universal"?!we.document_format:we.document_format===Te)&&we.item_type===Oe.value);Se.sort((we,he)=>{let os=0;switch(I){case"source_category":os=we.source_category.localeCompare(he.source_category);break;case"created_at":os=new Date(we.created_at).getTime()-new Date(he.created_at).getTime();break;case"target_category":const Ss=A(we),zs=A(he);os=(Ss.level1||"").localeCompare(zs.level1||"");break;case"target_subcategory":const ea=A(we).level2||"",qn=A(he).level2||"";os=ea.localeCompare(qn);break;default:os=0}return c==="asc"?os:-os}),Se.length>0&&(ge[Te][Oe.value]=Se)})}),ge},[X,I,c,P]);const Ce=t.useMemo(()=>{const C={};return Qs.forEach(ge=>{let Te=X.filter(Oe=>Oe.item_type===ge.value);Te.sort((Oe,Se)=>{let we=0;switch(I){case"source_category":we=Oe.source_category.localeCompare(Se.source_category);break;case"created_at":we=new Date(Oe.created_at).getTime()-new Date(Se.created_at).getTime();break;case"target_category":const he=A(Oe),os=A(Se);we=(he.level1||"").localeCompare(os.level1||"");break;case"target_subcategory":const Ss=A(Oe).level2||"",zs=A(Se).level2||"";we=Ss.localeCompare(zs);break;default:we=0}return c==="asc"?we:-we}),C[ge.value]=Te}),C},[X,I,c,P]),ze=t.useMemo(()=>({altmann:y.filter(C=>C.document_format==="altmann").length,blackpoint:y.filter(C=>C.document_format==="blackpoint").length,techem:y.filter(C=>C.document_format==="techem").length,universal:y.filter(C=>!C.document_format).length}),[y]),Me=C=>{h(ge=>ge.includes(C)?ge.filter(Te=>Te!==C):[...ge,C])},V=()=>y.filter(C=>{const ge=ie==="all"||C.source_document_type===ie,Te=Z==="all"||C.item_type===Z,Oe=l==="all"||(l==="universal"?!C.document_format:C.document_format===l);return ge&&Te&&Oe}).length,_e=async()=>{G(!0),pe(null);try{const ge=y.filter(Oe=>{const Se=ie==="all"||Oe.source_document_type===ie,we=Z==="all"||Oe.item_type===Z,he=l==="all"||(l==="universal"?!Oe.document_format:Oe.document_format===l);return Se&&we&&he}).map(Oe=>Oe.id);if(ge.length===0){s({title:"Info",description:"Žádná pravidla k smazánÃ."}),G(!1);return}const{error:Te}=await g.from("category_mappings").delete().in("id",ge);if(Te)throw Te;pe({deleted:ge.length,created:0}),s({title:"Hromadné smazánà dokonÄeno",description:`Smazáno ${ge.length} pravidel.`}),re()}catch(C){s({variant:"destructive",title:"Chyba",description:C.message||"NepodaÅilo se smazat pravidla."})}finally{G(!1)}},Ie=async()=>{G(!0),pe(null);try{const ge=y.filter(he=>{const os=ie==="all"||he.source_document_type===ie,Ss=Z==="all"||he.item_type===Z,zs=l==="all"||(l==="universal"?!he.document_format:he.document_format===l);return os&&Ss&&zs}).map(he=>he.id);let Te=0;if(ge.length>0){const{error:he}=await g.from("category_mappings").delete().in("id",ge);if(he)throw he;Te=ge.length}const Oe=Ja.filter(he=>Z!=="all"&&he.target.itemType!==Z?!1:l!=="all"?l==="universal"?!he.documentFormat:he.documentFormat===l||!he.documentFormat:!0).map(he=>({source_category:he.keywords[0],source_aliases:he.keywords.slice(1),target_category:he.target.isRepairFund?"Fond_oprav":"Provozni_naklady",target_subcategory:he.target.targetSubcategory,item_type:he.target.itemType,is_repair_fund:he.target.isRepairFund,source_document_type:ie==="all"?"betriebskosten":ie,document_format:he.documentFormat||(l!=="all"&&l!=="universal"?l:null),notes:`Auto-generováno z KEYWORD_RECOMMENDATIONS (confidence: ${he.confidence}${he.documentFormat?`, format: ${he.documentFormat}`:""})`})),Se=new Set(y.filter(he=>!ge.includes(he.id)).map(he=>he.source_category.toLowerCase())),we=Oe.filter(he=>!Se.has(he.source_category.toLowerCase()));if(we.length>0){const{error:he}=await g.from("category_mappings").insert(we);if(he)throw he}pe({deleted:Te,created:we.length}),s({title:"Regenerovánà dokonÄeno",description:`Smazáno ${Te}, vytvoÅeno ${we.length} nových pravidel.`}),re()}catch(C){s({variant:"destructive",title:"Chyba",description:C.message||"NepodaÅilo se regenerovat pravidla."})}finally{G(!1)}},Ve=C=>{ce(C),W("all"),K("all"),U("all"),pe(null),R(!0)};return N?e.jsx("div",{className:"flex items-center justify-center py-12",children:e.jsx(fe,{className:"h-8 w-8 animate-spin text-primary"})}):e.jsxs("div",{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-semibold",children:"Parsovacà pravidla"}),e.jsx("p",{className:"text-sm text-muted-foreground",children:"Pravidla pro pÅevod kategorià z PDF do aplikace - tÅÃdÄnà dle typu dokumentu"})]}),e.jsxs("div",{className:"flex gap-2",children:[e.jsxs(b,{variant:"outline",onClick:()=>Ve("delete"),children:[e.jsx(qe,{className:"h-4 w-4 mr-2"}),"HromadnÄ smazat"]}),e.jsxs(b,{variant:"outline",onClick:()=>Ve("regenerate"),children:[e.jsx(na,{className:"h-4 w-4 mr-2"}),"Regenerovat"]}),e.jsxs(b,{onClick:()=>le(),children:[e.jsx(Xe,{className:"h-4 w-4 mr-2"}),"Nové pravidlo"]})]})]}),e.jsx("div",{className:"grid grid-cols-2 md:grid-cols-4 lg:grid-cols-6 gap-3",children:Qs.map(C=>{const ge=y.filter(Oe=>Oe.item_type===C.value).length,Te=C.icon;
232return e.jsx(ee,{className:`cursor-pointer transition-all ${o===C.value?"ring-2 ring-primary":"hover:shadow-md"}`,onClick:()=>v(o===C.value?"all":C.value),children:e.jsx(ae,{className:"p-3",children:e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx("div",{className:`p-1.5 rounded ${C.color}`,children:e.jsx(Te,{className:"h-3.5 w-3.5"})}),e.jsxs("div",{children:[e.jsx("div",{className:"text-lg font-bold",children:ge}),e.jsx("div",{className:"text-xs text-muted-foreground truncate",children:C.label})]})]})})},C.value)})}),e.jsxs("div",{className:"grid grid-cols-2 md:grid-cols-4 gap-3",children:[e.jsx(ee,{className:`cursor-pointer transition-all ${T==="altmann"?"ring-2 ring-blue-500":"hover:shadow-md"}`,onClick:()=>r(T==="altmann"?"all":"altmann"),children:e.jsx(ae,{className:"p-3",children:e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(Q,{className:"bg-blue-100 text-blue-700 dark:bg-blue-900/30 dark:text-blue-300",children:"ALT"}),e.jsx("span",{className:"font-medium",children:"Altmann & Partner"})]}),e.jsx("div",{className:"text-lg font-bold",children:ze.altmann})]})})}),e.jsx(ee,{className:`cursor-pointer transition-all ${T==="blackpoint"?"ring-2 ring-gray-500":"hover:shadow-md"}`,onClick:()=>r(T==="blackpoint"?"all":"blackpoint"),children:e.jsx(ae,{className:"p-3",children:e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(Q,{className:"bg-gray-100 text-gray-700 dark:bg-gray-900/30 dark:text-gray-300",children:"BP"}),e.jsx("span",{className:"font-medium",children:"BlackPoint"})]}),e.jsx("div",{className:"text-lg font-bold",children:ze.blackpoint})]})})}),e.jsx(ee,{className:`cursor-pointer transition-all ${T==="techem"?"ring-2 ring-green-500":"hover:shadow-md"}`,onClick:()=>r(T==="techem"?"all":"techem"),children:e.jsx(ae,{className:"p-3",children:e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(Q,{className:"bg-green-100 text-green-700 dark:bg-green-900/30 dark:text-green-300",children:"TEC"}),e.jsx("span",{className:"font-medium",children:"Techem"})]}),e.jsx("div",{className:"text-lg font-bold",children:ze.techem})]})})}),e.jsx(ee,{className:`cursor-pointer transition-all ${T==="universal"?"ring-2 ring-purple-500":"hover:shadow-md"}`,onClick:()=>r(T==="universal"?"all":"universal"),children:e.jsx(ae,{className:"p-3",children:e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(Q,{className:"bg-purple-100 text-purple-700 dark:bg-purple-900/30 dark:text-purple-300",children:"UNI"}),e.jsx("span",{className:"font-medium",children:"UniverzálnÃ"})]}),e.jsx("div",{className:"text-lg font-bold",children:ze.universal})]})})})]}),O.length>0&&e.jsxs(ee,{className:"border-orange-200 bg-orange-50 dark:border-orange-900 dark:bg-orange-950/30",children:[e.jsx(ye,{className:"pb-2",children:e.jsxs(be,{className:"text-base flex items-center gap-2 text-orange-700 dark:text-orange-300",children:[e.jsx(is,{className:"h-5 w-5"}),O.length," nenamapovaných kategoriÃ"]})}),e.jsx(ae,{children:e.jsx("div",{className:"flex flex-wrap gap-2",children:O.map(C=>e.jsxs(Q,{variant:"outline",className:"cursor-pointer hover:bg-orange-100 dark:hover:bg-orange-900/50",onClick:()=>le(C),children:[C,e.jsx(Xe,{className:"h-3 w-3 ml-1"})]},C))})})]}),e.jsxs("div",{className:"flex flex-wrap gap-4 items-center",children:[e.jsxs("div",{className:"relative flex-1 max-w-sm",children:[e.jsx(fs,{className:"absolute left-3 top-1/2 -translate-y-1/2 h-4 w-4 text-muted-foreground"}),e.jsx(se,{placeholder:"Hledat mapovánÃ...",value:w,onChange:C=>M(C.target.value),className:"pl-9"})]}),e.jsxs(De,{value:u,onValueChange:p,children:[e.jsx(Pe,{className:"w-[200px]",children:e.jsx(Ae,{placeholder:"Filtr: Kategorie"})}),e.jsxs(Ee,{children:[e.jsx(me,{value:"all",children:"VÅ¡echny kategorie"}),i==null?void 0:i.filter(C=>C.id).map(C=>e.jsx(me,{value:C.id,children:e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx("div",{className:"w-2 h-2 rounded-full",style:{backgroundColor:C.color||"#64748b"}}),e.jsxs("span",{className:C.level===2?"pl-2":"",children:[C.level===2?"â³ "
232:"",C.name]})]})},C.id))]})]}),(o!=="all"||u!=="all"||T!=="all")&&e.jsxs(b,{variant:"ghost",size:"sm",onClick:()=>{v("all"),p("all"),r("all")},children:[e.jsx(Fa,{className:"h-4 w-4 mr-1"}),"ZruÅ¡it filtry"]}),e.jsxs("div",{className:"text-sm text-muted-foreground",children:["Celkem: ",X.length," pravidel",T!=="all"&&` (filtr: ${T==="universal"?"UniverzálnÃ":((Fe=ct.find(C=>C.value===T))==null?void 0:Fe.label)||T})`]})]}),e.jsx("div",{className:"space-y-4",children:Qs.map(C=>{const ge=Ce[C.value]||[];if(ge.length===0&&o!=="all"&&o!==C.value||ge.length===0&&o==="all")return null;const Te=C.icon,Oe=z.includes(C.value);return e.jsx(ee,{children:e.jsxs(xt,{open:Oe,onOpenChange:()=>Me(C.value),children:[e.jsx(ht,{asChild:!0,children:e.jsx(ye,{className:"cursor-pointer hover:bg-muted/50 transition-colors py-3",children:e.jsx("div",{className:"flex items-center justify-between",children:e.jsxs("div",{className:"flex items-center gap-3",children:[Oe?e.jsx(Js,{className:"h-4 w-4 text-muted-foreground"}):e.jsx(Ts,{className:"h-4 w-4 text-muted-foreground"}),e.jsx("div",{className:`p-1.5 rounded ${C.color}`,children:e.jsx(Te,{className:"h-4 w-4"})}),e.jsx(be,{className:"text-base",children:C.label}),e.jsx(Q,{variant:"secondary",children:ge.length})]})})})}),e.jsx(pt,{children:e.jsx(ae,{className:"p-0 border-t",children:e.jsxs($e,{children:[e.jsx(Be,{children:e.jsxs(Ne,{children:[e.jsx(D,{className:"cursor-pointer hover:bg-muted/50 select-none",onClick:()=>ue("source_category"),children:e.jsxs("div",{className:"flex items-center",children:["Zdrojová kategorie (PDF)",ve("source_category")]})}),e.jsx(D,{children:"Typ dok."}),e.jsx(D,{children:"Formát"}),e.jsx(D,{}),e.jsx(D,{className:"cursor-pointer hover:bg-muted/50 select-none",onClick:()=>ue("target_category"),children:e.jsxs("div",{className:"flex items-center",children:["1. úroveÅ",ve("target_category")]})}),e.jsx(D,{className:"cursor-pointer hover:bg-muted/50 select-none",onClick:()=>ue("target_subcategory"),children:e.jsxs("div",{className:"flex items-center",children:["2. úroveÅ",ve("target_subcategory")]})}),e.jsx(D,{children:"Status"}),e.jsx(D,{className:"cursor-pointer hover:bg-muted/50 select-none",onClick:()=>ue("created_at"),children:e.jsxs("div",{className:"flex items-center",children:["VytvoÅeno",ve("created_at")]})}),e.jsx(D,{className:"w-24",children:"Akce"})]})}),e.jsxs(Ue,{children:[ge.map(Se=>{const we=Ya.find(zs=>zs.value===Se.source_document_type),he=ct.find(zs=>zs.value===Se.document_format),os=new Date(Se.created_at),Ss=A(Se);return e.jsxs(Ne,{className:Se.skip_import?"opacity-50":"",children:[e.jsx(_,{className:"font-medium",children:e.jsxs("div",{className:"flex flex-col gap-1",children:[e.jsx("span",{children:Se.source_category}),Se.source_aliases&&Se.source_aliases.length>0&&e.jsx(as,{children:e.jsxs(Ke,{children:[e.jsx(Ze,{asChild:!0,children:e.jsxs(Q,{variant:"outline",className:"text-xs w-fit cursor-help",children:[e.jsx(Us,{className:"h-3 w-3 mr-1"}),"+",Se.source_aliases.length," aliasů"]})}),e.jsx(He,{className:"max-w-xs",children:e.jsxs("div",{className:"space-y-1",children:[e.jsx("p",{className:"font-medium",children:"Alternativnà názvy:"}),e.jsx("p",{className:"text-xs text-muted-foreground",children:"Tato pravidla se aplikujà i na následujÃcà kategorie z PDF:"}),e.jsx("ul",{className:"text-xs list-disc pl-4",children:Se.source_aliases.map((zs,ea)=>e.jsx("li",{children:zs},ea))})]})})]})})]})}),e.jsx(_,{children:e.jsxs(Q,{variant:"outline",className:"text-xs",children:[e.jsx(_s,{className:"h-3 w-3 mr-1"}),(we==null?void 0:we.short)||"BK"]})}),e.jsx(_,{children:he?e.jsx(Q,{className:`text-xs ${he.color}`,children:he.short}):e.jsx("span",{className:"text-muted-foreground text-xs",children:"â"})}),e.jsx(_,{children:e.jsx(Gs,{className:"h-4 w-4 text-muted-foreground"})}),e.jsx(_,{children:e.jsx(Q,{variant:Se.is_repair_fund?"secondary":"default",children:Ss.level1||"-"})}),e.jsx(_,{children:Ss.level2?e.jsx("span",{className:"text-sm",children:Ss.level2}):e.jsx("span",{className:"text-muted-foreground",children:"-"})}),e.jsx(_,{children:Se.skip_import?e.jsxs(Q,{variant:"outline",className:"bg-red-100 text-red-700 dark:bg-red-900/30 dark:text-red-300",children:[e.jsx(Va,{className:"h-3 w-3 mr-1"}),"Skip"]}
232):Se.target_category_id?e.jsxs(Q,{variant:"outline",className:"bg-green-100 text-green-700 dark:bg-green-900/30 dark:text-green-300",children:[e.jsx(qs,{className:"h-3 w-3 mr-1"}),"OK"]}):e.jsxs(Q,{variant:"outline",className:"bg-amber-100 text-amber-700 dark:bg-amber-900/30 dark:text-amber-300",children:[e.jsx(is,{className:"h-3 w-3 mr-1"}),"Text"]})}),e.jsx(_,{children:e.jsxs("div",{className:"text-xs text-muted-foreground",children:[e.jsx("div",{children:os.toLocaleDateString("cs-CZ")}),e.jsx("div",{children:os.toLocaleTimeString("cs-CZ",{hour:"2-digit",minute:"2-digit"})})]})}),e.jsx(_,{children:e.jsxs("div",{className:"flex gap-1",children:[e.jsx(as,{children:e.jsxs(Ke,{children:[e.jsx(Ze,{asChild:!0,children:e.jsx(b,{variant:"ghost",size:"icon",onClick:()=>oe(Se),children:e.jsx(Os,{className:"h-4 w-4 text-blue-500"})})}),e.jsx(He,{children:e.jsx("p",{children:"KopÃrovat pro jiného zpracovatele"})})]})}),e.jsx(b,{variant:"ghost",size:"icon",onClick:()=>ne(Se),children:e.jsx(Kt,{className:"h-4 w-4"})}),e.jsx(b,{variant:"ghost",size:"icon",onClick:()=>je(Se.id),children:e.jsx(qe,{className:"h-4 w-4 text-destructive"})})]})})]},Se.id)}),ge.length===0&&e.jsx(Ne,{children:e.jsx(_,{colSpan:9,className:"text-center py-6 text-muted-foreground",children:"Žádná pravidla v této kategorii"})})]})]})})})]})},C.value)})}),e.jsx(Ge,{open:m,onOpenChange:$,children:e.jsxs(Je,{className:"sm:max-w-2xl max-h-[90vh] overflow-y-auto",children:[e.jsxs(Ye,{children:[e.jsx(Qe,{className:"flex items-center gap-2",children:H?e.jsxs(e.Fragment,{children:[e.jsx(Kt,{className:"h-5 w-5"}),"Upravit pravidlo"]}):e.jsxs(e.Fragment,{children:[e.jsx(Xe,{className:"h-5 w-5"}),"Nové pravidlo"]})}),e.jsx(us,{children:"Definuje jak se nÄmecký text z PDF automaticky pÅiÅadà k Äeské kategorii."})]}),e.jsxs(xt,{children:[e.jsx(ht,{asChild:!0,children:e.jsxs("button",{type:"button",className:"w-full flex items-center justify-start gap-1.5 text-xs text-muted-foreground hover:text-foreground -mt-2 py-1.5 px-2 rounded-md transition-colors hover:bg-muted/50",children:[e.jsx(Us,{className:"h-3.5 w-3.5"}),"Jak funguje párovánÃ?",e.jsx(Ts,{className:"h-3.5 w-3.5 ml-auto transition-transform [[data-state=open]>&]:rotate-90"})]})}),e.jsx(pt,{children:e.jsx("div",{className:"text-xs bg-muted/50 rounded-md p-3 space-y-1.5 mb-4",children:e.jsxs("div",{className:"grid grid-cols-[auto_1fr] gap-x-2 gap-y-1",children:[e.jsx(Q,{variant:"outline",className:"text-[10px] bg-green-100 text-green-700 h-5",children:"95%"}),e.jsxs("span",{children:[e.jsx("strong",{children:"PÅesná shoda"}),' â "Wassergebühr" = "Wassergebühr"']}),e.jsx(Q,{variant:"outline",className:"text-[10px] bg-blue-100 text-blue-700 h-5",children:"90%"}),e.jsxs("span",{children:[e.jsx("strong",{children:"Alias"}),' â "Wasser" najde pravidlo s aliasem']}),e.jsx(Q,{variant:"outline",className:"text-[10px] bg-amber-100 text-amber-700 h-5",children:"80%"}),e.jsxs("span",{children:[e.jsx("strong",{children:"Obsahuje"}),' â "Kosten Wasser" obsahuje klÃÄ']}),e.jsx(Q,{variant:"outline",className:"text-[10px] bg-orange-100 text-orange-700 h-5",children:"60%"}),e.jsxs("span",{children:[e.jsx("strong",{children:"Fuzzy"})," â toleruje pÅeklepy"]})]})})})]}),e.jsxs("div",{className:"space-y-6",children:[e.jsxs("div",{className:"space-y-4 bg-muted/30 rounded-lg p-4 border",children:[e.jsxs("div",{className:"flex items-center gap-2 text-sm font-medium",children:[e.jsx(_s,{className:"h-4 w-4 text-muted-foreground"}),"ZDROJ â Co hledat v PDF"]}),e.jsxs("div",{children:[e.jsx(q,{className:"text-xs text-muted-foreground",children:"Typ reportu"}),e.jsxs(De,{value:xe.document_format||"none",onValueChange:C=>de({...xe,document_format:C==="none"?"":C}),children:[e.jsx(Pe,{className:"h-9 bg-background",children:e.jsx(Ae,{})}),e.jsxs(Ee,{children:[e.jsx(me,{value:"none",children:e.jsx("span",{className:"text-muted-foreground",children:"Univerzálnà (vÅ¡echny reporty)"})}),ct.map(C=>e.jsx(me,{value:C.value,children:e.jsxs("div",{className:"flex items-center gap-1.5",children:[e.jsx(Q,{className:`text-[10px] px-1 ${C.color}`,children:C.short}),e.jsx("span",{children:C.label})]})},C.value))]})]}),e.jsx("p",{className:"text-[10px] text-muted-foreground mt-0.5",children:"Pravidlo platà pouze pro vybraný typ reportu, nebo pro vÅ¡echny"})]}),e.jsxs("div",{className:"grid grid-cols-2 gap-4",children:[e.jsxs("div",{children:[e.jsx(q,{className:"text-xs text-muted-foreground",children:"Hledaný text (nÄmecky) *"}),e.jsx(se,{value:xe.source_category,onChange:C=>de({...xe,source_category:C.target.value}),placeholder:"napÅ. Wassergebühr, Personal...",disabled:!!H,className:"font-mono bg-background"}),xe.source_category&&e.jsxs("p",{className:"text-[10px] text-muted-foreground mt-0.5 font-mono",children:["Normalizováno: ",xe.source_category.toLowerCase().replace(/ä/g,"a").replace(/ö/g,"o").replace(/ü/g,"u").replace(/Ã/g,"ss")]})]}),e.jsxs("div",{children:[e.jsxs(q,{className:"text-xs text-muted-foreground flex items-center gap-1",children:[e.jsx(Xt,{className:"h-3 w-3"}),"Äeský pÅeklad"]}),e.jsxs("div",{className:"flex gap-2",children:[e.jsx(se,{value:xe.target_subcategory,onChange:C=>de({...xe,target_subcategory:C.target.value}),placeholder:"napÅ. Poplatek za vodu...",className:"bg-background flex-1"}),e.jsx(b,{type:"button",variant:"outline",size:"sm",onClick:L,disabled:B||!xe.source_category.trim(),className:"shrink-0 h-10",children:B?e.jsx(fe,{className:"h-4 w-4 animate-spin"}):e.jsxs(e.Fragment,{children:[e.jsx(na,{className:"h-4 w-4 mr-1"}),"PÅelož"]})})]})]})]}),e.jsxs("div",{children:[e.jsxs(q,{className:"text-xs text-muted-foreground flex items-center gap-1",children:["Alternativnà texty",e.jsx("span",{className:"font-normal",children:"(oddÄlené Äárkou)"})]}),e.jsx(se,{value:xe.source_aliases,onChange:C=>de({...xe,source_aliases:C.target.value}),placeholder:"napÅ. Wasser, Kanal, Abwasser",className:"font-mono text-sm bg-background"})]})]}),e.jsx("div",{className:"flex justify-center -my-1",children:e.jsx(Ma,{className:"h-5 w-5 text-muted-foreground
232/30"})}),e.jsxs("div",{className:"space-y-4 bg-muted/30 rounded-lg p-4 border",children:[e.jsxs("div",{className:"flex items-center gap-2 text-sm font-medium",children:[e.jsx(mt,{className:"h-4 w-4 text-muted-foreground"}),"CÃL â Kam pÅiÅadit"]}),e.jsxs("div",{className:"grid grid-cols-2 gap-4",children:[e.jsxs("div",{children:[e.jsx(q,{className:"text-xs text-muted-foreground",children:"Kategorie v databázi *"}),e.jsxs(De,{value:xe.target_category_id||"none",onValueChange:C=>{var Oe;const ge=C==="none"?"":C,Te=i==null?void 0:i.find(Se=>Se.id===ge);if(Te){const Se=Te.name==="Fond Oprav"||((Oe=Te.name)==null?void 0:Oe.toLowerCase().includes("oprav"));de({...xe,target_category_id:ge,target_category:Se?"Fond_oprav":"Provozni_naklady",is_repair_fund:Se})}else de({...xe,target_category_id:""})},children:[e.jsx(Pe,{className:"h-9 bg-background",children:e.jsx(Ae,{placeholder:"Vyberte..."})}),e.jsxs(Ee,{children:[e.jsx(me,{value:"none",children:e.jsx("span",{className:"text-muted-foreground italic",children:"â NepÅiÅazeno â"})}),i==null?void 0:i.filter(C=>C.id).map(C=>e.jsx(me,{value:C.id,children:e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx("div",{className:"w-2 h-2 rounded-full shrink-0",style:{backgroundColor:C.color||"#64748b"}}),e.jsxs("span",{className:C.level===2?"text-muted-foreground":"font-medium",children:[C.level===2?"â³ ":"",C.name]})]})},C.id))]})]})]}),e.jsxs("div",{children:[e.jsx(q,{className:"text-xs text-muted-foreground",children:"Typ položky"}),e.jsxs(De,{value:xe.item_type,onValueChange:C=>{de({...xe,item_type:C,is_repair_fund:C==="reserve_fund_expense"||C==="reserve_fund_contribution"})},children:[e.jsx(Pe,{className:"h-9 bg-background",children:e.jsx(Ae,{})}),e.jsx(Ee,{children:Qs.map(C=>{const ge=C.icon;return e.jsx(me,{value:C.value,children:e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(ge,{className:"h-3.5 w-3.5 text-muted-foreground"}),e.jsx("span",{children:C.label})]})},C.value)})})]})]})]})]}),e.jsxs("div",{className:"space-y-4",children:[e.jsxs("div",{className:"flex items-center gap-2 text-sm font-medium text-muted-foreground",children:[e.jsx(Fa,{className:"h-4 w-4"}),"MOŽNOSTI"]}),e.jsxs("div",{className:"flex items-center justify-between py-2 px-3 bg-red-50 dark:bg-red-950/20 rounded-lg border border-red-200 dark:border-red-900/50",children:[e.jsxs(q,{htmlFor:"skip_import",className:"text-sm flex items-center gap-2 cursor-pointer",children:[e.jsx(Va,{className:"h-4 w-4 text-red-500"}),"PÅeskoÄit pÅi importu",e.jsx("span",{className:"text-xs text-muted-foreground font-normal",children:"(ignorovat tuto položku)"})]}),e.jsx(ss,{id:"skip_import",checked:xe.skip_import,onCheckedChange:C=>de({...xe,skip_import:C})})]}),xe.skip_import&&e.jsx(se,{value:xe.skip_reason,onChange:C=>de({...xe,skip_reason:C.target.value}),placeholder:"Důvod pÅeskoÄenÃ...",className:"text-sm border-red-200"})]})]}),e.jsxs(ls,{className:"mt-6",children:[e.jsx(b,{variant:"outline",onClick:()=>$(!1),children:"ZruÅ¡it"}),e.jsxs(b,{onClick:ke,className:"gap-2",children:[e.jsx(Ds,{className:"h-4 w-4"}),H?"Uložit zmÄny":"VytvoÅit pravidlo"]})]})]})}),e.jsx(Ge,{open:f,onOpenChange:R,children:e.jsxs(Je,{className:"sm:max-w-md",children:[e.jsxs(Ye,{children:[e.jsx(Qe,{className:"flex items-center gap-2",children:F==="delete"?e.jsxs(e.Fragment,{children:[e.jsx(qe,{className:"h-5 w-5 text-destructive"}),"Hromadné smazánà pravidel"]}):e.jsxs(e.Fragment,{children:[e.jsx(na,{className:"h-5 w-5 text-primary"}),"Regenerovat pravidla"]})}),e.jsx(us,{children:F==="delete"?"Smažte pravidla podle typu dokumentu nebo typu položky.":"Smaže existujÃcà pravidla a vytvoÅà nová z pÅeddefinovaných doporuÄenÃ."})]}),e.jsxs("div",{className:"space-y-4 py-4",children:[e.jsxs("div",{children:[e.jsx(q,{children:"Typ dokumentu"}),e.jsxs(De,{value:ie,onValueChange:W,children:[e.jsx(Pe,{children:e.jsx(Ae,{})}),e.jsxs(Ee,{children:[e.jsx(me,{value:"all",children:e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(mt,{className:"h-4 w-4"}),"VÅ¡echny typy dokumentů"]})}),Ya.map(C=>e.jsx(me,{value:C.value,children:e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(_s,{className:"h-4 w-4"}),C.label," (",C.short,")"]})},C.value))]})]})]}),e.jsxs("div",{children:[e.jsx(q,{children:"Typ položky"}),e.jsxs(De,{value:Z,onValueChange:K,children:[e.jsx(Pe,{children:e.jsx(Ae,{})}),e.jsxs(Ee,{children:[e.jsx(me,{value:"all",children:e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(mt,{className:"h-4 w-4"}),"VÅ¡echny typy položek"]})}),Qs.map(C=>{const ge=C.icon;return e.jsx(me,{value:C.value,children:e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(ge,{className:"h-4 w-4"}),C.label]})},C.value)})]})]})]}),e.jsxs("div",{children:[e.jsx(q,{children:"Zpracovatel dokumentu"}),e.jsxs(De,{value:l,onValueChange:U,children:[e.jsx(Pe,{children:e.jsx(Ae,{})}),e.jsxs(Ee,{children:[e.jsx(me,{value:"all",children:e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(mt,{className:"h-4 w-4"}),"VÅ¡ichni zpracovatelé"]})}),ct.map(C=>e.jsx(me,{value:C.value,children:e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(Q,{className:`text-xs ${C.color}`,children:C.short}),C.label]})},C.value)),e.jsx(me,{value:"universal",children:e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(Q,{className:"bg-purple-100 text-purple-700 dark:bg-purple-900/30 dark:text-purple-300 text-xs",children:"UNI"}),"Univerzálnà (bez pÅiÅazenÃ)"]})})]})]})]}),e.jsxs(it,{children:[e.jsx(is,{className:"h-4 w-4"}),e.jsx(qt,{children:"DotÄená pravidla"}),e.jsx(lt,{children:F==="delete"?e.jsxs("span",{children:["Bude smazáno ",e.jsx("strong",{children:V()})," pravidel."]}):e.jsxs(e.Fragment,{children:[e.jsxs("span",{children:["Bude smazáno ",e.jsx("strong",{children:V()})," pravidel a vytvoÅeno "]}),e.jsx("strong",{children:Ja.filter(C=>Z!=="all"&&C.target.itemType!==Z?!1:l!=="all"?l==="universal"?!C.documentFormat:C.documentFormat===l||!C.documentFormat:!0).length}),e.jsx("span",{children:" nových z pÅeddefinovaných doporuÄenÃ."})]})})]}),Y&&e.jsxs(it,{className:"border-green-200 bg-green-50 dark:border-green-900 dark:bg-green-950/30",children:[e.jsx(qs,{className:"h-4 w-4 text-green-600"}),e.jsx(qt,{className:"text-green-700 dark:text-green-300",children:"Operace dokonÄena"}),e.jsxs(lt,{className:"text-green-600 dark:text-green-400",children:[Y.deleted>0&&e.jsxs("span",{children:["Smazáno: ",Y.deleted," pravidel. "]}),Y.created>0&&e.jsxs("span",{children:["VytvoÅeno: ",Y.created," pravidel."]})]})]})]}),e.jsxs(ls,{children:[e.jsx(b,{variant:"outline",onClick:()=>R(!1),children:"ZavÅÃt"}),F==="delete"?e.jsx(b,{variant:"destructive",onClick:_e,disabled:n||V()===0,children:n?e.jsxs(e.Fragment,{children:[e.jsx(fe,{className:"h-4 w-4 mr-2 animate-spin"}),"MazánÃ..."]}):e.jsxs(e.Fragment,{children:[e.jsx(qe,{className:"h-4 w-4 mr-2"}),"Smazat ",V()," pravidel"]})}):e.jsx(b,{onClick:Ie,disabled:n,children:n?e.jsxs(e.Fragment,{children:[e.jsx(fe,{className:"h-4 w-4 mr-2 animate-spin"}),"Regeneruji..."]}):e.jsxs(e.Fragment,{children:[e.jsx(wn,{className:"h-4 w-4 mr-2"}),"Regenerovat"]})})]})]})})]})},Qa={created:{label:"VytvoÅen",color:"bg-gray-500",icon:at},extracted:{label:"Extrahováno",color:"bg-blue-500",icon:_s},validated:{label:"Validováno",color:"bg-cyan-500",icon:qs},mapped:{label:"Mapováno",color:"bg-purple-500",icon:ei},translated:{label:"PÅeloženo",color:"bg-indigo-500",icon:_s}
232,reviewed:{label:"Zkontrolováno",color:"bg-amber-500",icon:_a},committed:{label:"DokonÄeno",color:"bg-green-500",icon:qs}},Xa=["created","extracted","validated","mapped","translated","reviewed","committed"],en=()=>{const s=Ks(),{toast:a}=Re(),[i,y]=t.useState([]),[E,P]=t.useState(!0),[x,O]=t.useState(!1),[S,N]=t.useState(!1),[j,w]=t.useState(new Date().getFullYear());t.useEffect(()=>{M()},[]);const M=async()=>{P(!0);try{const{data:p,error:m}=await g.from("import_batches").select("*").order("created_at",{ascending:!1});if(m)throw m;const $=await Promise.all((p||[]).map(async H=>{var h,I;let J=((h=H.document_ids)==null?void 0:h.length)||0,z=0;if(((I=H.document_ids)==null?void 0:I.length)>0){const{data:k}=await g.from("pdf_documents").select("page_count").in("id",H.document_ids);k&&(z=k.reduce((c,d)=>c+(d.page_count||0),0))}return{...H,document_count:J,page_count:z}}));y($)}catch(p){console.error("Error fetching batches:",p),a({variant:"destructive",title:"Chyba",description:"NepodaÅilo se naÄÃst seznam batchů."})}finally{P(!1)}},o=async()=>{N(!0);try{const{data:p,error:m}=await g.from("import_batches").insert({year:j,status:"created",total_items:0}).select().single();if(m)throw m;a({title:"Batch vytvoÅen",description:`Nový batch pro rok ${j} byl úspÄÅ¡nÄ vytvoÅen.`}),O(!1),s(`/admin/batch/${p.id}`)}catch(p){console.error("Error creating batch:",p),a({variant:"destructive",title:"Chyba",description:"NepodaÅilo se vytvoÅit batch."})}finally{N(!1)}},v=p=>{const m=Qa[p]||Qa.created,$=m.icon;return e.jsxs(Q,{className:`${m.color} text-white`,children:[e.jsx($,{className:"h-3 w-3 mr-1"}),m.label]})},u=p=>{const m=p.pipeline_step||p.status||"created",$=Xa.indexOf(m);return $===-1?0:Math.round($/(Xa.length-1)*100)};return E?e.jsx("div",{className:"flex items-center justify-center py-12",children:e.jsx(fe,{className:"h-8 w-8 animate-spin text-primary"})}):e.jsx("div",{className:"space-y-6",children:e.jsxs(ee,{children:[e.jsx(ye,{children:e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsxs("div",{children:[e.jsx(be,{children:"Import Batchy"}),e.jsx(Le,{children:"Správa importů nákladů z PDF dokumentů"})]}),e.jsxs(Ge,{open:x,onOpenChange:O,children:[e.jsx(yt,{asChild:!0,children:e.jsxs(b,{children:[e.jsx(Xe,{className:"h-4 w-4 mr-2"}),"Nový batch"]})}),e.jsxs(Je,{children:[e.jsxs(Ye,{children:[e.jsx(Qe,{children:"VytvoÅit nový batch"}),e.jsx(us,{children:"VytvoÅte nový import batch pro zpracovánà PDF dokumentů."})]}),e.jsx("div",{className:"space-y-4 py-4",children:e.jsxs("div",{className:"space-y-2",children:[e.jsx(q,{htmlFor:"year",children:"Rok"}),e.jsxs(De,{value:j.toString(),onValueChange:p=>w(parseInt(p)),children:[e.jsx(Pe,{children:e.jsx(Ae,{})}),e.jsx(Ee,{children:[2020,2021,2022,2023,2024,2025].map(p=>e.jsx(me,{value:p.toString(),children:p},p))})]})]})}),e.jsxs(ls,{children:[e.jsx(b,{variant:"outline",onClick:()=>O(!1),disabled:S,children:"ZruÅ¡it"}),e.jsxs(b,{onClick:o,disabled:S,children:[S&&e.jsx(fe,{className:"h-4 w-4 mr-2 animate-spin"}),"VytvoÅit"]})]})]})]})]})}),e.jsx(ae,{children:i.length===0?e.jsxs("div",{className:"text-center py-12 text-muted-foreground",children:[e.jsx(En,{className:"h-12 w-12 mx-auto mb-4 opacity-50"}),e.jsx("p",{children:"ZatÃm nebyly vytvoÅeny žádné batchy."}),e.jsx("p",{className:"text-sm mt-2",children:"VytvoÅte prvnà batch kliknutÃm na tlaÄÃtko výše."})]}):e.jsxs($e,{children:[e.jsx(Be,{children:e.jsxs(Ne,{children:[e.jsx(D,{children:"Rok"}),e.jsx(D,{children:"Stav"}),e.jsx(D,{className:"text-center",children:"Dokumenty"}),e.jsx(D,{className:"text-center",children:"Položky"}),e.jsx(D,{className:"text-center",children:"Progress"}),e.jsx(D,{children:"VytvoÅeno"}),e.jsx(D,{className:"text-right",children:"Akce"})]})}),e.jsx(Ue,{children:i.map(p=>e.jsxs(Ne,{className:"cursor-pointer hover:bg-muted/50",children:[e.jsx(_,{className:"font-medium",onClick:()=>s(`/admin/batch/${p.id}`),children:p.year}),e.jsx(_,{onClick:()=>s(`/admin/batch/${p.id}`),children:v(p.pipeline_step||p.status)}),e.jsx(_,{className:"text-center",onClick:()=>s(`/admin/batch/${p.id}`),children:e.jsxs("div",{className:"flex flex-col items-center",children:[e.jsx("span",{className:"font-medium",children:p.document_count||0}),(p.page_count||0)>0&&e.jsxs("span",{className:"text-xs text-muted-foreground",children:[p.page_count," stran"]})]})}),e.jsx(_,{className:"text-center",onClick:()=>s(`/admin/batch/${p.id}`),children:p.total_items}),e.jsx(_,{className:"text-center",onClick:()=>s(`/admin/batch/${p.id}`),children:e.jsxs("div",{className:"flex items-center justify-center gap-2",children:[e.jsx("div",{className:"w-20 h-2 bg-muted rounded-full overflow-hidden",children:e.jsx("div",{className:"h-full bg-primary transition-all",style:{width:`${u(p)}%`}})}),e.jsxs("span",{className:"text-xs text-muted-foreground",children:[u(p),"%"]})]})}),e.jsx(_,{className:"text-muted-foreground",onClick:()=>s(`/admin/batch/${p.id}`),children:hs(new Date(p.created_at),"d. M. yyyy HH:mm",{locale:ys})}),e.jsx(_,{className:"text-right",children:e.jsxs(b,{variant:"outline",size:"sm",onClick:()=>s(`/admin/batch/${p.id}`),children:[e.jsx($r,{className:"h-4 w-4 mr-1"}),"OtevÅÃt"]})})]}
232,p.id))})]})})]})})},sn={contact_type:"service",name:"",role:"",phone:"",email:"",address:"",website:"",sort_order:0,is_active:!0,additional_data:"{}",label_cs:"",label_de:"",label_en:"",service_cs:"",service_de:"",service_en:""},_t={manager:"Správa nemovitosti",caretaker:"Správce domu",emergency:"TÃsÅový kontakt",service:"Servisnà firma"},Xi={manager:rt,caretaker:Fn,emergency:is,service:Nn},el=()=>{const{toast:s}=Re(),[a,i]=t.useState([]),[y,E]=t.useState(!0),[P,x]=t.useState(!1),[O,S]=t.useState(null),[N,j]=t.useState(sn),[w,M]=t.useState(!1),[o,v]=t.useState("manager");t.useEffect(()=>{u()},[]);const u=async()=>{E(!0);const{data:z,error:h}=await g.from("house_contacts").select("*").order("sort_order");h?s({variant:"destructive",title:"Chyba",description:"NepodaÅilo se naÄÃst kontakty."}):i(z||[]),E(!1)},p=z=>{S(null);const h=a.filter(I=>I.contact_type===z).reduce((I,k)=>Math.max(I,k.sort_order),0);j({...sn,contact_type:z,sort_order:h+1}),x(!0)},m=z=>{S(z);const h=z.additional_data||{};j({contact_type:z.contact_type,name:z.name,role:z.role||"",phone:z.phone||"",email:z.email||"",address:z.address||"",website:z.website||"",sort_order:z.sort_order,is_active:z.is_active,additional_data:JSON.stringify(z.additional_data||{},null,2),label_cs:h.label_cs||"",label_de:h.label_de||"",label_en:h.label_en||"",service_cs:h.service_cs||"",service_de:h.service_de||"",service_en:h.service_en||""}),x(!0)},$=async()=>{if(!N.name.trim()){s({variant:"destructive",title:"Chyba",description:"Zadejte název."});return}let z={};try{z=JSON.parse(N.additional_data||"{}")}catch{s({variant:"destructive",title:"Chyba",description:"Neplatný JSON v additional_data."});return}const h=["label_cs","label_de","label_en","service_cs","service_de","service_en"];for(const k of h)N[k].trim()?z[k]=N[k].trim():delete z[k];M(!0);const I={contact_type:N.contact_type,name:N.name.trim(),role:N.role.trim()||null,phone:N.phone.trim()||null,email:N.email.trim()||null,address:N.address.trim()||null,website:N.website.trim()||null,sort_order:N.sort_order,is_active:N.is_active,additional_data:z};if(O){const{error:k}=await g.from("house_contacts").update(I).eq("id",O.id);s(k?{variant:"destructive",title:"Chyba",description:"NepodaÅilo se uložit."}:{title:"Kontakt upraven"})}else{const{error:k}=await g.from("house_contacts").insert(I);s(k?{variant:"destructive",title:"Chyba",description:"NepodaÅilo se vytvoÅit."}:{title:"Kontakt pÅidán"})}M(!1),x(!1),u()},H=async z=>{if(!confirm("Opravdu smazat tento kontakt?"))return;const{error:h}=await g.from("house_contacts").delete().eq("id",z);h?s({variant:"destructive",title:"Chyba",description:"NepodaÅilo se smazat."}):(s({title:"Kontakt smazán"}),u())},J=z=>a.filter(h=>h.contact_type===z);return y?e.jsx("div",{className:"flex justify-center py-12",children:e.jsx(fe,{className:"h-8 w-8 animate-spin text-primary"})}):e.jsxs("div",{className:"space-y-6",children:[e.jsxs("div",{children:[e.jsx("h2",{className:"text-lg font-semibold",children:"Kontakty domu"}),e.jsx("p",{className:"text-sm text-muted-foreground",children:"Správa kontaktnÃch údajů zobrazovaných majitelům"})]}),e.jsxs(ks,{value:o,onValueChange:v,children:[e.jsx(Cs,{children:Object.entries(_t).map(([z,h])=>{const I=Xi[z];return e.jsxs(We,{value:z,className:"flex items-center gap-2",children:[e.jsx(I,{className:"h-4 w-4"}),h,e.jsx(Q,{variant:"secondary",className:"ml-1 text-xs",children:J(z).length})]},z)})}),Object.keys(_t).map(z=>e.jsx(es,{value:z,children:e.jsxs(ee,{children:[e.jsxs(ye,{className:"flex flex-row items-center justify-between",children:[e.jsx(be,{className:"text-base",children:_t[z]}),e.jsxs(b,{size:"sm",onClick:()=>p(z),children:[e.jsx(Xe,{className:"h-4 w-4 mr-1"})," PÅidat"]})]}),e.jsx(ae,{children:J(z).length===0?e.jsx("p",{className:"text-center text-muted-foreground py-8",children:"Žádné kontakty"}):e.jsxs($e,{children:[e.jsx(Be,{children:e.jsxs(Ne,{className:"bg-muted/50 hover:bg-muted/50",children:[e.jsx(D,{className:"w-8 h-9 text-xs",children:"#"}),e.jsx(D,{className:"h-9 text-xs",children:"Název"}),e.jsx(D,{className:"h-9 text-xs",children:"Role / Popis"}),e.jsx(D,{className:"h-9 text-xs",children:"Telefon"}),e.jsx(D,{className:"h-9 text-xs",children:"Email"}),e.jsx(D,{className:"w-20 h-9 text-xs",children:"Akce"})]})}),e.jsx(Ue,{children:J(z).map(h=>e.jsxs(Ne,{className:"h-8",children:[e.jsx(_,{className:"text-muted-foreground text-xs py-1.5",children:h.sort_order}),e.jsx(_,{className:"font-medium text-sm py-1.5",children:h.name}),e.jsx(_,{className:"text-muted-foreground text-sm py-1.5",children:h.role||"-"}),e.jsx(_,{className:"text-sm py-1.5",children:h.phone||"-"}),e.jsx(_,{className:"text-sm py-1.5",children:h.email||"-"}),e.jsx(_,{children:e.jsxs("div",{className:"flex items-center gap-1",children:[e.jsx(b,{variant:"ghost",size:"icon",className:"h-7 w-7",onClick:()=>m(h),children:e.jsx(Ns,{className:"h-3.5 w-3.5"})}),e.jsx(b,{variant:"ghost",size:"icon",className:"h-7 w-7 text-destructive",onClick:()=>H(h.id),children:e.jsx(qe,{className:"h-3.5 w-3.5"})})]})})]}
232,h.id))})]})})]})},z))]}),e.jsx(Ge,{open:P,onOpenChange:x,children:e.jsxs(Je,{className:"max-w-lg",children:[e.jsx(Ye,{children:e.jsx(Qe,{children:O?"Upravit kontakt":"Nový kontakt"})}),e.jsxs("div",{className:"space-y-4 pt-2",children:[e.jsxs("div",{className:"grid grid-cols-2 gap-4",children:[e.jsxs("div",{className:"space-y-2",children:[e.jsx(q,{children:"Typ"}),e.jsxs(De,{value:N.contact_type,onValueChange:z=>j({...N,contact_type:z}),children:[e.jsx(Pe,{children:e.jsx(Ae,{})}),e.jsx(Ee,{children:Object.entries(_t).map(([z,h])=>e.jsx(me,{value:z,children:h},z))})]})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(q,{children:"PoÅadÃ"}),e.jsx(se,{type:"number",value:N.sort_order,onChange:z=>j({...N,sort_order:parseInt(z.target.value)||0})})]})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(q,{children:"Název *"}),e.jsx(se,{value:N.name,onChange:z=>j({...N,name:z.target.value}),placeholder:"Black Point GmbH"})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(q,{children:"Role / Popis"}),e.jsx(se,{value:N.role,onChange:z=>j({...N,role:z.target.value}),placeholder:"DI Markus Edenhauser"})]}),e.jsxs("div",{className:"grid grid-cols-2 gap-4",children:[e.jsxs("div",{className:"space-y-2",children:[e.jsx(q,{children:"Telefon"}),e.jsx(se,{value:N.phone,onChange:z=>j({...N,phone:z.target.value}),placeholder:"+43 501 141 50"})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(q,{children:"Email"}),e.jsx(se,{value:N.email,onChange:z=>j({...N,email:z.target.value}),placeholder:"[email protected]"})]})]}),e.jsxs("div",{className:"grid grid-cols-2 gap-4",children:[e.jsxs("div",{className:"space-y-2",children:[e.jsx(q,{children:"Adresa"}),e.jsx(se,{value:N.address,onChange:z=>j({...N,address:z.target.value})})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(q,{children:"Web"}),e.jsx(se,{value:N.website,onChange:z=>j({...N,website:z.target.value})})]})]}),e.jsx(gt,{}),e.jsx("p",{className:"text-xs font-semibold uppercase tracking-wide text-muted-foreground",children:"VÃcejazyÄné popisky"}),e.jsxs("div",{className:"grid grid-cols-3 gap-3",children:[e.jsxs("div",{className:"space-y-1",children:[e.jsx(q,{className:"text-xs",children:"Popisek CZ"}),e.jsx(se,{value:N.label_cs,onChange:z=>j({...N,label_cs:z.target.value}),placeholder:"HasiÄský sbor"})]}),e.jsxs("div",{className:"space-y-1",children:[e.jsx(q,{className:"text-xs",children:"Popisek DE"}),e.jsx(se,{value:N.label_de,onChange:z=>j({...N,label_de:z.target.value}),placeholder:"Feuerwehr"})]}),e.jsxs("div",{className:"space-y-1",children:[e.jsx(q,{className:"text-xs",children:"Popisek EN"}),e.jsx(se,{value:N.label_en,onChange:z=>j({...N,label_en:z.target.value}),placeholder:"Fire Department"})]})]}),e.jsxs("div",{className:"grid grid-cols-3 gap-3",children:[e.jsxs("div",{className:"space-y-1",children:[e.jsx(q,{className:"text-xs",children:"Služba CZ"}),e.jsx(se,{value:N.service_cs,onChange:z=>j({...N,service_cs:z.target.value}),placeholder:"Instalatér"})]}),e.jsxs("div",{className:"space-y-1",children:[e.jsx(q,{className:"text-xs",children:"Služba DE"}),e.jsx(se,{value:N.service_de,onChange:z=>j({...N,service_de:z.target.value}),placeholder:"Installateur"})]}),e.jsxs("div",{className:"space-y-1",children:[e.jsx(q,{className:"text-xs",children:"Služba EN"}),e.jsx(se,{value:N.service_en,onChange:z=>j({...N,service_en:z.target.value}),placeholder:"Plumber"})]})]}),e.jsx(gt,{}),e.jsxs("details",{className:"text-xs",children:[e.jsx("summary",{className:"cursor-pointer text-muted-foreground hover:text-foreground",children:"PokroÄilá data (JSON)"}),e.jsx("textarea",{className:"w-full min-h-[80px] rounded-md border border-input bg-background px-3 py-2 text-sm font-mono mt-2",value:N.additional_data,onChange:z=>j({...N,additional_data:z.target.value})}),e.jsx("p",{className:"text-xs text-muted-foreground mt-1",children:"NapÅ. poboÄky správce, speciálnà metadata apod."})]}),e.jsxs("div",{className:"flex justify-end gap-3 pt-2",children:[e.jsx(b,{variant:"outline",onClick:()=>x(!1),children:"ZruÅ¡it"}),e.jsxs(b,{onClick:$,disabled:w,children:[w&&e.jsx(fe,{className:"h-4 w-4 animate-spin mr-2"}),O?"Uložit":"PÅidat"]})]})]})]})})]})},ia={showSourceColumn:!0,autoImportAfterExtraction:!1},sl=()=>{const{language:s}=Zs(),[a,i]=t.useState(ia),[y,E]=t.useState(!0),[P,x]=t.useState(!1),O={cs:{title:"Nastavenà nákladů",description:"Konfigurace zobrazenà nákladových dat a importu",showSourceColumn:'Zobrazit sloupec "Zdroj"',showSourceColumnDesc:"Zobrazà u každé položky badge s informacà o zdroji dat (PDF import nebo manuálnà zadánÃ)",autoApprove:"Automatické schválenà položek",autoApproveDesc:"Po extrakci dat z PDF se položky automaticky schválÃ. Import se provede manuálnÄ v sekci Párovánà a import.",save:"Uložit nastavenÃ",saved:"Nastavenà uloženo",error:"Chyba pÅi ukládánÃ",displaySection:"ZobrazenÃ",importSection:"Import"},de:{title:"Kosteneinstellungen",description:"Konfiguration der Kostenanzeige und des Imports",showSourceColumn:'Spalte "Quelle" anzeigen',showSourceColumnDesc:"Zeigt bei jeder Position ein Badge mit Informationen zur Datenquelle (PDF-Import oder manuelle Eingabe)",autoApprove:"Automatische Genehmigung",autoApproveDesc:"Nach PDF-Extraktion werden Elemente automatisch genehmigt. Import erfolgt manuell im Bereich Abgleich und Import.",save:"Einstellungen speichern",saved:"Einstellungen gespeichert",error:"Fehler beim Speichern",displaySection:"Anzeige",importSection:"Import"},en:{title:"Cost Settings",description:"Configure cost data display and import",showSourceColumn:'Show "Source" column',showSourceColumnDesc:"Displays a badge on each item showing the data source (PDF import or manual entry)",autoApprove:"Auto-approve items",autoApproveDesc:"After PDF extraction, items are automatically approved. Import is performed manually in the Matching and Import section.",save:"Save settings",saved:"Settings saved",error:"Error saving settings",displaySection:"Display",importSection:"Import"}},S=O[s]||O.de;t.useEffect(()=>{N()},[]);const N=async()=>{E(!0);const{data:w,error:M}=await g.from("forum_settings").select("value").eq("key","cost_display_settings").single();if(w&&!M){const o=w.value;i({showSourceColumn:o.showSourceColumn??ia.showSourceColumn,autoImportAfterExtraction:o.autoImportAfterExtraction??ia.autoImportAfterExtraction})}E(!1)},j=async()=>{x(!0);const{data:w}=await g.from("forum_settings").select("id").eq("key","cost_display_settings").single(),M=JSON.parse(JSON.stringify(a));let o;if(w)o=(await g.from("forum_settings").update({value:M,description:"Settings for cost display (source column visibility, etc.)"}).eq("key","cost_display_settings")).error;else{const v={key:"cost_display_settings",value:M,description:"Settings for cost display (source column visibility, etc.)"};o=(await g.from("forum_settings").insert(v)).error}o?ts.error(S.error):ts.success(S.saved),x(!1)};return y?e.jsx("div",{className:"flex items-center justify-center py-12",children:e.jsx(fe,{className:"h-8 w-8 animate-spin text-primary"})}):e.jsxs("div",{className:"space-y-6",children:[e.jsxs("div",{children:[e.jsxs("h2",{className:"text-xl font-semibold flex items-center gap-2",children:[e.jsx(Gt,{className:"h-5 w-5 text-primary"}),S.title]}),e.jsx("p",{className:"text-sm text-muted-foreground",children:S.description})]}),e.jsxs(ee,{children:[e.jsxs(ye,{children:[e.jsxs(be,{className:"text-lg flex items-center gap-2",children:[a.showSourceColumn?e.jsx(bs,{className:"h-5 w-5 text-primary"}):e.jsx(ja,{className:"h-5 w-5 text-muted-foreground"}),S.displaySection]}),e.jsx(Le,{children:S.showSourceColumnDesc})]}),e.jsx(ae,{className:"space-y-4",children:e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsx(q,{htmlFor:"show-source",className:"flex-1",children:S.showSourceColumn}),e.jsx(ss,{id:"show-source",checked:a.showSourceColumn,onCheckedChange:w=>i(M=>({...M,showSourceColumn:w}))})]})})]}),e.jsxs(ee,{children:[e.jsxs(ye,{children:[e.jsx(be,{className:"text-lg flex items-center gap-2",children:S.importSection}),e.jsx(Le,{children:S.autoApproveDesc})]}),e.jsx(ae,{className:"space-y-4",children:e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsx(q,{htmlFor:"auto-import",className:"flex-1",children:S.autoApprove}),e.jsx(ss,{id:"auto-import",checked:a.autoImportAfterExtraction,onCheckedChange:w=>i(M=>({...M,autoImportAfterExtraction:w}))})]})})]}),e.jsx("div",{className:"flex justify-end",children:e.jsxs(b,{onClick:j,disabled:P,children:[P?e.jsx(fe,{className:"h-4 w-4 mr-2 animate-spin"}):e.jsx(Ds,{className:"h-4 w-4 mr-2"}),S.save]})})]})},tl=()=>{const{toast:s}=Re(),[a,i]=t.useState([]),[y,E]=t.useState([]),[P,x]=t.useState([]),[O,S]=t.useState(!0);t.useState(!1);const[N,j]=t.useState(""),[w,M]=t.useState(""),[o,v]=t.useState(""),[u,p]=t.useState(""),[m,$]=t.useState("custom"),[H,J]=t.useState(null);t.useEffect(()=>{z()},[]),t.useEffect(()=>{N&&h(N)},[N]);const z=async()=>{S(!0);const[F,ce]=await Promise.all([g.from("section_visibility").select("*").order("sort_order"),g.rpc("admin_list_profiles")]);F.data&&i(F.data),ce.data&&x(ce.data),S(!1)},h=async F=>{const{data:ce}=await g.from("user_section_overrides").select("*").eq("user_id",F);ce&&E(ce)},I=async(F,ce,ie)=>{const{error:W}=await g.from("section_visibility").update({[ce]:ie}).eq("id",F);if(W){s({variant:"destructive",title:"Chyba",description:W.message});return}i(Z=>Z.map(K=>K.id===F?{...K,[ce]:ie}:K))},k=async(F,ce)=>{if(N)if(ce===null)await g.from("user_section_overrides").delete().eq("user_id",N).eq("section_key",F),E(ie=>ie.filter(W=>W.section_key!==F));else{const{error:ie}=await g.from("user_section_overrides").upsert({user_id:N,section_key:F,visible:ce},{onConflict:"user_id,section_key"});if(ie){s({variant:"destructive",title:"Chyba",description:ie.message});return}h(N)}},c=async()=>
232{if(!o||!u)return;const F=Math.max(...a.map(ie=>ie.sort_order),0),{error:ce}=await g.from("section_visibility").insert({section_key:o,section_label:u,section_group:m,sort_order:F+1,visible_to_owner:!1,visible_to_beirat:!1,visible_to_spravce:!1});if(ce){s({variant:"destructive",title:"Chyba",description:ce.message});return}v(""),p(""),z(),s({title:"Sekce pÅidána"})},d=async F=>{const{error:ce}=await g.from("section_visibility").delete().eq("id",F.id);if(ce){s({variant:"destructive",title:"Chyba",description:ce.message});return}z(),s({title:"Sekce odstranÄna"}),J(null)},T=F=>{const ce=P.find(W=>W.user_id===F);return ce&&(ce.full_name||[ce.first_name,ce.last_name].filter(Boolean).join(" ")||ce.email)||F},r=P.filter(F=>{var ie,W,Z,K;if(!w)return!0;const ce=w.toLowerCase();return((ie=F.full_name)==null?void 0:ie.toLowerCase().includes(ce))||((W=F.email)==null?void 0:W.toLowerCase().includes(ce))||((Z=F.first_name)==null?void 0:Z.toLowerCase().includes(ce))||((K=F.last_name)==null?void 0:K.toLowerCase().includes(ce))}),f=a.reduce((F,ce)=>{const ie=ce.section_group||"general";return F[ie]||(F[ie]=[]),F[ie].push(ce),F},{}),R={main:"Hlavnà sekce",costs:"Náklady",custom:"Vlastnà sekce",general:"OstatnÃ"};return O?e.jsx("div",{className:"flex items-center justify-center py-12",children:e.jsx(fe,{className:"h-8 w-8 animate-spin text-primary"})}):e.jsxs("div",{className:"space-y-6",children:[e.jsxs(ks,{defaultValue:"roles",children:[e.jsxs(Cs,{children:[e.jsxs(We,{value:"roles",className:"gap-2",children:[e.jsx(As,{className:"h-4 w-4"}),"Viditelnost dle rolÃ"]}),e.jsxs(We,{value:"users",className:"gap-2",children:[e.jsx(Ut,{className:"h-4 w-4"}),"PÅepisy pro uživatele"]}),e.jsxs(We,{value:"sections",className:"gap-2",children:[e.jsx(Xe,{className:"h-4 w-4"}),"Správa sekcÃ"]})]}),e.jsx(es,{value:"roles",className:"space-y-4",children:e.jsxs(ee,{children:[e.jsxs(ye,{children:[e.jsx(be,{className:"text-lg",children:"Výchozà viditelnost dle rolÃ"}),e.jsx(Le,{children:"Nastavte, které sekce uvidà vlastnÃci (Owner) a Älenové poradnÃho sboru (Beirat). AdministrátoÅi vidà vždy vÅ¡e."})]}),e.jsx(ae,{children:Object.entries(f).map(([F,ce])=>e.jsxs("div",{className:"mb-6 last:mb-0",children:[e.jsx("h3",{className:"text-sm font-semibold text-muted-foreground uppercase tracking-wider mb-3",children:R[F]||F}),e.jsxs($e,{children:[e.jsx(Be,{children:e.jsxs(Ne,{children:[e.jsx(D,{className:"w-[40%]",children:"Sekce"}),e.jsx(D,{className:"text-center",children:e.jsxs("div",{className:"flex items-center justify-center gap-1",children:[e.jsx(Fs,{className:"h-3.5 w-3.5"}),"Owner"]})}),e.jsx(D,{className:"text-center",children:e.jsxs("div",{className:"flex items-center justify-center gap-1",children:[e.jsx(As,{className:"h-3.5 w-3.5"}),"Beirat"]})}),e.jsx(D,{className:"text-center",children:e.jsxs("div",{className:"flex items-center justify-center gap-1",children:[e.jsx(As,{className:"h-3.5 w-3.5"}),"Správce"]})})]})}),e.jsx(Ue,{children:ce.map(ie=>e.jsxs(Ne,{children:[e.jsx(_,{children:e.jsxs("div",{className:"flex items-center gap-2",children:[ie.visible_to_owner||ie.visible_to_beirat||ie.visible_to_spravce?e.jsx(bs,{className:"h-4 w-4 text-primary"}):e.jsx(ja,{className:"h-4 w-4 text-muted-foreground"}),e.jsx("span",{className:"font-medium",children:ie.section_label}),e.jsx(Q,{variant:"outline",className:"text-[10px]",children:ie.section_key})]})}),e.jsx(_,{className:"text-center",children:e.jsx(ss,{checked:ie.visible_to_owner,onCheckedChange:W=>I(ie.id,"visible_to_owner",W)})}),e.jsx(_,{className:"text-center",children:e.jsx(ss,{checked:ie.visible_to_beirat,onCheckedChange:W=>I(ie.id,"visible_to_beirat",W)})}),e.jsx(_,{className:"text-center",children:e.jsx(ss,{checked:ie.visible_to_spravce,onCheckedChange:W=>I(ie.id,"visible_to_spravce",W)})})]},ie.id))})]})]},F))})]})}),e.jsx(es,{value:"users",className:"space-y-4",children:e.jsxs(ee,{children:[e.jsxs(ye,{children:[e.jsx(be,{className:"text-lg",children:"Individuálnà pÅepisy"}),e.jsx(Le,{children:"Vyberte uživatele a pÅepiÅ¡te mu výchozà viditelnost sekcÃ. PÅepis má pÅednost pÅed nastavenÃm role."})]}),e.jsxs(ae,{className:"space-y-4",children:[e.jsxs("div",{className:"flex gap-3",children:[e.jsxs("div",{className:"flex-1 relative",children:[e.jsx(fs,{className:"absolute left-3 top-1/2 -translate-y-1/2 h-4 w-4 text-muted-foreground"}),e.jsx(se,{placeholder:"Hledat uživatele...",value:w,onChange:F=>M(F.target.value),className:"pl-9"})]}),e.jsxs(De,{value:N,onValueChange:j,children:[e.jsx(Pe,{className:"w-[300px]",children:e.jsx(Ae,{placeholder:"Vyberte uživatele"})}),e.jsx(Ee,{children:r.map(F=>
232e.jsxs(me,{value:F.user_id,children:[T(F.user_id)," ",F.email&&`(${F.email})`]},F.user_id))})]})]}),N&&e.jsxs($e,{children:[e.jsx(Be,{children:e.jsxs(Ne,{children:[e.jsx(D,{children:"Sekce"}),e.jsx(D,{className:"text-center",children:"Výchozà (role)"}),e.jsx(D,{className:"text-center",children:"PÅepis"}),e.jsx(D,{className:"text-center",children:"Výsledek"}),e.jsx(D,{})]})}),e.jsx(Ue,{children:a.map(F=>{const ce=y.find(Z=>Z.section_key===F.section_key),ie=F.visible_to_owner,W=ce?ce.visible:ie;return e.jsxs(Ne,{children:[e.jsx(_,{className:"font-medium",children:F.section_label}),e.jsx(_,{className:"text-center",children:ie?e.jsx(Q,{variant:"outline",className:"bg-primary/10 text-primary",children:"Viditelné"}):e.jsx(Q,{variant:"outline",className:"text-muted-foreground",children:"Skryté"})}),e.jsx(_,{className:"text-center",children:ce?e.jsx(ss,{checked:ce.visible,onCheckedChange:Z=>k(F.section_key,Z)}):e.jsxs(b,{variant:"ghost",size:"sm",onClick:()=>k(F.section_key,!ie),className:"text-xs",children:[e.jsx(Xe,{className:"h-3 w-3 mr-1"}),"PÅepsat"]})}),e.jsx(_,{className:"text-center",children:W?e.jsx(bs,{className:"h-4 w-4 text-primary mx-auto"}):e.jsx(ja,{className:"h-4 w-4 text-muted-foreground mx-auto"})}),e.jsx(_,{children:ce&&e.jsx(b,{variant:"ghost",size:"icon",className:"h-7 w-7",onClick:()=>k(F.section_key,null),children:e.jsx(qe,{className:"h-3.5 w-3.5 text-destructive"})})})]},F.id)})})]}),!N&&e.jsx("div",{className:"text-center py-8 text-muted-foreground",children:"Vyberte uživatele pro zobrazenà a úpravu jeho individuálnÃch pÅepisů."})]})]})}),e.jsxs(es,{value:"sections",className:"space-y-4",children:[e.jsxs(ee,{children:[e.jsxs(ye,{children:[e.jsx(be,{className:"text-lg",children:"PÅidat vlastnà sekci"}),e.jsx(Le,{children:"VytvoÅte nové sekce, které budete moci zapÃnat/vypÃnat pro různé role."})]}),e.jsx(ae,{children:e.jsxs("div",{className:"flex gap-3 items-end",children:[e.jsxs("div",{className:"flex-1 space-y-1",children:[e.jsx(q,{children:"KlÃÄ sekce"}),e.jsx(se,{placeholder:"custom_reports",value:o,onChange:F=>v(F.target.value)})]}),e.jsxs("div",{className:"flex-1 space-y-1",children:[e.jsx(q,{children:"Název sekce"}),e.jsx(se,{placeholder:"Vlastnà reporty",value:u,onChange:F=>p(F.target.value)})]}),e.jsxs("div",{className:"w-40 space-y-1",children:[e.jsx(q,{children:"Skupina"}),e.jsxs(De,{value:m,onValueChange:$,children:[e.jsx(Pe,{children:e.jsx(Ae,{})}),e.jsxs(Ee,{children:[e.jsx(me,{value:"main",children:"HlavnÃ"}),e.jsx(me,{value:"costs",children:"Náklady"}),e.jsx(me,{value:"custom",children:"VlastnÃ"})]})]})]}),e.jsxs(b,{onClick:c,disabled:!o||!u,children:[e.jsx(Xe,{className:"h-4 w-4 mr-2"}),"PÅidat"]})]})})]}),e.jsxs(ee,{children:[e.jsx(ye,{children:e.jsx(be,{className:"text-lg",children:"ExistujÃcà sekce"})}),e.jsx(ae,{children:e.jsxs($e,{children:[e.jsx(Be,{children:e.jsxs(Ne,{children:[e.jsx(D,{children:"KlÃÄ"}),e.jsx(D,{children:"Název"}),e.jsx(D,{children:"Skupina"}),e.jsx(D,{children:"PoÅadÃ"}),e.jsx(D,{})]})}),e.jsx(Ue,{children:a.map(F=>e.jsxs(Ne,{children:[e.jsx(_,{children:e.jsx(Q,{variant:"outline",className:"font-mono text-xs",children:F.section_key})}),e.jsx(_,{className:"font-medium",children:F.section_label}),e.jsx(_,{children:e.jsx(Q,{variant:"secondary",children:R[F.section_group]||F.section_group})}),e.jsx(_,{children:F.sort_order}),e.jsx(_,{children:F.section_group==="custom"&&e.jsx(b,{variant:"ghost",size:"icon",className:"h-7 w-7",onClick:()=>J(F),children:e.jsx(qe,{className:"h-3.5 w-3.5 text-destructive"})})})]},F.id))})]})})]})]})]}),e.jsx(ms,{open:!!H,onOpenChange:F=>!F&&J(null),title:"Smazat sekci?",description:`Opravdu chcete smazat sekci "${H==null?void 0:H.section_label}"? Tato akce je nevratná.`,onConfirm:()=>H&&d(H)})]})};kn.workerSrc="https://cdnjs.cloudflare.com/ajax/libs/pdf.js/4.4.168/pdf.worker.min.mjs";const tn=[{value:"areas",label:"Oblasti"},{value:"subcategories",label:"Podkategorie"},{value:"descriptions",label:"Popisy"}],al=[{value:"cs",label:"ÄeÅ¡tina",flag:"ð¨ð¿"},{value:"en",label:"English",flag:"ð¬ð§"}],nl=({open:s,onOpenChange:a})=>{const{toast:i}=Re(),y=ws(),E=t.useRef(null),[P,x]=t.useState("upload"),[O,S]=t.useState("file"),[N,j]=t.useState(""),[w,M]=t.useState(""),[o,v]=t.useState(!1),[u,p]=t.useState("cs"),[m,$]=t.useState("descriptions"),[H,J]=t.useState([]),[z,h]=t.useState(0),[I,k]=t.useState(!1),c=async K=>{const l=await K.arrayBuffer(),U=await Cn({data:l}).promise;let n="";const G=U.numPages;for(let Y=1;Y<=G;Y++){const te=(await(await U.getPage(Y)).getTextContent()).items.map(xe=>xe.str).join(" ");n+=te+` 233 234`,h(Y/G*100)}return n},d=ns({mutationFn:async K=>{k(!0),h(10);const{data:l,error:U}=await g.functions.invoke("extract-terms",{body:{text:K,targetLanguage:u}});if(U)throw U;return h(100),l.terms},onSuccess:K=>{const l=K.map(U=>({germanTerm:U.german,translation:U.translation,section:m,selected:!0}));J(l),x("review"),k(!1)},onError:K=>
234{i({variant:"destructive",title:"Chyba pÅi extrakci",description:K.message||"NepodaÅilo se extrahovat termÃny z textu."}),k(!1)}}),T=ns({mutationFn:async()=>{const l=H.filter(n=>n.selected).map(n=>({section:n.section,language:u,key:n.germanTerm,value:n.translation})),{error:U}=await g.from("translations").upsert(l,{onConflict:"section,language,key"});if(U)throw U;return l.length},onSuccess:K=>{tt(),y.invalidateQueries({queryKey:["translations"]}),y.invalidateQueries({queryKey:["database-translations"]}),i({title:"Import dokonÄen",description:`Importováno ${K} pÅekladů.`}),W()},onError:()=>{i({variant:"destructive",title:"Chyba",description:"NepodaÅilo se importovat pÅeklady."})}}),r=async K=>{var U;const l=(U=K.target.files)==null?void 0:U[0];if(l){if(l.type!=="application/pdf"){i({variant:"destructive",title:"Neplatný formát",description:"Nahrajte prosÃm PDF soubor."});return}v(!0),h(0),M(l.name);try{const n=await c(l);j(n),x("extract"),i({title:"PDF zpracováno",description:`Extrahováno ${n.length.toLocaleString()} znaků textu.`})}catch(n){console.error("PDF parsing error:",n),i({variant:"destructive",title:"Chyba pÅi zpracovánà PDF",description:"NepodaÅilo se extrahovat text z PDF. Zkuste vložit text ruÄnÄ."}),S("text")}finally{v(!1),h(0)}}},f=()=>{if(!N.trim()){i({variant:"destructive",title:"Chyba",description:"Vložte text z PDF dokumentu."});return}d.mutate(N)},R=K=>{J(l=>l.map((U,n)=>n===K?{...U,selected:!U.selected}:U))},F=(K,l)=>{J(U=>U.map((n,G)=>G===K?{...n,section:l}:n))},ce=(K,l)=>{J(U=>U.map((n,G)=>G===K?{...n,translation:l}:n))},ie=K=>{J(l=>l.map(U=>({...U,selected:K})))},W=()=>{x("upload"),S("file"),j(""),M(""),J([]),h(0),a(!1)},Z=H.filter(K=>K.selected).length;return e.jsx(Ge,{open:s,onOpenChange:W,children:e.jsxs(Je,{className:"max-w-3xl max-h-[90vh]",children:[e.jsxs(Ye,{children:[e.jsxs(Qe,{className:"flex items-center gap-2",children:[e.jsx(ha,{className:"h-5 w-5 text-primary"}),"Extrakce pÅekladů z PDF"]}),e.jsxs(us,{children:[P==="upload"&&"Vložte text z PDF dokumentu s nÄmeckými nákladovými položkami.",P==="extract"&&"Vložte zkopÃrovaný text z PDF a spusÅ¥te AI extrakci.",P==="review"&&"Zkontrolujte a upravte extrahované pÅeklady pÅed importem."]})]}),e.jsxs("div",{className:"py-4",children:[(P==="upload"||P==="extract")&&e.jsxs("div",{className:"space-y-4",children:[e.jsxs("div",{className:"grid grid-cols-2 gap-4",children:[e.jsxs("div",{className:"space-y-2",children:[e.jsx(q,{children:"CÃlový jazyk pÅekladu"}),e.jsxs(De,{value:u,onValueChange:K=>p(K),children:[e.jsx(Pe,{children:e.jsx(Ae,{})}),e.jsx(Ee,{children:al.map(K=>e.jsxs(me,{value:K.value,children:[K.flag," ",K.label]},K.value))})]})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(q,{children:"Výchozà sekce"}),e.jsxs(De,{value:m,onValueChange:K=>$(K),children:[e.jsx(Pe,{children:e.jsx(Ae,{})}),e.jsx(Ee,{children:tn.map(K=>e.jsx(me,{value:K.value,children:K.label},K.value))})]})]})]}),e.jsxs(ks,{value:O,onValueChange:K=>S(K),children:[e.jsxs(Cs,{className:"grid w-full grid-cols-2",children:[e.jsxs(We,{value:"file",children:[e.jsx(Ps,{className:"h-4 w-4 mr-2"}),"Nahrát PDF"]}),e.jsxs(We,{value:"text",children:[e.jsx(Ea,{className:"h-4 w-4 mr-2"}),"Vložit text"]})]}),e.jsx(es,{value:"file",className:"mt-4",children:e.jsxs("div",{className:"space-y-4",children:[e.jsx("input",{ref:E,type:"file",accept:".pdf",onChange:r,className:"hidden"}),w?e.jsx(ee,{children:e.jsx(ae,{className:"p-4",children:e.jsxs("div",{className:"flex items-center gap-3",children:[e.jsx(Ea,{className:"h-8 w-8 text-primary"}),e.jsxs("div",{className:"flex-1",children:[e.jsx("p",{className:"font-medium",children:w}),e.jsxs("p",{className:"text-sm text-muted-foreground",children:[N.length.toLocaleString()," znaků extrahováno"]})]}),e.jsx(b,{variant:"outline",size:"sm",onClick:()=>{M(""),j(""),x("upload")},children:"ZmÄnit"})]})})}):e.jsxs("div",{onClick:()=>{var K;return(K=E.current)==null?void 0:K.click()},className:"border-2 border-dashed border-muted-foreground/25 rounded-lg p-8 text-center cursor-pointer hover:border-primary/50 transition-colors",children:[e.jsx(Ps,{className:"h-10 w-10 mx-auto mb-4 text-muted-foreground"}),e.jsx("p",{className:"text-sm font-medium",children:"KliknÄte pro nahránà PDF"}),e.jsx("p",{className:"text-xs text-muted-foreground mt-1",children:"nebo pÅetáhnÄte soubor sem"})]}),o&&e.jsxs("div",{className:"space-y-2",children:[e.jsxs("div",{className:"flex items-center gap-2 text-sm text-muted-foreground",children:[e.jsx(fe,{className:"h-4 w-4 animate-spin"}),"NaÄÃtám text z PDF..."]}),e.jsx(Bt,{value:z})]})]})}),e.jsx(es,{value:"text",className:"mt-4",children:e.jsxs("div",{className:"space-y-2",children:[e.jsx(q,{children:"Text z PDF (zkopÃrujte a vložte)"}),e.jsx(vs,{value:N,onChange:K=>{j(K.target.value),K.target.value.trim()&&x("extract")},placeholder:"Vložte sem text zkopÃrovaný z PDF dokumentu obsahujÃcà nÄmecké nákladové položky...",className:"min-h-[200px] font-mono text-sm"}),e.jsx("p",{className:"text-xs text-muted-foreground",children:"Tip: OtevÅete PDF, oznaÄte text (Ctrl+A) a zkopÃrujte (Ctrl+C), pak vložte sem (Ctrl+V)."})]})})]}),I&&e.jsxs("div",{className:"space-y-2",children:[e.jsxs("div",{className:"flex items-center gap-2 text-sm text-muted-foreground",children:[e.jsx(fe,{className:"h-4 w-4 animate-spin"}),"AI analyzuje text a extrahuje nÄmecké termÃny..."]}),e.jsx(Bt,{value:z})]})]}),P==="review"&&e.jsxs("div",{className:"space-y-4",children:[e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsxs("div",{className:"text-sm text-muted-foreground",children:["Nalezeno ",H.length," termÃnů, vybráno ",Z]}),e.jsxs("div",{className:"flex gap-2",children:[e.jsxs(b,{variant:"outline",size:"sm",onClick:()=>ie(!0),children:[e.jsx(jt,{className:"h-4 w-4 mr-1"}),"Vybrat vÅ¡e"]}),e.jsxs(b,{variant:"outline",size:"sm",onClick:()=>ie(!1),children:[e.jsx(Wt,{className:"h-4 w-4 mr-1"}),"ZruÅ¡it výbÄr"]})]})]}),e.jsx(bt,{className:"h-[400px] pr-4",children:e.jsx("div",{className:"space-y-2",children:H.map((K,l)=>e.jsx(ee,{className:`transition-opacity ${K.selected?"":"opacity-50"}`,children:e.jsx(ae,{className:"p-3",children:e.jsxs("div",{className:"flex items-start gap-3",children:[e.jsx(xs,{checked:K.selected,onCheckedChange:()=>R(l),className:"mt-1"}),e.jsxs("div",{className:"flex-1 grid grid-cols-3 gap-3",children:[e.jsxs("div",{children:[e.jsx(q,{className:"text-xs text-muted-foreground",children:"NÄmecký termÃn"}),e.jsx("p",{className:"font-mono text-sm",children:K.germanTerm})]}),e.jsxs("div",{children:[e.jsx(q,{className:"text-xs text-muted-foreground",children:"PÅeklad"}),e.jsx("input",{type:"text",value:K.translation,onChange:U=>ce(l,U.target.value),className:"w-full text-sm bg-transparent border-b border-transparent hover:border-muted focus:border-primary focus:outline-none"})]}),e.jsxs("div",{children:[e.jsx(q,{className:"text-xs text-muted-foreground",children:"Sekce"}),e.jsxs(De,{value:K.section,onValueChange:U=>F(l,U),children:[e.jsx(Pe,{className:"h-7 text-xs",children:e.jsx(Ae,{})}),e.jsx(Ee,{children:tn.map(U=>e.jsx(me,{value:U.value,children:U.label},U.value))})]})]})]})]})})},l))})})]})]}),e.jsxs(ls,{children:[e.jsx(b,{variant:"outline",onClick:W,children:"ZruÅ¡it"}),(P==="upload"||P==="extract")&&e.jsxs(b,{onClick:f,disabled:!N.trim()||I,children:[I?e.jsx(fe,{className:"h-4 w-4 mr-2 animate-spin"}):e.jsx(ha,{className:"h-4 w-4 mr-2"}),"Extrahovat termÃny"]}),P==="review"&&e.jsxs(e.Fragment,{children:[e.jsx(b,{variant:"outline",onClick:()=>x("extract"),children:"ZpÄt"}),e.jsxs(b,{onClick:()=>T.mutate(),disabled:Z===0||T.isPending,children:[T.isPending&&e.jsx(fe,{className:"h-4 w-4 mr-2 animate-spin"}),"Importovat ",Z," pÅekladů"]})]})]})]})})},la=[{value:"areas",label:"Oblasti (Areas)"},{value:"subcategories",label:"Podkategorie (Subcategories)"},{value:"descriptions",label:"Popisy (Descriptions)"}],oa=[{value:"cs",label:"ÄeÅ¡tina",flag:"ð¨ð¿"},{value:"en",label:"English",flag:"ð¬ð§"},{value:"de",label:"Deutsch",flag:"ð©ðª"}],rl=()=>{const{toast:s}=Re(),a=ws(),[i,y]=t.useState("all"),[E,P]=t.useState("all"),[x,O]=t.useState(""),[S,N]=t.useState(!1),[j,w]=t.useState(!1),[M,o]=t.useState(!1),[v,u]=t.useState(!1),[p,m]=t.useState(null),[$,H]=t.useState(null),[J,z]=t.useState({section:"descriptions",language:"cs",key:"",value:""}),{data:h,isLoading:I}=ds({queryKey:["translations"],queryFn:async()=>{const{data:l,error:U}=await g.from("translations").select("*").order("section").order("key");if(U)throw U;return l}}),k=ns({mutationFn:async l=>{const{error:U}=await g.from("translations").insert(l);if(U)throw U},onSuccess:()=>{tt(),a.invalidateQueries({queryKey:["translations"]}),a.invalidateQueries({queryKey:["database-translations"]}),s({title:"PÅeklad pÅidán",description:"Nový pÅeklad byl úspÄÅ¡nÄ uložen."}),r()},onError:l=>{s({variant:"destructive",title:"Chyba",description:l.message.includes("duplicate")?"Tento pÅeklad již existuje.":"NepodaÅilo se pÅidat pÅeklad."})}}),c=ns({mutationFn:async({id:l,data:U})=>{const{error:n}=await g.from("translations").update(U).eq("id",l);if(n)throw n},onSuccess:()=>{tt(),a.invalidateQueries({queryKey:["translations"]}),a.invalidateQueries({queryKey:["database-translations"]}),s({title:"PÅeklad aktualizován"}),r()},onError:()=>{s({variant:"destructive",title:"Chyba",description:"NepodaÅilo se aktualizovat pÅeklad."})}}),d=ns({mutationFn:async l=>{const{error:U}=await g.from("translations").delete().eq("id",l);if(U)throw U},onSuccess:()=>{tt(),a.invalidateQueries({queryKey:["translations"]}),a.invalidateQueries({queryKey:["database-translations"]}),s({title:"PÅeklad smazán"}),w(!1),H(null)},onError:()=>{s({variant:"destructive",title:"Chyba",description:"NepodaÅilo se smazat pÅeklad."})}}),T=ns({mutationFn:async()=>{const l=[];
234Object.entries(sa.areas).forEach(([n,G])=>{Object.entries(G).forEach(([Y,pe])=>{l.push({section:"areas",language:n,key:Y,value:pe})})}),Object.entries(sa.subcategories).forEach(([n,G])=>{Object.entries(G).forEach(([Y,pe])=>{l.push({section:"subcategories",language:n,key:Y,value:pe})})}),Object.entries(sa.descriptions).forEach(([n,G])=>{Object.entries(G).forEach(([Y,pe])=>{l.push({section:"descriptions",language:n,key:Y,value:pe})})});const U=100;for(let n=0;n<l.length;n+=U){const G=l.slice(n,n+U),{error:Y}=await g.from("translations").upsert(G,{onConflict:"section,language,key"});if(Y)throw Y}return l.length},onSuccess:l=>{tt(),a.invalidateQueries({queryKey:["translations"]}),a.invalidateQueries({queryKey:["database-translations"]}),s({title:"Import dokonÄen",description:`Importováno ${l} pÅekladů z JSON souboru.`}),o(!1)},onError:()=>{s({variant:"destructive",title:"Chyba",description:"NepodaÅilo se importovat pÅeklady."})}}),r=()=>{z({section:"descriptions",language:"cs",key:"",value:""}),m(null),N(!1)},f=l=>{m(l),z({section:l.section,language:l.language,key:l.key,value:l.value}),N(!0)},R=l=>{H(l),w(!0)},F=l=>{if(l.preventDefault(),!J.key.trim()||!J.value.trim()){s({variant:"destructive",title:"Chyba",description:"VyplÅte vÅ¡echna pole."});return}p?c.mutate({id:p.id,data:J}):k.mutate(J)},ce=()=>{if(!h)return;const l={areas:{},subcategories:{},descriptions:{}};h.forEach(Y=>{l[Y.section][Y.language]||(l[Y.section][Y.language]={}),l[Y.section][Y.language][Y.key]=Y.value});const U=new Blob([JSON.stringify(l,null,2)],{type:"application/json"}),n=URL.createObjectURL(U),G=document.createElement("a");G.href=n,G.download="translations-export.json",G.click(),URL.revokeObjectURL(n),s({title:"Export dokonÄen",description:"PÅeklady byly exportovány do JSON souboru."})},ie=(h==null?void 0:h.filter(l=>{if(i!=="all"&&l.section!==i||E!=="all"&&l.language!==E)return!1;if(x){const U=x.toLowerCase();return l.key.toLowerCase().includes(U)||l.value.toLowerCase().includes(U)}return!0}))||[],W={total:(h==null?void 0:h.length)||0,areas:(h==null?void 0:h.filter(l=>l.section==="areas").length)||0,subcategories:(h==null?void 0:h.filter(l=>l.section==="subcategories").length)||0,descriptions:(h==null?void 0:h.filter(l=>l.section==="descriptions").length)||0},Z=l=>{var U;return((U=oa.find(n=>n.value===l))==null?void 0:U.flag)||""},K=l=>{var U;return((U=la.find(n=>n.value===l))==null?void 0:U.label)||l};return I?e.jsx("div",{className:"flex items-center justify-center py-12",children:e.jsx(fe,{className:"h-8 w-8 animate-spin text-primary"})}):e.jsxs("div",{className:"space-y-6",children:[e.jsxs("div",{className:"grid grid-cols-2 md:grid-cols-4 gap-4",children:[e.jsx(ee,{children:e.jsxs(ye,{className:"pb-2",children:[e.jsx(Le,{children:"Celkem pÅekladů"}),e.jsx(be,{className:"text-2xl",children:W.total})]})}),e.jsx(ee,{children:e.jsxs(ye,{className:"pb-2",children:[e.jsx(Le,{children:"Oblasti"}),e.jsx(be,{className:"text-2xl",children:W.areas})]})}),e.jsx(ee,{children:e.jsxs(ye,{className:"pb-2",children:[e.jsx(Le,{children:"Podkategorie"}),e.jsx(be,{className:"text-2xl",children:W.subcategories})]})}),e.jsx(ee,{children:e.jsxs(ye,{className:"pb-2",children:[e.jsx(Le,{children:"Popisy"}),e.jsx(be,{className:"text-2xl",children:W.descriptions})]})})]}),e.jsxs(ee,{children:[e.jsx(ye,{children:e.jsxs("div",{className:"flex flex-col sm:flex-row gap-4 justify-between",children:[e.jsxs("div",{children:[e.jsxs(be,{className:"flex items-center gap-2",children:[e.jsx(Xt,{className:"h-5 w-5"}),"Správa pÅekladů"]}),e.jsx(Le,{children:"PÅidávejte a upravujte pÅeklady nákladových položek"})]}),e.jsxs("div",{className:"flex flex-wrap gap-2",children:[e.jsxs(b,{variant:"outline",size:"sm",onClick:()=>u(!0),children:[e.jsx(_s,{className:"h-4 w-4 mr-2"}),"Extrakce z PDF"]}),e.jsxs(b,{variant:"outline",size:"sm",onClick:()=>o(!0),children:[e.jsx(Ps,{className:"h-4 w-4 mr-2"}),"Import z JSON"]}),e.jsxs(b,{variant:"outline",size:"sm",onClick:ce,disabled:!(h!=null&&h.length),children:[e.jsx(vt,{className:"h-4 w-4 mr-2"}),"Export"]}),e.jsxs(b,{size:"sm",onClick:()=>N(!0),children:[e.jsx(Xe,{className:"h-4 w-4 mr-2"}),"PÅidat pÅeklad"]})]})]})}),e.jsxs(ae,{children:[e.jsxs("div",{className:"flex flex-col sm:flex-row gap-4 mb-4",children:[e.jsxs("div",{className:"relative flex-1",children:[e.jsx(fs,{className:"absolute left-3 top-1/2 -translate-y-1/2 h-4 w-4 text-muted-foreground"}),e.jsx(se,{placeholder:"Hledat klÃÄ nebo hodnotu...",value:x,onChange:l=>O(l.target.value),className:"pl-9"})]}),e.jsxs(De,{value:i,onValueChange:l=>y(l),children:[e.jsx(Pe,{className:"w-[180px]",children:e.jsx(Ae,{placeholder:"Sekce"})}),e.jsxs(Ee,{children:[e.jsx(me,{value:"all",children:"VÅ¡echny sekce"}),la.map(l=>e.jsx(me,{value:l.value,children:l.label},l.value))]})]}),e.jsxs(De,{value:E,onValueChange:l=>P(l),children:[e.jsx(Pe,{className:"w-[140px]",children:e.jsx(Ae,{placeholder:"Jazyk"})}),e.jsxs(Ee,{children:[e.jsx(me,{value:"all",children:"VÅ¡echny jazyky"}
234),oa.map(l=>e.jsxs(me,{value:l.value,children:[l.flag," ",l.label]},l.value))]})]})]}),e.jsx(bt,{className:"h-[500px]",children:e.jsxs($e,{children:[e.jsx(Be,{children:e.jsxs(Ne,{children:[e.jsx(D,{children:"Sekce"}),e.jsx(D,{children:"Jazyk"}),e.jsx(D,{children:"KlÃÄ (DE)"}),e.jsx(D,{children:"Hodnota"}),e.jsx(D,{className:"w-[100px]",children:"Akce"})]})}),e.jsx(Ue,{children:ie.length===0?e.jsx(Ne,{children:e.jsx(_,{colSpan:5,className:"text-center text-muted-foreground py-8",children:(h==null?void 0:h.length)===0?"ZatÃm žádné pÅeklady. Importujte data z JSON nebo pÅidejte nový pÅeklad.":"Žádné výsledky pro zadané filtry."})}):ie.map(l=>e.jsxs(Ne,{children:[e.jsx(_,{children:e.jsx(Q,{variant:"outline",className:"text-xs",children:K(l.section)})}),e.jsxs(_,{children:[e.jsx("span",{className:"text-lg mr-1",children:Z(l.language)}),l.language.toUpperCase()]}),e.jsx(_,{className:"font-mono text-sm max-w-[200px] truncate",children:l.key}),e.jsx(_,{className:"max-w-[300px] truncate",children:l.value}),e.jsx(_,{children:e.jsxs("div",{className:"flex gap-1",children:[e.jsx(b,{variant:"ghost",size:"icon",onClick:()=>f(l),children:e.jsx(Ns,{className:"h-4 w-4"})}),e.jsx(b,{variant:"ghost",size:"icon",onClick:()=>R(l),children:e.jsx(qe,{className:"h-4 w-4 text-destructive"})})]})})]},l.id))})]})}),ie.length>0&&e.jsxs("div",{className:"text-sm text-muted-foreground mt-4",children:["Zobrazeno ",ie.length," z ",(h==null?void 0:h.length)||0," pÅekladů"]})]})]}),e.jsx(Ge,{open:S,onOpenChange:l=>!l&&r(),children:e.jsxs(Je,{children:[e.jsxs(Ye,{children:[e.jsx(Qe,{children:p?"Upravit pÅeklad":"PÅidat pÅeklad"}),e.jsx(us,{children:p?"Upravte hodnotu pÅekladu.":"PÅidejte nový pÅeklad do slovnÃku."})]}),e.jsxs("form",{onSubmit:F,children:[e.jsxs("div",{className:"grid gap-4 py-4",children:[e.jsxs("div",{className:"grid grid-cols-2 gap-4",children:[e.jsxs("div",{className:"space-y-2",children:[e.jsx(q,{children:"Sekce"}),e.jsxs(De,{value:J.section,onValueChange:l=>z(U=>({...U,section:l})),disabled:!!p,children:[e.jsx(Pe,{children:e.jsx(Ae,{})}),e.jsx(Ee,{children:la.map(l=>e.jsx(me,{value:l.value,children:l.label},l.value))})]})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(q,{children:"Jazyk"}),e.jsxs(De,{value:J.language,onValueChange:l=>z(U=>({...U,language:l})),disabled:!!p,children:[e.jsx(Pe,{children:e.jsx(Ae,{})}),e.jsx(Ee,{children:oa.map(l=>e.jsxs(me,{value:l.value,children:[l.flag," ",l.label]},l.value))})]})]})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(q,{children:"KlÃÄ (nÄmecký termÃn)"}),e.jsx(se,{value:J.key,onChange:l=>z(U=>({...U,key:l.target.value})),placeholder:"napÅ. Hallenbad",disabled:!!p})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(q,{children:"PÅeklad"}),e.jsx(se,{value:J.value,onChange:l=>z(U=>({...U,value:l.target.value})),placeholder:"napÅ. Krytý bazén"})]})]}),e.jsxs(ls,{children:[e.jsx(b,{type:"button",variant:"outline",onClick:r,children:"ZruÅ¡it"}),e.jsxs(b,{type:"submit",disabled:k.isPending||c.isPending,children:[(k.isPending||c.isPending)&&e.jsx(fe,{className:"h-4 w-4 mr-2 animate-spin"}),p?"Uložit zmÄny":"PÅidat"]})]})]})]})}),e.jsx(It,{open:j,onOpenChange:w,children:e.jsxs(Tt,{children:[e.jsxs(Ot,{children:[e.jsx(Ft,{children:"Smazat pÅeklad?"}),e.jsxs(Mt,{children:['Opravdu chcete smazat pÅeklad "',$==null?void 0:$.key,'" â "',$==null?void 0:$.value,'"? Tuto akci nelze vrátit zpÄt.']})]}),e.jsxs(Lt,{children:[e.jsx(Rt,{children:"ZruÅ¡it"}),e.jsxs(Vt,{onClick:()=>$&&d.mutate($.id),className:"bg-destructive text-destructive-foreground hover:bg-destructive/90",children:[d.isPending&&e.jsx(fe,{className:"h-4 w-4 mr-2 animate-spin"}),"Smazat"]})]})]})}),e.jsx(It,{open:M,onOpenChange:o,children:e.jsxs(Tt,{children:[e.jsxs(Ot,{children:[e.jsx(Ft,{children:"Importovat pÅeklady z JSON?"}),e.jsx(Mt,{children:"Tato akce naimportuje vÅ¡echny pÅeklady ze souboru translations.json do databáze. ExistujÃcà pÅeklady se stejným klÃÄem budou pÅepsány."})]}),e.jsxs(Lt,{children:[e.jsx(Rt,{children:"ZruÅ¡it"}),e.jsxs(Vt,{onClick:()=>T.mutate(),children:[T.isPending&&e.jsx(fe,{className:"h-4 w-4 mr-2 animate-spin"}),"Importovat"]})]})]})}),e.jsx(nl,{open:v,onOpenChange:u})]})},wt={magic_link:"Magic Link",duplicate_registration:"Duplicitnà registrace",vote_confirmation:"Potvrzenà hlasu",vote_coowner_notification:"Oznámenà spoluvlastnÃkům",vote_invitation:"Pozvánka k hlasovánÃ",vote_reminder:"PÅipomÃnka",vote_result:"Výsledky hlasovánÃ",announcement_notification:"OznámenÃ",forum_new_post:"Nový pÅÃspÄvek",forum_new_comment:"OdpovÄÄ ve fóru",test_magic_link:"Test: Magic Link",test_vote_confirmation:"Test: Potvrzenà hlasu",test_vote_coowner_notification:"Test: Oznámenà spoluvl.",test_vote_invitation:"Test: Pozvánka",test_vote_reminder:"Test: PÅipomÃnka",test_vote_result:"Test: Výsledky",test_announcement_notification:"Test: OznámenÃ",test_forum_new_post:"Test: Nový pÅÃspÄvek"},ca={cs:"ÄeÅ¡tina",de:"Deutsch",en:"English"},an={sent:{label:"Odesláno",variant:"default",icon:qs},failed:{label:"Chyba",variant:"destructive",icon:js},skipped:{label:"PÅeskoÄeno",variant:"secondary",icon:Br},unknown:{label:"Neznámý",variant:"outline",icon:Ur}},nn={sent:{label:"PÅijato poskytovatelem",variant:"secondary"},deferred:{label:"Odloženo",variant:"outline"},delivered:{label:"DoruÄeno",variant:"default"},opened:{label:"OtevÅeno",variant:"default"},clicked:{label:"OtevÅeno + proklik",variant:"default"},bounced:{label:"NedoruÄeno",variant:"destructive"},complained:{label:"OznaÄeno jako spam",variant:"destructive"}},Ws=["bounced","complained"],da=["delivered","opened","clicked"],il=[{value:"all",label:"VÅ¡e"},{value:"delivered",label:"DoruÄeno"},{value:"undelivered",label:"NedoruÄeno"},{value:"pending",label:"Bez potvrzenÃ"}],ll=[{value:"24h",label:"PoslednÃch 24 h"},{value:"7d",label:"PoslednÃch 7 dnÃ"},{value:"30d",label:"PoslednÃch 30 dnÃ"},{value:"all",label:"VÅ¡e"}],cs=({label:s,value:a,mono:i})=>{const{toast:y}=Re();return a?e.jsxs("div",{className:"flex items-start gap-2 py-1.5 border-b border-border/50 last:border-0",children:[e.jsx("span",{className:"text-xs font-medium text-muted-foreground w-40 shrink-0 pt-0.5",children:s}),e.jsx("span",{className:`text-xs flex-1 break-all ${i?"font-mono":""}`,children:a}),i&&e.jsx(b,{variant:"ghost",size:"icon",className:"h-5 w-5 shrink-0",onClick:()=>{navigator.clipboard.writeText(a),y({title:"ZkopÃrováno"})},children:e.jsx(Os,{className:"h-3 w-3"})})]}):null},ol=()=>{const[s,a]=t.useState([]),[i,y]=t.useState(!0),[E,P]=t.useState("7d"),[x,O]=t.useState("all"),[S,N]=t.useState("all"),[j,w]=t.useState("all"),[M,o]=t.useState(""),[v,u]=t.useState(""),[p,m]=t.useState([]),[$,H]=t.useState(null),[J,z]=t.useState(1),[h,I]=t.useState(20),[k,c]=t.useState(null),[d,T]=t.useState(""),[r,f]=t.useState(!1),[R,F]=t.useState(null),[ce,ie]=t.useState(!1),[W,Z]=t.useState(null),[K,l]=t.useState(null),[U,n]=t.useState("en"),[G,Y]=t.useState(""),[pe,B]=t.useState(""),{toast:te}=Re(),xe=async V=>{const{error:_e}=await g.from("email_history").delete().eq("id",V);_e?te({title:"Chyba pÅi mazánÃ",description:_e.message,variant:"destructive"}):(te({title:"Záznam smazán"}),a(Ie=>Ie.filter(Ve=>Ve.id!==V)),H(null)),F(null)},de=async()=>{const V=le.map(Ie=>Ie.id);if(V.length===0)return;const{error:_e}=await g.from("email_history").delete().in("id",V);_e?te({title:"Chyba pÅi mazánÃ",description:_e.message,variant:"destructive"}):(te({title:`Smazáno ${V.length} záznamů`}),a([])),ie(!1)},L=V=>{l(V),n(V.language||"en"),Y(V.recipient||""),B("")},re=async()=>
234{if(!K||!K.template_type)return;const V=G.trim();if(!/^[^@\s]+@[^@\s]+\.[^@\s]+$/.test(V)){te({variant:"destructive",title:"Neplatná adresa",description:"Zadejte platnou e-mailovou adresu pÅÃjemce."});return}Z(K.id);try{let _e=V;const{data:Ie}=await g.from("owner_contacts").select("first_name, last_name, company_name").eq("email",K.recipient).limit(1).maybeSingle();Ie&&(_e=Ie.company_name||`${Ie.first_name||""} ${Ie.last_name||""}`.trim()||V);const Ve=window.location.origin,{error:Fe}=await g.functions.invoke("send-notification-email",{body:{template_type:K.template_type.replace(/^test_/,""),language:U,recipient_email:V,variables:{"{userName}":_e,"{loginLink}":`${Ve}/auth`,"{resetPasswordUrl}":`${Ve}/reset-password`,"{emailSignature}":""}}});if(Fe)throw Fe;const C=[`Znovu odesláno ${new Date().toLocaleString("cs-CZ")} na ${V}`,pe.trim()?`Poznámka správce: ${pe.trim()}`:null,K.admin_note||null].filter(Boolean).join(` 235`);await g.from("email_history").update({resent_at:new Date().toISOString(),resent_to:V,admin_note:C}).eq("id",K.id),te({title:"Odesláno",description:`E-mail byl odeslán na ${V} (${ca[U]||U}).`}),l(null),ne()}catch(_e){te({variant:"destructive",title:"Chyba",description:_e.message||"NepodaÅilo se odeslat."})}Z(null)},A=async V=>{if(T(V.subject||""),V.rendered_html){c(V.rendered_html);return}if(!V.template_type||!V.language)return;f(!0),c(null);const _e=V.template_type.replace(/^test_/,""),{data:Ie}=await g.from("email_templates").select("body_html").eq("template_type",_e).eq("language",V.language).eq("is_active",!0).maybeSingle();c((Ie==null?void 0:Ie.body_html)||'<p style="padding:20px;color:#888;">Å ablona nenalezena.</p>'),f(!1)},ne=async()=>{y(!0);let V=g.from("email_history").select("*").order("sent_at",{ascending:!1}).limit(500);if(E!=="all"){const Ve=new Date,Fe=E==="24h"?24:E==="7d"?168:720,C=new Date(Ve.getTime()-Fe*60*60*1e3).toISOString();V=V.gte("sent_at",C)}if(x!=="all"&&(V=V.eq("template_type",x)),S!=="all"&&(V=V.eq("status",S)),v.trim()){const Ve=v.trim().replace(/[%,]/g,"");V=V.or(`recipient.ilike.%${Ve}%,actual_recipient.ilike.%${Ve}%`)}const{data:_e}=await V;a(_e||[]),z(1);const{data:Ie}=await g.from("email_history").select("template_type").not("template_type","is",null);if(Ie){const Ve=[...new Set(Ie.map(Fe=>Fe.template_type))];m(Ve)}y(!1)};t.useEffect(()=>{const V=setTimeout(()=>u(M),300);return()=>clearTimeout(V)},[M]),t.useEffect(()=>{ne()},[E,x,S,v]);const le=s.filter(V=>{if(j==="all")return!0;const _e=V.delivery_status||"";return j==="delivered"?da.includes(_e):j==="undelivered"?Ws.includes(_e)||V.status==="failed":!da.includes(_e)&&!Ws.includes(_e)&&V.status!=="failed"}),oe={total:le.length,sent:le.filter(V=>V.status==="sent").length,failed:le.filter(V=>V.status==="failed").length,delivered:le.filter(V=>da.includes(V.delivery_status||"")).length,undelivered:le.filter(V=>Ws.includes(V.delivery_status||"")).length},ke=(()=>{const V=new Map;return s.forEach(_e=>{const Ie=_e.delivery_status||"";if(!(Ws.includes(Ie)||_e.status==="failed"))return;const Fe=(_e.recipient||"").toLowerCase(),ge=V.get(Fe)||{email:_e.recipient,bounced:0,complained:0,failed:0,last:_e.sent_at,reason:null,row:_e};Ie==="bounced"&&(ge.bounced+=1),Ie==="complained"&&(ge.complained+=1),_e.status==="failed"&&(ge.failed+=1),ge.reason||(ge.reason=_e.bounce_reason||_e.error_message||null),new Date(_e.sent_at)>new Date(ge.last)&&(ge.last=_e.sent_at,ge.row=_e),V.set(Fe,ge)}),[...V.values()].sort((_e,Ie)=>new Date(Ie.last).getTime()-new Date(_e.last).getTime())})(),je=s.length>0?Math.round(s.filter(V=>Ws.includes(V.delivery_status||"")||V.status==="failed").length/s.length*1e3)/10:0,ue=h==="all"?Math.max(le.length,1):h,ve=Math.max(1,Math.ceil(le.length/ue)),X=h==="all"?le:le.slice((J-1)*ue,J*ue),Ce=V=>new Date(V).toLocaleString("cs-CZ",{day:"2-digit",month:"2-digit",year:"numeric",hour:"2-digit",minute:"2-digit",timeZone:"Europe/Prague"})+" CET",ze=V=>new Date(V).toLocaleString("cs-CZ",{day:"2-digit",month:"2-digit",year:"numeric",hour:"2-digit",minute:"2-digit",second:"2-digit",timeZone:"Europe/Prague"})+" CET",Me=[{value:"10",label:"10"},{value:"20",label:"20"},{value:"50",label:"50"},{value:"all",label:"VÅ¡e"}];return e.jsxs("div",{className:"space-y-6",children:[ke.length>0&&e.jsx(ee,{className:"border-destructive/40 bg-destructive/5",children:e.jsxs(ae,{className:"pt-4 pb-4 space-y-3",children:[e.jsxs("div",{className:"flex items-start gap-2",children:[e.jsx(is,{className:"h-4 w-4 text-destructive mt-0.5 shrink-0"}),e.jsxs("div",{className:"flex-1 space-y-0.5",children:[e.jsxs("p",{className:"text-sm font-medium text-destructive",children:[ke.length," ",ke.length===1?"adresa vyžaduje":"adres vyžaduje"," pozornost (",je," % zpráv v tomto obdobÃ)"]}),e.jsx("p",{className:"text-xs text-muted-foreground",children:"NedoruÄené zprávy (bounce), stÞnosti na spam nebo chyby pÅi odeslánÃ. OvÄÅte správnost adresy s vlastnÃkem a zprávu odeÅ¡lete znovu."})]}),e.jsx(b,{variant:"outline",size:"sm",onClick:()=>{w("undelivered"),z(1)},children:"Zobrazit jen nedoruÄené"})]}),e.jsxs("div",{className:"space-y-1",children:[ke.slice(0,6).map(V=>e.jsxs("div",{className:"flex flex-wrap items-center gap-2 text-xs border-t border-destructive/20 pt-1.5",children:[e.jsx("span",{className:"font-medium",children:V.email}),V.bounced>0&&e.jsxs(Q,{variant:"destructive",className:"text-[10px]",children:["nedoruÄeno Ã",V.bounced]}),V.complained>0&&e.jsxs(Q,{variant:"destructive",className:"text-[10px]",children:["spam Ã",V.c
235omplained]}),V.failed>0&&e.jsxs(Q,{variant:"destructive",className:"text-[10px]",children:["chyba odeslánà Ã",V.failed]}),e.jsx("span",{className:"text-muted-foreground",children:Ce(V.last)}),V.reason&&e.jsxs("span",{className:"text-muted-foreground truncate max-w-[280px]",title:V.reason,children:["· ",V.reason]}),e.jsxs(b,{variant:"ghost",size:"sm",className:"h-6 px-2 text-xs ml-auto",onClick:()=>L(V.row),children:[e.jsx($s,{className:"h-3 w-3 mr-1"}),"Odeslat znovu"]})]},V.email)),ke.length>6&&e.jsxs("p",{className:"text-xs text-muted-foreground pt-1",children:["a dalšà ",ke.length-6,"â¦"]})]})]})}),e.jsxs("div",{className:"grid grid-cols-2 sm:grid-cols-5 gap-3",children:[e.jsx(ee,{children:e.jsxs(ae,{className:"pt-4 pb-3 text-center",children:[e.jsx("div",{className:"text-2xl font-bold",children:oe.total}),e.jsx("div",{className:"text-xs text-muted-foreground",children:"Celkem"})]})}),e.jsx(ee,{children:e.jsxs(ae,{className:"pt-4 pb-3 text-center",children:[e.jsx("div",{className:"text-2xl font-bold text-green-600",children:oe.sent}),e.jsx("div",{className:"text-xs text-muted-foreground",children:"Odesláno"})]})}),e.jsx(ee,{children:e.jsxs(ae,{className:"pt-4 pb-3 text-center",children:[e.jsx("div",{className:"text-2xl font-bold text-green-700",children:oe.delivered}),e.jsx("div",{className:"text-xs text-muted-foreground",children:"DoruÄeno"})]})}),e.jsx(ee,{children:e.jsxs(ae,{className:"pt-4 pb-3 text-center",children:[e.jsx("div",{className:"text-2xl font-bold text-destructive",children:oe.undelivered}),e.jsx("div",{className:"text-xs text-muted-foreground",children:"NedoruÄeno"})]})}),e.jsx(ee,{children:e.jsxs(ae,{className:"pt-4 pb-3 text-center",children:[e.jsx("div",{className:"text-2xl font-bold text-destructive",children:oe.failed}),e.jsx("div",{className:"text-xs text-muted-foreground",children:"Chyba odeslánÃ"})]})})]}),e.jsxs("div",{className:"flex flex-wrap gap-3 items-end",children:[e.jsxs("div",{className:"space-y-1",children:[e.jsx("span",{className:"text-xs text-muted-foreground",children:"ObdobÃ"}),e.jsxs(De,{value:E,onValueChange:P,children:[e.jsx(Pe,{className:"w-44",children:e.jsx(Ae,{})}),e.jsx(Ee,{children:ll.map(V=>e.jsx(me,{value:V.value,children:V.label},V.value))})]})]}),e.jsxs("div",{className:"space-y-1",children:[e.jsx("span",{className:"text-xs text-muted-foreground",children:"Å ablona"}),e.jsxs(De,{value:x,onValueChange:O,children:[e.jsx(Pe,{className:"w-48",children:e.jsx(Ae,{})}),e.jsxs(Ee,{children:[e.jsx(me,{value:"all",children:"VÅ¡e"}),p.map(V=>e.jsx(me,{value:V,children:wt[V]||V},V))]})]})]}),e.jsxs("div",{className:"space-y-1",children:[e.jsx("span",{className:"text-xs text-muted-foreground",children:"Stav"}),e.jsxs(De,{value:S,onValueChange:N,children:[e.jsx(Pe,{className:"w-36",children:e.jsx(Ae,{})}),e.jsxs(Ee,{children:[e.jsx(me,{value:"all",children:"VÅ¡e"}),e.jsx(me,{value:"sent",children:"Odesláno"}),e.jsx(me,{value:"failed",children:"Chyba"})]})]})]}),e.jsxs("div",{className:"space-y-1",children:[e.jsx("span",{className:"text-xs text-muted-foreground",children:"DoruÄenÃ"}),e.jsxs(De,{value:j,onValueChange:V=>{w(V),z(1)},children:[e.jsx(Pe,{className:"w-40",children:e.jsx(Ae,{})}),e.jsx(Ee,{children:il.map(V=>e.jsx(me,{value:V.value,children:V.label},V.value))})]})]}),e.jsxs("div",{className:"space-y-1 flex-1 min-w-[200px]",children:[e.jsx("span",{className:"text-xs text-muted-foreground",children:"PÅÃjemce"}),e.jsxs("div",{className:"relative",children:[e.jsx(fs,{className:"absolute left-2 top-1/2 -translate-y-1/2 h-3.5 w-3.5 text-muted-foreground"}),e.jsx(se,{value:M,onChange:V=>o(V.target.value),placeholder:"Hledat podle e-mailuâ¦",className:"pl-7 pr-7 h-10"}),M&&e.jsx("button",{type:"button",onClick:()=>o(""),className:"absolute right-2 top-1/2 -translate-y-1/2 text-muted-foreground hover:text-foreground",children:e.jsx(Wt,{className:"h-3.5 w-3.5"})})]})]}),e.jsxs("div",{className:"space-y-1",children:[e.jsx("span",{className:"text-xs text-muted-foreground",children:"Åádků"}),e.jsxs(De,{value:String(h),onValueChange:V=>{I(V==="all"?"all":parseInt(V)),z(1)},children:[e.jsx(Pe,{className:"w-24",children:e.jsx(Ae,{})}),e.jsx(Ee,{children:Me.map(V=>e.jsx(me,{value:V.value,children:V.label},V.value))})]})]}),e.jsx(b,{variant:"outline",size:"icon",onClick:ne,disabled:i,children:e.jsx(Es,{className:`h-4 w-4 ${i?"animate-spin":""}`})}),le.length>0&&e.jsxs(b,{variant:"outline",size:"sm",className:"text-destructive hover:text-destructive",onClick:()=>ie(!0),children:[e.jsx(qe,{className:"h-4 w-4 mr-1"}),"Smazat zobrazené (",le.length,")"]})]}),i?e.jsx("div",{className:"flex justify-center py-8",children:e.jsx(fe,{className:"h-6 w-6 animate-spin text-muted-foreground"})}):le.length===0?e.jsx(ee,{children:e.jsxs(ae,{className:"py-12 text-center",children:[e.jsx(Bs,{className:"h-10 w-10 mx-auto text-muted-foreground mb-3"}),e.jsx("p",{className:"text-muted-foreground",children:"Žádné e-maily v tomto obdobÃ"})]})}):e.jsx(ee,{children:e.jsxs(ae,{className:"p-0",children:[e.jsxs($e,{children:[e.jsx(Be,{children:e.jsxs(Ne,{className:"bg-muted/50 h-9",children:[e.jsx(D,{className:"w-8"}),e.jsx(D,{className:"text-xs",children:"Datum"}),e.jsx(D,{className:"text-xs",children:"Typ"}),e.jsx(D,{className:"text-xs",children:"PÅÃjemce"}),e.jsx(D,{className:"text-xs",children:"PÅedmÄt"}),e.jsx(D,{className:"text-xs",children:"Jazyk"}),e.jsx(D,{className:"text-xs",children:"Stav"}),e.jsx(D,{className:"text-xs",children:"DoruÄenÃ"}),e.jsx(D,{className:"text-xs",children:"PÅeÄteno"}),e.jsx(D,{className:"w-10"})]})}),e.jsx(Ue,{children:X.map(V=>{var Fe;const _e=an[V.status]||an.unknown,Ie=_e.icon,Ve=$===V.id;return e.jsxs(e.Fragment,{children:[e.jsxs(Ne,{className:"cursor-pointer hover:bg-muted/50 h-8",onClick:()=>H(Ve?null:V.id),children:[e.jsx(_,{className:"px-2 py-1.5",children:Ve?e.jsx(Js,{className:"h-4 w-4 text-muted-foreground"}):e.jsx(Ts,{className:"h-4 w-4 text-muted-foreground"})}),e.jsx(_,{className:"text-xs whitespace-nowrap py-1.5",children:Ce(V.sent_at)}),e.jsx(_,{className:"py-1.5",children:e.jsx(Q,{variant:"secondary",className:"text-xs",children:wt[V.template_type||""]||V.template_type||"â"})}),e.jsxs(_,{className:"text-sm py-1.5",children:[e.jsx("div",{children:V.recipient}),V.actual_recipient&&V.actual_recipient!==V.recipient&&e.jsxs("div",{className:"text-xs text-amber-600",children:["â původnÄ: ",V.actual_recipient]})]}),e.jsx(_,{className:"text-sm max-w-[250px] truncate py-1.5",children:V.subject||"â"}),e.jsx(_,{className:"py-1.5",children:V.language&&e.jsx(Q,{variant:"outline",className:"text-xs",children:ca[
235V.language]||V.language})}),e.jsx(_,{className:"py-1.5",children:e.jsxs(Q,{variant:_e.variant,className:"gap-1",children:[e.jsx(Ie,{className:"h-3 w-3"}),_e.label]})}),e.jsx(_,{className:"py-1.5",children:(()=>{const C=V.status==="failed"?{label:"Chyba odeslánÃ",variant:"destructive"}:nn[V.delivery_status||""]||{label:"Bez potvrzenÃ",variant:"outline"};return e.jsx(Q,{variant:C.variant,className:"text-[10px] whitespace-nowrap",title:V.bounce_reason||V.error_message||void 0,children:C.label})})()}),e.jsx(_,{className:"py-1.5",children:V.opened_at?e.jsx(Q,{className:"text-[10px] whitespace-nowrap",title:ze(V.opened_at),children:"PÅeÄteno"}):e.jsx(Q,{variant:"outline",className:"text-[10px] whitespace-nowrap text-muted-foreground",children:"NepÅeÄteno"})}),e.jsx(_,{className:"px-2 py-1.5",children:e.jsxs("div",{className:"flex items-center gap-0.5",children:[e.jsx(b,{variant:"ghost",size:"icon",className:"h-7 w-7",title:"Náhled e-mailu",onClick:C=>{C.stopPropagation(),A(V)},children:e.jsx(bs,{className:"h-4 w-4 text-muted-foreground"})}),e.jsx(b,{variant:"ghost",size:"icon",className:"h-7 w-7",title:Ws.includes(V.delivery_status||"")||V.status==="failed"?"NedoruÄeno â odeslat znovu":"Odeslat znovu",disabled:W===V.id,onClick:C=>{C.stopPropagation(),L(V)},children:W===V.id?e.jsx(fe,{className:"h-4 w-4 animate-spin text-muted-foreground"}):e.jsx($s,{className:`h-4 w-4 ${Ws.includes(V.delivery_status||"")||V.status==="failed"?"text-destructive":"text-muted-foreground"}`})}),e.jsx(b,{variant:"ghost",size:"icon",className:"h-7 w-7",title:"Smazat",onClick:C=>{C.stopPropagation(),F(V.id)},children:e.jsx(qe,{className:"h-4 w-4 text-muted-foreground hover:text-destructive"})})]})})]},V.id),Ve&&e.jsx(Ne,{children:e.jsx(_,{colSpan:10,className:"bg-muted/30 px-6 py-4",children:e.jsxs("div",{className:"max-w-2xl space-y-0",children:[e.jsx("div",{className:"flex justify-end pb-2",children:e.jsxs(b,{variant:"outline",size:"sm",className:"h-7 text-xs",onClick:C=>{C.stopPropagation(),navigator.clipboard.writeText(JSON.stringify(V,null,2)),te({title:"Originálnà log zkopÃrován do schr
235ánky"})},children:[e.jsx(Os,{className:"h-3 w-3 mr-1"}),"ZkopÃrovat originálnà log"]})}),e.jsx(cs,{label:"ID záznamu",value:V.id,mono:!0}),e.jsx(cs,{label:"Odesláno",value:ze(V.sent_at)}),e.jsx(cs,{label:"PÅÃjemce",value:V.recipient}),V.actual_recipient&&V.actual_recipient!==V.recipient&&e.jsx(cs,{label:"Původnà pÅÃjemce",value:V.actual_recipient}),e.jsx(cs,{label:"Typ Å¡ablony",value:wt[V.template_type||""]||V.template_type}),e.jsx(cs,{label:"Jazyk",value:ca[V.language||""]||V.language}),e.jsx(cs,{label:"PÅedmÄt",value:V.subject}),e.jsx(cs,{label:"Stav",value:_e.label}),e.jsx(cs,{label:"Stav doruÄenÃ",value:V.status==="failed"?"Chyba odeslánÃ":((Fe=nn[V.delivery_status||""])==null?void 0:Fe.label)||"Bez potvrzenà poskytovatele"}),e.jsx(cs,{label:"DoruÄeno",value:V.delivered_at?ze(V.delivered_at):null}),e.jsx(cs,{label:"OtevÅeno",value:V.opened_at?ze(V.opened_at):null}),e.jsx(cs,{label:"NedoruÄeno dne",value:V.bounced_at?ze(V.bounced_at):null}),e.jsx(cs,{label:"Provider Message ID",value:V.provider_message_id,mono:!0}),e.jsx(cs,{label:"Related Entity Type",value:V.related_entity_type}),e.jsx(cs,{label:"Related Entity ID",value:V.related_entity_id,mono:!0}),e.jsx(cs,{label:"Odesláno uživatelem",value:V.sent_by,mono:!0}),e.jsx(cs,{label:"Znovu odesláno",value:V.resent_at?ze(V.resent_at):null}),e.jsx(cs,{label:"Znovu odesláno na",value:V.resent_to}),V.admin_note&&e.jsxs("div",{className:"mt-3 p-3 bg-muted rounded-md",children:[e.jsx("span",{className:"text-xs font-medium block mb-1",children:"Evidence správce:"}),e.jsx("pre",{className:"text-xs whitespace-pre-wrap break-all",children:V.admin_note})]}),V.bounce_reason&&e.jsxs("div",{className:"mt-3 p-3 bg-destructive/10 rounded-md",children:[e.jsx("span",{className:"text-xs font-medium text-destructive block mb-1",children:"Důvod nedoruÄenà (poskytovatel):"}),e.jsx("pre",{className:"text-xs text-destructive whitespace-pre-wrap break-all font-mono",children:V.bounce_reason})]}),V.error_message&&e.jsxs("div",{className:"mt-3 p-3 bg-destructive/10 rounded-md",children:[e.jsx("span",{className:"text-xs font-medium text-destructive block mb-1",children:"Chybová zpráva:"}),e.jsx("pre",{className:"text-xs text-destructive whitespace-pre-wrap break-all font-mono",children:V.error_message})]})]})})},`${V.id}-detail`)]})})})]}),h!=="all"&&ve>1&&e.jsxs("div",{className:"flex items-center justify-between px-4 py-3 border-t text-sm text-muted-foreground",children:[e.jsxs("span",{children:[(J-1)*ue+1,"â",Math.min(J*ue,s.length)," z ",s.length]}),e.jsxs("div",{className:"flex items-center gap-1",children:[e.jsx(b,{variant:"outline",size:"sm",disabled:J===1,onClick:()=>z(J-1),children:"â"}),e.jsxs("span",{className:"px-2",children:[J," / ",ve]}),e.jsx(b,{variant:"outline",size:"sm",disabled:J>=ve,onClick:()=>z(J+1),children:"â"})]})]})]})}),e.jsx(Ge,{open:k!==null,onOpenChange:V=>{V||c(null)},children:e.jsxs(Je,{className:"max-w-2xl max-h-[80vh] overflow-hidden flex flex-col",children:[e.jsx(Ye,{children:e.jsx(Qe,{className:"text-base",children:d||"Náhled e-mailu"})}),r?e.jsx("div",{className:"flex items-center justify-center py-12",children:e.jsx(fe,{className:"h-5 w-5 animate-spin text-muted-foreground"})}):e.jsx("div",{className:"flex-1 overflow-auto border rounded-md",children:e.jsx("iframe",{srcDoc:k||"",className:"w-full min-h-[400px] border-0",sandbox:"",title:"Email preview"})})]})}),e.jsx(ms,{open:!!R,onOpenChange:V=>{V||F(null)},title:"Smazat záznam",description:"Opravdu chcete smazat tento záznam z historie e-mailů?",confirmText:"Smazat",onConfirm:()=>R&&xe(R)}),e.jsx(ms,{open:ce,onOpenChange:ie,title:"Smazat vÅ¡echny zobrazené záznamy",description:`Opravdu chcete smazat ${s.length} záznamů z historie e-mailů? Tuto akci nelze vrátit.`,confirmText:`Smazat ${s.length} záznamů`,onConfirm:de}),e.jsx(Ge,{open:!!K,onOpenChange:V=>{V||l(null)},children:e.jsxs(Je,{className:"max-w-md",children:[e.jsx(Ye,{children:e.jsx(Qe,{children:"Odeslat e-mail znovu"})}),K&&e.jsxs("div",{className:"space-y-4",children:[e.jsxs("div",{className:"text-sm space-y-1",children:[e.jsxs("p",{children:[e.jsx("span",{className:"text-muted-foreground",children:"Původnà pÅÃjemce:"})," ",K.recipient]}),e.jsxs("p",{children:[e.jsx("span",{className:"text-muted-foreground",children:"Å ablona:"})," ",wt[K.template_type||""]||K.template_type]}),(K.bounce_reason||K.error_message)&&e.jsxs("p",{className:"text-xs text-destructive break-all",children:["Důvod selhánÃ: ",K.bounce_reason||K.error_message]})]}),e.jsxs("div",{className:"space-y-1.5",children:[e.jsx(q,{children:"Adresa pÅÃjemce"}),e.jsx(se,{value:G,onChange:V=>Y(V.target.value),placeholder:"[email protected]"}),e.jsx("p",{className:"text-[11px] text-muted-foreground",children:"Adresu můžete opravit, pokud byla původnà chybná."})]}),e.jsxs("div",{className:"space-y-1.5",children:[e.jsx(q,{children:"Jazyk e-mailu"}),e.jsxs(De,{value:U,onValueChange:n,children:[e.jsx(Pe,{children:e.jsx(Ae,{})}),e.jsxs(Ee,{children:[e.jsx(me,{value:"cs",children:"ÄeÅ¡tina"}),e.jsx(me,{value:"de",children:"Deutsch"}),e.jsx(me,{value:"en",children:"English"})]})]})]}),e.jsxs("div",{className:"space-y-1.5",children:[e.jsx(q,{children:"Poznámka správce (uložà se do evidence)"}
235),e.jsx(vs,{value:pe,onChange:V=>B(V.target.value),rows:3,placeholder:"NapÅ.: adresa opravena po telefonátu s vlastnÃkem"})]}),e.jsxs("div",{className:"flex justify-end gap-2",children:[e.jsx(b,{variant:"outline",onClick:()=>l(null),children:"ZruÅ¡it"}),e.jsxs(b,{onClick:re,disabled:W===K.id,children:[W===K.id&&e.jsx(fe,{className:"h-4 w-4 animate-spin mr-1"}),e.jsx($s,{className:"h-4 w-4 mr-1"}),"Odeslat"]})]})]})]})})]})},rn=[{value:"magic_link",label:"Magic Link"},{value:"signup_confirmation",label:"Potvrzenà registrace"},{value:"password_reset",label:"Obnova hesla"},{value:"vote_confirmation",label:"Potvrzenà hlasu"},{value:"vote_coowner_notification",label:"Oznámenà spoluvlastnÃkům"},{value:"vote_invitation",label:"Pozvánka k hlasovánÃ"},{value:"vote_reminder",label:"PÅipomÃnka hlasovánÃ"},{value:"vote_result",label:"Výsledky hlasovánÃ"},{value:"announcement_notification",label:"OznámenÃ"},{value:"forum_new_post",label:"Nový pÅÃspÄvek na fóru"},{value:"forum_new_comment",label:"Nová odpovÄÄ ve fóru"},{value:"suspicious_login_alert",label:"PodezÅelé pÅihlášenÃ"},{value:"duplicate_registration",label:"Duplicitnà registrace"},{value:"registration_approved",label:"Schválenà registrace"}],kt=[{value:"cs",label:"ÄeÅ¡tina"},{value:"de",label:"Deutsch"},{value:"en",label:"English"}],cl={magic_link:["{userName}","{magicLink}","{expirationMinutes}","{emailSignature}"],signup_confirmation:["{userName}","{confirmationLink}","{emailSignature}"],password_reset:["{userName}","{resetLink}","{expirationMinutes}","{emailSignature}"],vote_confirmation:["{userName}","{pollTitle}","{selectedOption}","{apartmentCode}","{voterName}","{coOwnersRow}","{timestamp}","{fingerprint}","{emailSignature}","{pollLink}"],vote_coowner_notification:["{userName}","{pollTitle}","{apartmentCode}","{voterName}","{voteBasis}","{loginLink}","{emailSignature}"],vote_invitation:["{userName}","{pollTitle}","{pollDescription}","{deadline}","{pollLink}","{emailSignature}"],vote_reminder:["{userName}","{pollTitle}","{deadline}","{pollLink}","{loginInstructions}","{participationInfo}","{apartmentCodes}","{emailSignature}"],vote_result:["{firstName}","{lastName}","{userName}","{pollTitle}","{resolutionText}","{announcementDate}","{finalVerdict}","{evaluationSummary}","{legalBasisShort}","{verdictAccent}","{verdictBg}","{majorityType}","{majorityPercent}","{majorityPercentLabel}","{majorityWegRv}","{quorumDetail}","{decisiveOption}","{postingDate}","{challengeDeadline}","{deadlineInfo}","{challengeRight}","{ackLink}","{pollUrl}","{apartmentCodes}","{emailSignature}"],announcement_notification:["{userName}","{announcementTitle}","{announcementContent}","{emailSignature}"],forum_new_post:["{userName}","{authorName}","{threadTitle}","{categoryName}","{postPreview}","{forumLink}","{emailSignature}"],forum_new_comment:["{userName}","{authorName}","{threadTitle}","{categoryName}","{postPreview}","{forumLink}","{emailSignature}"],suspicious_login_alert:["{userName}","{loginTime}","{deviceLabel}","{severity}","{signalsSummary}","{resetPasswordUrl}","{contactAdminText}","{emailSignature}"],duplicate_registration:["{userName}","{loginLink}","{resetPasswordUrl}","{emailSignature}"],registration_approved:["{userName}","{loginLink}","{resetPasswordUrl}","{emailSignature}"]},ln={cs:{"{resolutionText}":'<div style="font-size:15px;line-height:23px;color:#1f2937;">VlastnÃci schvalujà rekonstrukci stÅechy domu Hintermoos v rozsahu dle nabÃdky ze dne 12.02.2026, s celkovými náklady do 148 000 EUR, financovanou z fondu oprav.</div>',"{deadlineInfo}":'<table role="presentation" width="100%" cellpadding="0" cellspacing="0" border="0" style="width:100%;background-color:#ffffff;border:1px solid #e2e7eb;border-radius:9px;overflow:hidden;"><tr><td width="50%" valign="top" class="deadline-cell deadline-cell-left" style="width:50%;padding:16px 18px;background-color:#f8fafb;border-right:1px solid #e2e7eb;font-family:Arial,Helvetica,sans-serif;"><table role="presentation" cellpadding="0" cellspacing="0" border="0"><tr><td style="width:8px;padding-right:10px;vertical-align:top;"><div style="width:8px;height:8px;border-radius:50%;background-color:#8a9aa8;margin-top:4px;"></div></td><td><div style="font-size:11px;line-height:16px;font-weight:600;letter-spacing:0.5px;text-transform:uppercase;color:#6b7c8a;">Datum vyvÄÅ¡enà v domÄ:</div><div style="margin-top:3px;font-size:17px;line-height:25px;font-weight:bold;color:#1f2937;">15.03.2026</div></td></tr></table></td><td width="50%" valign="top" class="deadline-cell" style="width:50%;padding:16px 18px;background-color:#f0f7fb;font-family:Arial,Helvetica,sans-serif;"><table role="presentation" cellpadding="0" cellspacing="0" border="0"><tr><td style="width:8px;padding-right:10px;vertical-align:top;"><div style="width:8px;height:8px;border-radius:50%;background-color:#3b82f6;margin-top:4px;"></div></td><td><div style="font-size:11px;line-height:16px;font-weight:600;letter-spacing:0.5px;text-transform:uppercase;color:#3b82f6;">Konec jednomÄsÃÄnà lhůty:</div><div style="margin-top:3px;font-size:17px;line-height:25px;font-weight:bold;color:#1f2937;">15.04.2026</div></td></tr></table></td></tr></table>',"{challengeRight}":"Každý vlastnÃk může podle § 24 odst. 6 WEG 2002 do jednoho mÄsÃce od vyvÄÅ¡enà usnesenà v domÄ podat u pÅÃsluÅ¡ného okresnÃho soudu (Bezirksgericht) návrh na urÄenà právnà neúÄinnosti usnesenÃ. Návrh se projednává v nesporném ÅÃzenà podle § 52 odst. 1 Ä. 4 WEG 2002.<br><br>Návrh musà procesnÄ smÄÅovat proti vÅ¡em ostatnÃm vlastnÃkům. Na stranÄ odpůrců jsou proto vedeni vÅ¡ichni vlastnÃci kromÄ navrhovatele â bez ohledu na to, zda hlasovali pro pÅijetà usnesenÃ, hlasovali proti, zdrželi se hlasovánà nebo se hlasovánà nezúÄastnili.<br><br>Toto procesnà postavenà neznamená, že dotÄený vlastnÃk usnesenà podporuje, nesouhlasà s návrhem na jeho napadenà nebo odpovÃdá za namÃtanou vadu. Vyplývá pÅÃmo ze zákonné úpravy tohoto ÅÃzenÃ.","{majorityPercentLabel}":"PodÃl vÅ¡ech spoluvlastnických podÃlů hlasujÃcÃch PRO","{postingDate}":"15.03.2026","{legalBasisShort}":'Podle § 24 odst. 4 WEG 2002. <a href="https://www.ris.bka.gv.at/NormDokument.wxe?Abfrage=Bundesnormen&Gesetzesnummer=20001921&
235Paragraf=24" style="color:#1a5276;text-decoration:underline;">ZnÄnà zákona (RIS) â</a> · <a href="https://www.ris.bka.gv.at/eli/bgbl/i/2002/70/P24/NOR40240614" style="color:#1a5276;text-decoration:underline;">§ 24 WEG 2002 â ELI (RIS)</a>',"{verdictAccent}":"#387851","{verdictBg}":"#edf6f0","{firstName}":"Jan","{lastName}":"KuÄera","{userName}":"Jan KuÄera","{pollTitle}":"SouhlasÃte s rekonstrukcà stÅechy?","{selectedOption}":"Ano, souhlasÃm","{voterName}":"Jan KuÄera","{voteBasis}":"dohoda spoluvlastnÃků (Äestné prohlášenÃ)","{coOwnersRow}":'<tr><td style="padding:12px 14px;background:#f9fafb;border-bottom:1px solid #e5e7eb;font-weight:bold;">VlastnÃci</td><td style="padding:12px 14px;border-bottom:1px solid #e5e7eb;">Jan KuÄera<br>Marie KuÄerová</td></tr>',"{pollDescription}":"Hlasovánà o rekonstrukci stÅechy domu.","{announcementTitle}":"Nové oznámenÃ","{finalVerdict}":"Návrh byl pÅijat","{evaluationSummary}":"Návrh pÅijat kvalifikovanou vÄtÅ¡inou odevzdaných hlasů, tedy (2/3 odevzdaných hlasů a zároveÅ min. 1/3 vÅ¡ech WEG podÃlů).","{legalBasis}":'<div style="margin-top:14px;padding:12px 14px;background:#ffffff;border:1px solid #dcece3;border-radius:10px;"><div style="font-size:11px;text-transform:uppercase;letter-spacing:0.5px;color:#6b7280;font-weight:bold;">Zákonný základ â § 24 odst. 4 WEG 2002</div><div style="margin-top:5px;font-size:13px;line-height:20px;color:#374151;font-style:italic;">âFür die Mehrheit der Stimmen der Wohnungseigentümer ist entweder die Mehrheit aller Miteigentumsanteile oder die Mehrheit von zwei Dritteln der abgegebenen Stimmen, ebenfalls berechnet nach dem Verhältnis der Miteigentumsanteile, erforderlich. Im zweitgenannten Fall muss die Mehrheit überdies zumindest ein Drittel aller Miteigentumsanteile erreichen.â</div><div style="margin-top:7px;font-size:12px;line-height:18px;"><a href="https://www.ris.bka.gv.at/NormDokument.wxe?Abfrage=Bundesnormen&Gesetzesnummer=20001921&Paragraf=24" style="color:#1a5276;text-decoration:underline;">Aktuálnà znÄnà § 24 WEG 2002 v RIS (nÄmecky) â</a></div></div>',"{resultsTableRows}":'<tr><td style="padding:11px 14px;border-bottom:1px solid #e5e7eb;font-size:14px;">Ano</td><td style="padding:11px 14px;border-bottom:1px solid #e5e7eb;text-align:center;font-size:14px;">18</td><td style="padding:11px 14px;border-bottom:1px solid #e5e7eb;text-align:right;font-size:14px;">28 540</td><td style="padding:11px 14px;border-bottom:1px solid #e5e7eb;text-align:right;font-size:14px;font-weight:bold;color:#1f6f43;">68,2 %</td></tr><tr><td style="padding:11px 14px;border-bottom:1px solid #e5e7eb;font-size:14px;">Ne</td><td style="padding:11px 14px;border-bottom:1px solid #e5e7eb;text-align:center;font-size:14px;">6</td><td style="padding:11px 14px;border-bottom:1px solid #e5e7eb;text-align:right;font-size:14px;">13 330</td><td style="padding:11px 14px;border-bottom:1px solid #e5e7eb;text-align:right;font-size:14px;">31,8 %</td></tr>',"{participationSummary}":'<div style="font-size:17px;line-height:23px;font-weight:bold;color:#1f2937;font-variant-numeric:tabular-nums;">24 z 32 <span style="font-weight:normal;font-size:12px;color:#6b7280;">jednotek</span><span style="color:#1a7f4b;"> · 75 %</span></div><div style="margin-top:5px;font-size:13px;line-height:19px;color:#1f2937;font-variant-numeric:tabular-nums;">41 870 z 55 230 <span style="color:#6b7280;font-size:12px;">WEG podÃlů</span><span style="color:#1a7f4b;font-weight:bold;"> · 75,8 %</span></div>',"{quorumSummary}":"SplnÄno â 41 870 z 55 230","{majorityType}":"Kvalifikovaná vÄtÅ¡ina (§ 24 odst. 4 druhá vÄta WEG 2002)","{challengeDeadline}":"15.04.2026","{majorityPercent}":"58,3 %","{majorityWegRv}":"855 314","{quorumDetail}":'<table role="presentation" width="100%" cellpadding="0" cellspacing="0" border="0" style="margin-top:10px;background:#ffffff;border:1px solid #e1e7e4;border-radius:10px;"><tr><td style="padding:14px 18px;font-family:Arial,Helvetica,sans-serif;"><table role="presentation" width="100%" cellpadding="0" cellspacing="0" border="0"><tr><td align="left" style="font-family:Arial,Helvetica,sans-serif;font-size:11px;letter-spacing:1px;text-transform:uppercase;color:#7a8794;font-weight:bold;vertical-align:middle;">Požadované kvórum</td><td align="right" style="font-family:Arial,Helvetica,sans-serif;vertical-align:middle;"><span style="display:inline-block;background:#e6f2ea;color:#2f6a49;font-size:11px;letter-spacing:0.8px;text-transform:uppercase;font-weight:bold;padding:4px 10px;border-radius:999px;white-space:nowrap;">SplnÄno</span></td></tr></table><div style="margin-top:10px;font-size:12px;line-height:19px;color:#6b7280;">
235Kvalifikovaná vÄtÅ¡ina podle § 24 odst. 4 druhé vÄty WEG 2002 (ve znÄnà novely WEG 2022) je druhá, mÃrnÄjšà cesta k pÅijetà usnesenÃ; uplatnà se, pokud nebylo dosaženo absolutnà vÄtÅ¡iny vÅ¡ech podÃlů. Musà být kumulativnÄ splnÄny dvÄ podmÃnky: (1) pro návrh musà být nejménÄ dvÄ tÅetiny skuteÄnÄ odevzdaných hlasů, poÄÃtáno podle WEG podÃlů, nikoli podle poÄtu osob, a zároveÅ (2) tyto souhlasné hlasy musà pÅedstavovat nejménÄ jednu tÅetinu vÅ¡ech WEG podÃlů na nemovitosti. Prvnà podmÃnka zajišťuje jasnou pÅevahu mezi hlasujÃcÃmi, druhá podmÃnka je pojistkou proti tomu, aby pÅi nÃzké úÄasti rozhodla o domÄ velmi malá menÅ¡ina vlastnÃků. NesplnÄnà byÅ¥ jediné z obou podmÃnek znamená, že usnesenà nebylo pÅijato.</div><div style="margin-top:12px;padding-top:10px;border-top:1px solid #eef1f0;"><div style="font-size:10px;letter-spacing:1px;text-transform:uppercase;color:#9aa5b1;font-weight:bold;">Hlasy proti a neúÄast</div><div style="margin-top:4px;font-size:11px;line-height:17px;color:#6b7280;">Proti návrhu / pro jiné varianty: 180 452 WEG-RV. Nehlasovalo: 733 546 WEG-RV. Celkem v domÄ: 1 467 092 WEG-RV.</div></div></td></tr></table>',"{decisiveOption}":"Varianta A","{abstainSummary}":"Nehlasovalo / zdrželo se: 8 jednotek · 13 360 WEG podÃlů (24,2 %)","{abstainNote}":"Jednotky, které nehlasovaly, se nezapoÄÃtávajà mezi odevzdané hlasy.","{voteBreakdown}":"<div>RozdÄlenà hlasůâ¦</div>","{notVotedCount}":"8","{notVotedShares}":"13 360","{notVotedPercent}":"24,2 %","{ackLink}":"https://hintermoos.at/auth?redirect=/owners/polls/123?ack=abc","{announcementContent}":"Obsah oznámenÃ...","{authorName}":"Marie Nováková","{threadTitle}":"Oprava výtahu â termÃn a náklady","{categoryName}":"Správa domu","{postPreview}":'<p style="margin:0;">Dobrý den, chtÄla bych se zeptat na plánovanou opravu výtahu. Kdy se pÅedpokládá zahájenà pracà a jaké budou odhadované náklady? Podle poslednÃch informacà z výboru SVJ by mÄla oprava probÄhnout v průbÄhu dubna, ale zatÃm jsme neobdrželi žádný oficiálnà harmonogram ani â¦</p>'},de:{"{resolutionText}":'<div style="font-size:15px;line-height:23px;color:#1f2937;">Die Wohnungseigentümer beschlieÃen die Sanierung des Daches des Hauses Hintermoos im Umfang des Angebots vom 12.02.2026 mit Gesamtkosten von bis zu 148.000 EUR, finanziert aus der Rücklage.</div>',"{deadlineInfo}":'<table role="presentation" width="100%" cellpadding="0" cellspacing="0" border="0" style="width:100%;background-color:#ffffff;border:1px solid #e2e7eb;border-radius:9px;overflow:hidden;"><tr><td width="50%" valign="top" class="deadline-cell deadline-cell-left" style="width:50%;padding:16px 18px;background-color:#f8fafb;border-right:1px solid #e2e7eb;font-family:Arial,Helvetica,sans-serif;"><table role="presentation" cellpadding="0" cellspacing="0" border="0"><tr><td style="width:8px;padding-right:10px;vertical-align:top;"><div style="width:8px;height:8px;border-radius:50%;background-color:#8a9aa8;margin-top:4px;"></div></td><td><div style="font-size:11px;line-height:16px;font-weight:600;letter-spacing:0.5px;text-transform:uppercase;color:#6b7c8a;">Datum des Anschlags im Haus:</div><div style="margin-top:3px;font-size:17px;line-height:25px;font-weight:bold;color:#1f2937;">15.03.2026</div></td></tr></table></td><td width="50%" valign="top" class="deadline-cell" style="width:50%;padding:16px 18px;background-color:#f0f7fb;font-family:Arial,Helvetica,sans-serif;"><table role="presentation" cellpadding="0" cellspacing="0" border="0"><tr><td style="width:8px;padding-right:10px;vertical-align:top;"><div style="width:8px;height:8px;border-radius:50%;background-color:#3b82f6;margin-top:4px;"></div></td><td><div style="font-size:11px;line-height:16px;font-weight:600;letter-spacing:0.5px;text-transform:uppercase;color:#3b82f6;">Ende der einmonatigen Frist:</div><div style="margin-top:3px;font-size:17px;line-height:25px;font-weight:bold;color:#1f2937;">15.04.2026</div></td></tr></table></td></tr></table>',"{challengeRight}":"Jeder Wohnungseigentümer kann gemäà § 24 Abs 6 WEG 2002 binnen eines Monats ab dem Anschlag des Beschlusses im Haus beim zuständigen Bezirksgericht die Feststellung der Rechtsunwirksamkeit des Beschlusses beantragen. Der Antrag wird im wohnrechtlichen AuÃerstreitverfahren nach § 52 Abs 1 Z 4 WEG 2002 behandelt.<br><br>Der Antrag ist verfahrensrechtlich gegen alle übrigen Wohnungseigentümer zu richten. Antragsgegner sind daher sämtliche Wohnungseigentümer mit Ausnahme des Antragstellers â unabhängig davon, ob sie für den Beschluss gestimmt, dagegen gestimmt, sich der Stimme enthalten oder gar nicht abgestimmt haben.<br><br>Diese Verfahrensstellung bedeutet nicht, dass der betroffene Wohnungseigentümer den Beschluss befürwortet, der Anfechtung entgegentritt oder für den behaupteten Mangel einzustehen hat. Sie ergibt sich unmittelbar aus der gesetzlichen Ausgestaltung dieses Verfahrens.","{majorityPercentLabel}":"Anteil aller Miteigentumsanteile, die dafür gestimmt haben","{postingDate}":"15.03.2026","{legalBasisShort}":'Gemäà § 24 Abs 4 WEG 2002. <a href="https://www.ris.bka.gv.at/NormDokument.wxe?Abfrage=Bundesnormen&Gesetzesnummer=20001921&
235Paragraf=24" style="color:#1a5276;text-decoration:underline;">Gesetzestext (RIS) â</a> · <a href="https://www.ris.bka.gv.at/eli/bgbl/i/2002/70/P24/NOR40240614" style="color:#1a5276;text-decoration:underline;">§ 24 WEG 2002 â ELI (RIS)</a>',"{verdictAccent}":"#387851","{verdictBg}":"#edf6f0","{firstName}":"Jan","{lastName}":"KuÄera","{userName}":"Jan KuÄera","{pollTitle}":"Stimmen Sie der Dachsanierung zu?","{selectedOption}":"Ja, ich stimme zu","{voterName}":"Jan KuÄera","{voteBasis}":"Vereinbarung der Miteigentümer (eidesstattliche Erklärung)","{coOwnersRow}":'<tr><td style="padding:12px 14px;background:#f9fafb;border-bottom:1px solid #e5e7eb;font-weight:bold;">Eigentümer</td><td style="padding:12px 14px;border-bottom:1px solid #e5e7eb;">Jan KuÄera<br>Marie KuÄerová</td></tr>',"{pollDescription}":"Abstimmung über die Dachsanierung des Hauses.","{announcementTitle}":"Neue Ankündigung","{finalVerdict}":"Der Antrag wurde angenommen","{evaluationSummary}":"Beschluss mit der Mehrheit von zwei Dritteln der abgegebenen Stimmen angenommen, also 2/3 der abgegebenen Stimmen und zugleich mind. 1/3 aller Miteigentumsanteile (§ 24 Abs 4 zweiter Fall WEG 2002).","{legalBasis}":'<div style="margin-top:14px;padding:12px 14px;background:#ffffff;border:1px solid #dcece3;border-radius:10px;"><div style="font-size:11px;text-transform:uppercase;letter-spacing:0.5px;color:#6b7280;font-weight:bold;">Rechtsgrundlage â § 24 Abs 4 WEG 2002</div><div style="margin-top:5px;font-size:13px;line-height:20px;color:#374151;font-style:italic;">âFür die Mehrheit der Stimmen der Wohnungseigentümer ist entweder die Mehrheit aller Miteigentumsanteile oder die Mehrheit von zwei Dritteln der abgegebenen Stimmen, ebenfalls berechnet nach dem Verhältnis der Miteigentumsanteile, erforderlich. Im zweitgenannten Fall muss die Mehrheit überdies zumindest ein Drittel aller Miteigentumsanteile erreichen.â</div><div style="margin-top:7px;font-size:12px;line-height:18px;"><a href="https://www.ris.bka.gv.at/NormDokument.wxe?Abfrage=Bundesnormen&Gesetzesnummer=20001921&Paragraf=24" style="color:#1a5276;text-decoration:underline;">Aktuelle Fassung des § 24 WEG 2002 im RIS â</a></div></div>',"{resultsTableRows}":'<tr><td style="padding:11px 14px;border-bottom:1px solid #e5e7eb;font-size:14px;">Ja</td><td style="padding:11px 14px;border-bottom:1px solid #e5e7eb;text-align:center;font-size:14px;">18</td><td style="padding:11px 14px;border-bottom:1px solid #e5e7eb;text-align:right;font-size:14px;">28 540</td><td style="padding:11px 14px;border-bottom:1px solid #e5e7eb;text-align:right;font-size:14px;font-weight:bold;color:#1f6f43;">68,2 %</td></tr><tr><td style="padding:11px 14px;border-bottom:1px solid #e5e7eb;font-size:14px;">Nein</td><td style="padding:11px 14px;border-bottom:1px solid #e5e7eb;text-align:center;font-size:14px;">6</td><td style="padding:11px 14px;border-bottom:1px solid #e5e7eb;text-align:right;font-size:14px;">13 330</td><td style="padding:11px 14px;border-bottom:1px solid #e5e7eb;text-align:right;font-size:14px;">31,8 %</td></tr>',"{participationSummary}":'<div style="font-size:17px;line-height:23px;font-weight:bold;color:#1f2937;font-variant-numeric:tabular-nums;">24 von 32 <span style="font-weight:normal;font-size:12px;color:#6b7280;">Einheiten</span><span style="color:#1a7f4b;"> · 75 %</span></div><div style="margin-top:5px;font-size:13px;line-height:19px;color:#1f2937;font-variant-numeric:tabular-nums;">41 870 von 55 230 <span style="color:#6b7280;font-size:12px;">Miteigentumsanteile</span><span style="color:#1a7f4b;font-weight:bold;"> · 75,8 %</span></div>',"{quorumSummary}":"Erfüllt â 41 870 von 55 230","{majorityType}":"Qualifizierte Mehrheit (§ 24 Abs 4 zweiter Satz WEG 2002)","{challengeDeadline}":"15.04.2026","{majorityPercent}":"58,3 %","{quorumDetail}":'<table role="presentation" width="100%" cellpadding="0" cellspacing="0" border="0" style="margin-top:10px;background:#ffffff;border:1px solid #e1e7e4;border-radius:10px;"><tr><td style="padding:14px 18px;font-family:Arial,Helvetica,sans-serif;"><table role="presentation" width="100%" cellpadding="0" cellspacing="0" border="0"><tr><td align="left" style="font-family:Arial,Helvetica,sans-serif;font-size:11px;letter-spacing:1px;text-transform:uppercase;color:#7a8794;font-weight:bold;vertical-align:middle;">Erforderliches Quorum</td><td align="right" style="font-family:Arial,Helvetica,sans-serif;vertical-align:middle;"><span style="display:inline-block;background:#e6f2ea;color:#2f6a49;font-size:11px;letter-spacing:0.8px;text-transform:uppercase;font-weight:bold;padding:4px 10px;border-radius:999px;white-space:nowrap;">Erfüllt</span></td></tr></table><div style="margin-top:10px;font-size:12px;line-height:19px;color:#6b7280;">Die Mehrheit von zwei Dritteln der abgegebenen Stimmen nach § 24 Abs 4 erster Satz zweiter Fall WEG 2002 (idF der WEG-Novelle 2022) ist der zweite gleichwertige Weg zur Beschlussfassung; sie kommt zum Tragen, wenn die Mehrheit aller Miteigentumsanteile nicht erreicht wurde. Zwei Voraussetzungen müssen kumulativ vorliegen: (1) mindestens zwei Drittel der abgegebenen Stimmen â berechnet nach dem Verhältnis der Miteigentumsanteile, nicht nach Köpfen â müssen zustimmen und (2) diese Mehrheit muss überdies zumindest ein Drittel aller Miteigentumsanteile erreichen (§ 24 Abs 4 zweiter Satz WEG 2002). Fehlt auch nur eine der beiden Voraussetzungen, kommt kein Beschluss zustande.</div><div style="margin-top:12px;padding-top:10px;border-top:1px solid #eef1f0;"><div style="font-size:10px;letter-spacing:1px;text-transform:uppercase;color:#9aa5b1;font-weight:bold;">Gegenstimmen und Nichtteilnahme</div><div style="margin-top:4px;font-size:11px;line-height:17px;color:#6b7280;">Gegen den Antrag / für andere Varianten: 180 452 WEG-RV. Keine Stimmabgabe: 733 546 WEG-RV. Gesamt auf der Liegenschaft: 1 467 092 WEG-RV.</div></div></td></tr></table>',"{decisiveOption}":"Variante A","{abstainSummary}":"Keine Stimmabgabe / Enthaltung: 8 Einheiten · 13 360 Miteigentumsanteile (24,2 %)","{abstainNote}":"Nicht abgegebene Stimmen zählen nicht zu den abgegebenen Stimmen.","{voteBreakdown}":"<div>Stimmenverteilungâ¦</div>","{notVotedCount}":"8","{notVotedShares}":"13 360","{notVotedPercent}":"24,2 %","{ackLink}":"https://hintermoos.at/auth?redirect=/owners/polls/123?ack=abc","{announcementContent}":"Inhalt der Ankündigung...","{authorName}":"Marie Nováková","{threadTitle}":"Aufzugreparatur â Termin und Kosten","{categoryName}":"Hausverwaltung","{postPreview}":'<p style="margin:0;">Guten Tag, ich möchte mich nach der geplanten Aufzugreparatur erkundigen. Wann wird mit den Arbeiten begonnen und wie hoch werden die geschätzten Kosten sein? Laut den letzten Informationen des Verwaltungsbeirats soll die Reparatur im Laufe des Aprils stattfinden, aber wir haben bisher weder einen offiziellen Zeitplan â¦</p>'},en:{"{resolutionText}":'<div style="font-size:15px;line-height:23px;color:#1f2937;">The co-owners resolve to carry out the roof renovation of the Hintermoos building in the scope of the offer dated 12 February 2026, with total costs of up to EUR 148,000, financed from the reserve fund.</div>',"{deadlineInfo}":'<table role="presentation" width="100%" cellpadding="0" cellspacing="0" border="0" style="width:100%;background-color:#ffffff;border:1px solid #e2e7eb;border-radius:9px;overflow:hidden;"><tr><td width="50%" valign="top" class="deadline-cell deadline-cell-left" style="width:50%;padding:16px 18px;background-color:#f8fafb;border-right:1px solid #e2e7eb;font-family:Arial,Helvetica,sans-serif;"><table role="presentation" cellpadding="0" cellspacing="0" border="0"><tr><td style="width:8px;padding-right:10px;vertical-align:top;"><div style="width:8px;height:8px;border-radius:50%;background-color:#8a9aa8;margin-top:4px;"></div></td><td><div style="font-size:11px;line-height:16px;font-weight:600;letter-spacing:0.5px;text-transform:uppercase;color:#6b7c8a;">Date of posting in the building:</div><div style="margin-top:3px;font-size:17px;line-height:25px;font-weight:bold;color:#1f2937;">15 March 2026</div></td></tr></table></td><td width="50%" valign="top" class="deadline-cell" style="width:50%;padding:16px 18px;background-color:#f0f7fb;font-family:Arial,Helvetica,sans-serif;"><table role="presentation" cellpadding="0" cellspacing="0" border="0"><tr><td style="width:8px;padding-right:10px;vertical-align:top;"><div style="width:8px;height:8px;border-radius:50%;background-color:#3b82f6;margin-top:4px;"></div></td><td><div style="font-size:11px;line-height:16px;font-weight:600;letter-spacing:0.5px;text-transform:uppercase;color:#3b82f6;">End of the one-month time limit:</div><div style="margin-top:3px;font-size:17px;line-height:25px;font-weight:bold;color:#1f2937;">15 April 2026</div></td></tr></table></td></tr></table>',"{challengeRight}":"Under § 24 para 6 WEG 2002, any owner may, within one month of the resolution being posted in the building, apply to the competent district court (Bezirksgericht) for a declaration that the resolution is legally ineffective. The application is heard in non-contentious proceedings under § 52 para 1 no 4 WEG 2002.<br><br>Procedurally, the application must be directed against all other owners. All owners other than the applicant are therefore named as respondents â irrespective of whether they voted in favour of the resolution, voted against it, abstained or did not take part in the vote.<br><br>This procedural position does not mean that the owner concerned supp
235orts the resolution, opposes the challenge or is answerable for the alleged defect. It follows directly from the statutory design of these proceedings.","{majorityPercentLabel}":"Share of all co-ownership shares voting in favour","{postingDate}":"15 March 2026","{legalBasisShort}":'Pursuant to § 24 para 4 WEG 2002. <a href="https://www.ris.bka.gv.at/NormDokument.wxe?Abfrage=Bundesnormen&Gesetzesnummer=20001921&Paragraf=24" style="color:#1a5276;text-decoration:underline;">Text of the law (RIS) â</a> · <a href="https://www.ris.bka.gv.at/eli/bgbl/i/2002/70/P24/NOR40240614" style="color:#1a5276;text-decoration:underline;">§ 24 WEG 2002 â ELI (RIS)</a>',"{verdictAccent}":"#387851","{verdictBg}":"#edf6f0","{firstName}":"Jan","{lastName}":"KuÄera","{userName}":"Jan KuÄera","{pollTitle}":"Do you agree with the roof renovation?","{selectedOption}":"Yes, I agree","{voterName}":"Jan KuÄera","{voteBasis}":"co-owner agreement (statutory declaration)","{coOwnersRow}":'<tr><td style="padding:12px 14px;background:#f9fafb;border-bottom:1px solid #e5e7eb;font-weight:bold;">Owners</td><td style="padding:12px 14px;border-bottom:1px solid #e5e7eb;">Jan KuÄera<br>Marie KuÄerová</td></tr>',"{pollDescription}":"Vote on the roof renovation of the building.","{announcementTitle}":"New announcement","{finalVerdict}":"The proposal was accepted","{evaluationSummary}":"Motion accepted by qualified majority of votes cast, i.e. 2/3 of votes cast and at least 1/3 of all WEG shares.","{legalBasis}":'<div style="margin-top:14px;padding:12px 14px;background:#ffffff;border:1px solid #dcece3;border-radius:10px;"><div style="font-size:11px;text-transform:uppercase;letter-spacing:0.5px;color:#6b7280;font-weight:bold;">Legal basis â § 24 para 4 WEG 2002</div><div style="margin-top:5px;font-size:13px;line-height:20px;color:#374151;font-style:italic;">âFür die Mehrheit der Stimmen der Wohnungseigentümer ist entweder die Mehrheit aller Miteigentumsanteile oder die Mehrheit von zwei Dritteln der abgegebenen Stimmen, ebenfalls berechnet nach dem Verhältnis der Miteigentumsanteile, erforderlich. Im zweitgenannten Fall muss die Mehrheit überdies zumindest ein Drittel aller Miteigentumsanteile erreichen.â</div><div style="margin-top:7px;font-size:12px;line-height:18px;"><a href="https://www.ris.bka.gv.at/NormDokument.wxe?Abfrage=Bundesnormen&Gesetzesnummer=20001921&Paragraf=24" style="color:#1a5276;text-decoration:underline;">Current text of § 24 WEG 2002 in the RIS (German) â</a></div></div>',"{resultsTableRows}":'<tr><td style="padding:11px 14px;border-bottom:1px solid #e5e7eb;font-size:14px;">Yes</td><td style="padding:11px 14px;border-bottom:1px solid #e5e7eb;text-align:center;font-size:14px;">18</td><td style="padding:11px 14px;border-bottom:1px solid #e5e7eb;text-align:right;font-size:14px;">28 540</td><td style="padding:11px 14px;border-bottom:1px solid #e5e7eb;text-align:right;font-size:14px;font-weight:bold;color:#1f6f43;">68.2%</td></tr><tr><td style="padding:11px 14px;border-bottom:1px solid #e5e7eb;font-size:14px;">No</td><td style="padding:11px 14px;border-bottom:1px solid #e5e7eb;text-align:center;font-size:14px;">6</td><td style="padding:11px 14px;border-bottom:1px solid #e5e7eb;text-align:right;font-size:14px;">13 330</td><td style="padding:11px 14px;border-bottom:1px solid #e5e7eb;text-align:right;font-size:14px;">31.8%</td></tr>',"{participationSummary}":'<div style="font-size:17px;line-height:23px;font-weight:bold;color:#1f2937;font-variant-numeric:tabular-nums;">24 of 32 <span style="font-weight:normal;font-size:12px;color:#6b7280;">units</span><span style="color:#1a7f4b;"> · 75 %</span></div><div style="margin-top:5px;font-size:13px;line-height:19px;color:#1f2937;font-variant-numeric:tabular-nums;">41 870 of 55 230 <span style="color:#6b7280;font-size:12px;">WEG shares</span><span style="color:#1a7f4b;font-weight:bold;"> · 75.8%</span></div>',"{quorumSummary}":"Met â 41 870 of 55 230","{majorityType}":"Qualified majority (§ 24 para 4 second sentence WEG 2002)","{challengeDeadline}":"15 April 2026","{majorityPercent}":"58.3 %","{majorityWegRv}":"855 314","{quorumDetail}":'<table role="presentation" width="100%" cellpadding="0" cellspacing="0" border="0" style="margin-top:10px;background:#ffffff;border:1px solid #e1e7e4;border-radius:10px;"><tr><td style="padding:14px 18px;font-family:Arial,Helvetica,sans-serif;"><table role="presentation" width="100%" cellpadding="0" cellspacing="0" border="0"><tr><td align="left" style="font-family:Arial,Helvetica,sans-serif;font-size:11px;letter-spacing:1px;text-transform:uppercase;color:#7a8794;font-weight:bold;vertical-align:middle;">Required quorum</td><td align="right" style="font-family:Arial,Helvetica,sans-serif;vertical-align:middle;"><span style="display:inline-block;background:#e6f2ea;color:#2f6a49;font-size:11px;letter-spacing:0.8px;text-transform:uppercase;font-weight:bold;padding:4px 10px;border-radius:999px;white-space:nowrap;">Met</span></td></tr></table><div style="margin-top:10px;font-size:12px;line-height:19px;color:#6b7280;">The qualified majority under § 24 para 4 second sentence WEG 2002 (as amended by the 2022 WEG reform) is the second, softer route to a resolution; it applies where the absolute majority of all shares was not reached. Two conditions must be met cumulatively: (1) at least two thirds of the votes actually cast â counted by WEG shares, not by heads â must be in favour, and (2) those votes in favour must at the same time represent at least one third of all WEG shares in the property. The first condition secures a clear majority among those voting; the second safeguards against a very small minority deciding for the whole building when turnout is low. If even one of the two conditions fail
235s, no resolution is adopted.</div><div style="margin-top:12px;padding-top:10px;border-top:1px solid #eef1f0;"><div style="font-size:10px;letter-spacing:1px;text-transform:uppercase;color:#9aa5b1;font-weight:bold;">Votes against and non-participation</div><div style="margin-top:4px;font-size:11px;line-height:17px;color:#6b7280;">Against the proposal / for other options: 180 452 WEG-RV. Did not vote: 733 546 WEG-RV. Total in the building: 1 467 092 WEG-RV.</div></div></td></tr></table>',"{decisiveOption}":"Option A","{abstainSummary}":"Did not vote / abstained: 8 units · 13 360 WEG shares (24.2 %)","{abstainNote}":"Units that did not vote are not counted among the votes cast.","{voteBreakdown}":"<div>Vote breakdownâ¦</div>","{notVotedCount}":"8","{notVotedShares}":"13 360","{notVotedPercent}":"24.2 %","{ackLink}":"https://hintermoos.at/auth?redirect=/owners/polls/123?ack=abc","{announcementContent}":"Announcement content...","{authorName}":"Marie Nováková","{threadTitle}":"Elevator repair â schedule and costs","{categoryName}":"Building Management","{postPreview}":'<p style="margin:0;">Hello, I would like to ask about the planned elevator repair. When is the work expected to begin and what will the estimated costs be? According to the latest information from the HOA board, the repair should take place during April, but we have not yet received an official â¦</p>'}},dl={"{apartmentCode}":"TOP 13","{timestamp}":"15.03.2026 18:42","{fingerprint}":"a1b2c3d4e5f6...abcdef123456","{emailSignature}":'<p style="color:#999;font-size:11px">WEG Bachwinkl 34, Maria Alm</p>',"{magicLink}":"https://example.com/auth/verify?token=xxx","{confirmationLink}":"https://example.com/auth/verify?token=xxx","{resetLink}":"https://example.com/reset-password?token=xxx","{expirationMinutes}":"60","{pollLink}":"https://example.com/owners/polls/123","{pollUrl}":"https://example.com/owners/polls/123","{deadline}":"31.03.2026","{totalVotes}":"24","{announcementDate}":"15.03.2026","{forumLink}":"https://example.com/owners/forum","{loginLink}":"https://example.com/auth","{loginInstructions}":'KliknÄte na tlaÄÃtko výše. Pokud nemáte heslo, použijte možnost âPÅihlásit se odkazem".',"{participationInfo}":"Dosud hlasovalo 12 z 28 oprávnÄných jednotek (43 %).","{apartmentCodes}":"TOP 13, TOP 14","{loginTime}":"27.03.2026 14:32","{deviceLabel}":"Chrome · Windows · Desktop","{severity}":"medium","{signalsSummary}":"Nové zaÅÃzenà (chrome|windows|desktop), 3 neúspÄÅ¡né pokusy za 30 min","{resetPasswordUrl}":"https://example.com/reset-password","{contactAdminText}":"kontaktujte správce"},ml=()=>{var xe,de;const{toast:s}=Re(),[a,i]=t.useState("config"),[y,E]=t.useState({email_from:"",email_from_name:"",email_reply_to:"",email_bcc_address:"",email_test_mode:"false",email_test_address:"",email_signature:"",default_email_language:"de",email_provider:"resend"}),[P,x]=t.useState(!0),[O,S]=t.useState(!1),[N,j]=t.useState(null),[w,M]=t.useState(!1),[o,v]=t.useState("vote_confirmation"),[u,p]=t.useState("cs"),[m,$]=t.useState({template_type:"vote_confirmation",language:"cs",subject:"",body_html:"",body_text:"",is_active:!0}),[H,J]=t.useState(!1),[z,h]=t.useState(!1),[I,k]=t.useState(!1),[c,d]=t.useState(!1),[T,r]=t.useState("cs"),[f,R]=t.useState(""),[F,ce]=t.useState(""),[ie,W]=t.useState(null);t.useEffect(()=>{Z(),K()},[]);const Z=async()=>{x(!0);const L=Object.keys(y),{data:re,error:A}=await g.from("system_settings").select("setting_key, setting_value").in("setting_key",L);if(!A&&re){const ne={...y};re.forEach(le=>{le.setting_key in ne&&(ne[le.setting_key]=le.setting_value)}),E(ne)}x(!1)},K=async()=>{M(!0);try{const{data:L,error:re}=await g.functions.invoke("check-email-config");!re&&L&&j(L)}catch{}M(!1)},l=async()=>{S(!0);try{for(const[L,re]of Object.entries(y))await g.from("system_settings").upsert({setting_key:L,setting_value:re,updated_at:new Date().toISOString()},{onConflict:"setting_key"});s({title:"Konfigurace uložena"}),await K()}catch{s({title:"Chyba pÅi ukládánÃ",variant:"destructive"})}S(!1)},U=t.useCallback(async(L,re)=>{J(!0);const{data:A,error:ne}=await g.from("email_templates").select("*").eq("template_type",L).eq("language",re).maybeSingle();$(!ne&&A?{id:A.id,template_type:A.template_type,language:A.language,subject:A.subject,body_html:A.body_html,body_text:A.body_text||"",is_active:A.is_active??!0}:{template_type:L,language:re,subject:"",body_html:"",body_text:"",is_active:!0}),J(!1),k(!1)},[]);t.useEffect(()=>{U(o,u)},[o,u,U]);const n=async()=>{var L;h(!0);try{const{data:re}=await g.auth.getUser(),A={template_type:m.template_type,language:m.language,subject:m.subject,body_html:m.body_html,body_text:m.body_text||null,is_active:m.is_active,updated_by:((L=re==null?void 0:re.user)==null?void 0:L.id)||null,updated_at:new Date().toISOString()};m.id?await g.from("email_templates").update(A).eq("id",m.id):await g.from("email_templates").insert(A),s({title:"Å ablona uložena"}),await U(o,u)}catch{s({title:"Chyba pÅi ukládánÃ",variant:"destructive"})}h(!1)},G=L=>{const A=ln[L||u]||ln.de;return{...dl,...A}},Y=()=>{let L=m.body_html;const re=G();for(const[A,ne]of Object.entries(re))L=L.split(A).join(ne);return L},pe=async()=>{d(!0);try{const L=G(T),{data:re,error:A}=await g.functions.invoke("send-test-email",{body:{template_type:o,language:T,recipient_email:f||void 0,sample_data:L}});if(A)throw A;if(re!=null&&re.error)throw new Error(re.error);s({title:"Testovacà e-mail odeslán",description:`PÅÃjemce: ${re.recipient}`})}catch(L){s({title:"Chyba pÅi odesÃlánÃ",description:L instanceof Error?L.message:"Neznámá chyba",variant:"destructive"})}d(!1)},B=async L=>{if(!F||!F.includes("@")){s({title:"Zadejte platnou e-mailovou adresu",variant:"destructive"});return}W(L);try{const{data:re,error:A}=await g.functions.invoke("test-email-provider",{body:{recipient_email:F,provider:L}});if(A)throw A;if(re!=null&&re.error)throw new Error(re.error);const ne=L==="brevo"?"Brevo":"Resend",le=re.fallbackUsed?` (použ
235it fallback: ${re.provider})`:"";s({title:`${ne} â e-mail odeslán â`,description:`PÅÃjemce: ${re.recipient}${le}`})}catch(re){s({title:`Chyba pÅi odesÃlánà pÅes ${L==="brevo"?"Brevo":"Resend"}`,description:re instanceof Error?re.message:"Neznámá chyba",variant:"destructive"})}W(null)},te=({ok:L,label:re})=>e.jsxs("div",{className:"flex items-center gap-2 text-sm",children:[L===void 0?e.jsx(_a,{className:"h-4 w-4 text-muted-foreground"}):L?e.jsx(qs,{className:"h-4 w-4 text-green-600"}):e.jsx(js,{className:"h-4 w-4 text-destructive"}),e.jsx("span",{children:re})]});return e.jsx("div",{className:"space-y-6",children:e.jsxs(ks,{value:a,onValueChange:i,children:[e.jsxs(Cs,{children:[e.jsx(We,{value:"config",children:"Konfigurace"}),e.jsx(We,{value:"templates",children:"Å ablony"}),e.jsxs(We,{value:"history",className:"gap-1",children:[e.jsx(qr,{className:"h-3.5 w-3.5"}),"Historie"]})]}),e.jsx(es,{value:"config",className:"space-y-6",children:P?e.jsx("div",{className:"flex justify-center py-8",children:e.jsx(fe,{className:"h-6 w-6 animate-spin text-muted-foreground"})}):e.jsxs(e.Fragment,{children:[e.jsxs(ee,{children:[e.jsxs(ye,{children:[e.jsx(be,{className:"text-base",children:"Stav e-mailové služby"}),e.jsx(Le,{children:"OvÄÅenà konfigurace odesÃlánÃ"})]}),e.jsx(ae,{className:"space-y-3",children:w?e.jsx(fe,{className:"h-4 w-4 animate-spin"}):N?e.jsxs(e.Fragment,{children:[e.jsx(te,{ok:N.resendConfigured,label:"Resend API klÃÄ"}),e.jsx(te,{ok:N.brevoConfigured,label:"Brevo API klÃÄ"}),e.jsxs("div",{className:"flex items-center gap-2 text-sm",children:[e.jsxs(Q,{variant:"outline",className:"text-xs",children:["AktivnÃ: ",N.activeProvider==="brevo"?"Brevo":"Resend"]}),e.jsxs("span",{className:"text-muted-foreground text-xs",children:["(fallback na ",N.activeProvider==="brevo"?"Resend":"Brevo",")"]})]}),e.jsx(te,{ok:N.fromConfigured,label:"OdesÃlacà adresa"}),e.jsx(te,{ok:N.replyToConfigured,label:"Reply-To adresa"})]}):e.jsx("p",{className:"text-sm text-muted-foreground",children:"Nelze ovÄÅit stav"})})]}),e.jsxs(ee,{children:[e.jsxs(ye,{children:[e.jsx(be,{className:"text-base",children:"Poskytovatel e-mailů"}),e.jsx(Le,{children:"Primárnà služba pro odesÃlánÃ. PÅi selhánà se automaticky použije záložnÃ."})]}),e.jsx(ae,{children:e.jsxs(De,{value:y.email_provider,onValueChange:L=>E({...y,email_provider:L}),children:[e.jsx(Pe,{className:"w-48",children:e.jsx(Ae,{})}),e.jsxs(Ee,{children:[e.jsx(me,{value:"resend",children:"Resend"}),e.jsx(me,{value:"brevo",children:"Brevo"})]})]})})]}),e.jsxs(ee,{children:[e.jsx(ye,{children:e.jsx(be,{className:"text-base",children:"OdesÃlatel"})}),e.jsxs(ae,{className:"space-y-4",children:[e.jsxs("div",{className:"grid gap-4 sm:grid-cols-2",children:[e.jsxs("div",{className:"space-y-2",children:[e.jsx(q,{children:"Jméno odesÃlatele"}),e.jsx(se,{value:y.email_from_name,onChange:L=>E({...y,email_from_name:L.target.value}),placeholder:"WEG Bachwinkl 34"})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(q,{children:"E-mail odesÃlatele (From)"}),e.jsx(se,{value:y.email_from,onChange:L=>E({...y,email_from:L.target.value}),placeholder:"[email protected]"})]})]}),e.jsxs("div",{className:"grid gap-4 sm:grid-cols-2",children:[e.jsxs("div",{className:"space-y-2",children:[e.jsx(q,{children:"Reply-To"}),e.jsx(se,{value:y.email_reply_to,onChange:L=>E({...y,email_reply_to:L.target.value}),placeholder:"[email protected]"})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(q,{children:"BCC"}),e.jsx(se,{value:y.email_bcc_address,onChange:L=>E({...y,email_bcc_address:L.target.value}),placeholder:"[email protected]"})]})]})]})]}),e.jsxs(ee,{children:[e.jsxs(ye,{children:[e.jsx(be,{className:"text-base",children:"Testovacà režim"}),e.jsx(Le,{children:"PÅi zapnutém testovacÃm režimu budou vÅ¡echny e-maily pÅesmÄrovány na testovacà adresu"})]}),e.jsxs(ae,{className:"space-y-4",children:[e.jsxs("div",{className:"flex items-center gap-3",children:[e.jsx(ss,{checked:y.email_test_mode==="true",onCheckedChange:L=>E({...y,email_test_mode:L?"true":"false"})}),e.jsx(q,{children:"Testovacà režim"}),y.email_test_mode==="true"&&e.jsx(Q,{variant:"outline",className:"text-amber-600 border-amber-300",children:"AKTIVNÃ"})]}),y.email_test_mode==="true"&&e.jsxs("div",{className:"space-y-2",children:[e.jsx(q,{children:"Testovacà e-mail"}),e.jsx(se,{value:y.email_test_address,onChange:L=>E({...y,email_test_address:L.target.value}),placeholder:"[email protected]"})]})]})]}),e.jsxs(ee,{children:[e.jsx(ye,{children:e.jsx(be,{className:"text-base",children:"Podpis a jazyk"})}),e.jsxs(ae,{className:"space-y-4",children:[e.jsxs("div",{className:"space-y-2",children:[e.jsx(q,{children:"Výchozà jazyk e-mailů"}),e.jsxs(De,{value:y.default_email_language,onValueChange:L=>E({...y,default_email_language:L}),children:[e.jsx(Pe,{className:"w-48",children:e.jsx(Ae,{})}),e.jsx(Ee,{children:kt.map(L=>e.jsx(me,{value:L.value,children:L.label},L.value))})]})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(q,{children:"Podpis (HTML)"}),e.jsx(vs,{value:y.email_signature,onChange:L=>E({...y,email_signature:L.target.value}),rows:4,placeholder:'<p style="color:#999">WEG Bachwinkl 34, Maria Alm</p>'})]})]})]}),e.jsxs(ee,{children:[e.jsxs(ye,{children:[e.jsx(be,{className:"text-base",children:"Test poskytovatele"}),e.jsx(Le,{children:"OdeÅ¡lete testovacà e-mail pÅÃmo pÅes Resend nebo Brevo a ovÄÅte, že API klÃÄe fungujÃ."})]}),e.jsxs(ae,{className:"space-y-4",children:[e.jsxs("div",{className:"space-y-2",children:[e.jsx(q,{children:"E-mail pÅÃjemce"}),e.jsx(se,{value:F,onChange:L=>ce(L.target.value),placeholder:"[email protected]",type:"email"})]}),e.jsxs("div",{className:"flex flex-wrap gap-3",children:[e.jsxs(b,{variant:"outline",onClick:()=>B("resend"),disabled:ie!==null||!F,children:[ie==="resend"?e.jsx(fe,{className:"h-4 w-4 animate-spin mr-2"}):e.jsx($s,{className:"h-4 w-4 mr-2"}),"Test Resend"]}),e.jsxs(b,{variant:"outline",onClick:()=>B("brevo"),disabled:ie!==null||!F,children:[ie==="brevo"?e.jsx(fe,{className:"h-4 w-4 animate-spin mr-2"}):e.jsx($s,{className:"h-4 w-4 mr-2"}),"Test Brevo"]})]})]})]}),e.jsxs(b,{onClick:l,disabled:O,children:[O?e.jsx(fe,{className:"h-4 w-4 animate-spin mr-2"}):e.jsx(Ds,{className:"h-4 w-4 mr-2"}),"Uložit konfiguraci"]})]})}),e.jsxs(es,{value:"templates",className:"space-y-6",children:[e.jsxs("div",{className:"flex flex-wrap gap-4 items-end",children:[e.jsxs("div",{className:"space-y-2",children:[e.jsx(q,{children:"Typ Å¡ablony"}),e.jsxs(De,{value:o,onValueChange:v,children:[e.jsx(Pe,{className:"w-56",children:e.jsx(Ae,{})}),e.jsx(Ee,{children:rn.map(L=>e.jsx(me,{value:L.value,children:L.label},L.value))})]})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(q,{children:"Jazyk"}),e.jsx("div",{className:"flex gap-1",children:kt.map(L=>e.jsx(b,{variant:u===L.value?"default":"outline",size:"sm",onClick:()=>
235p(L.value),children:L.label},L.value))})]})]}),H?e.jsx("div",{className:"flex justify-center py-8",children:e.jsx(fe,{className:"h-6 w-6 animate-spin text-muted-foreground"})}):e.jsxs(e.Fragment,{children:[e.jsxs(ee,{children:[e.jsx(ye,{children:e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsxs("div",{children:[e.jsxs(be,{className:"text-base",children:[(xe=rn.find(L=>L.value===o))==null?void 0:xe.label," â"," ",(de=kt.find(L=>L.value===u))==null?void 0:de.label]}),e.jsx(Le,{children:m.id?"Ãprava existujÃcà šablony":"Nová Å¡ablona"})]}),e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(q,{className:"text-sm",children:"AktivnÃ"}),e.jsx(ss,{checked:m.is_active,onCheckedChange:L=>$({...m,is_active:L})})]})]})}),e.jsxs(ae,{className:"space-y-4",children:[e.jsxs("div",{className:"space-y-2",children:[e.jsx(q,{children:"PÅedmÄt"}),e.jsx(se,{value:m.subject,onChange:L=>$({...m,subject:L.target.value}),placeholder:"PÅedmÄt e-mailu"})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(q,{children:"TÄlo (HTML)"}),e.jsx(vs,{value:m.body_html,onChange:L=>$({...m,body_html:L.target.value}),rows:12,className:"font-mono text-xs",placeholder:"<div>...</div>"})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(q,{children:"TÄlo (prostý text) â volitelné"}),e.jsx(vs,{value:m.body_text,onChange:L=>$({...m,body_text:L.target.value}),rows:6,className:"font-mono text-xs",placeholder:"Textová verze e-mailu..."})]}),e.jsxs("div",{className:"space-y-1",children:[e.jsx(q,{className:"text-xs text-muted-foreground",children:"Dostupné promÄnné"}),e.jsx("div",{className:"flex flex-wrap gap-1",children:(cl[o]||[]).map(L=>e.jsx(Q,{variant:"secondary",className:"text-xs font-mono cursor-pointer",onClick:()=>{navigator.clipboard.writeText(L),s({title:`${L} zkopÃrováno`})},children:L},L))})]})]})]}),e.jsxs("div",{className:"flex gap-3",children:[e.jsxs(b,{onClick:n,disabled:z,children:[z?e.jsx(fe,{className:"h-4 w-4 animate-spin mr-2"}):e.jsx(Ds,{className:"h-4 w-4 mr-2"}),"Uložit Å¡ablonu"]}),e.jsxs(b,{variant:"outline",onClick:()=>k(!I),children:[e.jsx(bs,{className:"h-4 w-4 mr-2"}),I?"Skrýt náhled":"Náhled"]})]}),e.jsxs(ee,{children:[e.jsxs(ye,{children:[e.jsxs(be,{className:"text-base flex items-center gap-2",children:[e.jsx($s,{className:"h-4 w-4"}),"Odeslat testovacà e-mail"]}),e.jsx(Le,{children:"OdeÅ¡le Å¡ablonu se vzorovými daty. PÅi zapnutém testovacÃm režimu se odeÅ¡le na testovacà adresu."})]}),e.jsxs(ae,{className:"space-y-4",children:[e.jsxs("div",{className:"flex flex-wrap gap-4 items-end",children:[e.jsxs("div",{className:"space-y-2",children:[e.jsx(q,{children:"Jazyk zprávy"}),e.jsxs(De,{value:T,onValueChange:r,children:[e.jsx(Pe,{className:"w-40",children:e.jsx(Ae,{})}),e.jsx(Ee,{children:kt.map(L=>e.jsx(me,{value:L.value,children:L.label},L.value))})]})]}),e.jsxs("div",{className:"space-y-2 flex-1 min-w-[200px]",children:[e.jsx(q,{children:"PÅÃjemce (volitelné â výchozÃ: váš e-mail)"}),e.jsx(se,{value:f,onChange:L=>R(L.target.value),placeholder:"[email protected]",type:"email"})]}),e.jsxs(b,{onClick:pe,disabled:c||!m.id,children:[c?e.jsx(fe,{className:"h-4 w-4 animate-spin mr-2"}):e.jsx($s,{className:"h-4 w-4 mr-2"}),"Odeslat test"]})]}),!m.id&&e.jsx("p",{className:"text-sm text-muted-foreground",children:"Å ablona musà být nejprve uložena, než ji lze odeslat."})]})]}),I&&e.jsxs(ee,{children:[e.jsxs(ye,{children:[e.jsx(be,{className:"text-base",children:"Náhled se vzorovými daty"}),e.jsxs(Le,{children:["PÅedmÄt: ",m.subject.replace(/\{(\w+)\}/g,L=>G()[L]||L)]})]}),e.jsx(ae,{children:e.jsx("div",{className:"border rounded-md overflow-hidden",children:e.jsx("iframe",{srcDoc:Y(),title:"Email preview",className:"w-full min-h-[400px] bg-white",sandbox:""})})})]})]})]}),e.jsx(es,{value:"history",children:e.jsx(ol,{})})]})})},ul=()=>{const{toast:s}=Re(),[a,i]=t.useState({winterImageUrl:"",summerImageUrl:"",winterStart:"11-01",summerStart:"04-15"}),[y,E]=t.useState(!0),[P,x]=t.useState(!1),[O,S]=t.useState(!1),[N,j]=t.useState(!1),w=t.useRef(null),M=t.useRef(null);t.useEffect(()=>{(async()=>{const{data:J}=await g.from("system_settings").select("setting_key, setting_value").in("setting_key",["hero_winter_image_url","hero_summer_image_url","hero_winter_start","hero_summer_start"]);if(J){const z={};J.forEach(h=>z[h.setting_key]=h.setting_value),i({winterImageUrl:z.hero_winter_image_url||"",summerImageUrl:z.hero_summer_image_url||"",winterStart:z.hero_winter_start||"11-01",
235summerStart:z.hero_summer_start||"04-15"})}E(!1)})()},[]);const o=async(H,J)=>{const z=J==="winter"?S:j;z(!0);const h=H.name.split(".").pop(),I=`hero-${J}-${Date.now()}.${h}`,{error:k}=await g.storage.from("hero-images").upload(I,H,{upsert:!0});if(k){s({variant:"destructive",title:"Chyba",description:k.message}),z(!1);return}const{data:c}=g.storage.from("hero-images").getPublicUrl(I),d=c.publicUrl;i(T=>({...T,[J==="winter"?"winterImageUrl":"summerImageUrl"]:d})),z(!1),s({title:"Nahráno",description:`${J==="winter"?"ZimnÃ":"LetnÃ"} obrázek byl nahrán.`})},v=(H,J)=>{var h;const z=(h=H.target.files)==null?void 0:h[0];z&&o(z,J),H.target.value=""},u=async(H,J)=>{const{error:z}=await g.from("system_settings").update({setting_value:J,updated_at:new Date().toISOString()}).eq("setting_key",H);z&&await g.from("system_settings").insert({setting_key:H,setting_value:J,description:""})},p=async()=>{x(!0),await Promise.all([u("hero_winter_image_url",a.winterImageUrl),u("hero_summer_image_url",a.summerImageUrl),u("hero_winter_start",a.winterStart),u("hero_summer_start",a.summerStart)]),s({title:"Uloženo",description:"Nastavenà pozadà bylo uloženo."}),x(!1)},m=()=>{const H=new Date,J=`${String(H.getMonth()+1).padStart(2,"0")}-${String(H.getDate()).padStart(2,"0")}`;return a.winterStart<=a.summerStart?J>=a.winterStart&&J<a.summerStart?"winter":"summer":J>=a.winterStart||J<a.summerStart?"winter":"summer"};if(y)return e.jsx("div",{className:"flex justify-center py-8",children:e.jsx(fe,{className:"h-6 w-6 animate-spin text-primary"})});const $=m();return e.jsxs(ee,{children:[e.jsxs(ye,{children:[e.jsxs(be,{className:"flex items-center gap-2",children:[e.jsx(Kr,{className:"h-5 w-5"}),"Pozadà úvodnà stránky"]}),e.jsxs(Le,{children:["Nastavte různé pozadà pro zimnà a letnà sezónu. Obrázky se automaticky pÅepÃnajà podle nastaveného data.",e.jsx("br",{}),e.jsxs("span",{className:"font-medium text-foreground",children:["Aktuálnà sezóna: ",$==="winter"?"âï¸ Zima":"âï¸ Léto"]})]})]}),e.jsxs(ae,{className:"space-y-8",children:[e.jsxs("div",{className:"space-y-4",children:[e.jsxs("div",{className:"flex items-center gap-2 text-lg font-semibold",children:[e.jsx(Zr,{className:"h-5 w-5 text-primary"}),"Zimnà pozadÃ"]}),a.winterImageUrl&&e.jsxs("div",{className:"relative rounded-lg overflow-hidden border border-border",children:[e.jsx("img",{src:a.winterImageUrl,alt:"Winter hero",className:"w-full h-48 object-cover"}),e.jsx(b,{variant:"destructive",size:"icon",className:"absolute top-2 right-2",onClick:()=>i({...a,winterImageUrl:""}),children:e.jsx(qe,{className:"h-4 w-4"})})]}),e.jsx("input",{ref:w,type:"file",accept:"image/*",className:"hidden",onChange:H=>v(H,"winter")}),e.jsxs(b,{variant:"outline",onClick:()=>{var H;return(H=w.current)==null?void 0:H.click()},disabled:O,children:[O?e.jsx(fe,{className:"h-4 w-4 mr-2 animate-spin"}):e.jsx(Ps,{className:"h-4 w-4 mr-2"}),"Nahrát zimnà obrázek"]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(q,{children:"ZaÄátek zimnà sezóny (MM-DD)"}),e.jsx(se,{value:a.winterStart,onChange:H=>i({...a,winterStart:H.target.value}),placeholder:"11-01",className:"max-w-[200px]"}),e.jsx("p",{className:"text-xs text-muted-foreground",children:"NapÅ. 11-01 = 1. listopadu"})]})]}),e.jsxs("div",{className:"space-y-4",children:[e.jsxs("div",{className:"flex items-center gap-2 text-lg font-semibold",children:[e.jsx(Hr,{className:"h-5 w-5 text-accent"}),"Letnà pozadÃ"]}),a.summerImageUrl&&e.jsxs("div",{className:"relative rounded-lg overflow-hidden border border-border",children:[e.jsx("img",{src:a.summerImageUrl,alt:"Summer hero",className:"w-full h-48 object-cover"}),e.jsx(b,{variant:"destructive",size:"icon",className:"absolute top-2 right-2",onClick:()=>i({...a,summerImageUrl:""}),children:e.jsx(qe,{className:"h-4 w-4"})})]}),e.jsx("input",{ref:M,type:"file",accept:"image/*",className:"hidden",onChange:H=>v(H,"summer")}),e.jsxs(b,{variant:"outline",onClick:()=>{var H;return(H=M.current)==null?void 0:H.click()},disabled:N,children:[N?e.jsx(fe,{className:"h-4 w-4 mr-2 animate-spin"}):e.jsx(Ps,{className:"h-4 w-4 mr-2"}),"Nahrát letnà obrázek"]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(q,{children:"ZaÄátek letnà sezóny (MM-DD)"}
235),e.jsx(se,{value:a.summerStart,onChange:H=>i({...a,summerStart:H.target.value}),placeholder:"04-15",className:"max-w-[200px]"}),e.jsx("p",{className:"text-xs text-muted-foreground",children:"NapÅ. 04-15 = 15. dubna"})]})]}),e.jsxs(b,{onClick:p,disabled:P,children:[P?e.jsx(fe,{className:"h-4 w-4 mr-2 animate-spin"}):e.jsx(Ds,{className:"h-4 w-4 mr-2"}),"Uložit nastavenÃ"]})]})]})},xl=()=>{const{toast:s}=Re(),[a,i]=t.useState(""),[y,E]=t.useState("30"),[P,x]=t.useState(!0),[O,S]=t.useState(!1);t.useEffect(()=>{(async()=>{const{data:M}=await g.from("system_settings").select("setting_key, setting_value").in("setting_key",["app_url","inactivity_timeout_minutes"]);if(M)for(const o of M)o.setting_key==="app_url"&&i(o.setting_value),o.setting_key==="inactivity_timeout_minutes"&&E(o.setting_value);x(!1)})()},[]);const N=async(w,M,o)=>{const{error:v}=await g.from("system_settings").update({setting_value:M,updated_at:new Date().toISOString()}).eq("setting_key",w);v&&await g.from("system_settings").insert({setting_key:w,setting_value:M,description:o})},j=async()=>{S(!0),await N("app_url",a,"URL adresa webu pro odkazy v e-mailech"),await N("inactivity_timeout_minutes",y,"Doba neÄinnosti v minutách pro automatické odhlášenÃ"),s({title:"Uloženo",description:"Nastavenà bylo uloženo."}),S(!1)};return P?e.jsx("div",{className:"flex justify-center py-8",children:e.jsx(fe,{className:"h-6 w-6 animate-spin text-primary"})}):e.jsxs("div",{className:"space-y-6",children:[e.jsxs(ee,{children:[e.jsxs(ye,{children:[e.jsxs(be,{className:"flex items-center gap-2",children:[e.jsx(wa,{className:"h-5 w-5"}),"URL adresa webu"]}),e.jsx(Le,{children:"Adresa webu použitá v e-mailových notifikacÃch (odkazy na fórum, hlasovánà apod.)"})]}),e.jsx(ae,{className:"space-y-4",children:e.jsxs("div",{className:"space-y-2",children:[e.jsx(q,{htmlFor:"app_url",children:"Web URL"}),e.jsx(se,{id:"app_url",value:a,onChange:w=>i(w.target.value),placeholder:"https://hintermoos.at"}),e.jsx("p",{className:"text-xs text-muted-foreground",children:"NapÅ. https://hintermoos.at â bez lomÃtka na konci"})]})})]}),e.jsxs(ee,{children:[e.jsxs(ye,{children:[e.jsxs(be,{className:"flex items-center gap-2",children:[e.jsx(Gt,{className:"h-5 w-5"}),"Automatické odhlášenÃ"]}),e.jsx(Le,{children:"Po uplynutà doby neÄinnosti bude uživatel automaticky odhlášen"})]}),e.jsx(ae,{className:"space-y-4",children:e.jsxs("div",{className:"space-y-2",children:[e.jsx(q,{htmlFor:"inactivity_timeout",children:"Doba neÄinnosti (minuty)"}),e.jsx(se,{id:"inactivity_timeout",type:"number",min:"5",max:"480",value:y,onChange:w=>E(w.target.value),className:"max-w-[200px]"}),e.jsx("p",{className:"text-xs text-muted-foreground",children:"DoporuÄeno: 30 minut. Rozsah: 5â480 minut."})]})})]}),e.jsxs(b,{onClick:j,disabled:O,children:[O?e.jsx(fe,{className:"h-4 w-4 mr-2 animate-spin"}):e.jsx(Ds,{className:"h-4 w-4 mr-2"}),"Uložit nastavenÃ"]})]})},hl=()=>{const{toast:s}=Re(),[a,i]=t.useState(!1),[y,E]=t.useState("medium"),[P,x]=t.useState("360"),[O,S]=t.useState(!0),[N,j]=t.useState(!1);t.useEffect(()=>{(async()=>{const{data:v}=await g.from("system_settings").select("setting_key, setting_value").in("setting_key",["login_alert_email_enabled","login_alert_min_severity","login_alert_email_cooldown_minutes"]);if(v)for(const u of v)u.setting_key==="login_alert_email_enabled"&&i(u.setting_value==="true"),u.setting_key==="login_alert_min_severity"&&E(u.setting_value),u.setting_key==="login_alert_email_cooldown_minutes"&&x(u.setting_value);S(!1)})()},[]);const w=async(o,v)=>{const{error:u}=await g.from("system_settings").update({setting_value:v,updated_at:new Date().toISOString()}).eq("setting_key",o);u&&await g.from("system_settings").insert({setting_key:o,setting_value:v})},M=async()=>{j(!0),await w("login_alert_email_enabled",a?"true":"false"),await w("login_alert_min_severity",y),await w("login_alert_email_cooldown_minutes",P),s({title:"Uloženo",description:"BezpeÄnostnà nastavenà bylo uloženo."}),j(!1)};return O?e.jsx("div",{className:"flex justify-center py-8",children:e.jsx(fe,{className:"h-6 w-6 animate-spin text-primary"})}):e.jsxs(ee,{children:[e.jsxs(ye,{children:[e.jsxs(be,{className:"flex items-center gap-2",children:[e.jsx(nt,{className:"h-5 w-5"}),"BezpeÄnostnà notifikace"]}),e.jsx(Le,{children:"E-mailová upozornÄnà pÅi podezÅelém pÅihlášenà (nové zaÅÃzenÃ, neúspÄÅ¡né pokusy apod.)"})]}),e.jsxs(ae,{className:"space-y-5",children:[e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsxs("div",{className:"space-y-0.5",children:[e.jsx(q,{children:"E-mail pÅi podezÅelém pÅihlášenÃ"}),e.jsx("p",{className:"text-xs text-muted-foreground",children:"OdesÃlat uživateli e-mail, když je detekováno podezÅelé pÅihlášenÃ"})]}),e.jsx(ss,{checked:a,onCheckedChange:i})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(q,{children:"Minimálnà závažnost pro odeslánÃ"}),e.jsxs(De,{value:y,onValueChange:E,children:[e.jsx(Pe,{className:"max-w-[200px]",children:e.jsx(Ae,{})}),e.jsxs(Ee,{children:[e.jsx(me,{value:"low",children:"NÃzká (low)"}),e.jsx(me,{value:"medium",children:"StÅednà (medium)"}),e.jsx(me,{value:"high",children:"Vysoká (high)"})]})]}),e.jsx("p",{className:"text-xs text-muted-foreground",children:"E-mail se odeÅ¡le jen pokud závažnost alertu dosáhne zvolené úrovnÄ nebo vyššÃ"})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(q,{htmlFor:"cooldown",children:"Cooldown (minuty)"}),e.jsx(se,{id:"cooldown",type:"number",min:"30",max:"1440",value:P,onChange:o=>x(o.target.value),className:"max-w-[200px]"}),e.jsx("p",{className:"text-xs text-muted-foreground",children:"Minimálnà doba mezi dvÄma e-maily pro jednoho uživatele. VýchozÃ: 360 min (6 h)."})]}),e.jsxs(b,{onClick:M,disabled:N,size:"sm",children:[N?e.jsx(fe,{className:"h-4 w-4 mr-2 animate-spin"}):e.jsx(Ds,{className:"h-4 w-4 mr-2"}),"Uložit bezpeÄnostnà nastavenÃ"]})]})]})},pl=()=>e.jsxs(ks,{defaultValue:"general",className:"space-y-6",children:[e.jsxs(Cs,{className:"grid w-full max-w-3xl grid-cols-4",children:[e.jsxs(We,{value:"general",className:"flex items-center gap-2",children:[e.jsx(Gt,{className:"h-4 w-4"}),e.jsx("span",{children:"Obecné"})]}),e.jsxs(We,{value:"display",className:"flex items-center gap-2",children:[e.jsx(bs,{className:"h-4 w-4"}),e.jsx("span",{children:"ZobrazenÃ"})]}),e.jsxs(We,{value:"translations",className:"flex items-center gap-2",children:[e.jsx(Xt,{className:"h-4 w-4"}),e.jsx("span",{children:"PÅeklady"})]}),e.jsxs(We,{value:"email",className:"flex items-center gap-2",children:[e.jsx(Bs,{className:"h-4 w-4"}),e.jsx("span",{children:"E-maily"})]})]}),e.jsxs(es,{value:"general",className:"space-y-8",children:[e.jsx(xl,{}),e.jsx(hl,{}),e.jsx(ul,{})]}),e.jsxs(es,{value:"display",className:"space-y-8",children:[e.jsx(sl,{}),e.jsx(tl,{})]}),e.jsx(es,{value:"translations",children:e.jsx(rl,{})}),e.jsx(es,{value:"email",children:e.jsx(ml,{})})]}),Un={auth_header:{label:"Autorizace",tooltip:"Kontrola pÅÃtomnosti a formátu JWT tokenu v hlaviÄce požadavku",okDesc:"JWT token byl nalezen a má správný formát",failDesc:"Chybà nebo je neplatný Authorization header â požadavek nebyl autorizován",skipDesc:"AutorizaÄnà hlaviÄka pÅeskoÄena"},user_validation:{label:"OvÄÅenà uživatele",tooltip:"OvÄÅenà identity uživatele pomocà JWT tokenu pÅes Supabase Auth",okDesc:"Uživatel byl úspÄÅ¡nÄ identifikován",failDesc:"Token je neplatný, expirovaný nebo uživatel neexistuje",skipDesc:"OvÄÅenà uživatele p
235ÅeskoÄeno"},session_type:{label:"Typ relace",tooltip:"RozliÅ¡enà mezi bÄžným pÅihlášenÃm a recovery/password-reset session",okDesc:"Standardnà pÅihlaÅ¡ovacà relace",failDesc:"Neplatný typ relace",skipDesc:"Recovery session â nejedná se o skuteÄné pÅihlášenÃ, záznam pÅeskoÄen"},ip_resolution:{label:"Rozpoznánà IP",tooltip:"Extrakce klientské IP z X-Forwarded-For / X-Real-IP hlaviÄek",okDesc:"VeÅejná IP adresa úspÄÅ¡nÄ rozpoznána",failDesc:"NepodaÅilo se rozpoznat IP adresu klienta",skipDesc:"IP je privátnÃ, lokálnà nebo nevalidnà â nelze použÃt pro geo lookup"},ip_hash:{label:"Hash IP",tooltip:"SHA-256 hash IP adresy se solà pro anonymnà korelaci bez ukládánà raw IP",okDesc:"IP hash úspÄÅ¡nÄ vygenerován pro anonymnà tracking",failDesc:"Chyba pÅi generovánà IP hashe",skipDesc:"IP hash pÅeskoÄen â IP je nevalidnà nebo privátnÃ"},db_insert:{label:"Zápis do DB",tooltip:"Uloženà záznamu o pÅihlášenà do tabulky login_history",okDesc:"Záznam úspÄÅ¡nÄ uložen",failDesc:"Chyba pÅi ukládánà záznamu â záznam nebyl vytvoÅen",skipDesc:"Zápis do DB pÅeskoÄen"},geo_enrichment:{label:"Geolokace",tooltip:"Obohacenà záznamu o geografická data (zemÄ, mÄsto, ISP) z externÃch providerů",okDesc:"Geo data úspÄÅ¡nÄ zÃskána",failDesc:"Geo lookup selhal â provider neodpovÄdÄl nebo vrátil chybu",skipDesc:"Geo lookup pÅeskoÄen â nevalidnà IP nebo negative cache hit"},unhandled:{label:"NeoÅ¡etÅená chyba",tooltip:"NeoÄekávaná chyba v průbÄhu zpracovánà pÅihlášenÃ",okDesc:"",failDesc:"DoÅ¡lo k neoÄekávané chybÄ â záznam mohl být neúplný",skipDesc:""}},gl=s=>{const a=Un[s.phase];return a?s.status==="ok"?a.okDesc:s.status==="fail"?a.failDesc:a.skipDesc:s.detail||""},jl=s=>s==="ok"?e.jsx(ps,{className:"h-4 w-4 text-emerald-600 shrink-0"}):s==="fail"?e.jsx(js,{className:"h-4 w-4 text-red-600 shrink-0"}):e.jsx(zn,{className:"h-4 w-4 text-amber-500 shrink-0"}),vl=s=>s==="ok"?"OK":s==="fail"?"SELHÃNÃ":"PÅESKOÄENO",fl=s=>s==="ok"?"bg-emerald-50 border-emerald-200 dark:bg-emerald-950/20 dark:border-emerald-800":s==="fail"?"bg-red-50 border-red-200 dark:bg-red-950/20 dark:border-red-800":"bg-amber-50 border-amber-200 dark:bg-amber-950/20 dark:border-amber-800",on=s=>{if(!s||s.length!==2)return"ð";const a=127397;return String.fromCodePoint(...[...s.toUpperCase()].map(i=>i.charCodeAt(0)+a))},cn=s=>s?s==="password"?"Heslo":s==="magiclink"||s==="otp"?"Magic link":s==="recovery"?"Obnova hesla":s:"Neznámá",Et=s=>s?{invalid_credentials:"Neplatné pÅihlaÅ¡ovacà údaje",email_not_confirmed:"Nepotvrzený e-mail",user_not_found:"Uživatel nenalezen",account_locked:"ÃÄet uzamÄen",invali
235d_token:"Neplatný nebo expirovaný token",expired_token:"Expirovaný token",too_many_attempts:"PÅÃliÅ¡ mnoho pokusů",not_approved:"ÃÄet neschválen"}[s]||s:"Neznámý důvod",yl=s=>s==="high"?"Vysoká":s==="medium"?"StÅednÃ":"NÃzká",bl=s=>s==="high"?"bg-red-500/15 text-red-700 border-red-200":s==="medium"?"bg-orange-500/15 text-orange-700 border-orange-200":"bg-yellow-500/15 text-yellow-700 border-yellow-200",Nl=s=>({new_device:"Nové zaÅÃzenÃ",failed_attempts:"NeúspÄÅ¡né pokusy",failed_attempts_heavy:"Mnoho neúspÄÅ¡ných pokusů",bot_score:"PodezÅelý klient"})[s]||s,Xs={resolved:{label:"OvÄÅeno",color:"bg-emerald-100 text-emerald-700 border-emerald-300",desc:"Geo data úspÄÅ¡nÄ zÃskána z externÃho provideru nebo cache"},failed:{label:"Selhalo",color:"bg-red-100 text-red-700 border-red-300",desc:"Geo lookup selhal â provider neodpovÄdÄl v Äasovém limitu"},skipped:{label:"PÅeskoÄeno",color:"bg-amber-100 text-amber-700 border-amber-300",desc:"Geo lookup nebyl proveden â IP je privátnÃ, lokálnà nebo nevalidnÃ"},pending:{label:"Äeká",color:"bg-blue-100 text-blue-700 border-blue-300",de
235sc:"Geo lookup jeÅ¡tÄ nebyl dokonÄen"}},et=s=>s||"â",_l=s=>{const[a,i]=t.useState({isKnownDevice:null,deviceFirstSeen:null,deviceLastSeen:null,deviceUsageCount:0,isKnownLocation:null,sameCountryAsLast:null,cityChanged:null,previousLogin:null,successfulLogins30d:0,failedAttemptsByAccount:0,failedAttemptsByIp:0,accountResolved:null,loading:!0});return t.useEffect(()=>{let y=!1;return(async()=>{let P=s.user_id,x=null;if(s.status==="failed"&&!P&&s.attempted_email){const{data:M}=await g.from("profiles").select("user_id").eq("email",s.attempted_email).maybeSingle();M!=null&&M.user_id?(P=M.user_id,x=!0):x=!1}else s.status==="failed"&&!P||s.status==="success"?x=null:x=!0;const O=[s.browser,s.os,s.device_type].map(M=>(M||"").toLowerCase()).join("|"),S=new Date(Date.now()-30*24*60*60*1e3).toISOString(),N=new Date(Date.now()-30*60*1e3).toISOString(),j=[];if(P?j.push(Promise.resolve(g.from("login_history").select("logged_in_at").eq("user_id",P).eq("status","success").neq("id",s.id).order("logged_in_at",{ascending:!1}).limit(100)).then(({data:M})=>M?{rawDeviceHistory:M}:{rawDeviceHistory:[]})):j.push(Promise.resolve(null)),P?j.push(Promise.resolve(g.from("login_history").select("logged_in_at, login_method, country, city, browser, os, device_type").eq("user_id",P).eq("status","success").neq("id",s.id).order("logged_in_at",{ascending:!1}).limit(50)).then(({data:M})=>M||[])):j.push(Promise.resolve([])),P?j.push(Promise.resolve(g.from("login_history").select("id",{count:"exact",head:!0}).eq("user_id",P).eq("status","success").gte("logged_in_at",S)).then(({count:M})=>M||0)):j.push(Promise.resolve(0)),s.user_id||s.attempted_email){const M=s.user_id?g.from("login_history").select("id",{count:"exact",head:!0}
235).eq("user_id",s.user_id).eq("status","failed").gte("logged_in_at",N):g.from("login_history").select("id",{count:"exact",head:!0}).eq("attempted_email",s.attempted_email).eq("status","failed").gte("logged_in_at",N);j.push(Promise.resolve(M).then(({count:o})=>o||0))}else j.push(Promise.resolve(0));s.ip_hash?j.push(Promise.resolve(g.from("login_history").select("id",{count:"exact",head:!0}).eq("ip_hash",s.ip_hash).eq("status","failed").gte("logged_in_at",N)).then(({count:M})=>M||0)):j.push(Promise.resolve(0));try{const[M,o,v,u,p]=await Promise.all(j);if(y)return;let m=null,$=null,H=null,J=0;if(P&&Array.isArray(o)&&o.length>0){const c=o.filter(d=>[d.browser,d.os,d.device_type].map(r=>(r||"").toLowerCase()).join("|")===O);J=c.length,m=c.length>0,c.length>0&&(H=c[0].logged_in_at,$=c[c.length-1].logged_in_at)}else P||(m=null);let z=null,h=null,I=null,k=null;if(P&&Array.isArray(o)&&o.length>0){const c=o[0];k={time:c.logged_in_at,method:c.login_method||"unknown",city:c.city,country:c.country},s.country&&c.country&&(h=s.country===c.country),s.city&&c.city&&(I=s.city!==c.city),z=o.some(T=>T.country===s.country&&(T.city===s.city||!s.city))}else P||(z=null);i({isKnownDevice:m,deviceFirstSeen:$,deviceLastSeen:H,deviceUsageCount:J,isKnownLocation:z,sameCountryAsLast:h,cityChanged:I,previousLogin:k,successfulLogins30d:v,failedAttemptsByAccount:u,failedAttemptsByIp:p,accountResolved:x,loading:!1})}catch{y||i(M=>({...M,loading:!1}))}})(),()=>{y=!0}},[s.id]),a},wl=(s,a)=>{if(a.loading)return"";if(s.status==="success"){const x=a.isKnownDevice===!0?"známého zaÅÃzenÃ":a.isKnownDevice===!1?"nového zaÅÃzenÃ":"zaÅÃzenÃ",O=a.isKnownLocation===!0?"bÄžné lokality":a.isKnownLocation===!1?"nové lokality":"neovÄÅené lokality",S=a.failedAttemptsByAccount>0?` PÅed pÅihlášenÃm probÄhlo ${a.failedAttemptsByAccount} neúspÄÅ¡ných pokusů.`:"";return`PÅihlášenà probÄhlo úspÄÅ¡nÄ z ${x}, z ${O}.${S}`}const i=Et(s.failure_reason),y=a.accountResolved===!0?" ÃÄet byl rozpoznán v systému.":a.accountResolved===!1?" ÃÄet nebyl nalezen v systému.":"",E=a.failedAttemptsByAccount>1?` Za poslednÃch 30 minut probÄhlo ${a.failedAttemptsByAccount} neúspÄÅ¡ných pokusů pro tento úÄet.`:"",P=a.failedAttemptsByIp>1&&a.failedAttemptsByIp!==a.failedAttemptsByAccount?` Ze stejné IP probÄhlo ${a.failedAttemptsByIp} pokusů.`:"";return`Pokus o pÅihlášenà selhal: ${i}.${y}${E}${P}`},kl=(s,a)=>{var E;if(a.loading)return{text:"",level:"info"};const i=((E=s.alert)==null?void 0:E.risk_score)||0;return s.status==="success"?i>=70?{text:"Vysoké riziko. DoporuÄeno kontaktovat uživatele.",level:"danger"}:i>=50?{text:"DoporuÄeno ovÄÅit s uživatelem.",level:"warning"}:a.isKnownDevice===!1&&a.isKnownLocation!==!1?{text:"Nové zaÅÃzenÃ. Sledujte dalšà aktivitu.",level:"warning"}:a.isKnownDevice===!1&&a.isKnownLocation===!1?{text:"Nové zaÅÃzenà i lokalita. DoporuÄeno ovÄÅit s uživatelem.",level:"warning"}:{text:"Nenà nutná akce.",level:"info"}:a.failedAttemptsByAccount+a.failedAttemptsByIp>=10?{text:"Zvažte rate limiting nebo doÄasné blokovánÃ.",level:"danger"}:a.failedAttemptsByAccount>=3?{text:"Sledujte opakované pokusy pro tento úÄet.",level:"warning"}:a.failedAttemptsByIp>=3?{text:"Sledujte pokusy ze stejné IP adresy.",level:"warning"}:{text:"PravdÄpodobná uživatelská chyba.",level:"info"}},dt=(s,a,i,y="Nelze urÄit")=>s===!0?a:s===!1?i:y,dn=(s,a,i,y="Nelze urÄit")=>{if(s===null)return null;const E=s===!0;return e.jsx(Q,{variant:"outline",className:`text-[10px] ${E?"bg-emerald-50 text-emerald-700 border-emerald-300":"bg-amber-50 text-amber-700 border-amber-300"}`,children:E?a:i})},Cl=({event:s,onBack:a})=>{var m,$,H,J,z,h,I;const[i,y]=t.useState("unknown"),[E,P]=t.useState(!1),x=_l(s),O=s.status==="success",S=s.status==="failed",N=()=>{if(!s.profile)return s.attempted_email||(s.user_id?s.user_id.slice(0,8):"â");const k=[s.profile.first_name,s.profile.last_name].filter(Boolean);return k.length>0?k.join(" "):s.profile.full_name||s.profile.email||"â"},j=()=>{var k;return((k=s.profile)==null?void 0:k.email)||s.attempted_email||"â"};t.useEffect(()=>{if(!s.magic_link_token_prefix||s.login_method!=="magiclink"){y("unknown");return}(async()=>{var T;y("loading");const c=(T=s.profile)==null?void 0:T.email;if(!c){y("unknown");return}const{data:d}=await g.from("email_history").select("magic_link_token_prefix, sent_at").eq("template_type","magic_link").eq("status","sent").eq("recipient",c).order("sent_at",{ascending:!1}).limit(1).maybeSingle();d!=null&&d.magic_link_token_prefix?d.magic_link_token_prefix===s.magic_link_token_prefix?y("latest"):y("outdated"):y("unknown")})()},[s.magic_link_token_prefix,s.login_method,(m=s.profile)==null?void 0:m.email]);
235const w=s.login_phases||[],M=w.length>0?Math.max(...w.map(k=>k.ms||0)):null,o=t.useMemo(()=>wl(s,x),[s,x]),v=t.useMemo(()=>kl(s,x),[s,x]),u=[s.city,s.country?`${on(s.country)} ${s.country}`:null].filter(Boolean).join(", "),p=[s.browser,s.os,s.device_type].filter(Boolean).join(" · ");return e.jsx(as,{delayDuration:200,children:e.jsxs("div",{className:"space-y-5",children:[e.jsxs(b,{variant:"ghost",size:"sm",className:"gap-1.5 -ml-2",onClick:a,children:[e.jsx(ut,{className:"h-4 w-4"}),"ZpÄt na historii pÅihlášenÃ"]}),e.jsxs(ee,{children:[e.jsxs("div",{className:`px-6 pt-6 pb-4 rounded-t-lg ${O?"bg-emerald-50/80 dark:bg-emerald-950/20":"bg-red-50/80 dark:bg-red-950/20"}`,children:[e.jsxs("div",{className:"flex items-center gap-3",children:[O?e.jsx(ps,{className:"h-6 w-6 text-emerald-600"}):e.jsx(js,{className:"h-6 w-6 text-red-600"}),e.jsxs("div",{children:[e.jsx("span",{className:"text-lg font-semibold",children:O?"ÃspÄÅ¡né pÅihlášenÃ":"NeúspÄÅ¡ný pokus o pÅihlášenÃ"}),e.jsxs("span",{className:"text-sm text-muted-foreground ml-2",children:["pÅes ",cn(s.login_method)]})]})]}),e.jsxs("div",{className:"flex flex-wrap items-center gap-x-5 gap-y-1 mt-3 text-sm text-muted-foreground",children:[e.jsxs("span",{children:[e.jsx("span",{className:"font-medium text-foreground",children:N()})," · ",j()]}),e.jsx("span",{children:hs(new Date(s.logged_in_at),"dd.MM.yyyy HH:mm:ss",{locale:ys})}),u&&e.jsx("span",{children:u}),p&&e.jsx("span",{className:"text-xs",children:p})]}),S&&e.jsxs("div",{className:"mt-3 bg-red-100/60 border border-red-200 rounded-lg p-3 flex items-start gap-2 dark:bg-red-950/30 dark:border-red-800",children:[e.jsx(js,{className:"h-4 w-4 text-red-600 mt-0.5 shrink-0"}),e.jsxs("div",{children:[e.jsxs("p",{className:"text-sm font-medium text-red-700",children:["Důvod selhánÃ: ",Et(s.failure_reason)]}),s.attempted_email&&e.jsxs("p",{className:"text-xs text-red-500 mt-0.5",children:["Zadaný e-mail: ",s.attempted_email]})]})]})]}),e.jsxs(ae,{className:"px-6 pb-6 pt-4 space-y-4",children:[e.jsxs("div",{className:"flex flex-wrap gap-2",children:[s.alert&&e.jsxs(Q,{className:`${bl(s.alert.severity)} text-[10px]`,children:[e.jsx(As,{className:"h-3 w-3 mr-0.5"}),"Riziko: ",yl(s.alert.severity)," · ",s.alert.risk_score,"b"]}),x.isKnownDevice!==null&&!x.loading&&dn(x.isKnownDevice,"Známé zaÅÃzenÃ","Nové zaÅÃzenÃ"),x.isKnownLocation!==null&&!x.loading&&dn(x.isKnownLocation,"Známá lokalita","Nová lokalita"),s.geo_status&&e.jsxs(Ke,{children:[e.jsx(Ze,{asChild:!0,children:e.jsxs(Q,{variant:"outline",className:`text-[10px] cursor-help ${(($=Xs[s.geo_status])==null?void 0:$.color)||""}`,children:[e.jsx(wa,{className:"h-3 w-3 mr-0.5"}),"Geo: ",((H=Xs[s.geo_status])==null?void 0:H.label)||s.geo_status]})}),e.jsx(He,{className:"text-xs max-w-xs",children:((J=Xs[s.geo_status])==null?void 0:J.desc)||""})]}),s.login_method==="magiclink"&&i!=="unknown"&&i!=="loading"&&e.jsxs(Ke,{children:[e.jsx(Ze,{asChild:!0,children:e.jsxs(Q,{variant:"outline",className:`text-[10px] cursor-help ${i==="latest"?"bg-emerald-50 text-emerald-700 border-emerald-300":"bg-amber-50 text-amber-700 border-amber-300"}`,children:[i==="latest"?e.jsx(Ln,{className:"h-3 w-3 mr-0.5"}):e.jsx(Na,{className:"h-3 w-3 mr-0.5"}),i==="latest"?"Token ovÄÅen":"Staršà token"]})}),e.jsx(He,{className:"text-xs max-w-xs",children:i==="latest"?"Uživatel použil poslednà vygenerovaný magic link.":"Uživatel použil staršà magic link â po tomto tokenu byl odeslán novÄjÅ¡Ã."})]}),!x.loading&&x.failedAttemptsByAccount>0&&e.jsxs(Q,{variant:"outline",className:`text-[10px] ${x.failedAttemptsByAccount>=5?"bg-red-50 text-red-700 border-red-300":"bg-amber-50 text-amber-700 border-amber-300"}`,children:[e.jsx(is,{className:"h-3 w-3 mr-0.5"}),x.failedAttemptsByAccount,"à pokusy pro úÄet"]}),!x.loading&&x.failedAttemptsByIp>0&&x.failedAttemptsByIp!==x.failedAttemptsByAccount&&e.jsxs(Q,{variant:"outline",className:`text-[10px] ${x.failedAttemptsByIp>=5?"bg-red-50 text-red-700 border-red-300":"bg-amber-50 text-amber-700 border-amber-300"}`,children:[e.jsx(Wr,{className:"h-3 w-3 mr-0.5"}),x.failedAttemptsByIp,"à ze stejné IP"]}),S&&s.failure_reason&&e.jsx(Q,{variant:"outline",className:"text-[10px] bg-red-50 text-red-700 border-red-300",children:Et(s.failure_reason)}),S&&!x.loading&&x.accountResolved!==null&&e.jsxs(Q,{variant:"outline",className:`text-[10px] ${x.accountResolved?"bg-blue-50 text-blue-700 border-blue-300":"bg-gray-50 text-gray-600 border-gray-300"}`,children:[e.jsx(ba,{className:"h-3 w-3 mr-0.5"}),x.accountResolved?"ÃÄet rozpoznán":"ÃÄet nerozpoznán"]}),x.loading&&e.jsxs(e.Fragment,{children:[e.jsx(Hs,{className:"h-5 w-28 rounded-full"}),e.jsx(Hs,{className:"h-5 w-24 rounded-full"})]})]}),e.jsx("div",{className:`rounded-lg p-3 text-sm ${v.level==="danger"?"bg-red-50 border border-red-200 dark:bg-red-950/20 dark:border-red-800":v.level==="warning"?"bg-amber-50 border border-amber-200 dark:bg-amber-950/20 dark:border-amber-800":"bg-muted/50 border border-border"}`,children:x.loading?e.jsxs("div",{className:"space-y-1.5",children:[e.jsx(Hs,{className:"h-4 w-full"}),e.jsx(Hs,{className:"h-4 w-3/4"})]}):e.jsxs(e.Fragment,{children:[e.jsx("p",{className:"text-muted-foreground",children:o}
235),v.text&&e.jsxs("p",{className:`font-medium mt-1 ${v.level==="danger"?"text-red-700":v.level==="warning"?"text-amber-700":"text-foreground"}`,children:["â ",v.text]})]})})]})]}),e.jsxs("div",{className:"grid grid-cols-1 md:grid-cols-2 gap-4",children:[e.jsxs(ee,{children:[e.jsx(ye,{className:"pb-3",children:e.jsxs(be,{className:"text-sm font-semibold flex items-center gap-1.5",children:[e.jsx(_n,{className:"h-4 w-4 text-primary"}),O?"PÅihlášenÃ":"Pokus o pÅihlášenÃ"]})}),e.jsxs(ae,{className:"space-y-3 pt-0",children:[e.jsxs("div",{className:"grid grid-cols-2 gap-3",children:[e.jsx(rs,{label:"Metoda",value:cn(s.login_method)}),e.jsx(rs,{label:"Äas",value:hs(new Date(s.logged_in_at),"dd.MM.yyyy HH:mm",{locale:ys})})]}),O&&e.jsxs("div",{className:"grid grid-cols-2 gap-3",children:[e.jsx(rs,{label:"Loginů za 30 dnÃ",value:x.loading?"â¦":String(x.successfulLogins30d)}),e.jsx(rs,{label:"Poslednà login",value:x.loading?"â¦":x.previousLogin?hs(new Date(x.previousLogin.time),"dd.MM. HH:mm",{locale:ys}):"Prvnà login"})]}),O&&!x.loading&&x.failedAttemptsByAccount>0&&e.jsxs("div",{className:"bg-amber-50 border border-amber-200 rounded px-2.5 py-1.5 text-xs text-amber-700 dark:bg-amber-950/20 dark:border-amber-800",children:["Navazuje na ",x.failedAttemptsByAccount," neúspÄÅ¡ných pokusů"]}),O&&!x.loading&&x.isKnownDevice===!1&&e.jsx("div",{className:"bg-blue-50 border border-blue-200 rounded px-2.5 py-1.5 text-xs text-blue-700 dark:bg-blue-950/20 dark:border-blue-800",children:"Prvnà login z tohoto zaÅÃzenÃ"}),S&&e.jsxs(e.Fragment,{children:[e.jsx(rs,{label:"Důvod selhánÃ",value:Et(s.failure_reason),highlight:"danger"}),e.jsxs("div",{className:"grid grid-cols-2 gap-3",children:[e.jsx(rs,{label:"Pokusy pro úÄet (30 min)",value:x.loading?"â¦":String(x.failedAttemptsByAccount),highlight:x.failedAttemptsByAccount>=5?"danger":x.failedAttemptsByAccount>=3?"warning":void 0}),e.jsx(rs,{label:"Pokusy ze stejné IP (30 min)",value:x.loading?"â¦":String(x.failedAttemptsByIp),highlight:x.failedAttemptsByIp>=5?"danger":x.failedAttemptsByIp>=3?"warning":void 0})]}),e.jsxs("div",{className:"grid grid-cols-2 gap-3",children:[e.jsx(rs,{label:"Poslednà úspÄÅ¡ný login",value:x.loading?"â¦":x.previousLogin?hs(new Date(x.previousLogin.time),"dd.MM. HH:mm",{locale:ys}):"â"}),e.jsx(rs,{label:S?"Rozpoznánà úÄtu":"ÃÄet",value:x.loading?"â¦":dt(x.accountResolved,"Ano","Ne","Nelze urÄit")})]})]}),M!==null&&e.jsxs("div",{className:"text-xs text-muted-foreground flex items-center gap-1",children:[e.jsx(ii,{className:"h-3 w-3"})," ZpracovánÃ: ",M,"ms"]})]})]}),e.jsxs(ee,{children:[e.jsx(ye,{className:"pb-3",children:e.jsxs(be,{className:"text-sm font-semibold flex items-center gap-1.5",children:[e.jsx(Gr,{className:"h-4 w-4 text-primary"}),"ZaÅÃzenà a klient"]})}),e.jsxs(ae,{className:"space-y-3 pt-0",children:[e.jsxs("div",{className:"grid grid-cols-2 gap-3",children:[e.jsx(rs,{label:"ProhlÞeÄ",value:et(s.browser)}
235),e.jsx(rs,{label:"OperaÄnà systém",value:et(s.os)})]}),e.jsxs("div",{className:"grid grid-cols-2 gap-3",children:[e.jsx(rs,{label:"Typ zaÅÃzenÃ",value:et(s.device_type)}),s.bot_score>0&&e.jsxs(Ke,{children:[e.jsx(Ze,{asChild:!0,children:e.jsx("div",{className:"cursor-help",children:e.jsx(rs,{label:"Bot skóre",value:`${s.bot_score}/100`,highlight:s.bot_score>50?"warning":void 0})})}),e.jsxs(He,{className:"text-xs max-w-xs",children:["0 = s jistotou ÄlovÄk, 100 = s jistotou bot.",s.bot_detection_reason&&e.jsxs("div",{className:"mt-1",children:["Důvod: ",s.bot_detection_reason]})]})]})]}),!x.loading&&e.jsxs("div",{className:"text-xs space-y-1",children:[O&&e.jsx("p",{className:"text-muted-foreground",children:dt(x.isKnownDevice,`Známé zaÅÃzenà · ${x.deviceUsageCount}à použito`,"Nové zaÅÃzenà â dosud nepoužito","Nelze spolehlivÄ urÄit")}),S&&x.accountResolved===!0&&e.jsx("p",{className:"text-muted-foreground",children:dt(x.isKnownDevice,"ZaÅÃzenà odpovÃdá dÅÃvÄjÅ¡Ãm pokusům tohoto úÄtu","ZaÅÃzenà neodpovÃdá dÅÃvÄjÅ¡Ãm pokusům tohoto úÄtu","Nelze spolehlivÄ urÄit")}),S&&x.accountResolved!==!0&&e.jsx("p",{className:"text-muted-foreground italic",children:"Nelze spolehlivÄ urÄit (úÄet nerozpoznán)"}),x.isKnownDevice&&x.deviceFirstSeen&&e.jsxs("p",{className:"text-muted-foreground",children:["Poprvé: ",hs(new Date(x.deviceFirstSeen),"dd.MM.yyyy",{locale:ys}),x.deviceLastSeen&&` · Naposledy: ${hs(new Date(x.deviceLastSeen),"dd.MM.yyyy",{locale:ys})}`]})]}),x.loading&&e.jsx(Hs,{className:"h-4 w-48"}),s.user_agent&&e.jsxs(xt,{children:[e.jsxs(ht,{className:"text-[10px] text-muted-foreground hover:text-foreground flex items-center gap-1 transition-colors",children:[e.jsx(Js,{className:"h-3 w-3"})," User-Agent"]}),e.jsx(pt,{children:e.jsx("p",{className:"font-mono text-[10px] text-muted-foreground break-all mt-1 p-2 bg-muted/50 rounded",children:s.user_agent})})]})]})]}),e.jsxs(ee,{children:[e.jsx(ye,{className:"pb-3",children:e.jsxs(be,{className:"text-sm font-semibold flex items-center gap-1.5",children:[e.jsx($t,{className:"h-4 w-4 text-blue-600"}),"Lokalita a sÃÅ¥",s.geo_status&&e.jsxs(Ke,{children:[e.jsx(Ze,{asChild:!0,children:e.jsx(Q,{variant:"outline",className:`text-[10px] ml-1 cursor-help ${((z=Xs[s.geo_status])==null?void 0:z.color)||""}`,children:((h=Xs[s.geo_status])==null?void 0:h.label)||s.geo_status})}),e.jsx(He,{className:"text-xs max-w-xs",children:((I=Xs[s.geo_status])==null?void 0:I.desc)||""})]})]})}),e.jsxs(ae,{className:"space-y-3 pt-0",children:[e.jsxs("div",{className:"grid grid-cols-2 gap-3",children:[e.jsx(rs,{label:"ZemÄ",value:s.country?`${on(s.country)} ${s.country}`:"â"}),e.jsx(rs,{label:"MÄsto",value:et(s.city)})]}),e.jsxs("div",{className:"grid grid-cols-2 gap-3",children:[e.jsx(rs,{label:"Region",value:et(s.region)}),e.jsx(rs,{label:"ISP",value:et(s.isp)})]}),!x.loading&&e.jsxs("div",{className:"text-xs space-y-1 text-muted-foreground",children:[O&&e.jsx("p",{children:dt(x.isKnownLocation,"Známá lokalita","Nová lokalita â dosud nepozorována","Nelze porovnat")}),S&&x.accountResolved===!0&&e.jsx("p",{children:dt(x.isKnownLocation,"Ve shodÄ s poslednà známou lokalitou úÄtu","Neshoduje se s poslednà známou lokalitou úÄtu","Nelze porovnat")}),S&&x.accountResolved!==!0&&e.jsx("p",{className:"italic",children:"Nelze porovnat (úÄet nerozpoznán)"}),x.sameCountryAsLast!==null&&x.previousLogin&&e.jsxs("p",{children:[x.sameCountryAsLast?"â Stejná zemÄ jako poslednÄ":"â Jiná zemÄ než poslednÄ",x.cityChanged===!0&&", jiné mÄsto",x.cityChanged===!1&&", stejné mÄsto"]})]}),x.loading&&e.jsx(Hs,{className:"h-4 w-40"})]})]}),e.jsxs(ee,{children:[e.jsx(ye,{className:"pb-3",children:e.jsxs(be,{className:"text-sm font-semibold flex items-center gap-1.5",children:[e.jsx(nt,{className:"h-4 w-4 text-orange-600"}),"BezpeÄnostnà vyhodnocenÃ"]})}),e.jsxs(ae,{className:"space-y-3 pt-0",children:[s.alert?e.jsxs(e.Fragment,{children:[e.jsxs("div",{className:"grid grid-cols-2 gap-3",children:[e.jsx(rs,{label:"Risk skóre",value:`${s.alert.risk_score}/100`,highlight:s.alert.risk_score>=70?"danger":s.alert.risk_score>=50?"warning":void 0}),e.jsx(rs,{label:"Notifikováno",value:s.alert.notified_at?"â
Ano":"â Ne"})]}),e.jsxs("div",{children:[e.jsx("p",{className:"text-[10px] text-muted-foreground uppercase tracking-wide mb-1.5",children:"Detekované signály"}),e.jsx("div",{className:"flex flex-wrap gap-2",children:(s.alert.signals||[]).map((k,c)=>e.jsxs(Ke,{children:[e.jsx(Ze,{asChild:!0,children:e.jsxs(Q,{variant:"outline",className:"text-xs cursor-help",children:[Nl(k.type)," (+",k.score,")"]})}),e.jsx(He,{className:"text-xs",children:k.detail||"Bez detailu"})]},c))})]})]}):e.jsx("p",{className:"text-sm text-muted-foreground",children:"Žádný aktivnà bezpeÄnostnà alert"}),!x.loading&&v.text&&e.jsxs("div",{className:`rounded px-3 py-2 text-xs font-medium ${v.level==="danger"?"bg-red-50 text-red-700 dark:bg-red-950/20":v.level==="warning"?"bg-amber-50 text-amber-700 dark:bg-amber-950/20":"bg-muted/50 text-foreground"}`,children:["DoporuÄenÃ: ",v.text]}),x.loading&&e.jsx(Hs,{className:"h-8 w-full"})]})]})]}),e.jsx(ee,{children:e.jsxs(xt,{open:E,onOpenChange:P,children:[e.jsxs(ht,{className:"w-full px-6 py-4 flex items-center justify-between text-sm font-semibold hover:bg-muted/50 transition-colors rounded-lg",children:[e.jsxs("span",{className:"flex items-center gap-1.5",children:[e.jsx(Us,{className:"h-4 w-4 text-muted-foreground"}),"Technický detail"]}),e.jsx(Js,{className:`h-4 w-4 text-muted-foreground transition-transform ${E?"rotate-180":""}`})]}),e.jsx(pt,{children:e.jsxs(ae,{className:"pt-0 pb-5 px-6 space-y-4",children:[e.jsxs("div",{className:"grid grid-cols-2 sm:grid-cols-4 gap-3",children:[e.jsx(rs,{label:"User ID",value:s.user_id||"â",mono:!0}),e.jsx(rs,{label:"ID záznamu",value:s.id,mono:!0}),e.jsx(rs,{label:"IP hash",value:s.ip_hash||"â",mono:!0}),s.login_method==="magiclink"&&e.jsx(rs,{label:"Token prefix",value:s.magic_link_token_prefix||"â",mono:!0})]}),s.login_method==="magiclink"&&s.magic_link_token_prefix&&e.jsxs("div",{className:"text-xs text-muted-foreground",children:["Stav tokenu:"," ",i==="loading"?"OvÄÅujiâ¦":i==="latest"?"â
NejnovÄjšà â poslednà odeslaný":i==="outdated"?"â ï¸ Staršà â po tomto byl odeslán novÄjÅ¡Ã":"â Nelze ovÄÅit"]}),s.user_agent&&e.jsxs("div",{children:[e.jsx("p",{className:"text-[10px] text-muted-foreground uppercase tracking-wide mb-1",children:"User-Agent"}),e.jsx("p",{className:"font-mono text-[10px] text-muted-foreground break-all p-2 bg-muted/50 rounded",children:s.user_agent})]}),w.length>0?e.jsxs("div",{children:[e.jsxs("div",{className:"flex items-center justify-between mb-3",children:[e.jsxs("h4",{className:"text-xs font-semibold flex items-center gap-1.5",children:[e.jsx(at,{className:"h-3.5 w-3.5 text-primary"}),"Fáze pÅihlášenÃ",e.jsxs(Ke,{children:[e.jsx(Ze,{asChild:!0,children:e.jsx(Us,{className:"h-3 w-3 text-muted-foreground cursor-help"})}),e.jsx(He,{className:"text-xs max-w-xs",children:"Chronologický průbÄh zpracovánà pÅihlášenà na serveru."})]})]}),e.jsxs("div",{className:"flex items-center gap-2 text-[10px]",children:[e.jsxs("span",{className:"flex items-center gap-0.5 text-emerald-600",children:[e.jsx(ps,{className:"h-3 w-3"})," ",w.filter(k=>k.status==="ok").length]}),w.filter(k=>k.status==="fail").length>0&&e.jsxs("span",{className:"flex items-center gap-0.5 text-red-600",children:[e.jsx(js,{className:"h-3 w-3"})," ",w.filter(k=>k.status==="fail").length]}),w.filter(k=>k.status==="skip").length>0&&e.jsxs("span",{className:"flex items-center gap-0.5 text-amber-500",children:[e.jsx(zn,{className:"h-3 w-3"})," ",w.filter(k=>k.status==="skip").length]}),M!==null&&e.jsxs("span",{className:"text-muted-foreground",children:["· ",M,"ms"]})]})]}),e.jsxs("div",{className:"space-y-0 relative",children:[e.jsx("div",{className:"absolute left-[11px] top-3 bottom-3 w-px bg-border"}),w.map((k,c)=>{const d=Un[k.phase],T=c>0&&w[c-1].ms||0,r=(k.ms||0)-T;return e.jsxs(Ke,{children:[e.jsx(Ze,{asChild:!0,children:e.jsxs("div",{className:`relative flex items-start gap-3 py-2 px-3 rounded-md border cursor-help transition-colors hover:bg-muted/50 ${fl(k.status)} ${c>0?"mt-1":""}`,children:[e.jsx("div",{className:"relative z-10 bg-background rounded-full p-0.5",children:jl(k.status)}),e.jsxs("div",{className:"flex-1 min-w-0",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx("span",{className:"text-xs font-semibold",children:(d==null?void 0:d.label)||k.phase}),e.jsx(Q,{variant:"outline",className:`text-[9px] px-1 py-0 h-4 ${k.status==="ok"?"text-emerald-600 border-emerald-300":k.status==="fail"?"text-red-600 border-red-300":"text-amber-600 border-amber-300"}`,children:vl(k.status)})]}),e.jsx("p",{className:"text-[11px] text-muted-foreground mt-0.5",children:gl(k)}),k.detail&&e.jsx("p",{className:"text-[10px] font-mono text-muted-foreground
235/70 mt-0.5 truncate",children:k.detail})]}),e.jsxs("div",{className:"text-right shrink-0",children:[e.jsx("div",{className:"text-xs font-mono font-medium text-foreground",children:k.ms!==void 0?`${k.ms}ms`:"â"}),c>0&&r>0&&e.jsxs("div",{className:"text-[10px] text-muted-foreground flex items-center justify-end gap-0.5",children:[e.jsx(Mn,{className:"h-2.5 w-2.5"})," +",r,"ms"]})]})]})}),e.jsx(He,{side:"top",align:"start",className:"text-xs max-w-sm z-[100]",children:e.jsxs("div",{className:"space-y-1",children:[e.jsx("p",{className:"font-semibold",children:(d==null?void 0:d.label)||k.phase}),e.jsx("p",{children:(d==null?void 0:d.tooltip)||"Internà fáze zpracovánà požadavku"}),k.detail&&e.jsxs("p",{className:"font-mono text-[10px] text-muted-foreground",children:["raw: ",k.detail]}),k.ms!==void 0&&e.jsxs("p",{children:["Absolutnà Äas: ",k.ms,"ms od zaÄátku požadavku"]}),c>0&&r>0&&e.jsxs("p",{children:["Doba trvánà fáze: ",r,"ms"]})]})})]},c)})]})]}):e.jsxs("div",{className:"flex items-center gap-2 text-sm text-muted-foreground py-3 px-3 bg-muted/30 rounded-md",children:[e.jsx(is,{className:"h-4 w-4 shrink-0"}),e.jsxs("div",{children:[e.jsx("p",{className:"font-medium",children:"Detailnà fázový log nenà k dispozici"}),e.jsx("p",{className:"text-xs mt-0.5",children:"Staršà záznamy nemajà fázový debug log."})]})]})]})})]})})]})})},rs=({label:s,value:a,mono:i,highlight:y})=>e.jsxs("div",{children:[e.jsx("p",{className:"text-[10px] text-muted-foreground uppercase tracking-wide mb-0.5",children:s}),e.jsx("p",{className:`text-sm font-medium truncate ${i?"font-mono text-xs":""} ${y==="danger"?"text-red-600":y==="warning"?"text-amber-600":""}`,title:a,children:a})]}),Sl=[{prefix:"/admin/users",label:"Admin · Uživatelé"},{prefix:"/admin/apartments",label:"Admin · Byty"},{prefix:"/admin/costs",label:"Admin · Náklady"},{prefix:"/admin/documents",label:"Admin · Dokumenty"},{prefix:"/admin/polls",label:"Admin · HlasovánÃ"},{prefix:"/admin/forum",label:"Admin · Fórum"},{prefix:"/admin/settings",label:"Admin · NastavenÃ"},{prefix:"/admin/announcements",label:"Admin · OznámenÃ"},{prefix:"/admin/vendors",label:"Admin · Dodavatelé"},{prefix:"/admin/translations",label:"Admin · PÅeklady"},{prefix:"/admin/email",label:"Admin · E-maily"},{prefix:"/admin/owners",label:"Admin · VlastnÃci"},{prefix:"/admin/reserve",label:"Admin · Fond oprav"},{prefix:"/admin/batch",label:"Admin · Import dávky"},{prefix:"/admin/data",label:"Admin · Data"},{prefix:"/admin",label:"Administrace"},{prefix:"/owners/costs/heating",label:"Náklady · TopenÃ"},{prefix:"/owners/costs/reserve",label:"Náklady · Fond oprav"},{prefix:"/owners/costs/vendors",label:"Náklady · Dodavatelé"},{prefix:"/owners/costs/categories",label:"Náklady · Kategorie"},{prefix:"/owners/costs",label:"Náklady · PÅehled"},{prefix:"/owners/forum",label:"Fórum"},{prefix:"/owners/polls",label:"HlasovánÃ"}
235,{prefix:"/owners/documents",label:"Dokumenty"},{prefix:"/owners/contacts",label:"Kontakty"},{prefix:"/owners/profile",label:"Můj profil"},{prefix:"/owners/news",label:"Novinky"},{prefix:"/owners/wifi",label:"Wi-Fi"},{prefix:"/owners/voting-rules",label:"Pravidla hlasovánÃ"},{prefix:"/owners",label:"Portál vlastnÃků"},{prefix:"/forum",label:"Fórum"},{prefix:"/gallery",label:"Galerie"},{prefix:"/webcam",label:"Webkamera"},{prefix:"/login",label:"PÅihlášenÃ"},{prefix:"/auth",label:"PÅihlášenÃ"}];function mn(s){if(!s||s.trim()==="")return"Neznámá stránka";let a=s.split("?")[0].split("#")[0].replace(/\/+$/,"")||"/";if(a==="/"||a==="")return"Ãvodnà stránka";for(const{prefix:i,label:y}of Sl)if(a===i||a.startsWith(i+"/"))return y;return a}const zl=({isOpen:s})=>{const[a,i]=t.useState([]),[y,E]=t.useState(!0),[P,x]=t.useState(!1),O=t.useCallback(async()=>{const o=new Date(Date.now()-18e4).toISOString(),v=new Date(Date.now()-90*1e3).toISOString(),{data:u,error:p}=await g.from("user_activity").select("user_id, last_active_at, last_page").gte("last_active_at",o);if(p||!u){i([]),E(!1);return}const m=u.map(z=>z.user_id).filter(Boolean);let $=new Map;if(m.length>0){const{data:z}=await g.rpc("admin_get_profiles_by_ids",{_user_ids:m});if(z)for(const h of z){const I=h.first_name&&h.last_name?`${h.first_name} ${h.last_name}`:h.full_name||null;$.set(h.user_id,{full_name:I,email:h.email||null})}}let H=new Map;if(m.length>0){const{data:z}=await g.from("login_history").select("user_id, logged_in_at").in("user_id",m).eq("status","success").order("logged_in_at",{ascending:!1});if(z)for(const h of z)h.user_id&&!H.has(h.user_id)&&H.set(h.user_id,h.logged_in_at)}const J=u.map(z=>{const h=$.get(z.user_id);return{user_id:z.user_id,last_active_at:z.last_active_at,last_page:z.last_page,full_name:(h==null?void 0:h.full_name)||null,email:(h==null?void 0:h.email)||null,isActiveNow:z.last_active_at>=v,lastLoginAt:H.get(z.user_id)||null}});J.sort((z,h)=>z.isActiveNow!==h.isActiveNow?z.isActiveNow?-1:1:new Date(h.last_active_at).getTime()-new Date(z.last_active_at).getTime()),i(J),E(!1)},[]),S=t.useCallback(async()=>{x(!0),await O(),x(!1)},[O]);t.useEffect(()=>{if(!s)return;O();const o=setInterval(()=>{document.visibilityState==="visible"&&O()},15e3);return()=>clearInterval(o)},[s,O]);const{activeNowList:N,recentlyActiveList:j}=t.useMemo(()=>({activeNowList:a.filter(o=>o.isActiveNow),recentlyActiveList:a.filter(o=>!o.isActiveNow)}),[a]),w=t.useMemo(()=>{if(a.length<3)return null;const o=new Map;a.forEach(p=>{const m=mn(p.last_page);o.set(m,(o.get(m)||0)+1)});let v="",u=0;return o.forEach((p,m)=>{p>u&&(u=p,v=m)}),v},[a]);if(!s)return null;const M=o=>{if(!o.lastLoginAt)return e.jsx("span",{className:"text-[10px] text-muted-foreground/60 italic",children:"â"});const v=new Date(o.lastLoginAt),u=fi(new Date,v),p=u>=24,m=Math.floor(u/24),$=hs(v,"d.M.yyyy HH:mm");return p?e.jsxs(Ke,{children:[e.jsx(Ze,{asChild:!0,children:e.jsx("span",{className:"text-[11px] text-amber-600 font-medium cursor-help",children:hs(v,"d.M.yyyy")})}),e.jsxs(He,{side:"top",className:"text-xs max-w-xs",children:[e.jsxs("div",{className:"font-medium text-amber-700",children:["Session trvá ",m," ",m===1?"den":m<5?"dny":"dnÃ"]}),e.jsxs("div",{className:"text-muted-foreground",children:["Poslednà pÅihlášenÃ: ",$]})]})]}):e.jsx("span",{className:"text-[11px] text-muted-foreground",children:hs(v,"HH:mm")})};return e.jsx(ee,{className:"border-primary/20 bg-primary/5",children:e.jsx(ae,{className:"p-4",children:y?e.jsx("div",{className:"flex justify-center py-6",children:e.jsx(fe,{className:"h-5 w-5 animate-spin text-primary"})}):a.length===0?e.jsxs("div",{className:"text-center py-6",children:[e.jsx(Fs,{className:"h-8 w-8 text-muted-foreground mx-auto mb-2"}),e.jsx("p",{className:"text-sm font-medium text-muted-foreground",children:"MomentálnÄ nenà aktivnà žádný uživatel."}),e.jsx("p",{className:"text-xs text-muted-foreground mt-1",children:"Zobrazujà se uživatelé s aktivitou za poslednà 3 minuty."})]}):e.jsxs(e.Fragment,{children:[e.jsxs("div",{className:"flex items-center justify-between mb-3",children:[e.jsxs("div",{className:"flex items-center gap-2 text-xs text-muted-foreground",children:[e.jsxs("span",{className:"font-medium text-foreground",children:[N.length," aktivnà nynÃ"]}),e.jsx("span",{children:"·"}),e.jsxs("span",{children:[j.length," nedávno aktivnÃ"]}),w&&e.jsxs(e.Fragment,{children:[e.jsx("span",{children:"·"}),e.jsxs("span",{children:["nejÄastÄjšà oblast: ",e.jsx("span",{className:"font-medium text-foreground",children:w})]})]})]}),e.jsxs(b,{variant:"ghost",size:"sm",onClick:S,disabled:P,className:"h-7 px-2",children:[e.jsx(Es,{className:`h-3.5 w-3.5 ${P?"animate-spin":""}`}),e.jsx("span",{className:"ml-1 text-xs",children:"Obnovit"})]})]}),e.jsx(as,{children:e.jsxs($e,{children:[e.jsx(Be,{children:e.jsxs(Ne,{children:[e.jsx(D,{className:"w-[40px]",children:"Stav"}),e.jsx(D,{children:"Jméno"}),e.jsx(D,{children:"Poslednà stránka"}),e.jsx(D,{className:"text-right",children:"PÅihlášen"}),e.jsx(D,{className:"text-right",children:"Naposledy aktivnÃ"})]})}),e.jsx(Ue,{children:a.map(o=>e.jsxs(Ne,{className:"h-10",children:[e.jsx(_,{className:"py-1.5",children:e.jsx("span",{className:`inline-block h-2.5 w-2.5 rounded-full ${o.isActiveNow?"bg-emerald-500":"bg-gray-400"}`,title:o.isActiveNow?"Aktivnà nynÃ":"Nedávno aktivnÃ"})}),e.jsx(_,{className:"py-1.5",children:o.email?e.jsxs(Ke,{children:[e.jsx(Ze,{asChild:!0,children:e.jsx("span",{className:"text-sm font-medium cursor-default",children:o.full_name||o.user_id.slice(0,8)})}),e.jsx(He,{side:"top",className:"text-xs",children:o.email})]}):e.jsx("span",{className:"text-sm font-medium",children:o.full_name||o.user_id.slice(0,8)})}),e.jsxs(_,{className:"py-1.5",children:[e.jsx("div",{className:"text-sm text-muted-foreground",children:mn(o.last_page)}),o.last_page&&e.jsx("div",{className:"text-[10px] font-mono text-muted-foreground
235/60 truncate max-w-[300px]",title:o.last_page,children:o.last_page.split("?")[0]})]}),e.jsx(_,{className:"py-1.5 text-right",children:M(o)}),e.jsx(_,{className:"py-1.5 text-right text-xs text-muted-foreground",children:Dn(new Date(o.last_active_at),{addSuffix:!0,locale:ys})})]},o.user_id))})]})})]})})})},Dl=[20,30,50,100],Pl=new Set(["admin","spravce","beirat"]),Al=s=>s==="high"?"bg-red-500/15 text-red-700 border-red-200":s==="medium"?"bg-orange-500/15 text-orange-700 border-orange-200":"bg-yellow-500/15 text-yellow-700 border-yellow-200",El=s=>s==="high"?"Vysoká":s==="medium"?"StÅednÃ":"NÃzká",Il=s=>({new_device:"Nové zaÅÃzenÃ",failed_attempts:"NeúspÄÅ¡né pokusy",failed_attempts_heavy:"Mnoho neúspÄÅ¡ných pokusů",bot_score:"PodezÅelý klient"})[s]||s,Tl=s=>s.includes("admin")?e.jsx(Q,{className:"bg-red-600 text-white text-[10px] whitespace-nowrap",children:"Admin"}):s.includes("beirat")?e.jsx(Q,{className:"bg-blue-600 text-white text-[10px] whitespace-nowrap",children:"Beirat"}):s.includes("spravce")?e.jsx(Q,{className:"bg-amber-500 text-white text-[10px] whitespace-nowrap",children:"Správce"}):s.includes("owner")?e.jsx(Q,{variant:"secondary",className:"text-[10px] whitespace-nowrap",children:"VlastnÃk"}):e.jsx(Q,{variant:"outline",className:"text-[10px] whitespace-nowrap",children:"â"}),un=s=>s?s==="password"?"Heslo":s==="magiclink"||s==="otp"?"Magic link":s:"Neznámá",xn=s=>s?{invalid_credentials:"Neplatné pÅihlaÅ¡ovacà údaje",email_not_confirmed:"Nepotvrzený e-mail",user_not_found:"Uživatel nenalezen",account_locked:"ÃÄet uzamÄen",invali
235d_token:"Neplatný/expirovaný token",expired_token:"Expirovaný token",too_many_attempts:"PÅÃliÅ¡ mnoho pokusů",not_approved:"ÃÄet neschválen"}[s]||s:"Neznámý důvod",Ct=(s,a)=>{if(s.status==="failed")return"failed";if(s.status!=="success")return"unknown";if(!s.session_fingerprint)return"legacy";const i=a[s.session_fingerprint];return i?Math.abs(new Date(s.logged_in_at).getTime()-new Date(i).getTime())<1e3?"new_session":"continuation":"new_session"},Ol={new_session:"ZaÄátek relace",continuation:"PokraÄovánà relace",legacy:"PÅihlášenÃ",failed:"NeúspÄÅ¡ný pokus",unknown:"Neznámá událost"},hn={new_session:"Prvnà zaznamenaný záznam této klientské relace.",continuation:"Dalšà záznam ze stejné relace po reloadu nebo opÄtovném naÄtenà aplikace.",legacy:"Historický záznam bez session fingerprintu; nelze rozliÅ¡it zaÄátek a pokraÄovánà relace.",failed:"",unknown:""},Fl=(s,a)=>{if(a==="failed")return e.jsxs("div",{children:[e.jsxs("div",{className:"flex items-center gap-1",children:[e.jsx(js,{className:"h-3.5 w-3.5 text-red-600 shrink-0"}),e.jsx("span",{className:"text-xs font-medium text-red-700",children:"NeúspÄÅ¡ný pokus"})]}),e.jsx("div",{className:"text-[10px] text-red-600/80 ml-[18px] max-w-[160px] truncate",title:xn(s.failure_reason),children:xn(s.failure_reason)})]});if(a==="continuation"){const P=hn.continuation;return e.jsxs(Ke,{children:[e.jsx(Ze,{asChild:!0,children:e.jsxs("div",{className:"cursor-help",children:[e.jsxs("div",{className:"flex items-center gap-1",children:[e.jsx(ni,{className:"h-3.5 w-3.5 text-muted-foreground shrink-0"}),e.jsx("span",{className:"text-xs font-medium text-muted-foreground",children:"PokraÄovánà relace"})]}),e.jsxs("div",{className:"text-[10px] text-muted-foreground/70 ml-[18px]",children:["via ",un(s.login_method)]})]})}),e.jsx(He,{side:"top",className:"text-xs max-w-xs",children:P})]})}const i=hn[a],y=Ol[a],E=e.jsxs("div",{children:[e.jsxs("div",{className:"flex items-center gap-1",children:[e.jsx(ps,{className:"h-3.5 w-3.5 text-emerald-600 shrink-0"}),e.jsx("span",{className:"text-xs font-medium text-emerald-700",children:y})]}),e.jsxs("div",{className:"text-[10px] text-muted-foreground ml-[18px]",children:["via ",un(s.login_method)]})]});return i?e.jsxs(Ke,{children:[e.jsx(Ze,{asChild:!0,children:e.jsx("div",{className:"cursor-help",children:E})}),e.jsx(He,{side:"top",className:"text-xs max-w-xs",children:i})]}):E},Ml=s=>s.alert?e.jsxs(Q,{className:`${Al(s.alert.severity)} text-[10px] whitespace-nowrap`,children:["ð¡ï¸ ",El(s.alert.severity)," (",s.alert.risk_score,")"]}):e.jsx("span",{className:"text-[10px] text-muted-foreground",children:"â"}),Ll=s=>{var O,S,N;const a=[],i=((O=s.alert)==null?void 0:O.signals)||[],y=i.find(j=>j.type==="failed_attempts"||j.type==="failed_attempts_heavy");if(y){const j=(N=(S=y.detail)==null?void 0:S.match(/\d+/))==null?void 0:N[0];a.push(j?`Po ${j} failed pokusech`:"Po neúspÄÅ¡ných pokusech")}s.is_suspected_bot&&a.push("PodezÅelý klient"),i.some(j=>j.type==="new_device")&&a.push("Nové zaÅÃzenÃ"),a.length===0&&s.status==="failed"&&!s.alert&&a.push("Pokus o pÅÃstup"),a.length===0&&s.status==="success"&&(s.login_method==="magiclink"||s.login_method==="otp")&&!s.alert&&a.push("Magic link"),a.length===0&&s.status==="success"&&s.login_method==="recovery"&&!s.alert&&a.push("Obnova pÅÃstupu"),a.length===0&&a.push("BÄžná aktivita");const E=a.slice(0,2),P=i.length>0,x=e.jsx("div",{className:"space-y-0.5",children:E.map((j,w)=>e.jsx("div",{className:`text-[10px] ${w===0?"font-medium":"text-muted-foreground"}`,children:j},w))});return P?e.jsxs(Ke,{children:[e.jsx(Ze,{asChild:!0,children:e.jsx("div",{className:"cursor-help",children:x})}),e.jsxs(He,{side:"top",className:"text-xs max-w-xs",children:[e.jsx("div",{className:"font-medium mb-1",children:"Signály alertu:"}),i.map((j,w)=>e.jsxs("div",{children:[Il(j.type)," (skóre: ",j.score,")",j.detail?` â ${j.detail}`:""]},w))]})]}):x},ma=s=>s||"Neznámý",Rl=s=>{if(!s||s.length!==2)return"ð";const a=127397;return String.fromCodePoint(...[...s.toUpperCase()].map(i=>i.charCodeAt(0)+a))},Vl=s=>s==="pending"?"Geo lookup probÃhá":s==="failed"?"Geo lookup selhal":s==="skipped"?"Geo lookup pÅeskoÄen (privátnÃ/neplatná IP)":"",$l=s=>s.geo_status==="resolved"&&s.country?e.jsxs("span",{className:"text-[11px] whitespace-nowrap",title:`${s.country} · ${s.city||"?"} · ${s.isp||"?"}`,children:[Rl(s.country)," ",s.city||s.country]}):e.jsxs(Ke,{children:[e.jsx(Ze,{asChild:!0,children:e.jsx("span",{className:"text-[10px] text-muted-foreground whitespace-nowrap cursor-help",children:"Geo N/A"})}),e.jsx(He,{side:"top",className:"text-xs",children:Vl(s.geo_status)})]}),pn=()=>{const s=new Date;return s.setHours(0,0,0,0),s.toISOString()},ua=s=>{const a=new Date;return a.setDate(a.getDate()-s),a.setHours(0,0,0,0),a.toISOString()},Bl=()=>{const{user:s}=Ht(),[a,i]=t.useState([]),[y,E]=t.useState(!0),[P,x]=t.useState(0),[O,S]=t.useState(""),[N,j]=t.useState(0),[w,M]=t.useState(20),[o,v]=t.useState("all"),[u,p]=t.useState("all"),[m,$]=t.useState("all"),[H,J]=t.useState("today"),[z,h]=t.useState(!1),[I,k]=t.useState(!0),[c,d]=t.useState("all");t.useState(null);const[T,r]=t.useState(null),[f,R]=t.useState("all"),[F,ce]=t.useState({alerts24h:0,failed24h:0,usersWithAlert24h:0}),[ie,W]=t.useState(!1),[Z,K]=t.useState(0),[l,U]=t.useState(!1),[n,G]=t.useState(!1),[Y,pe]=t.useState(!1),[B,te]=t.useState(null),[xe,de]=t.useState({}),L=t.useCallback(async()=>{E(!0);const[ue,ve,X]=await Promise.all([g.from("login_history").select("id, user_id, logged_in_at, login_method, browser, os, device_type, status, failure_reason, attempted_email, is_suspected_bot, bot_detection_reason, bot_score, ip_hash, country, city, region, isp, geo_status, login_ph
235ases, magic_link_token_prefix, user_agent, session_fingerprint",{count:"exact"}).order("logged_in_at",{ascending:!1}).limit(1e3),g.from("login_alerts").select("id, login_history_id, severity, risk_score, signals, notified_at, notification_attempts, created_at, user_id").order("created_at",{ascending:!1}).limit(2e3),g.rpc("admin_login_session_first_seen")]),Ce=ue.data,ze=ue.count;if(!Ce||Ce.length===0){i([]),x(0),E(!1);return}x(ze||Ce.length);const Me=[...new Set(Ce.map(he=>he.user_id).filter(Boolean))],[V,_e]=await Promise.all([Me.length>0?g.rpc("admin_get_profiles_by_ids",{_user_ids:Me}):Promise.resolve({data:[]}),Me.length>0?g.from("user_roles").select("user_id, role").in("user_id",Me):Promise.resolve({data:[]})]),Ie=new Map((V.data||[]).map(he=>[he.user_id,he])),Ve=new Map;(_e.data||[]).forEach(he=>{const os=Ve.get(he.user_id)||[];os.push(he.role),Ve.set(he.user_id,os)});const Fe=new Map;(ve.data||[]).forEach(he=>{Fe.set(he.login_history_id,he)});const C=new Date(Date.now()-24*60*60*1e3).toISOString(),ge=(ve.data||[]).filter(he=>he.created_at>=C).length,Te=new Set((ve.data||[]).filter(he=>he.created_at>=C).map(he=>he.user_id)).size,Oe=Ce.filter(he=>he.status==="failed"&&he.logged_in_at>=C).length;ce({alerts24h:ge,failed24h:Oe,usersWithAlert24h:Te});const Se={};(X.data||[]).forEach(he=>{he.session_fingerprint&&(Se[he.session_fingerprint]=he.first_seen)});const we=Ce.map(he=>({...he,status:he.status||"success",failure_reason:he.failure_reason||null,attempted_email:he.attempted_email||null,is_suspected_bot:he.is_suspected_bot||!1,bot_detection_reason:he.bot_detection_reason||null,bot_score:he.bot_score||0,ip_hash:he.ip_hash||null,country:he.country||null,city:he.city||null,region:he.region||null,isp:he.isp||null,geo_status:he.geo_status||null,session_fingerprint:he.session_fingerprint||null,login_phases:Array.isArray(he.login_ph
235ases)?he.login_phases:[],profile:he.user_id&&Ie.get(he.user_id)||void 0,roles:he.user_id?Ve.get(he.user_id)||[]:[],alert:Fe.get(he.id)||null}));i(we),de(Se),te(new Date),E(!1)},[]);t.useEffect(()=>{L();const ue=setInterval(()=>{document.visibilityState==="visible"&&L()},3e4);return()=>clearInterval(ue)},[L]),t.useEffect(()=>{const ue=async()=>{const X=new Date(Date.now()-12e4).toISOString(),{data:Ce,error:ze}=await g.from("user_activity").select("user_id").gte("last_active_at",X);if(!ze&&Ce){const Me=new Set(Ce.map(V=>V.user_id));K(Me.size)}};ue();const ve=setInterval(()=>{document.visibilityState==="visible"&&ue()},3e4);return()=>clearInterval(ve)},[]),t.useEffect(()=>{j(0)},[O,o,u,m,H,z,I,c,f,w]);const re=ue=>{var X;if(!ue.profile)return ue.user_id?ue.user_id.slice(0,8):"â";const ve=[ue.profile.first_name,ue.profile.last_name].filter(Boolean);return ve.length>0?ve.join(" "):ue.profile.full_name||ue.profile.email||((X=ue.user_id)==null?void 0:X.slice(0,8))||"â"},A=t.useMemo(()=>{const ue=H==="today"?pn():H==="7d"?ua(7):H==="30d"?ua(30):null;return a.filter(ve=>{var X,Ce,ze,Me;if(ue&&ve.logged_in_at<ue||o==="owners"&&(!ve.roles.includes("owner")||ve.roles.some(V=>Pl.has(V)))||u!=="all"&&ve.status!==u||m!=="all"&&ve.login_method!==m||z&&s&&ve.user_id===s.id||I&&Ct(ve,xe)==="continuation"||c==="suspected"&&!ve.is_suspected_bot||c==="humans"&&ve.is_suspected_bot||f==="with_alert"&&!ve.alert||f==="severity_low"&&((X=ve.alert)==null?void 0:X.severity)!=="low"||f==="severity_medium"&&((Ce=ve.alert)==null?void 0:Ce.severity)!=="medium"||f==="severity_high"&&((ze=ve.alert)==null?void 0:ze.severity)!=="high"||f==="notified"&&(!ve.alert||!ve.alert.notified_at)||f==="not_notified"&&(!ve.alert||ve.alert.notified_at))return!1;if(O){const V=O.toLowerCase(),_e=ve.profile?[ve.profile.first_name,ve.profile.last_name,ve.profile.full_name,ve.profile.email].filter(Boolean).join(" ").toLowerCase():"",Ie=((Me=ve.attempted_email)==null?void 0:Me.toLowerCase())||"";if(!_e.includes(V)&&!Ie.includes(V))return!1}return!0})},[a,O,o,u,m,H,z,I,c,f,s,xe]),ne=t.useMemo(()=>{const ue=pn(),ve=a.filter(Fe=>Fe.logged_in_at>=ue),X=ve.filter(Fe=>{if(Fe.status!=="success")return!1;if(!Fe.session_fingerprint)return!0;const C=Ct(Fe,xe);return C==="new_session"||C==="legacy"}).length,Ce=ve.filter(Fe=>Fe.status==="failed").length,ze=new Set(ve.filter(Fe=>Fe.status==="success"&&Fe.user_id).map(Fe=>Fe.user_id)),Me=ve.filter(Fe=>Fe.is_suspected_bot).length,V=ve.filter(Fe=>Fe.ip_hash),_e=new Map;V.forEach(Fe=>{Fe.ip_hash&&Fe.user_id&&(_e.has(Fe.ip_hash)||_e.set(Fe.ip_hash,new Set),_e.get(Fe.ip_hash).add(Fe.user_id))});const Ie=[..._e.values()].filter(Fe=>Fe.size>1).length,Ve=F.alerts24h+Me+Ie;return{successToday:X,failedToday:Ce,activeUsers:ze.size,suspectedBotToday:Me,sharedIpToday:Ie,securityTotal:Ve}},[a,F.alerts24h,xe]),le=Math.max(1,Math.ceil(A.length/w)),oe=A.slice(N*w,(N+1)*w),ke=async()=>{pe(!0),await g.from("login_alerts").delete().neq("id","00000000-0000-0000-0000-000000000000");const{error:ue}=await g.from("login_history").delete().neq("id","00000000-0000-0000-0000-000000000000");pe(!1),U(!1),ue&&console.error("Delete all error:",ue),L()},je=async()=>{pe(!0);const ue=ua(60);await g.from("login_alerts").delete().lt("created_at",ue);const{error:ve}=await g.from("login_history").delete().lt("logged_in_at",ue);pe(!1),G(!1),ve&&console.error("Delete old error:",ve),L()};return y&&a.length===0?e.jsx("div",{className:"flex justify-center py-12",children:e.jsx(fe,{className:"h-8 w-8 animate-spin text-primary"})}):T?e.jsx(Cl,{event:T,onBack:()=>r(null)}):e.jsxs("div",{className:"space-y-6",children:[e.jsxs("div",{className:"flex flex-col sm:flex-row sm:items-center justify-between gap-4",children:[e.jsxs("div",{children:[e.jsx("h2",{className:"font-serif text-2xl font-bold text-foreground",children:"PÅehled pÅihlášenà a pokusů"}),e.jsx("p",{className:"text-muted-foreground text-sm mt-1",children:"PÅehled skuteÄných pÅihlášenà a pokusů o pÅihlášenÃ"}),B&&e.jsxs("p",{className:"text-xs text-muted-foreground/70 mt-0.5",children:["Naposledy obnoveno: ",hs(B,"dd.MM.yyyy HH:mm:ss",{locale:ys})]})]}),e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsxs(b,{variant:ie?"default":"outline",size:"sm",className:"gap-1.5",onClick:()=>W(ue=>!ue),children:[e.jsx("span",{className:`inline-block h-2 w-2 rounded-full ${Z>0?"bg-emerald-400 animate-pulse":"bg-gray-400"}`}),"PrávÄ aktivnà (",Z,")"]}),e.jsxs(b,{variant:"outline",size:"sm",className:"gap-1.5",onClick:L,disabled:y,children:[e.jsx(Es,{className:`h-3.5 w-3.5 ${y?"animate-spin":""}`}),"Obnovit"]}),e.jsxs(dr,{children:[e.jsx(mr,{asChild:!0,children:e.jsxs(b,{variant:"outline",size:"sm",className:"gap-1.5 text-destructive border-destructive/30 hover:bg-destructive/10",children:[e.jsx(qe,{className:"h-3.5 w-3.5"}),"Smazat log"]})}),e.jsxs(ur,{align:"end",children:[e.jsxs(Ia,{onClick:()=>G(!0),className:"gap-2",children:[e.jsx(qe,{className:"h-4 w-4"}),"Smazat záznamy staršà 60 dnů"]}),e.jsxs(Ia,{onClick:()=>U(!0),className:"gap-2 text-destructive focus:text-destructive",children:[e.jsx(qe,{className:"h-4 w-4"}),"Smazat celý log"]})]})]})]})]}),e.jsxs("div",{className:"grid grid-cols-2 lg:grid-cols-4 gap-4",children:[e.jsx(ee,{className:"border-l-4 border-l-emerald-500",children:e.jsx(ae,{className:"p-4",children:e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsxs("div",{children:[e.jsx("p",{className:"text-xs font-medium uppercase tracking-wide text-muted-foreground",children:"Nová pÅihlášenà dnes"}),e.jsx("p",{className:"text-3xl font-bold text-foreground mt-1",children:ne.successToday}),e.jsxs("p",{className:"text-xs text-muted-foreground mt-1",children:[ne.successToday," úspÄÅ¡ných z ",ne.successToday+ne.failedToday," pokusů"]})]}),e.jsx("div",{className:"h-10 w-10 rounded-full bg-emerald-500/10 flex items-center justify-center",children:e.jsx(La,{className:"h-5 w-5 text-emerald-600"})})]})})}),e.jsx(ee,{className:`border-l-4 ${ne.failedToday>0?"border-l-red-500 bg-red-50/50 dark:bg-red-950/20":"border-l-red-300"}`,children:e.jsx(ae,{className:"p-4",children:e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsxs("div",{children:[e.jsx("p",{className:"text-xs font-medium uppercase tracking-wide text-muted-foreground",children:"NeúspÄÅ¡né pokusy"}),e.jsx("p",{className:"text-3xl font-bold text-foreground mt-1",children:ne.failedToday}),e.jsx("p",{className:"text-xs text-muted-foreground mt-1",children:"neúspÄÅ¡né pokusy o pÅihlášenÃ"})]}),e.jsx("div",{className:`h-10 w-10 rounded-full flex items-center justify-center ${ne.failedToday>0?"bg-red-500/20":"bg-red-500/10"}`,children:e.jsx(js,{className:`h-5 w-5 ${ne.failedToday>0?"text-red-600":"text-red-400"}`})})]})})}),e.jsx(ee,{className:"border-l-4 border-l-primary",children:e.jsx(ae,{className:"p-4",children:e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsxs("div",{children:[e.jsx("p",{className:"text-xs font-medium uppercase tracking-wide text-muted-foreground",children:"Aktivnà uživatelé"}),e.jsx("p",{className:"text-3xl font-bold text-foreground mt-1",children:ne.activeUsers}),e.jsx("p",{className:"text-xs text-muted-foreground mt-1",children:"unikátnà uživatelé dnes"})]}),e.jsx("div",{className:"h-10 w-10 rounded-full bg-primary/10 flex items-center justify-center",children:e.jsx(Fs,{className:"h-5 w-5 text-primary"})})]})})}),e.jsx(ee,{className:`border-l-4 ${ne.securityTotal>0?"border-l-orange-500 bg-orange-50/50 dark:bg-orange-950/20":"border-l-amber-400"}`,children:e.jsx(ae,{className:"p-4",children:e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsxs("div",{children:[e.jsx("p",{className:"text-xs font-medium uppercase tracking-wide text-muted-foreground",children:"BezpeÄnostnà alerty"}),e.jsx("p",{className:"text-3xl font-bold text-foreground mt-1",children:ne.securityTotal}),e.jsxs("p",{className:"text-xs text-muted-foreground mt-1",children:["Alerty ",F.alerts24h," · PodezÅelé ",ne.suspectedBotToday," · SdÃlené IP ",ne.sharedIpToday]})]}),e.jsx("div",{className:`h-10 w-10 rounded-full flex items-center justify-center ${ne.securityTotal>
2350?"bg-orange-500/20":"bg-amber-500/10"}`,children:e.jsx(nt,{className:`h-5 w-5 ${ne.securityTotal>0?"text-orange-600":"text-amber-500"}`})})]})})})]}),e.jsx(zl,{isOpen:ie}),e.jsxs(ee,{children:[e.jsxs(ye,{className:"flex flex-row items-center justify-between",children:[e.jsxs(be,{className:"text-base flex items-center gap-2",children:[e.jsx(La,{className:"h-4 w-4"}),"PÅehled událostà (",A.length,")"]}),e.jsx("div",{className:"flex items-center gap-1 bg-muted/50 rounded-lg p-1",children:[{key:"owners",label:"VlastnÃci"},{key:"all",label:"VÅ¡echny události"}].map(({key:ue,label:ve})=>e.jsx("button",{onClick:()=>v(ue),className:`px-3 py-1.5 text-xs font-medium rounded-md transition-colors ${o===ue?"bg-background shadow-sm text-foreground":"text-muted-foreground hover:text-foreground"}`,children:ve},ue))})]}),e.jsxs(ae,{children:[e.jsxs("div",{className:"flex flex-wrap items-center gap-3 mb-4",children:[e.jsxs("div",{className:"relative",children:[e.jsx(fs,{className:"absolute left-3 top-1/2 -translate-y-1/2 h-4 w-4 text-muted-foreground"}),e.jsx(se,{placeholder:"Hledat jméno, emailâ¦",value:O,onChange:ue=>S(ue.target.value),className:"pl-9 bg-background max-w-xs"})]}),e.jsxs(De,{value:u,onValueChange:p,children:[e.jsx(Pe,{className:"h-9 w-[130px] text-xs",children:e.jsx(Ae,{placeholder:"Výsledek"})}),e.jsxs(Ee,{children:[e.jsx(me,{value:"all",className:"text-xs",children:"VÅ¡e"}),e.jsx(me,{value:"success",className:"text-xs",children:"ÃspÄÅ¡né"}),e.jsx(me,{value:"failed",className:"text-xs",children:"NeúspÄÅ¡né"})]})]}),e.jsxs(De,{value:m,onValueChange:$,children:[e.jsx(Pe,{className:"h-9 w-[130px] text-xs",children:e.jsx(Ae,{placeholder:"Metoda"})}),e.jsxs(Ee,{children:[e.jsx(me,{value:"all",className:"text-xs",children:"VÅ¡echny metody"}),e.jsx(me,{value:"password",className:"text-xs",children:"Heslo"}),e.jsx(me,{value:"magiclink",className:"text-xs",children:"Magic link"})]})]}),e.jsxs(De,{value:H,onValueChange:ue=>J(ue),children:[e.jsx(Pe,{className:"h-9 w-[110px] text-xs",children:e.jsx(Ae,{placeholder:"ObdobÃ"})}),e.jsxs(Ee,{children:[e.jsx(me,{value:"today",className:"text-xs",children:"Dnes"}),e.jsx(me,{value:"7d",className:"text-xs",children:"7 dnÃ"}),e.jsx(me,{value:"30d",className:"text-xs",children:"30 dnÃ"}),e.jsx(me,{value:"all",className:"text-xs",children:"VÅ¡e"})]})]}),e.jsxs(De,{value:c,onValueChange:ue=>d(ue),children:[e.jsx(Pe,{className:"h-9 w-[140px] text-xs",children:e.jsx(Ae,{placeholder:"Typ klienta"})}),e.jsxs(Ee,{children:[e.jsx(me,{value:"all",className:"text-xs",children:"VÅ¡e"}),e.jsx(me,{value:"humans",className:"text-xs",children:"Pouze bÄžnÃ"}),e.jsx(me,{value:"suspected",className:"text-xs",children:"Pouze podezÅelÃ"})]})]}),e.jsxs(De,{value:f,onValueChange:ue=>R(ue),children:[e.jsx(Pe,{className:"h-9 w-[155px] text-xs",children:e.jsx(Ae,{placeholder:"Alerty"})}),e.jsxs(Ee,{children:[e.jsx(me,{value:"all",className:"text-xs",children:"VÅ¡e"}),e.jsx(me,{value:"with_alert",className:"text-xs",children:"Jen s alertem"}),e.jsx(me,{value:"severity_low",className:"text-xs",children:"NÃzké riziko"}),e.jsx(me,{value:"severity_medium",className:"text-xs",children:"StÅednà riziko"}),e.jsx(me,{value:"severity_high",className:"text-xs",children:"Vysoké riziko"}),e.jsx(me,{value:"notified",className:"text-xs",children:"Notifikováno"}),e.jsx(me,{value:"not_notified",className:"text-xs",children:"Nenotifikováno"})]})]}),e.jsxs("div",{className:"flex items-center gap-1.5 ml-auto",children:[e.jsx(ss,{id:"hide-my",checked:z,onCheckedChange:h,className:"scale-75"}),e.jsx(q,{htmlFor:"hide-my",className:"text-xs cursor-pointer text-muted-foreground",children:"Skrýt moje"})]}),e.jsxs("div",{className:"flex items-center gap-1.5",children:[e.jsx(ss,{id:"hide-continuation",checked:I,onCheckedChange:k,className:"scale-75"}),e.jsx(q,{htmlFor:"hide-continuation",className:"text-xs cursor-pointer text-muted-foreground",children:"Skrýt pokraÄovánÃ"})]})]}),A.length===0?e.jsxs("div",{className:"flex flex-col items-center justify-center py-12 text-center",children:[e.jsx(nt,{className:"h-10 w-10 text-muted-foreground
235/40 mb-3"}),e.jsx("p",{className:"text-muted-foreground font-medium",children:O||u!=="all"||m!=="all"||H!=="today"||c!=="all"||f!=="all"?"Za zvolené obdobà a filtry nebyly nalezeny žádné události. Zkuste upravit filtry.":"ZatÃm žádné zaznamenané pÅihlaÅ¡ovacà události."})]}):e.jsxs(e.Fragment,{children:[e.jsxs($e,{children:[e.jsx(Be,{children:e.jsxs(Ne,{className:"bg-muted/50 hover:bg-muted/50",children:[e.jsx(D,{className:"h-9 text-xs w-[130px]",children:"Datum a Äas"}),e.jsx(D,{className:"h-9 text-xs w-[150px]",children:"Událost"}),e.jsx(D,{className:"h-9 text-xs",children:"Uživatel"}),e.jsx(D,{className:"h-9 text-xs w-[130px]",children:"Lokalita"}),e.jsx(D,{className:"h-9 text-xs",children:"ZaÅÃzenÃ"}),e.jsx(D,{className:"h-9 text-xs w-[100px]",children:"Riziko"}),e.jsx(D,{className:"h-9 text-xs w-[170px]",children:"Kontext"})]})}),e.jsx(Ue,{children:oe.map(ue=>{var Ce;const X=Ct(ue,xe)==="continuation";return e.jsxs(Ne,{className:`h-8 cursor-pointer hover:bg-muted/30 ${ue.status==="failed"?"bg-red-50/50 dark:bg-red-950/10":""} ${X?"opacity-60":""}`,onClick:()=>r(ue),children:[e.jsx(_,{className:"py-1 text-xs",children:e.jsxs("div",{className:"flex items-center gap-1",children:[e.jsx(Ys,{className:"h-3 w-3 text-muted-foreground shrink-0"}),e.jsxs("div",{children:[e.jsx("div",{className:"whitespace-nowrap",children:hs(new Date(ue.logged_in_at),"dd.MM.yyyy HH:mm",{locale:ys})}),e.jsx("div",{className:"text-[10px] text-muted-foreground whitespace-nowrap",children:Dn(new Date(ue.logged_in_at),{addSuffix:!0,locale:ys})})]})]})}),e.jsx(_,{className:"py-1",children:e.jsx(as,{children:Fl(ue,Ct(ue,xe))})}),e.jsxs(_,{className:"py-1",children:[e.jsxs("div",{className:"flex items-center gap-1.5",children:[e.jsx("span",{className:"text-xs font-medium whitespace-nowrap",children:re(ue)}),Tl(ue.roles)]}),e.jsx("div",{className:"text-[10px] text-muted-foreground truncate max-w-[200px]",children:((Ce=ue.profile)==null?void 0:Ce.email)||ue.attempted_email||"â"})]}),e.jsx(_,{className:"py-1",children:e.jsx(as,{children:$l(ue)}
235)}),e.jsxs(_,{className:"py-1 text-[11px] text-muted-foreground whitespace-nowrap",children:[ma(ue.browser)," · ",ma(ue.os)," · ",ma(ue.device_type)]}),e.jsx(_,{className:"py-1",children:Ml(ue)}),e.jsx(_,{className:"py-1",children:e.jsx(as,{children:Ll(ue)})})]},ue.id)})})]}),e.jsxs("div",{className:"flex items-center justify-between pt-3 border-t mt-3",children:[e.jsxs("div",{className:"flex items-center gap-3",children:[e.jsxs("p",{className:"text-xs text-muted-foreground",children:[N*w+1,"â",Math.min((N+1)*w,A.length)," z ",A.length]}),e.jsxs("div",{className:"flex items-center gap-1.5",children:[e.jsx("span",{className:"text-xs text-muted-foreground",children:"Zobrazit:"}),e.jsxs(De,{value:String(w),onValueChange:ue=>M(Number(ue)),children:[e.jsx(Pe,{className:"h-7 w-[65px] text-xs",children:e.jsx(Ae,{})}),e.jsx(Ee,{children:Dl.map(ue=>e.jsx(me,{value:String(ue),className:"text-xs",children:ue},ue))})]})]})]}),e.jsxs("div",{className:"flex items-center gap-1",children:[e.jsx(b,{variant:"outline",size:"sm",className:"h-7 w-7 p-0",onClick:()=>j(ue=>ue-1),disabled:N===0,children:e.jsx(Yr,{className:"h-3.5 w-3.5"})}),e.jsxs("span",{className:"text-xs px-2 text-muted-foreground",children:[N+1," / ",le]}),e.jsx(b,{variant:"outline",size:"sm",className:"h-7 w-7 p-0",onClick:()=>j(ue=>ue+1),disabled:N>=le-1,children:e.jsx(Ts,{className:"h-3.5 w-3.5"})})]})]})]})]})]}),e.jsx(ms,{open:n,onOpenChange:G,title:"Smazat staré záznamy",description:"Budou smazány vÅ¡echny záznamy o pÅihlášenà staršà než 60 dnů. Tato akce je nevratná.",confirmText:Y?"Mažuâ¦":"Smazat staré záznamy",onConfirm:je}),e.jsx(ms,{open:l,onOpenChange:U,title:"Smazat celý log",description:"Budou smazány VÅ ECHNY záznamy o pÅihlášenÃ. Tato akce je nevratná.",confirmText:Y?"Mažuâ¦":"Smazat vÅ¡e",onConfirm:ke})]})},Ul=["active","lost","historical","planned"],gn={active:"AktivnÃ",lost:"Ztracený",historical:"Historický",planned:"Plánovaný"},ql={active:"bg-green-100 text-green-700",lost:"bg-gray-100 text-gray-600",historical:"bg-gray-100 text-gray-500",planned:"bg-blue-100 text-blue-700"},Kl=()=>{const{toast:s}=Re(),a=ws(),[i,y]=t.useState(null),[E,P]=t.useState(!1),[x,O]=t.useState(!1),[S,N]=t.useState(null),[j,w]=t.useState(""),[M,o]=t.useState("all"),{data:v,isLoading:u}=ds({queryKey:["admin-monitoring-points"],queryFn:async()=>{const{data:c,error:d}=await g.from("monitoring_points").select("*, monitoring_areas(name)").order("display_order");if(d)throw d;return c}}),{data:p}=ds({queryKey:["monitoring-areas"],queryFn:async()=>{const{data:c,error:d}=await g.from("monitoring_areas").select("*").order("sort_order");if(d)throw d;return c}}),{data:m}=ds({queryKey:["admin-point-measurement-dates"],queryFn:async()=>{var r;const{data:c,error:d}=await g.from("monitoring_measurements").select("point_id, campaign_id, measurement_campaigns(measured_at)");if(d)throw d;const T={};for(const f of c||[]){const R=(r=f.measurement_campaigns)==null?void 0:r.measured_at;R&&(T[f.point_id]?(R<T[f.point_id].first&&(T[f.point_id].first=R),R>T[f.point_id].last&&(T[f.point_id].last=R)):T[f.point_id]={first:R,last:R})}return T}}),$=t.useMemo(()=>v?M==="all"?v:v.filter(c=>c.status===M):[],[v,M]),H=ns({mutationFn:async c=>{const d={code:c.code,label:c.label||null,area_id:c.area_id||null,status:c.status,x:c.x||0,y:c.y||0,is_reference_point:c.is_reference_point||!1,notes:c.notes||null,installed_at:c.installed_at||null,deactivated_at:c.deactivated_at||null};if(c.id){const{error:T}=await g.from("monitoring_points").update(d).eq("id",c.id);if(T)throw T}else{const{error:T}=await g.from("monitoring_points").insert(d);if(T)throw T}},onSuccess:()=>{a.invalidateQueries({queryKey:["admin-monitoring-points"]}),P(!1),s({title:"Uloženo"})},onError:c=>s({variant:"destructive",title:"Chyba",description:c.message})}),J=ns({mutationFn:async c=>{const{error:d}=await g.from("monitoring_points").delete().eq("id",c);if(d)throw d},onSuccess:()=>{a.invalidateQueries({queryKey:["admin-monitoring-points"]}),s({title:"Smazáno"})}}),z=ns({mutationFn:async c=>{const{error:d}=await g.from("monitoring_points").update({status:"lost",deactivated_at:new Date().toISOString().split("T")[0]}).eq("id",c.id);if(d)throw d},onSuccess:()=>{a.invalidateQueries({queryKey:["admin-monitoring-points"]}),s({title:"Bod oznaÄen jako ztracený"})}}),h=ns({mutationFn:async({pointId:c,replacedById:d})=>{const{error:T}=await g.from("monitoring_points").update({replaced_by_point_id:d}).eq("id",c);if(T)throw T;const{error:r}=await g.from("monitoring_points").update({replaces_point_id:c}).eq("id",d);if(r)throw r},onSuccess:()=>{a.invalidateQueries({queryKey:["admin-monitoring-points"]}),O(!1),s({title:"Náhrada propojena"})}}),I=()=>{y({code:"",status:"active",x:.5,y:.5,is_reference_point:!1}),P(!0)},k=[{key:"all",label:"VÅ¡e"},{key:"active",label:"AktivnÃ"},{key:"lost",label:"Ztracené"},{key:"historical",label:"Historické"},{key:"planned",label:"Plánované"}];return e.jsxs("div",{className:"space-y-4",children:[e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsx("h2",{className:"text-lg font-serif font-bold",children:"MÄÅicà body"}),e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx("div",{className:"flex gap-1",children:k.map(c=>e.jsx(Q,{variant:M===c.key?"default":"outline",className:"cursor-pointer",onClick:()=>o(c.key),children:c.label},c.key))}),e.jsxs(b,{onClick:I,size:"sm",children:[e.jsx(Xe,{className:"h-4 w-4 mr-1"})," Nový bod"]})]})]}),e.jsxs($e,{children:[e.jsx(Be,{children:e.jsxs(Ne,{children:[e.jsx(D,{children:"Kód"}),e.jsx(D,{children:"Oblast"}),e.jsx(D,{children:"Status"}),e.jsx(D,{children:"Instalace"}),e.jsx(D,{children:"Deaktivace"}),e.jsx(D,{children:"Prvnà mÄÅenÃ"}),e.jsx(D,{children:"Poslednà mÄÅenÃ"}),e.jsx(D,{children:"Pozice"}),e.jsx(D,{children:"Ref."}),e.jsx(D,{className:"w-28"})]})}),e.jsx(Ue,{children:$.map(c=>{var T;const d=m==null?void 0:m[c.id];return e.jsxs(Ne,{children:[e.jsx(_,{className:"font-medium",children:c.code}),e.jsx(_,{children:((T=c.monitoring_areas)==null?void 0:T.name)||"â"}),e.jsx(_,{children:e.jsx(Q,{className:ql[c.status]||"",variant:"outline",children:gn[c.status]})}),e.jsx(_,{className:"text-xs",children:c.installed_at?new Date(c.installed_at).toLocaleDateString("cs-CZ"):"â"}),e.jsx(_,{className:"text-xs",children:c.deactivated_at?new Date(c.deactivated_at).toLocaleDateString("cs-CZ"):"â"}),e.jsx(_,{className:"text-xs",children:d!=null&&d.first?new Date(d.first).toLocaleDateString("cs-CZ"):"â"}),e.jsx(_,{className:"text-xs",children:d!=null&&d.last?new Date(d.last).toLocaleDateString("cs-CZ"):"â"}),e.jsxs(_,{className:"text-xs text-muted-foreground",children:[Number(c.x).toFixed(2),", ",Number(c.y).toFixed(2)]}),e.jsx(_,{children:c.is_reference_point?"â":""}),e.jsx(_,{children:e.jsxs("div",{className:"flex gap-1",children:[e.jsx(b,{variant:"ghost",size:"icon",className:"h-7 w-7",onClick:()=>{y({...c}),P(!0)},children:e.jsx(Ns,{className:"h-3.5 w-3.5"})}),c.status==="active"&&e.jsx(b,{variant:"ghost",size:"icon",className:"h-7 w-7 text-amber-600",title:"OznaÄit jako ztracený",onClick:()=>z.mutate(c),children:e.jsx(js,{className:"h-3.5 w-3.5"})}),e.jsx(b,{variant:"ghost",size:"icon",className:"h-7 w-7 text-blue-600",title:"Propojit náhradu",onClick:()=>{N(c),w(""),O(!0)},children:e.jsx(Vs,{className:"h-3.5 w-3.5"})}),e.jsx(b,{variant:"ghost",size:"icon",className:"h-7 w-7 text-destructive",onClick:()=>J.mutate(c.id),children:e.jsx(qe,{className:"h-3.5 w-3.5"})})]})})]},c.id)})})]}),e.jsx(Ge,{open:E,onOpenChange:P,children:e.jsxs(Je,{children:[e.jsx(Ye,{children:e.jsx(Qe,{children:i!=null&&i.id?"Upravit bod":"Nový bod"})}),i&&e.jsxs("div",{className:"space-y-3",children:[e.jsxs("div",{children:[e.jsx(q,{children:"Kód"}),e.jsx(se,{value:i.code,onChange:c=>y({...i,code:c.target.value})})]}),e.jsxs("div",{children:[e.jsx(q,{children:"Popis"}),e.jsx(se,{value:i.label||"",onChange:c=>y({...i,label:c.target.value})})]}),e.jsxs("div",{children:[e.jsx(q,{children:"Oblast"}),e.jsxs(De,{value:i.area_id||"",onValueChange:c=>y({...i,area_id:c}),children:[e.jsx(Pe,{children:e.jsx(Ae,{placeholder:"Vyberte oblast"})}),e.jsx(Ee,{children:(p||[]).map(c=>e.jsx(me,{value:c.id,children:c.name},c.id))})]})]}),e.jsxs("div",{children:[e.jsx(q,{children:"Status"}),e.jsxs(De,{value:i.status,onValueChange:c=>y({...i,status:c}),children:[e.jsx(Pe,{children:e.jsx(Ae,{})}),e.jsx(Ee,{children:Ul.map(c=>e.jsx(me,{value:c,children:gn[c]},c))})]})]}),e.jsxs("div",{className:"grid grid-cols-2 gap-3",children:[e.jsxs("div",{children:[e.jsx(q,{children:"Instalace"}),e.jsx(se,{type:"date",value:i.installed_at||"",onChange:c=>y({...i,installed_at:c.target.value})})]}),e.jsxs("div",{children:[e.jsx(q,{children:"Deaktivace"}),e.jsx(se,{type:"date",value:i.deactivated_at||"",onChange:c=>y({...i,deactivated_at:c.target.value})})]})]}),e.jsxs("div",{className:"grid grid-cols-2 gap-3",children:[e.jsxs("div",{children:[e.jsx(q,{children:"X (0â1)"}),e.jsx(se,{type:"number",step:"0.01",value:i.x,onChange:c=>y({...i,x:parseFloat(c.target.value)})})]}),e.jsxs("div",{children:[e.jsx(q,{children:"Y (0â1)"}),e.jsx(se,{type:"number",step:"0.01",value:i.y,onChange:c=>y({...i,y:parseFloat(c.target.value)})})]})]}),e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(xs,{checked:i.is_reference_point||!1,onCheckedChange:c=>y({...i,is_reference_point:!!c}),id:"ref"}),e.jsx(q,{htmlFor:"ref",children:"ReferenÄnà bod"})]}),e.jsxs("div",{children:[e.jsx(q,{children:"Poznámky"}),e.jsx(vs,{value:i.notes||"",onChange:c=>y({...i,notes:c.target.value})})]})]}),e.jsxs(ls,{children:[e.jsx(b,{variant:"outline",onClick:()=>P(!1),children:"ZruÅ¡it"}),e.jsx(b,{onClick:()=>H.mutate(i),disabled:H.isPending,children:"Uložit"})]})]})}),e.jsx(Ge,{open:x,onOpenChange:O,children:e.jsxs(Je,{children:[e.jsx(Ye,{children:e.jsxs(Qe,{children:["Propojit náhradu bodu ",S==null?void 0:S.code]})}),e.jsxs("div",{className:"space-y-3",children:[e.jsx(q,{children:"Náhradnà bod"}),e.jsxs(De,{value:j,onValueChange:w,children:[e.jsx(Pe,{children:e.jsx(Ae,{placeholder:"Vyberte bod"})}),e.jsx(Ee,{children:(v||[]).filter(c=>c.id!==(S==null?void 0:S.id)).map(c=>e.jsx(me,{value:c.id,children:c.code},c.id))})]})]}),e.jsxs(ls,{children:[e.jsx(b,{variant:"outline",onClick:()=>O(!1),children:"ZruÅ¡it"}),e.jsx(b,{disabled:!j,onClick:()=>h.mutate({pointId:S.id,replacedById:j}),children:"Propojit"})]})]})})]})},Zl=()=>{const{toast:s}=Re(),a=ws(),[i,y]=t.useState(null),[E,P]=t.useState(!1),[x,O]=t.useState(null),{data:S}=ds({queryKey:["admin-monitoring-measurements"],queryFn:async()=>{const{data:v,error:u}=await g.from("measurement_campaigns").select("*").order("measured_at",{ascending:!1});if(u)throw u;return v}}),{data:N}=ds({queryKey:["admin-measurement-counts"],queryFn:async()=>{const{data:v,error:u}=await g.from("monitoring_measurements").select("campaign_id, import_batch_id, source_file_name, imported_at");if(u)throw u;const p={};for(const m of v||[])p[m.campaign_id]||(p[m.campaign_id]={count:0,batchId:m.import_batch_id,sourceFile:m.source_file_name,importedAt:m.imported_at}),p[m.campaign_id].count++;return p}}),{data:j}=ds({queryKey:["admin-measurement-values",x],enabled:!!x,queryFn:async()=>{const{data:v,error:u}=await g.from("monitoring_measurements").select("*, monitoring_points(code)").eq("campaign_id",x).order("created_at");if(u)throw u;return v}}),w=ns({mutationFn:async v=>{const u={measured_at:v.measured_at,label:v.label||null,order_index:v.order_index||null,
235notes:v.notes||null};if(v.id){const{error:p}=await g.from("measurement_campaigns").update(u).eq("id",v.id);if(p)throw p}else{const{error:p}=await g.from("measurement_campaigns").insert(u);if(p)throw p}},onSuccess:()=>{a.invalidateQueries({queryKey:["admin-monitoring-measurements"]}),P(!1),s({title:"Uloženo"})},onError:v=>s({variant:"destructive",title:"Chyba",description:v.message})}),M=ns({mutationFn:async v=>{const{error:u}=await g.from("measurement_campaigns").delete().eq("id",v);if(u)throw u},onSuccess:()=>{a.invalidateQueries({queryKey:["admin-monitoring-measurements"]}),s({title:"Smazáno"})}}),o={ok:"bg-green-100 text-green-700",estimated:"bg-yellow-100 text-yellow-700",uncertain:"bg-orange-100 text-orange-700",missing:"bg-red-100 text-red-700"};return e.jsxs("div",{className:"space-y-4",children:[e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsx("h2",{className:"text-lg font-serif font-bold",children:"MÄÅenÃ"}),e.jsxs(b,{onClick:()=>{y({measured_at:"",label:""}),P(!0)},size:"sm",children:[e.jsx(Xe,{className:"h-4 w-4 mr-1"})," Nové mÄÅenÃ"]})]}),e.jsxs($e,{children:[e.jsx(Be,{children:e.jsxs(Ne,{children:[e.jsx(D,{className:"w-8"}),e.jsx(D,{children:"Datum"}),e.jsx(D,{children:"Název"}),e.jsx(D,{children:"Bodů"}),e.jsx(D,{children:"Zdrojový soubor"}),e.jsx(D,{children:"Import batch"}),e.jsx(D,{children:"Poznámka"}),e.jsx(D,{className:"w-20"})]})}),e.jsx(Ue,{children:(S||[]).map(v=>{const u=N==null?void 0:N[v.id],p=x===v.id;return e.jsx(xt,{open:p,onOpenChange:()=>O(p?null:v.id),asChild:!0,children:e.jsxs(e.Fragment,{children:[e.jsxs(Ne,{children:[e.jsx(_,{children:e.jsx(ht,{asChild:!0,children:e.jsx(b,{variant:"ghost",size:"icon",className:"h-6 w-6",children:p?e.jsx(Js,{className:"h-3.5 w-3.5"}):e.jsx(Ts,{className:"h-3.5 w-3.5"})})})}),e.jsx(_,{className:"font-medium",children:new Date(v.measured_at).toLocaleDateString("cs-CZ")}),e.jsx(_,{children:v.label||"â"}),e.jsx(_,{children:e.jsx(Q,{variant:"secondary",children:(u==null?void 0:u.count)||0})}),e.jsx(_,{className:"text-xs text-muted-foreground",children:(u==null?void 0:u.sourceFile)||"â"}),e.jsx(_,{className:"text-xs text-muted-foreground font-mono",children:u!=null&&u.batchId?u.batchId.substring(0,8)+"â¦":"â"}),e.jsx(_,{className:"text-xs text-muted-foreground max-w-[150px] truncate",children:v.notes||""}),e.jsx(_,{children:e.jsxs("div",{className:"flex gap-1",children:[e.jsx(b,{variant:"ghost",size:"icon",className:"h-7 w-7",onClick:()=>{y({...v}),P(!0)},children:e.jsx(Ns,{className:"h-3.5 w-3.5"})}),e.jsx(b,{variant:"ghost",size:"icon",className:"h-7 w-7 text-destructive",onClick:()=>M.mutate(v.id),children:e.jsx(qe,{className:"h-3.5 w-3.5"})})]})})]}),e.jsx(pt,{asChild:!0,children:e.jsx("tr",{children:e.jsx("td",{colSpan:8,className:"p-0",children:e.jsxs("div",{className:"bg-muted/30 p-4 border-t",children:[(u==null?void 0:u.importedAt)&&e.jsxs("p",{className:"text-xs text-muted-foreground mb-2",children:["Importováno: ",new Date(u.importedAt).toLocaleString("cs-CZ")]}),e.jsxs($e,{children:[e.jsx(Be,{children:e.jsxs(Ne,{children:[e.jsx(D,{children:"Bod"}),e.jsx(D,{children:"Absolutnà [mm]"}),e.jsx(D,{children:"Î od baseline [mm]"}),e.jsx(D,{children:"Î od pÅedchozÃho [mm]"}),e.jsx(D,{children:"Kvalita"})]})}),e.jsx(Ue,{children:(j||[]).map(m=>{var $;return e.jsxs(Ne,{children:[e.jsx(_,{className:"font-medium",children:(($=m.monitoring_points)==null?void 0:$.code)||"â"}),e.jsx(_,{children:m.absolute_value_mm!=null?Number(m.absolute_value_mm).toFixed(2):"â"}),e.jsx(_,{children:m.delta_from_baseline_mm!=null?Number(m.delta_from_baseline_mm).toFixed(2):"â"}),e.jsx(_,{children:m.delta_from_previous_mm!=null?Number(m.delta_from_previous_mm).toFixed(2):"â"}),e.jsx(_,{children:e.jsx(Q,{className:o[m.quality_status]||"",variant:"outline",children:m.quality_status})})]},m.id)})})]})]})})})})]})},v.id)})})]}),e.jsx(Ge,{open:E,onOpenChange:P,children:e.jsxs(Je,{children:[e.jsx(Ye,{children:e.jsx(Qe,{children:i!=null&&i.id?"Upravit mÄÅenÃ":"Nové mÄÅenÃ"})}),i&&e.jsxs("div",{className:"space-y-3",children:[e.jsxs("div",{children:[e.jsx(q,{children:"Datum mÄÅenÃ"}),e.jsx(se,{type:"date",value:i.measured_at,onChange:v=>y({...i,measured_at:v.target.value})})]}),e.jsxs("div",{children:[e.jsx(q,{children:"Název"}),e.jsx(se,{value:i.label||"",onChange:v=>y({...i,label:v.target.value})})]}),e.jsxs("div",{children:[e.jsx(q,{children:"PoÅadÃ"}),e.jsx(se,{type:"number",value:i.order_index||"",onChange:v=>y({...i,order_index:parseInt(v.target.value)||null})})]}),e.jsxs("div",{children:[e.jsx(q,{children:"Poznámka"}),e.jsx(vs,{value:i.notes||"",onChange:v=>y({...i,notes:v.target.value})})]})]}),e.jsxs(ls,{children:[e.jsx(b,{variant:"outline",onClick:()=>P(!1),children:"ZruÅ¡it"}),e.jsx(b,{onClick:()=>w.mutate(i),disabled:w.isPending,children:"Uložit"})]})]})})]})},Hl=[{max:0,color:"#22c55e",label:"0 až -10 mm"},{max:-10,color:"#eab308",label:"-10 až -30 mm"},{max:-30,color:"#f97316",label:"-30 až -50 mm"},{max:-50,color:"#ef4444",label:"> -50 mm"}],Wl=()=>{const{toast:s}=Re(),a=ws(),[i,y]=t.useState(Hl),[E,P]=t.useState("cumulative"),{data:x}=ds({queryKey:["monitoring-settings-admin"],queryFn:async()=>{const{data:N,error:j}=await g.from("monitoring_settings").select("*");if(j)throw j;const w={};for(const M of N||[])w[M.key]=M.value;return w}});t.useEffect(()=>{x&&(x.color_thresholds&&Array.isArray(x.color_thresholds)&&y(x.color_thresholds),x.default_display_mode&&P(x.default_display_mode))},[x]);const O=ns({mutationFn:async()=>{const{error:N}=await g.from("monitoring_settings").upsert({key:"color_thresholds",value:i},{onConflict:"key"});if(N)throw N;const{error:j}=await g.from("monitoring_settings").upsert({key:"default_display_mode",value:E},{onConflict:"key"});if(j)throw j},onSuccess:()=>{a.invalidateQueries({queryKey:["monitoring-settings"]}),a.invalidateQueries({queryKey:["monitoring-settings-admin"]}),s({title:"Nastavenà uloženo"})},onError:N=>s({variant:"destructive",title:"Chyba",description:N.message})}),S=(N,j,w)=>{const M=[...i];M[N]={...M[N],[j]:j==="max"?parseFloat(w)||0:w},y(M)};return e.jsxs("div",{className:"space-y-4",children:[e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsx("h2",{className:"text-lg font-serif font-bold",children:"Nastavenà monitoringu"}),e.jsxs(b,{onClick:()=>O.mutate(),disabled:O.isPending,size:"sm",children:[e.jsx(Ds,{className:"h-4 w-4 mr-1"}),"Uložit"]})]}),e.jsxs(ee,{children:[e.jsx(ye,{children:e.jsx(be,{className:"text-sm",children:"Barevné prahy"})}),e.jsx(ae,{className:"space-y-3",children:i.map((N,j)=>e.jsxs("div",{className:"flex items-center gap-3",children:[e.jsx("input",{type:"color",value:N.color,onChange:w=>S(j,"color",w.target.value),className:"w-10 h-8 rounded border cursor-pointer"}),e.jsxs("div",{className:"flex-1",children:[e.jsx(q,{className:"text-xs",children:"Popis"}),e.jsx(se,{value:N.label,onChange:w=>S(j,"label",w.target.value),className:"h-8 text-sm"})]}),e.jsxs("div",{className:"w-24",children:[e.jsx(q,{className:"text-xs",children:"Max [mm]"}),e.jsx(se,{type:"number",value:N.max,onChange:w=>S(j,"max",w.target.value),className:"h-8 text-sm"})]})]},j))})]}),e.jsxs(ee,{children:[e.jsx(ye,{children:e.jsx(be,{className:"text-sm",children:"Výchozà režim zobrazenÃ"})}),e.jsx(ae,{children:e.jsxs(De,{value:E,onValueChange:N=>P(N),children:[e.jsx(Pe,{className:"w-[240px]",children:e.jsx(Ae,{})}),e.jsxs(Ee,{children:[e.jsx(me,{value:"cumulative",children:"Kumulativnà (celkový pokles od roku 2000)"}),e.jsx(me,{value:"interval",children:"Interval (zmÄna od pÅedchozÃho mÄÅenÃ)"})]})]})})]})]})},jn=()=>{const{data:s}=ds({queryKey:["mon-overview-points"],queryFn:async()=>{const{data:o,error:v}=await g.from("monitoring_points").select("id, status, x, y, area_id");if(v)throw v;return o}}),{data:a}=ds({queryKey:["mon-overview-campaigns"],queryFn:async()=>{const{data:o,error:v}=await g.from("measurement_campaigns").select("id, measured_at, label").order("measured_at",{ascending:!1});if(v)throw v;return o}}),{data:i}=ds({queryKey:["mon-overview-imports"],queryFn:async()=>{const{data:o,error:v}=await g.from("monitoring_measurements").select("import_batch_id");if(v)throw v;return new Set((o||[]).map(p=>
235p.import_batch_id).filter(Boolean)).size}}),{data:y}=ds({queryKey:["mon-overview-measurement-count"],queryFn:async()=>{const{count:o,error:v}=await g.from("monitoring_measurements").select("id",{count:"exact",head:!0});if(v)throw v;return o||0}}),E=(s==null?void 0:s.length)||0,P=(s==null?void 0:s.filter(o=>o.status==="active").length)||0,x=(s==null?void 0:s.filter(o=>o.status==="lost"||o.status==="historical").length)||0,O=(s==null?void 0:s.filter(o=>o.status==="planned").length)||0,S=a==null?void 0:a[0],N=[],j=(s==null?void 0:s.filter(o=>o.x===0&&o.y===0||o.x===null).length)||0,w=(s==null?void 0:s.filter(o=>!o.area_id).length)||0;j>0&&N.push(`${j} bod${j>1?"ů":""} bez souÅadnic`),w>0&&N.push(`${w} bod${w>1?"ů":""} bez pÅiÅazené oblasti`);const M=[{label:"Celkem bodů",value:E,icon:$t,color:"text-foreground"},{label:"AktivnÃ",value:P,icon:_n,color:"text-green-600"},{label:"Ztracené / historické",value:x,icon:bs,color:"text-muted-foreground"},{label:"Plánované",value:O,icon:$t,color:"text-blue-500"},{label:"MÄÅenà celkem",value:(a==null?void 0:a.length)||0,icon:Qt,color:"text-foreground"},{label:"Importovaných datasetů",value:i||0,icon:mt,color:"text-foreground"}];return e.jsxs("div",{className:"space-y-6",children:[e.jsx("h2",{className:"text-lg font-serif font-bold",children:"PÅehled monitoringu"}),e.jsx("div",{className:"grid grid-cols-2 md:grid-cols-3 lg:grid-cols-6 gap-3",children:M.map(o=>{const v=o.icon;return e.jsx(ee,{children:e.jsxs(ae,{className:"p-4 flex flex-col items-center text-center gap-1",children:[e.jsx(v,{className:`h-5 w-5 ${o.color}`}),e.jsx("span",{className:"text-2xl font-bold",children:o.value}),e.jsx("span",{className:"text-xs text-muted-foreground",children:o.label})]})},o.label)})}),e.jsxs("div",{className:"grid md:grid-cols-2 gap-4",children:[e.jsxs(ee,{children:[e.jsx(ye,{children:e.jsx(be,{className:"text-sm",children:"Poslednà mÄÅenÃ"})}),e.jsx(ae,{children:S?e.jsxs("div",{className:"space-y-1",children:[e.jsx("p",{className:"font-medium",children:S.label||"â"}),e.jsx("p",{className:"text-sm text-muted-foreground",children:new Date(S.measured_at).toLocaleDateString("cs-CZ")}),e.jsxs("p",{className:"text-xs text-muted-foreground",children:[y," namÄÅených hodnot celkem"]})]}):e.jsx("p",{className:"text-sm text-muted-foreground",children:"Žádná mÄÅenÃ"})})]}),e.jsxs(ee,{children:[e.jsx(ye,{children:e.jsxs(be,{className:"text-sm flex items-center gap-2",children:[e.jsx(is,{className:"h-4 w-4 text-amber-500"}),"UpozornÄnÃ"]})}),e.jsx(ae,{children:N.length===0?e.jsx("p",{className:"text-sm text-muted-foreground",children:"Žádná upozornÄnÃ"}):e.jsx("div",{className:"space-y-1",children:N.map((o,v)=>e.jsx(Q,{variant:"outline",className:"text-amber-600 border-amber-300",children:o},v))})})]})]})]})},Gl=s=>{const a=s.trim(),i=a.includes(",")&&!a.includes(".");return{normalized:i?a.replace(",","."):a,wasComma:i}},Jl=()=>{const{toast:s}=Re(),a=ws(),[i,y]=t.useState("upload"),[E,P]=t.useState(null),[x,O]=t.useState({pointCodeCol:0,measurementCols:[]}),[S,N]=t.useState([]),[j,w]=t.useState([]),[M,o]=t.useState(!1),{data:v}=ds({queryKey:["import-existing-points"],queryFn:async()=>{const{data:c,error:d}=await g.from("monitoring_points").select("id, code, status, area_id, x, y, installed_at, deactivated_at");if(d)throw d;return c}}),{data:u}=ds({queryKey:["import-existing-campaigns"],queryFn:async()=>{const{data:c,error:d}=await g.from("measurement_campaigns").select("id, measured_at, label");if(d)throw d;return c}}),p=t.useMemo(()=>{const c=new Map;for(const d of v||[])c.set(d.code,d);return c},[v]),m=t.useCallback(c=>{var r;const d=(r=c.target.files)==null?void 0:r[0];if(!d)return;const T=new FileReader;T.onload=f=>{const R=new Uint8Array(f.target.result),F=vr(R,{type:"array"}),ce=F.Sheets[F.SheetNames[0]],ie=fr.sheet_to_json(ce,{header:1,raw:!1,defval:""});if(ie.length<2){s({variant:"destructive",title:"Prázdný soubor"});return}P({headers:ie[0],rows:ie.slice(1),fileName:d.name}),O({pointCodeCol:0,measurementCols:[]}),y("preview")},T.readAsArrayBuffer(d)},[s]),$=()=>{const c=x.measurementCols.length+1;E&&c<E.headers.length&&O(d=>({...d,measurementCols:[...d.measurementCols,{colIndex:c,date:"",label:E.headers[c]||""}]}))},H=t.useCallback(()=>{var f,R;
235if(!E)return;const c=[],d=[],T=new Set,r=new Set;for(const F of x.measurementCols){if(!F.date){c.push({type:"error",message:`Sloupec "${F.label}" nemá nastavené datum mÄÅenÃ`});continue}r.has(F.date)&&c.push({type:"warning",message:`Duplicitnà datum kampanÄ: ${F.date}`}),r.add(F.date);const ce=E.rows.map(Z=>{var K;return(K=Z[F.colIndex])==null?void 0:K.trim()}),ie=ce.filter(Z=>Z&&Z!=="").length,W=ce.length-ie;ie>0&&W>ie*.5&&c.push({type:"warning",col:F.label,message:`Sloupec "${F.label}" je jen ÄásteÄnÄ vyplnÄný (${ie}/${ce.length})`});for(let Z=0;Z<E.rows.length;Z++){const K=E.rows[Z],l=(f=K[x.pointCodeCol])==null?void 0:f.trim();if(!l)continue;const U=((R=K[F.colIndex])==null?void 0:R.trim())||"",n=p.get(l);if(!n){c.push({type:"error",row:Z+2,message:`Neznámý bod: ${l}`}),d.push({pointCode:l,campaignDate:F.date,campaignLabel:F.label,absoluteValue:null,originalValue:U,pointId:null,valid:!1});continue}n.area_id||c.push({type:"warning",row:Z+2,message:`Bod ${l} nemá pÅiÅazenou oblast`}),n.x===0&&n.y===0&&c.push({type:"warning",row:Z+2,message:`Bod ${l} nemá souÅadnice`});const G=`${l}::${F.date}`;if(T.has(G)){c.push({type:"error",row:Z+2,message:`Duplicitnà bod ${l} v mÄÅenà ${F.date}`});continue}if(T.add(G),!U){d.push({pointCode:l,campaignDate:F.date,campaignLabel:F.label,absoluteValue:null,originalValue:"",pointId:n.id,valid:!0});continue}const{normalized:Y,wasComma:pe}=Gl(U),B=parseFloat(Y);if(isNaN(B)){c.push({type:"error",row:Z+2,message:`NeÄÃselná hodnota v bodu ${l}: "${U}"`}),d.push({pointCode:l,campaignDate:F.date,campaignLabel:F.label,absoluteValue:null,originalValue:U,pointId:n.id,valid:!1});continue}if(pe&&c.push({type:"warning",row:Z+2,message:`Desetinná Äárka normalizována na teÄku: ${U} â ${Y}`}),n.installed_at&&F.date<n.installed_at){c.push({type:"error",row:Z+2,message:`MÄÅenà ${F.date} je staršà než instalace bodu ${l} (${n.installed_at})`}),d.push({pointCode:l,campaignDate:F.date,campaignLabel:F.label,absoluteValue:B,originalValue:U,pointId:n.id,valid:!1});continue}if(n.deactivated_at&&F.date>n.deactivated_at&&(n.status==="lost"||n.status==="historical")){c.push({type:"error",row:Z+2,message:`Bod ${l} je deaktivován od ${n.deactivated_at}, mÄÅenà ${F.date} nelze importovat`}),d.push({pointCode:l,campaignDate:F.date,campaignLabel:F.label,absoluteValue:B,originalValue:U,pointId:n.id,valid:!1});continue}d.push({pointCode:l,campaignDate:F.date,campaignLabel:F.label,absoluteValue:B,originalValue:U,pointId:n.id,valid:!0})}}N(c),w(d),y("validate")},[E,x,p]),J=async()=>{o(!0);try{const c=crypto.randomUUID(),d=j.filter(r=>r.valid&&r.pointId),T=new Map;for(const r of d){const f=T.get(r.campaignDate)||[];f.push(r),T.set(r.campaignDate,f)}for(const[r,f]of T){let R;const F=u==null?void 0:u.find(W=>W.measured_at===r);if(F)R=F.id;else{const{data:W,error:Z}=await g.from("measurement_campaigns").insert({measured_at:r,label:f[0].campaignLabel||null}).select("id").single();if(Z)throw Z;R=W.id}const ce=f.map(W=>({point_id:W.pointId,campaign_id:R,absolute_value_mm:W.absoluteValue,quality_status:W.absoluteValue!==null?"ok":"missing",import_batch_id:c,source_file_name:(E==null?void 0:E.fileName)||null,imported_at:new Date().toISOString()})),{error:ie}=await g.from("monitoring_measurements").insert(ce);if(ie)throw ie}a.invalidateQueries({queryKey:["admin-monitoring-measurements"]}),a.invalidateQueries({queryKey:["monitoring-measurements"]}),s({title:"Import dokonÄen",description:`${d.length} hodnot importováno`}),y("confirm")}catch(c){s({variant:"destructive",title:"Chyba importu",description:c.message})}finally{o(!1)}},z=S.filter(c=>c.type==="error").length,h=S.filter(c=>c.type==="warning").length,I=j.filter(c=>c.valid).length,k=()=>{y("upload"),P(null),O({pointCodeCol:0,measurementCols:[]}),N([]),w([])};return e.jsxs("div",{className:"space-y-4",children:[e.jsx("h2",{className:"text-lg font-serif font-bold",children:"Import mÄÅenÃ"}),e.jsx("div",{className:"flex items-center gap-2 text-xs text-muted-foreground",children:["upload","preview","map","validate","confirm"].map((c,d)=>e.jsxs("span",{className:`flex items-center gap-1 ${i===c?"text-primary font-semibold":""}`,children:[d>0&&e.jsx(Gs,{className:"h-3 w-3"}),c==="upload"?"NahránÃ":c==="preview"?"Náhled":c==="map"?"MapovánÃ":c==="validate"?"Validace":"Hotovo"]},c))}),i==="upload"&&e.jsx(ee,{children:e.jsx(ae,{className:"p-6",children:e.jsxs("div",{className:"flex flex-col items-center gap-4 py-8",children:[e.jsx(Ps,{className:"h-12 w-12 text-muted-foreground"}),e.jsx("p",{className:"text-sm text-muted-foreground",children:"Nahrajte soubor ODS, XLSX nebo CSV s daty mÄÅenÃ"}),e.jsx(se,{type:"file",accept:".xlsx,.xls,.ods,.csv",onChange:m,className:"max-w-xs"})]})})}),i==="preview"&&E&&e.jsxs(ee,{children:[e.jsx(ye,{children:e.jsxs(be,{className:"text-sm",children:["Náhled: ",E.fileName]})}),e.jsxs(ae,{children:[e.jsxs("div",{className:"overflow-auto max-h-[400px]",children:[e.jsxs($e,{children:[e.jsx(Be,{children:e.jsx(Ne,{children:E.headers.map((c,d)=>e.jsx(D,{children:c},d))})}),e.jsx(Ue,{children:E.rows.slice(0,20).map((c,d)=>e.jsx(Ne,{children:c.map((T,r)=>e.jsx(_,{className:"text-xs",children:T},r))},d))})]}),E.rows.length>20&&e.jsxs("p",{className:"text-xs text-muted-foreground mt-2",children:["⦠a dalÅ¡Ãch ",E.rows.length-20," Åádků"]})]}),e.jsxs("div",{className:"flex justify-between mt-4",children:[e.jsxs(b,{variant:"outline",onClick:k,children:[e.jsx(ut,{className:"h-4 w-4 mr-1"}),"ZpÄt"]}),e.jsxs(b,{onClick:()=>y("map"),children:["PokraÄovat na mapovánÃ",e.jsx(Gs,{className:"h-4 w-4 ml-1"})]})]})]})]}),i==="map"&&E&&e.jsxs(ee,{children:[e.jsx(ye,{children:e.jsx(be,{className:"text-sm",children:"Mapovánà sloupců"})}),e.jsxs(ae,{className:"space-y-4",children:[e.jsxs("div",{children:[e.jsx(q,{children:"Sloupec s kódem bodu"}),e.jsxs(De,{value:String(x.pointCodeCol),onValueChange:c=>O(d=>({...d,pointCodeCol:parseInt(c)})),children:[e.jsx(Pe,{children:e.jsx(Ae,{})}),e.jsx(Ee,{children:E.headers.map((c,d)=>e.jsx(me,{value:String(d),children:c||`Sloupec ${d+1}`},d))})]})]}),e.jsxs("div",{children:[e.jsx(q,{children:"Sloupce s mÄÅenÃmi"}),x.measurementCols.map((c,d)=>e.jsxs("div",{className:"flex items-end gap-2 mt-2",children:[e.jsxs("div",{className:"flex-1",children:[e.jsx(q,{className:"text-xs",children:"Sloupec"}),e.jsxs(De,{value:String(c.colIndex),onValueChange:T=>{const r=[...x.measurementCols];r[d]={...r[d],colIndex:parseInt(T),label:E.headers[parseInt(T)]||""},O(f=>({...f,measurementCols:r}))},children:[e.jsx(Pe,{children:e.jsx(Ae,{})}),e.jsx(Ee,{children:E.headers.map((T,r)=>e.jsx(me,{value:String(r),children:T||`Sloupec ${r+1}`},r))})]})]}),e.jsxs("div",{className:"flex-1",children:[e.jsx(q,{className:"text-xs",children:"Datum mÄÅenÃ"}),e.jsx(se,{type:"date",value:c.date,onChange:T=>{const r=[...x.measurementCols];r[d]={...r[d],date:T.target.value},O(f=>({...f,measurementCols:r}))}})]}),e.jsx(b,{variant:"ghost",size:"sm",className:"text-destructive",onClick:()=>{O(T=>({...T,measurementCols:T.measurementCols.filter((r,f)=>f!==d)}))},children:"Ã"})]},d)),e.jsx(b,{variant:"outline",size:"sm",className:"mt-2",onClick:$,children:"+ PÅidat sloupec mÄÅenÃ"})]}),e.jsxs("div",{className:"flex justify-between mt-4",children:[e.jsxs(b,{variant:"outline",onClick:()=>y("preview"),children:[e.jsx(ut,{className:"h-4 w-4 mr-1"}),"ZpÄt"]}),e.jsxs(b,{onClick:H,disabled:x.measurementCols.length===0,children:["Spustit validaci (dry run)",e.jsx(Gs,{className:"h-4 w-4 ml-1"})]})]})]})]}),i==="validate"&&e.jsxs("div",{className:"space-y-4",children:[e.jsxs("div",{className:"grid grid-cols-3 gap-3",children:[e.jsx(ee,{children:e.jsxs(ae,{className:"p-4 text-center",children:[e.jsx(ps,{className:"h-5 w-5 text-green-600 mx-auto mb-1"}),e.jsx("span",{className:"text-2xl font-bold",children:I}),e.jsx("p",{className:"text-xs text-muted-foreground",children:"ValidnÃch Åádků"})]})}),e.jsx(ee,{children:e.jsxs(ae,{className:"p-4 text-center",children:[e.jsx(is,{className:"h-5 w-5 text-amber-500 mx-auto mb-1"}),e.jsx("span",{className:"text-2xl font-bold",children:h}),e.jsx("p",{className:"text-xs text-muted-foreground",children:"UpozornÄnÃ"})]})}),e.jsx(ee,{children:e.jsxs(ae,{className:"p-4 text-center",children:[e.jsx(js,{className:"h-5 w-5 text-destructive mx-auto mb-1"}),e.jsx("span",{className:"text-2xl font-bold",children:z}),e.jsx("p",{className:"text-xs text-muted-foreground",children:"Chyb"})]})})]}),S.length>0&&e.jsxs(ee,{children:[e.jsx(ye,{children:e.jsxs(be,{className:"text-sm",children:["Problémy (",S.length,")"]})}),e.jsx(ae,{children:e.jsx("div",{className:"max-h-[300px] overflow-auto space-y-1",children:S.map((c,d)=>e.jsxs("div",{className:"flex items-start gap-2 text-xs",children:[c.type==="error"?e.jsx(js,{className:"h-3.5 w-3.5 text-destructive shrink-0 mt-0.5"}):e.jsx(is,{className:"h-3.5 w-3.5 text-amber-500 shrink-0 mt-0.5"}),e.jsxs("span",{children:[c.row&&e.jsxs(Q,{variant:"outline",className:"mr-1 text-[10px]",children:["Å. ",c.row]}),c.message]})]},d))})})]}),e.jsxs("div",{className:"flex justify-between",children:[e.jsxs(b,{variant:"outline",onClick:()=>y("map"),children:[e.jsx(ut,{className:"h-4 w-4 mr-1"}),"ZpÄt na mapovánÃ"]}),e.jsx(b,{onClick:J,disabled:M||I===0,children:M?"Importujiâ¦":`Importovat ${I} hodnot`})]})]}),i==="confirm"&&e.jsx(ee,{children:e.jsxs(ae,{className:"p-6 text-center space-y-4",children:[e.jsx(ps,{className:"h-12 w-12 text-green-600 mx-auto"}),e.jsx("h3",{className:"text-lg font-semibold",children:"Import dokonÄen"}),e.jsxs("p",{className:"text-sm text-muted-foreground",children:[I," hodnot bylo úspÄÅ¡nÄ importováno."]}),e.jsx(b,{onClick:k,children:"Nový import"})]})})]})},Ms=730,Ls=1470,Rs={x1:20,y1:170,x2:700,y2:1120},Yl={active:"#22c55e",lost:"#9ca3af",historical:"#6b7280",planned:"#3b82f6"},vn={active:"AktivnÃ",lost:"Ztracený",historical:"Historický",planned:"Plánovaný"},Ql=()=>{const{toast:s}=Re(),a=ws(),i=t.useRef(null),[y,E]=t.useState(1),[P,x]=t.useState({x:0,y:0}),[O,S]=t.useState(!1),[N,j]=t.useState({x:0,y:0}),[w,M]=t.useState(null),[o,v]=t.useState({}),[u,p]=t.useState(null),[m,$]=t.useState(!1),[H,J]=t.useState(!1),[z,h]=t.useState(!1),[I,k]=t.useState({active:!0,lost:!0,historical:!1,planned:!0}),{data:c}=ds({queryKey:["floorplan-points"],queryFn:async()=>{const{data:n,error:G}=await g.from("monitoring_points").select("*").order("display_order");if(G)throw G;return n}}),{data:d}=ds({queryKey:["monitoring-areas"],queryFn:async()=>{const{data:n,error:G}=await g.from("monitoring_areas").select("*").order("sort_order");if(G)throw G;return n}}),T=new Map((d||[]).map(n=>[n.id,n.color||"#64748b"])),r=t.useCallback(()=>
235{if(!i.current)return;const n=i.current.getBoundingClientRect(),G=Rs.x2-Rs.x1,Y=Rs.y2-Rs.y1,pe=Math.min(n.width/Ms,n.height/Ls),B=Ms*pe,te=Ls*pe,xe=(n.width-B)/2,de=(n.height-te)/2,L=Math.min(n.width/(G*pe),n.height/(Y*pe)),re=Math.min(4,Math.max(.5,L)),A=xe+(Rs.x1+Rs.x2)/2*pe,ne=de+(Rs.y1+Rs.y2)/2*pe;E(re),x({x:n.width/2-A*re,y:n.height/2-ne*re})},[]);t.useEffect(()=>{!z&&i.current&&requestAnimationFrame(()=>{r(),h(!0)})},[z,r]);const f=ns({mutationFn:async n=>{for(const[G,Y]of Object.entries(n)){const{error:pe}=await g.from("monitoring_points").update({x:Y.x,y:Y.y}).eq("id",G);if(pe)throw pe}},onSuccess:()=>{a.invalidateQueries({queryKey:["floorplan-points"]}),v({}),s({title:"SouÅadnice uloženy"})},onError:n=>s({variant:"destructive",title:"Chyba",description:n.message})}),R=ns({mutationFn:async n=>{const{error:G}=await g.from("monitoring_points").insert({code:n.code,status:n.status||"active",x:n.x,y:n.y,area_id:n.area_id||null,label:n.label||null});if(G)throw G},onSuccess:()=>{a.invalidateQueries({queryKey:["floorplan-points"]}),$(!1),J(!1),s({title:"Bod vytvoÅen"})}}),F=ns({mutationFn:async n=>{const{error:G}=await g.from("monitoring_points").update({code:n.code,status:n.status,area_id:n.area_id||null,label:n.label||null,notes:n.notes||null}).eq("id",n.id);if(G)throw G},onSuccess:()=>{a.invalidateQueries({queryKey:["floorplan-points"]}),$(!1),s({title:"Uloženo"})}}),ce=n=>{const G=o[n.id],Y=G?G.x:Number(n.x)>1?Number(n.x):Number(n.x)*Ms,pe=G?G.y:Number(n.y)>1?Number(n.y):Number(n.y)*Ls;return{x:Y,y:pe}},ie=t.useCallback((n,G)=>{if(!i.current)return{x:0,y:0};const Y=i.current.getBoundingClientRect(),pe=Math.min(Y.width/Ms,Y.height/Ls),B=Ms*pe,te=Ls*pe,xe=(Y.width-B)/2,de=(Y.height-te)/2,L=(n-Y.left-P.x)/y,re=(G-Y.top-P.y)/y,A=(L-xe)/pe,ne=(re-de)/pe;return{x:Math.max(0,Math.min(Ms,A)),y:Math.max(0,Math.min(Ls,ne))}},[P,y]),W=t.useCallback(n=>{n.preventDefault(),E(G=>Math.max(.5,Math.min(4,G*(n.deltaY>0?.9:1.1))))},[]),Z=t.useCallback(n=>{if(n.button===0){if(H){const G=ie(n.clientX,n.clientY);p({code:"",status:"active",x:G.x,y:G.y}),$(!0);return}S(!0),j({x:n.clientX-P.x,y:n.clientY-P.y})}},[P,H,ie]),K=t.useCallback(n=>{if(w){const G=ie(n.clientX,n.clientY);v(Y=>({...Y,[w]:G}));return}O&&x({x:n.clientX-N.x,y:n.clientY-N.y})},[O,N,w,ie]),l=t.useCallback(()=>{S(!1),M(null)},[]),U=(c||[]).filter(n=>I[n.status]);return e.jsxs("div",{className:"space-y-4",children:[e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsx("h2",{className:"text-lg font-serif font-bold",children:"Půdorys â editor bodů"}),e.jsx("div",{className:"flex items-center gap-2",children:Object.entries(vn).map(([n,G])=>e.jsxs("label",{className:"flex items-center gap-1 text-xs",children:[e.jsx(xs,{checked:I[n],onCheckedChange:Y=>k(pe=>({...pe,[n]:!!Y}))}),G]},n))})]}),e.jsxs("div",{className:"flex gap-2 mb-2",children:[e.jsxs(b,{variant:H?"default":"outline",size:"sm",onClick:()=>J(!H),children:[e.jsx(Xe,{className:"h-4 w-4 mr-1"}),H?"KliknÄte do plánuâ¦":"PÅidat bod kliknutÃm"]}),Object.keys(o).length>0&&e.jsxs(b,{size:"sm",onClick:()=>f.mutate(o),disabled:f.isPending,children:[e.jsx(Ds,{className:"h-4 w-4 mr-1"}),"Uložit pozice (",Object.keys(o).length,")"]}),e.jsxs(b,{variant:"outline",size:"sm",onClick:r,children:[e.jsx(rt,{className:"h-4 w-4 mr-1"}),"Budova"]})]}),e.jsx(ee,{className:"overflow-hidden",children:e.jsx(ae,{className:"p-0",children:e.jsxs("div",{ref:i,className:`relative overflow-hidden bg-muted/30 ${H?"cursor-crosshair":"cursor-grab active:cursor-grabbing"}`,style:{height:"650px"},onWheel:W,onMouseDown:Z,onMouseMove:K,onMouseUp:l,onMouseLeave:l,children:[e.jsx("div",{style:{transform:`translate(${P.x}px, ${P.y}px) scale(${y})`,transformOrigin:"0 0",transition:O||w?"none":"transform 0.15s ease-out",position:"relative",width:"100%",height:"100%"},children:e.jsxs("svg",{viewBox:`0 0 ${Ms} ${Ls}`,className:"w-full h-full",preserveAspectRatio:"xMidYMid meet",children:[e.jsx("image",{href:"/floorplan-monitoring.svg",x:"0",y:"0",width:Ms,height:Ls,preserveAspectRatio:"none",pointerEvents:"none"}),U.map(n=>{const{x:G,y:Y}=ce(n),pe=n.status==="lost"||n.status==="historical",B=n.status==="planned",te=T.get(n.area_id||"")||Yl[n.status]||"#64748b",xe=!!o[n.id];return e.jsxs("g",{style:{cursor:"grab"},onMouseDown:de=>{de.stopPropagation(),!H&&M(n.id)},onDoubleClick:de=>{de.stopPropagation(),p({...n}),$(!0)},children:[xe&&e.jsx("circle",{cx:G,cy:Y,r:20,fill:"none",stroke:"hsl(var(--primary))",strokeWidth:2,strokeDasharray:"4 2"}),e.jsx("circle",{cx:G,cy:Y,r:16,fill:te,fillOpacity:pe?.4:B?.5:.85,stroke:pe?"#9ca3af":te,strokeWidth:pe?1.5:2,strokeDasharray:pe?"5 3":B?"3 3":"none"}),e.jsx("text",{x:G,y:Y,textAnchor:"middle",dominantBaseline:"central",fill:"white",fontSize:11,fontWeight:"bold",style:{pointerEvents:"none"},children:n.code})]},n.id)})]})}),e.jsxs("div",{className:"absolute bottom-3 right-3 flex flex-col gap-1",children:[e.jsx("button",{onClick:()=>E(n=>Math.min(4,n*1.2)),className:"w-8 h-8 bg-background border rounded-md flex items-center justify-center text-sm font-bold hover:bg-muted",children:"+"}),e.jsx("button",{onClick:()=>E(n=>Math.max(.5,n/1.2)),className:"w-8 h-8 bg-background border rounded-md flex items-center justify-center text-sm font-bold hover:bg-muted",children:"â"})]})]})})}),e.jsx(Ge,{open:m,onOpenChange:$,children:e.jsxs(Je,{children:[e.jsx(Ye,{children:e.jsx(Qe,{children:u!=null&&u.id?`Bod ${u.code}`:"Nový bod"})}),u&&e.jsxs("div",{className:"space-y-3",children:[e.jsxs("div",{children:[e.jsx(q,{children:"Kód"}),e.jsx(se,{value:u.code,onChange:n=>p({...u,code:n.target.value})})]}),e.jsxs("div",{children:[e.jsx(q,{children:"Popis"}),e.jsx(se,{value:u.label||"",onChange:n=>p({...u,label:n.target.value})})]}),e.jsxs("div",{children:[e.jsx(q,{children:"Oblast"}),e.jsxs(De,{value:u.area_id||"",onValueChange:n=>
235p({...u,area_id:n}),children:[e.jsx(Pe,{children:e.jsx(Ae,{placeholder:"Vyberte oblast"})}),e.jsx(Ee,{children:(d||[]).map(n=>e.jsx(me,{value:n.id,children:n.name},n.id))})]})]}),e.jsxs("div",{children:[e.jsx(q,{children:"Status"}),e.jsxs(De,{value:u.status,onValueChange:n=>p({...u,status:n}),children:[e.jsx(Pe,{children:e.jsx(Ae,{})}),e.jsx(Ee,{children:Object.entries(vn).map(([n,G])=>e.jsx(me,{value:n,children:G},n))})]})]}),u.x!=null&&e.jsxs("p",{className:"text-xs text-muted-foreground",children:["Pozice: ",Number(u.x).toFixed(1),", ",Number(u.y).toFixed(1)]})]}),e.jsxs(ls,{children:[e.jsx(b,{variant:"outline",onClick:()=>$(!1),children:"ZruÅ¡it"}),e.jsx(b,{onClick:()=>u!=null&&u.id?F.mutate(u):R.mutate(u),children:u!=null&&u.id?"Uložit":"VytvoÅit"})]})]})})]})},fn=[{id:"24h",label:"PoslednÃch 24 h",hours:24},{id:"7d",label:"PoslednÃch 7 dnÃ",hours:24*7},{id:"30d",label:"PoslednÃch 30 dnÃ",hours:24*30},{id:"all",label:"VÅ¡e",hours:null}],Xl=()=>{const[s,a]=t.useState([]),[i,y]=t.useState(!0),[E,P]=t.useState(""),[x,O]=t.useState("7d"),S=async()=>{y(!0);const w=fn.find(I=>I.id===x);let M=g.from("forum_email_clicks").select("id, thread_id, user_id, recipient_email, notification_run_id, template_type, user_agent, clicked_at").order("clicked_at",{ascending:!1}).limit(500);if(w.hours){const I=new Date(Date.now()-w.hours*3600*1e3).toISOString();M=M.gte("clicked_at",I)}const{data:o,error:v}=await M;if(v){console.error(v),a([]),y(!1);return}const u=o||[],p=Array.from(new Set(u.map(I=>I.thread_id).filter(Boolean))),m=Array.from(new Set(u.map(I=>I.user_id).filter(Boolean))),[$,H]=await Promise.all([p.length?g.from("forum_threads").select("id, title").in("id",p):Promise.resolve({data:[],error:null}),m.length?g.rpc("admin_get_profiles_by_ids",{_user_ids:m}):Promise.resolve({data:[],error:null})]),J=new Map;($.data||[]).forEach(I=>J.set(I.id,I.title));const z=new Map;(H.data||[]).forEach(I=>{const k=[I.first_name,I.last_name].filter(Boolean).join(" ")||I.full_name||I.email||I.user_id;z.set(I.user_id,k)});const h=u.map(I=>({...I,thread_title:I.thread_id&&J.get(I.thread_id)||null,user_name:I.user_id&&z.get(I.user_id
235)||null}));a(h),y(!1)};t.useEffect(()=>{S()},[x]);const N=t.useMemo(()=>{const w=E.trim().toLowerCase();return w?s.filter(M=>[M.recipient_email,M.thread_title,M.user_name,M.template_type].filter(Boolean).some(o=>String(o).toLowerCase().includes(w))):s},[s,E]),j=t.useMemo(()=>{const w=N.length,M=new Set(N.map(v=>v.user_id||v.recipient_email).filter(Boolean)).size,o=new Set(N.map(v=>v.thread_id).filter(Boolean)).size;return{totalClicks:w,uniqueUsers:M,uniqueThreads:o}},[N]);return e.jsxs("div",{className:"space-y-6",children:[e.jsxs("div",{children:[e.jsxs("h2",{className:"font-serif text-2xl font-bold flex items-center gap-2",children:[e.jsx(Pa,{className:"h-6 w-6 text-primary"}),"Kliknutà na odkazy v e-mailech"]}),e.jsx("p",{className:"text-sm text-muted-foreground mt-1",children:"Záznamy o tom, kdo otevÅel pÅÃspÄvek fóra kliknutÃm v e-mailové notifikaci. Kliknutà se poÄÃtá pÅi pÅesmÄrovánà pÅes server (spolehlivé), na rozdÃl od pouhého otevÅenà e-mailu."})]}),e.jsxs("div",{className:"grid grid-cols-1 sm:grid-cols-3 gap-4",children:[e.jsxs(ee,{children:[e.jsx(ye,{className:"pb-2",children:e.jsxs(be,{className:"text-sm font-medium text-muted-foreground flex items-center gap-2",children:[e.jsx(Pa,{className:"h-4 w-4"}),"Celkem kliknutÃ"]})}),e.jsx(ae,{children:e.jsx("div",{className:"text-2xl font-bold",children:j.totalClicks})})]}),e.jsxs(ee,{children:[e.jsx(ye,{className:"pb-2",children:e.jsxs(be,{className:"text-sm font-medium text-muted-foreground flex items-center gap-2",children:[e.jsx(Fs,{className:"h-4 w-4"}),"Unikátnà uživatelé"]})}),e.jsx(ae,{children:e.jsx("div",{className:"text-2xl font-bold",children:j.uniqueUsers})})]}),e.jsxs(ee,{children:[e.jsx(ye,{className:"pb-2",children:e.jsxs(be,{className:"text-sm font-medium text-muted-foreground flex items-center gap-2",children:[e.jsx(bs,{className:"h-4 w-4"}),"OtevÅená vlákna"]})}),e.jsx(ae,{children:e.jsx("div",{className:"text-2xl font-bold",children:j.uniqueThreads})})]})]}),e.jsxs("div",{className:"flex flex-wrap items-center gap-2",children:[fn.map(w=>e.jsx(b,{variant:x===w.id?"default":"outline",size:"sm",onClick:()=>O(w.id),children:w.label},w.id)),e.jsxs("div",{className:"relative ml-auto w-full sm:w-72",children:[e.jsx(fs,{className:"absolute left-2.5 top-1/2 -translate-y-1/2 h-4 w-4 text-muted-foreground"}),e.jsx(se,{placeholder:"Hledat (e-mail, vlákno, uživatel)â¦",value:E,onChange:w=>P(w.target.value),className:"pl-8"})]}),e.jsx(b,{variant:"outline",size:"sm",onClick:S,disabled:i,children:e.jsx(Es,{className:`h-4 w-4 ${i?"animate-spin":""}`})})]}),e.jsx(ee,{children:e.jsx(ae,{className:"p-0",children:i?e.jsx("div",{className:"flex items-center justify-center py-16",children:e.jsx(fe,{className:"h-6 w-6 animate-spin text-primary"})}):N.length===0?e.jsx("div",{className:"text-center text-muted-foreground py-16",children:"Žádná zaznamenaná kliknutà v tomto obdobÃ."}):e.jsxs($e,{children:[e.jsx(Be,{children:e.jsxs(Ne,{children:[e.jsx(D,{children:"Äas"}),e.jsx(D,{children:"Uživatel"}),e.jsx(D,{children:"E-mail pÅÃjemce"}),e.jsx(D,{children:"Vlákno"}),e.jsx(D,{children:"Typ"})]})}),e.jsx(Ue,{children:N.map(w=>e.jsxs(Ne,{children:[e.jsx(_,{className:"whitespace-nowrap text-sm text-muted-foreground",children:hs(new Date(w.clicked_at),"d. MMM yyyy HH:mm",{locale:ys})}),e.jsx(_,{className:"font-medium",children:w.user_name||e.jsx("span",{className:"text-muted-foreground italic",children:"neznámý"})}),e.jsx(_,{className:"text-sm",children:w.recipient_email||"â"}),e.jsx(_,{className:"max-w-[320px] truncate",children:w.thread_title||e.jsx("span",{className:"text-muted-foreground",children:"smazané vlákno"})}),e.jsx(_,{children:e.jsx(Q,{variant:"secondary",children:w.template_type||"forum"})})]},w.id))})]})})})]})},eo=()=>crypto.randomUUID().replace(/-/g,"").slice(0,14)+"A1!",so=()=>{const[s,a]=t.useState([]),[i,y]=t.useState([]),[E,P]=t.useState(!0),[x,O]=t.useState(null),[S,N]=t.useState(null),j=async()=>{var c;P(!0);const{data:o}=await g.from("owner_contacts").select("id, first_name, last_name, company_name, email, user_id").not("user_id","is",null),{data:v}=await g.from("owner_contact_persons").select("id, first_name, last_name, email, user_id, owner_
235contact_id, can_login"),u=Array.from(new Set([...(o||[]).map(d=>d.user_id),...(v||[]).filter(d=>d.user_id).map(d=>d.user_id)])),{data:p}=u.length?await g.rpc("admin_get_profiles_by_ids",{_user_ids:u}):{data:[]},m=new Map((p||[]).map(d=>[d.user_id,d.email??null])),$=Array.from(new Set([...(o||[]).map(d=>d.id),...(v||[]).map(d=>d.owner_contact_id)])),{data:H}=$.length?await g.from("apartment_owners").select("owner_contact_id, apartments!inner(code)").eq("is_current",!0).in("owner_contact_id",$):{data:[]},J=new Map;(H||[]).forEach(d=>{var r;const T=J.get(d.owner_contact_id)||[];(r=d.apartments)!=null&&r.code&&T.push(d.apartments.code),J.set(d.owner_contact_id,T)});const z=[];for(const d of o||[]){const T=m.get(d.user_id);T&&(d.email||"").toLowerCase()!==T.toLowerCase()&&z.push({kind:"email_mismatch",source_table:"owner_contacts",record_id:d.id,display_name:[d.first_name,d.last_name].filter(Boolean).join(" ")||d.company_name||"â",evidence_email:d.email,profile_email:T,user_id:d.user_id,apartment_codes:J.get(d.id)||[],detail:"VlastnÃk: e-mail v evidenci â e-mail úÄtu"})}for(const d of v||[]){if(!d.user_id)continue;const T=m.get(d.user_id);T&&(d.email||"").toLowerCase()!==T.toLowerCase()&&z.push({kind:"email_mismatch",source_table:"owner_contact_persons",record_id:d.id,display_name:[d.first_name,d.last_name].filter(Boolean).join(" ")||"â",evidence_email:d.email,profile_email:T,user_id:d.user_id,apartment_codes:J.get(d.owner_contact_id)||[],detail:"Zástupce: e-mail v evidenci â e-mail úÄtu"})}const h=new Map;(o||[]).forEach(d=>h.set(d.user_id,d));for(const d of v||[])if(d.user_id&&h.has(d.user_id)){const T=h.get(d.user_id);z.push({kind:"shared_user_id",source_table:"cross-table",record_id:d.id,display_name:`${[T.first_name,T.last_name].filter(Boolean).join(" ")||T.company_name} â ${[d.first_name,d.last_name].filter(Boolean).join(" ")}`,evidence_email:T.email,profile_email:m.get(d.user_id)??null,user_id:d.user_id,apartment_codes:J.get(d.owner_contact_id)||[],detail:"Stejný úÄet je propojen jako vlastnÃk i jako zástupce"})}a(z);const I=new Map;(c=(await g.from("owner_contacts").select("id, first_name, last_name, company_name")).data)==null||c.forEach(d=>I.set(d.id,d));const k=(v||[]).filter(d=>d.can_login&&!d.user_id&&d.email&&d.email.includes("@")).map(d=>{const T=I.get(d.owner_contact_id);return{ocp_id:d.id,owner_contact_id:d.owner_contact_id,first_name:d.first_name,last_name:d.last_name,email:d.email,represents:T&&([T.first_name,T.last_name].filter(Boolean).join(" ")||T.company_name)||"â",apartment_codes:J.get(d.owner_contact_id)||[]}}).sort((d,T)=>(d.last_name||"").localeCompare(T.last_name||""));y(k),P(!1)};t.useEffect(()=>{j()},[]);const w=async o=>{O(o.ocp_id);try{const v=eo(),u=[o.first_name,o.last_name].filter(Boolean).join(" ")||"Zástupce",{data:p,error:m}=await g.functions.invoke("admin-create-user",{body:{email:o.email,password:v,first_name:o.first_name,last_name:o.last_name,role:"owner",contact_person_id:o.ocp_id}});if(m)throw m;if(p!=null&&p.error)throw new Error(p.error);ts.success(`ÃÄet pro ${u} vytvoÅen a propojen.`),N({name:u,email:o.email,password:v}),await j()}catch(v){console.error(v),ts.error(`VytvoÅenà úÄtu selhalo: ${v.message||"neznámá chyba"}`)}finally{O(null)}},M=()=>{if(!S)return;const o=`E-mail: ${S.email} 236Heslo: ${S.password}`;navigator.clipboard.writeText(o),ts.success("PÅihlaÅ¡ovacà údaje zkopÃrovány.")};return e.jsxs(e.Fragment,{children:[e.jsxs(ee,{className:"border-amber-200",children:[e.jsxs(ye,{children:[e.jsxs(be,{className:"flex items-center gap-2",children:[e.jsx(is,{className:"h-5 w-5 text-amber-600"}),"Rozpory identity"]}),e.jsxs(Le,{children:["Pravidlo: ",e.jsx("strong",{children:"1 pÅihlaÅ¡ovacà úÄet = 1 identita"})," (vlastnÃk / spoluvlastnÃk / zástupce vlastnÃka / zástupce firmy). Databáze duplikace novÄ blokuje, panel sloužà jako kontrolnà pojistka."]})]}),e.jsx(ae,{className:"space-y-6",children:E?e.jsxs("div",{className:"flex items-center gap-2 text-muted-foreground py-6",children:[e.jsx(fe,{className:"h-4 w-4 animate-spin"})," NaÄÃtámâ¦"]}):e.jsxs(e.Fragment,{children:[e.jsxs("div",{children:[e.jsx("h3",{className:"font-semibold text-sm mb-2 text-amber-900",children:"Aktivnà rozpory"}),s.length===0?e.jsxs("div",{className:"flex items-center gap-2 text-emerald-700 py-3 px-3 bg-emerald-50 rounded border border-emerald-200",children:[e.jsx(ps,{className:"h-5 w-5"}),e.jsx("span",{className:"font-medium",children:"Žádné rozpory."}),e.jsx("span",{className:"text-muted-foreground text-sm",children:"VÅ¡echny vazby vlastnÃkâúÄet jsou v poÅádku."})]}):e.jsx("div",{className:"overflow-x-auto",children:e.jsxs($e,{children:[e.jsx(Be,{children:e.jsxs(Ne,{children:[e.jsx(D,{children:"Typ"}),e.jsx(D,{children:"Osoba"}),e.jsx(D,{children:"E-mail v evidenci"}),e.jsx(D,{children:"E-mail úÄtu"}),e.jsx(D,{children:"Apartmány"}),e.jsx(D,{children:"Akce"})]})}),e.jsx(Ue,{children:s.map((o,v)=>{var u;return e.jsxs(Ne,{children:[e.jsxs(_,{children:[e.jsx(Q,{variant:"outline",className:o.kind==="shared_user_id"?"bg-rose-50 text-rose-800 border-rose-200":"bg-amber-50 text-amber-800 border-amber-200",children:o.kind==="shared_user_id"?"SdÃlený úÄet":"Nesoulad e-mailu"}),e.jsx("div",{className:"text-xs text-muted-foreground mt-1",children:o.detail})]}),e.jsx(_,{className:"font-medium",children:o.display_name}),e.jsx(_,{className:"text-sm",children:o.evidence_email||"â"}),e.jsx(_,{className:"text-sm",children:o.profile_email||"â"}),e.jsx(_,{className:"text-sm",children:(u=o.apartment_codes)!=null&&u.length?o.apartment_codes.join(", "):"â"}),e.jsx(_,{children:e.jsx(b,{asChild:!0,size:"sm",variant:"outline",children:e.jsxs(bn,{to:`/admin/owner/${o.user_id}`,children:[e.jsx(Ys,{className:"h-3 w-3 mr-1"})," Profil"]})})})]},`${o.source_table}-${o.record_id}-${v}`)})})]})})]}),e.jsxs("div",{children:[e.jsx("h3",{className:"font-semibold text-sm mb-2 text-amber-900",children:"Identity bez vlastnÃho úÄtu"}),e.jsxs("p",{className:"text-xs text-muted-foreground mb-3",children:["Zástupci, kteÅà majà povolen pÅÃstup do portálu (",e.jsx("code",{children:"can_login=true"}),') a platný e-mail, ale dosud nemajà vytvoÅený pÅihlaÅ¡ovacà úÄet. TlaÄÃtkem âVytvoÅit správné propojenÃ" se úÄet vytvoÅà a okamžitÄ propojà se správnou identitou.']}),i.length===0?e.jsxs("div",{className:"flex items-center gap-2 text-emerald-700 py-3 px-3 bg-emerald-50 rounded border border-emerald-200",children:[e.jsx(ps,{className:"h-5 w-5"}),e.jsx("span",{className:"font-medium",children:"VÅ¡ichni zástupci majà vlastnà úÄet."})]}):e.jsx("div",{className:"overflow-x-auto",children:e.jsxs($e,{children:[e.jsx(Be,{children:e.jsxs(Ne,{children:[e.jsx(D,{children:"Zástupce"}),e.jsx(D,{children:"Zastupuje"}),e.jsx(D,{children:"E-mail (správný)"}),e.jsx(D,{children:"Apartmány"}),e.jsx(D,{className:"text-right",children:"Akce"})]})}),e.jsx(Ue,{children:i.map(o=>
236{const v=[o.first_name,o.last_name].filter(Boolean).join(" ");return e.jsxs(Ne,{children:[e.jsx(_,{className:"font-medium",children:v}),e.jsx(_,{className:"text-sm",children:o.represents}),e.jsx(_,{className:"text-sm",children:o.email}),e.jsx(_,{className:"text-sm",children:o.apartment_codes.length?o.apartment_codes.join(", "):"â"}),e.jsx(_,{className:"text-right",children:e.jsxs(b,{size:"sm",onClick:()=>w(o),disabled:x===o.ocp_id,children:[x===o.ocp_id?e.jsx(fe,{className:"h-3 w-3 mr-1 animate-spin"}):e.jsx(Qr,{className:"h-3 w-3 mr-1"}),"VytvoÅit správné propojenÃ"]})})]},o.ocp_id)})})]})})]})]})})]}),e.jsx(It,{open:!!S,onOpenChange:o=>!o&&N(null),children:e.jsxs(Tt,{children:[e.jsxs(Ot,{children:[e.jsxs(Ft,{className:"flex items-center gap-2",children:[e.jsx(ps,{className:"h-5 w-5 text-emerald-600"})," ÃÄet vytvoÅen a propojen"]}),e.jsx(Mt,{asChild:!0,children:e.jsxs("div",{className:"space-y-3",children:[e.jsxs("p",{children:["Pro ",e.jsx("strong",{children:S==null?void 0:S.name})," byl vytvoÅen úÄet a propojen se správnou identitou. PÅedejte uživateli nÞe uvedené pÅihlaÅ¡ovacà údaje (heslo se zobrazuje jen jednou)."]}),e.jsxs("div",{className:"bg-muted p-3 rounded font-mono text-sm space-y-1",children:[e.jsxs("div",{children:["E-mail: ",S==null?void 0:S.email]}),e.jsxs("div",{children:["Heslo: ",S==null?void 0:S.password]})]})]})})]}),e.jsxs(Lt,{children:[e.jsxs(b,{variant:"outline",onClick:M,children:[e.jsx(Os,{className:"h-3 w-3 mr-1"})," ZkopÃrovat"]}),e.jsx(Rt,{children:"ZavÅÃt"}),e.jsx(Vt,{onClick:()=>N(null),children:"Hotovo"})]})]})})]})},to={linked:{label:"Propojeno",cls:"bg-emerald-100 text-emerald-800 border-emerald-200",Icon:Vs},unlinked:{label:"Odpojeno",cls:"bg-rose-100 text-rose-800 border-rose-200",Icon:ga},changed:{label:"ZmÄnÄno",cls:"bg-amber-100 text-amber-800 border-amber-200",Icon:Es}},ao=()=>{const[s,a]=t.useState([]),[i,y]=t.useState(!0),[E,P]=t.useState("");t.useEffect(()=>{(async()=>{const{data:O}=await g.from("owner_user_link_audit").select("*").order("created_at",{ascending:!1}).limit(500);a(O||[]),y(!1)})()},[]);const x=s.filter(O=>{if(!E.trim())return!0;const S=E.toLowerCase();return(O.owner_name||"").toLowerCase().includes(S)||(O.owner_email||"").toLowerCase().includes(S)||(O.old_user_email||"").toLowerCase().includes(S)||(O.new_user_email||"").toLowerCase().includes(S)||(O.performed_by_email||"").toLowerCase().includes(S)||(O.apartment_codes||[]).join(" ").toLowerCase().includes(S)});return e.jsxs("div",{className:"space-y-4",children:[e.jsxs("div",{children:[e.jsxs("h2",{className:"font-serif text-2xl font-bold flex items-center gap-2",children:[e.jsx(As,{className:"h-5 w-5 text-primary"}),"Audit propojenà vlastnÃk â úÄet"]}),e.jsx("p",{className:"text-sm text-muted-foreground mt-1",children:"Každá zmÄna vazby mezi vlastnickou kartou (owner_contact) a uživatelským úÄtem je zaznamenána. Auditnà záznamy nejsou upravitelné z administrace aplikace."})]}),e.jsx(so,{}),e.jsxs(ee,{children:[e.jsx(ye,{children:e.jsxs(be,{className:"text-base flex items-center justify-between",children:[e.jsxs("span",{children:["Záznamy (",x.length,")"]}),e.jsxs("div",{className:"relative w-72",children:[e.jsx(fs,{className:"absolute left-3 top-1/2 -translate-y-1/2 h-4 w-4 text-muted-foreground"}),e.jsx(se,{placeholder:"Hledat e-mail, jméno, TOP, admin...",value:E,onChange:O=>P(O.target.value),className:"pl-9 h-9"})]})]})}),e.jsx(ae,{children:i?e.jsx("div",{className:"flex justify-center py-12",children:e.jsx(fe,{className:"h-6 w-6 animate-spin text-primary"})}):e.jsxs($e,{children:[e.jsx(Be,{children:e.jsxs(Ne,{children:[e.jsx(D,{className:"w-[140px]",children:"Kdy"}),e.jsx(D,{className:"w-[110px]",children:"Akce"}),e.jsx(D,{className:"w-[120px]",children:"TOP"}),e.jsx(D,{children:"VlastnÃk"}),e.jsx(D,{children:"PÅed â po"}),e.jsx(D,{className:"w-[200px]",children:"Provedl"})]})}),e.jsx(Ue,{children:x.length===0?e.jsx(Ne,{children:e.jsx(_,{colSpan:6,className:"text-center py-10 text-muted-foreground",children:"Žádné záznamy"})}):x.map(O=>{const S=to[O.action];return e.jsxs(Ne,{children:[e.jsx(_,{className:"text-xs text-muted-foreground",children:hs(new Date(O.created_at),"dd.MM.yyyy HH:mm",{locale:ys})}),e.jsx(_,{children:e.jsxs(Q,{className:`${S.cls} gap-1 text-xs`,children:[e.jsx(S.Icon,{className:"h-3 w-3"}),S.label]})}),e.jsx(_,{className:"text-xs font-medium",children:(O.apartment_codes||[]).join(", ")||"â"}),e.jsxs(_,{className:"text-sm",children:[e.jsx("div",{children:O.owner_name||"â"}),O.owner_email&&e.jsx("div",{className:"text-xs text-muted-foreground",children:O.owner_email})]}),e.jsxs(_,{className:"text-xs",children:[e.jsx("div",{className:"text-rose-700 line-through",children:O.old_user_email||(O.old_user_id?O.old_user_id.slice(0,8):"â")}),e.jsx("div",{className:"text-emerald-700",children:O.new_user_email||(O.new_user_id?O.new_user_id.slice(0,8):"â")})]}),e.jsxs(_,{className:"text-xs text-muted-foreground",children:[O.performed_by_email||(O.performed_by?O.performed_by.slice(0,8):"systém"),O.source&&O.source!=="app"&&e.jsx(Q,{variant:"outline",className:"ml-1 text-[10px]",children:O.source})]})]},O.id)})})]})})]})]})},no={account_invited:{label:"Pozváno",cls:"bg-emerald-100 text-emerald-800 border-emerald-200"},account_reinvited:{label:"Znovu pozváno",cls:"bg-amber-100 text-amber-800 border-amber-200"},account_invite_skipped:{label:"PÅeskoÄeno",cls:"bg-slate-100 text-slate-700 border-slate-200"},account_invite_failed:{label:"Selhalo",cls:"bg-rose-100 text-rose-800 border-rose-200"},account_already_active:{label:"ÃÄet aktivnÃ",cls:"bg-sky-100 text-sky-800 border-sky-200"}},ro=s=>{if(s==null)return"";const a=String(s);return/[",\n;]/.test(a)?`"${a.replace(/"/g,'""')}"`:a},io=()=>{const{toast:s}=Re(),[a,i]=t.useState([]),[y,E]=t.useState({}),[P,x]=t.useState(!0),[O,S]=t.useState(""),[N,j]=t.useState("all"),[w,M]=t.useState(""),[o,v]=t.useState(""),[u,p]=t.useState(1),m=25,$=async()=>{x(!0);const{data:I,error:k}=await g.from("admin_audit_log").select("*").in("action",["account_invited","account_reinvited","account_invite_skipped","account_invite_failed","account_already_active"]).order("created_at",{ascending:!1}).limit(1e3);if(k){s({variant:"destructive",title:"Chyba",description:k.message}),x(!1);return}const c=I||[];i(c);const d=Array.from(new Set(c.map(T=>
236T.performed_by).filter(Boolean)));if(d.length>0){const{data:T}=await g.rpc("admin_get_profiles_by_ids",{_user_ids:d}),r={};(T||[]).forEach(f=>{r[f.user_id]={id:f.user_id,email:f.email,name:[f.first_name,f.last_name].filter(Boolean).join(" ")||null}}),E(r)}x(!1)};t.useEffect(()=>{$()},[]);const H=t.useMemo(()=>a.filter(I=>{if(N!=="all"&&I.action!==N||w&&new Date(I.created_at)<new Date(w))return!1;if(o){const k=new Date(o);if(k.setHours(23,59,59,999),new Date(I.created_at)>k)return!1}if(O.trim()){const k=O.toLowerCase(),c=y[I.performed_by];if(![I.target_email,I.reason,c==null?void 0:c.email,c==null?void 0:c.name,JSON.stringify(I.details)].filter(Boolean).join(" ").toLowerCase().includes(k))return!1}return!0}),[a,O,N,w,o,y]),J=H.slice((u-1)*m,u*m),z=t.useMemo(()=>{const I={invited:0,reinvited:0,failed:0,skipped:0};return a.forEach(k=>{k.action==="account_invited"?I.invited++:k.action==="account_reinvited"?I.reinvited++:k.action==="account_invite_failed"?I.failed++:k.action==="account_invite_skipped"&&I.skipped++}),I},[a]),h=()=>{const k=[["created_at","action","target_email","performed_by_email","performed_by_name","reason","details"].join(",")];H.forEach(f=>{const R=y[f.performed_by];k.push([f.created_at,f.action,f.target_email,R==null?void 0:R.email,R==null?void 0:R.name,f.reason,f.details?JSON.stringify(f.details):""].map(ro).join(","))});const c=new Blob(["\uFEFF"+k.join(` 237`)],{type:"text/csv;charset=utf-8"}),d=URL.createObjectURL(c),T=document.createElement("a"),r=new Date().toISOString().slice(0,19).replace(/[:T]/g,"-");T.href=d,T.download=`pozvanky-audit-${r}.csv`,document.body.appendChild(T),T.click(),T.remove(),URL.revokeObjectURL(d),s({title:"Export hotov",description:`${H.length} záznamů exportováno do CSV.`})};return e.jsx("div",{className:"space-y-4",children:e.jsxs(ee,{children:[e.jsx(ye,{children:e.jsxs("div",{className:"flex items-center justify-between gap-4 flex-wrap",children:[e.jsxs("div",{children:[e.jsx(be,{className:"font-serif",children:"Audit pozvánek"}),e.jsx(Le,{children:"Kdo, kdy a komu posÃlal pozvánky pro nastavenà hesla. Záznamy pocházejà z administrátorského audit logu."})]}),e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsxs(b,{variant:"outline",size:"sm",onClick:$,disabled:P,children:[e.jsx(Es,{className:`h-4 w-4 mr-2 ${P?"animate-spin":""}`}),"Obnovit"]}),e.jsxs(b,{size:"sm",onClick:h,disabled:H.length===0,children:[e.jsx(vt,{className:"h-4 w-4 mr-2"}),"Export CSV (",H.length,")"]})]})]})}),e.jsxs(ae,{children:[e.jsxs("div",{className:"grid grid-cols-2 md:grid-cols-4 gap-3 mb-4",children:[e.jsxs("div",{className:"rounded-md border p-3",children:[e.jsxs("div",{className:"text-xs text-muted-foreground flex items-center gap-1",children:[e.jsx(Bs,{className:"h-3 w-3"})," Pozváno"]}),e.jsx("div",{className:"text-2xl font-semibold text-emerald-700",children:z.invited})]}),e.jsxs("div",{className:"rounded-md border p-3",children:[e.jsxs("div",{className:"text-xs text-muted-foreground flex items-center gap-1",children:[e.jsx(Es,{className:"h-3 w-3"})," Znovu pozváno"]}),e.jsx("div",{className:"text-2xl font-semibold text-amber-700",children:z.reinvited})]}),e.jsxs("div",{className:"rounded-md border p-3",children:[e.jsxs("div",{className:"text-xs text-muted-foreground flex items-center gap-1",children:[e.jsx(at,{className:"h-3 w-3"})," PÅeskoÄeno"]}),e.jsx("div",{className:"text-2xl font-semibold text-slate-700",children:z.skipped})]}),e.jsxs("div",{className:"rounded-md border p-3",children:[e.jsxs("div",{className:"text-xs text-muted-foreground flex items-center gap-1",children:[e.jsx(is,{className:"h-3 w-3"})," Selhalo"]}),e.jsx("div",{className:"text-2xl font-semibold text-rose-700",children:z.failed})]})]}),e.jsxs("div",{className:"flex flex-wrap items-end gap-3 mb-4",children:[e.jsxs("div",{className:"relative flex-1 min-w-[200px]",children:[e.jsx(fs,{className:"absolute left-2 top-2.5 h-4 w-4 text-muted-foreground"}),e.jsx(se,{placeholder:"Hledat e-mail, jméno, důvodâ¦",value:O,onChange:I=>{S(I.target.value),p(1)},className:"pl-8"})]}),e.jsxs(De,{value:N,onValueChange:I=>{j(I),p(1)},children:[e.jsx(Pe,{className:"w-[180px]",children:e.jsx(Ae,{placeholder:"Status"})}),e.jsxs(Ee,{children:[e.jsx(me,{value:"all",children:"VÅ¡echny statusy"}),e.jsx(me,{value:"account_invited",children:"Pozváno"}),e.jsx(me,{value:"account_reinvited",children:"Znovu pozváno"}),e.jsx(me,{value:"account_invite_skipped",children:"PÅeskoÄeno"}),e.jsx(me,{value:"account_invite_failed",children:"Selhalo"}),e.jsx(me,{value:"account_already_active",children:"ÃÄet aktivnÃ"})]})]}),e.jsxs("div",{className:"flex flex-col",children:[e.jsx("label",{className:"text-xs text-muted-foreground mb-1",children:"Od"}),e.jsx(se,{type:"date",value:w,onChange:I=>{M(I.target.value),p(1)},className:"w-[150px]"})]}),e.jsxs("div",{className:"flex flex-col",children:[e.jsx("label",{className:"text-xs text-muted-foreground mb-1",children:"Do"}),e.jsx(se,{type:"date",value:o,onChange:I=>{v(I.target.value),p(1)},className:"w-[150px]"})]})]}),P?e.jsx("div",{className:"flex justify-center py-8",children:e.jsx(fe,{className:"h-6 w-6 animate-spin text-primary"})}):H.length===0?e.jsx("div",{className:"text-center py-8 text-muted-foreground text-sm",children:"Žádné záznamy odpovÃdajÃcà filtrům."}):e.jsxs(e.Fragment,{children:[e.jsx("div",{className:"rounded-md border overflow-hidden",children:e.jsxs($e,{children:[e.jsx(Be,{children:e.jsxs(Ne,{children:[e.jsx(D,{children:"Kdy"}),e.jsx(D,{children:"Akce"}),e.jsx(D,{children:"Komu (e-mail)"}),e.jsx(D,{children:"Kdo pozval"}),e.jsx(D,{children:"Důvod / detail"})]})}),e.jsx(Ue,{children:J.map(I=>{const k=no[I.action]||{label:I.action,cls:"bg-muted"},c=y[I.performed_by];return e.jsxs(Ne,{children:[e.jsx(_,{className:"text-xs whitespace-nowrap",children:new Date(I.created_at).toLocaleDateString("cs-CZ",{day:"2-digit",month:"2-digit",year:"numeric",hour:"2-digit",minute:"2-digit"})}),e.jsx(_,{children:e.jsx(Q,{variant:"outline",className:k.cls,children:k.label})}),e.jsx(_,{className:"font-mono text-xs",children:I.target_email||"â"}),e.jsx(_,{className:"text-xs",children:c?e.jsxs("div",{children:[e.jsx("div",{className:"font-medium",children:c.name||c.email}),c.name&&e.jsx("div",{className:"text-muted-foreground",children:c.email})]}):e.jsxs("span",{className:"text-muted-foreground",children:[I.performed_by.slice(0,8),"â¦"]})}),e.jsxs(_,{className:"text-xs text-muted-foreground max-w-[280px]",children:[e.jsx("div",{className:"truncate",title:I.reason||"",children:I.reason||"â"}),I.details&&Object.keys(I.details).length>0&&e.jsx("div",{className:"text-[10px] font-mono truncate text-muted-foreground
237/70",title:JSON.stringify(I.details),children:JSON.stringify(I.details)})]})]},I.id)})})]})}),e.jsx(Xr,{currentPage:u,totalPages:Math.max(1,Math.ceil(H.length/m)),onPageChange:p,totalItems:H.length,pageSize:m,onPageSizeChange:()=>{}})]})]})]})})},lo=[{who:"PÅÃmý vlastnÃk",whoIcon:Ut,link:"direct",canVote:"yes",mechanism:"apartment_owners.user_id = auth.uid()",edgeCase:"Standardnà pÅÃpad â jednoznaÄný majitel jednotky se schváleným úÄtem.",module:{label:"VlastnÃci (WEG)",section:"property",subSection:"owners"}},{who:"VlastnÃk pÅes kartu (owner_contact)",whoIcon:Ut,link:"contact",canVote:"yes",mechanism:"owner_contacts.user_id = auth.uid() â apartment_owners.owner_contact_id",edgeCase:"ÃÄet je propojen pÅes vlastnickou kartu (typicky firmy a staršà importované záznamy).",module:{label:"VlastnÃci (WEG)",section:"property",subSection:"owners"}},{who:"Zástupce / kontaktnà osoba",whoIcon:di,link:"representative",canVote:"yes",mechanism:"owner_contact_persons.user_id (s can_login=true) â owner_contacts â apartment_owners",edgeCase:"Jednatel nebo zmocnÄnec firemnÃho vlastnÃka. Hlasuje za TOP pÅiÅazené k owner_contact.",module:{label:"VlastnÃci (WEG)",section:"property",subSection:"owners"}},{who:"SpoluvlastnÃk TOP",whoIcon:Fs,link:"co_owner",canVote:"one_per_unit",mechanism:"UNIQUE(poll_id, apartment_code) na tabulce poll_ballots",edgeCase:"Jeden TOP = jeden hlas. Prvnà spoluvlastnÃk odeÅ¡le hlas (sole_owner / joint_vote_declared / written_proxy / retroactive_approval_pending). Druhý spoluvlastnÃk dostane 409 a UI mu zobrazÃ, kdo už hlasoval.",errorCode:"409 / 23505",module:{label:"HlasovánÃ",section:"polls"}},{who:"VlastnÃk vÃce TOP",whoIcon:rt,link:"multi",canVote:"yes",mechanism:"submit-vote ovÄÅà OR(user_id, owner_contact_id â moje karty) pro každý apartment_code v batchi",edgeCase:"Hlasy se posÃlajà jako jeden batch. Pokud ALESPOÅ JEDEN apartment_code nenà vlastnÃkův, celý batch je atomicky odmÃtnut (403 NOT_OWNER, žádný ballot se neuložÃ).",errorCode:"403 / NOT_OWNER",module:{label:"HlasovánÃ",section:"polls"}},{who:"Bývalý vlastnÃk",whoIcon:yr,link:"former",canVote:"no",mechanism:"apartment_owners.is_current = false â vyfiltrován z ownership lookupu",edgeCase:"Po pÅevodu vlastnictvà ztrácà pÅÃstup k hlasovánà pro danou jednotku v tomtéž okamžiku.",errorCode:"403 / NOT_OWNER",module:{label:"VlastnÃci (WEG)",section:"property",subSection:"owners"}},{who:"Neschválený uživatel (pending)",whoIcon:nt,link:"none",canVote:"no",mechanism:"profiles.approval_status != approved â typicky bez vazby na apartment_owners â 403",edgeCase:"ÃÄet existuje a je pÅihlášen, ale nemá vazbu na žádný TOP. UI hlasovánà mu vůbec nezobrazà formuláÅ.",errorCode:"403 / NOT_OWNER",module:{label:"PÅÃstupy do portálu",section:"users"}},{who:"Anonymnà návÅ¡tÄvnÃk",whoIcon:Na,link:"none",canVote:"no",mechanism:"Chybà Authorization: Bearer ⦠â 401 Unauthorized",edgeCase:"Hlasovánà nenà pÅÃstupné bez pÅihlášenÃ. Edge funkce odmÃtne jeÅ¡tÄ pÅed naÄtenÃm tÄla requestu.",errorCode:"401",module:{label:"PÅÃstupy do portálu",section:"users"}},{who:"Administrátor (bez TOP)",whoIcon:Ln,link:"admin",canVote:"no",mechanism:"Role admin nepÅinášà hlasovacà právo. Admin smà jen mazat/spravovat hlasy pÅes admin UI.",edgeCase:"Admin, který sám nenà vlastnÃkem, nemůže odeslat hlas pÅes /functions/v1/submit-vote (vrátà 403). Smazánà cizÃho hlasu vyžaduje doložený důkaz (PollResults).",errorCode:"403 / NOT_OWNER",module:{label:"HlasovánÃ",section:"polls"}}],oo=s=>{const i={direct:{label:"apartment_owners.user_id",cls:"bg-emerald-100 text-emerald-800 border-emerald-200"},contact:{label:"via owner_contacts",cls:"bg-emerald-100 text-emerald-800 border-emerald-200"},representative:{label:"via owner_contact_persons",cls:"bg-emerald-100 text-emerald-800 border-emerald-200"},co_owner:{label:"sdÃlené TOP",cls:"bg-amber-100 text-amber-800 border-amber-200"},multi:{label:"vÃce TOP",cls:"bg-blue-100 text-blue-800 border-blue-200"},former:{label:"is_current=false",cls:"bg-slate-100 text-slate-700 border-slate-200"},admin:{label:"role=admin",cls:"bg-purple-100 text-purple-800 border-purple-200"},none:{label:"bez vazby",cls:"bg-rose-100 text-rose-800 border-rose-200"}}[s];return e.jsx(Q,{variant:"outline",className:`text-xs font-mono ${i.cls}`,children:i.label})},co=s=>s==="yes"?e.jsx(Q,{className:"bg-emerald-600 hover:bg-emerald-600",children:"â
Ano"}):s==="one_per_unit"?e.jsx(Q,{className:"bg-amber-600 hover:bg-amber-600",children:"â ï¸ 1à za TOP"}):e.jsx(Q,{className:"bg-rose-600 hover:bg-rose-600",children:"â Ne"}),mo=s=>{if(!s)return e.jsx("span",{className:"text-muted-foreground text-xs",children:"â"});const a=s.startsWith("401")||s.includes("NOT_OWNER");return e.jsx(Q,{variant:"outline",className:`font-mono text-xs ${a?"border-rose-300 text-rose-700":"border-amber-300 text-amber-700"}`,children:s})};function uo({onNavigate:s}){return e.jsxs("div",{className:"space-y-6",children:[e.jsxs(ee,{children:[e.jsx(ye,{children:e.jsxs(be,{className:"flex items-center gap-2",children:[e.jsx(Jn,{className:"h-5 w-5 text-primary"}),"Kdo a jak může hlasovat"]})}),e.jsxs(ae,{className:"space-y-4",children:[e.jsxs(it,{children:[e.jsx(Us,{className:"h-4 w-4"}),e.jsxs(lt,{className:"text-sm",children:["Tato matice popisuje ",e.jsx("strong",{children:"autoritativnà pravidla"}),", podle kterých edge funkce ",e.jsx("code",{className:"font-mono text-xs",children:"submit-vote"})," pÅijÃmá nebo odmÃtá hlasy. Stejnou logiku (3 cesty vlastnictvÃ: pÅÃmá / pÅes ",e.jsx("code",{children:"owner_
237contacts"})," / pÅes ",e.jsx("code",{children:"owner_contact_persons"}),") použÃvá i UI pro filtraci viditelných TOP a generovánà badgà ve správÄ uživatelů. Vynucenà v DB: ",e.jsx("code",{className:"font-mono text-xs",children:"UNIQUE(poll_id, apartment_code)"})," na ",e.jsx("code",{className:"font-mono text-xs",children:"poll_ballots"}),"."]})]}),e.jsx("div",{className:"overflow-x-auto rounded-md border",children:e.jsxs($e,{children:[e.jsx(Be,{children:e.jsxs(Ne,{className:"bg-muted/40",children:[e.jsx(D,{className:"w-[220px]",children:"Kdo"}),e.jsx(D,{className:"w-[180px]",children:"Vazba"}),e.jsx(D,{className:"w-[120px]",children:"Může hlasovat"}),e.jsx(D,{children:"Mechanismus / hraniÄnà pÅÃpad"}),e.jsx(D,{className:"w-[140px]",children:"HTTP / kód"}),e.jsx(D,{className:"w-[160px]",children:"Modul"})]})}),e.jsx(Ue,{children:lo.map(a=>{const i=a.whoIcon;return e.jsxs(Ne,{children:[e.jsx(_,{className:"align-top",children:e.jsxs("div",{className:"flex items-center gap-2 font-medium",children:[e.jsx(i,{className:"h-4 w-4 text-muted-foreground shrink-0"}),e.jsx("span",{children:a.who})]})}),e.jsx(_,{className:"align-top",children:oo(a.link)}),e.jsx(_,{className:"align-top",children:co(a.canVote)}),e.jsxs(_,{className:"align-top text-sm",children:[e.jsx("div",{className:"font-mono text-xs text-muted-foreground mb-1",children:a.mechanism}),a.edgeCase&&e.jsx("div",{className:"text-foreground/80",children:a.edgeCase})]}),e.jsx(_,{className:"align-top",children:mo(a.errorCode)}),e.jsx(_,{className:"align-top",children:a.module&&s?e.jsxs(b,{variant:"ghost",size:"sm",className:"h-7 px-2 text-xs gap-1",onClick:()=>s(a.module.section,a.module.subSection),children:[a.module.label,e.jsx(Gs,{className:"h-3 w-3"})]}):a.module?e.jsx("span",{className:"text-xs text-muted-foreground",children:a.module.label}):null})]},a.who)})})]})})]})]}),e.jsxs("div",{className:"grid gap-4 md:grid-cols-3",children:[e.jsxs(ee,{children:[e.jsx(ye,{className:"pb-2",children:e.jsxs(be,{className:"text-base flex items-center gap-2",children:[e.jsx(Na,{className:"h-4 w-4 text-rose-600"}),"401 â Anonym"]})}),e.jsxs(ae,{className:"text-sm text-muted-foreground space-y-1",children:[e.jsxs("div",{children:["Chybà nebo nevalidnà ",e.jsx("code",{className:"font-mono text-xs",children:"Authorization: Bearer â¦"})]}),e.jsx("div",{className:"font-mono text-xs",children:'{ error: "Unauthorized" }'})]})]}),e.jsxs(ee,{children:[e.jsx(ye,{className:"pb-2",children:e.jsxs(be,{className:"text-base flex items-center gap-2",children:[e.jsx(nt,{className:"h-4 w-4 text-amber-600"}),"403 â NOT_OWNER"]})}),e.jsxs(ae,{className:"text-sm text-muted-foreground space-y-1",children:[e.jsx("div",{children:"Žádná z 3 cest vlastnictvà neodpovÃdá. Pokrývá: neschválené úÄty, cizà TOP, bývalé vlastnÃky a admin bez TOP."}),e.jsx("div",{className:"font-mono text-xs",children:'{ code: "NOT_OWNER", unauthorized_codes: [...] }'})]})]}),e.jsxs(ee,{children:[e.jsx(ye,{className:"pb-2",children:e.jsxs(be,{className:"text-base flex items-center gap-2",children:[e.jsx(Fs,{className:"h-4 w-4 text-amber-600"}),"409 â 23505"]})}),e.jsxs(ae,{className:"text-sm text-muted-foreground space-y-1",children:[e.jsx("div",{children:"Druhý hlas pro stejnou dvojici (poll_id, apartment_code). Typicky druhý spoluvlastnÃk."}),e.jsx("div",{className:"font-mono text-xs",children:'{ code: "23505", ballot_conflict: true }'})]})]})]}),e.jsxs(ee,{children:[e.jsx(ye,{className:"pb-2",children:e.jsxs(be,{className:"text-base flex items-center gap-2",children:[e.jsx(Ys,{className:"h-4 w-4"}),"ReferenÄnà dokumentace"]})}),e.jsxs(ae,{className:"text-sm space-y-1.5",children:[e.jsxs("div",{children:[e.jsx("span",{className:"text-muted-foreground",children:"Edge funkce: "}),e.jsx("code",{className:"font-mono text-xs",children:"supabase/functions/submit-vote/index.ts"})]}),e.jsxs("div",{children:[e.jsx("span",{className:"text-muted-foreground",children:"Unit testy: "}),e.jsx("code",{className:"font-mono text-xs",children:"src/test/edge-functions/submitVoteErrorCodes.test.ts"}),", ",e.jsx("code",{className:"font-mono text-xs",children:"voteOwnershipMapping.test.ts"})]}),e.jsxs("div",{children:[e.jsx("span",{className:"text-muted-foreground",children:"IntegraÄnà testy: "}),e.jsx("code",{className:"font-mono text-xs",children:"supabase/functions/submit-vote/errorCodes.test.ts"}),", ",e.jsx("code",{className:"font-mono text-xs",children:"index.test.ts"})]}),e.jsxs("div",{children:[e.jsx("span",{className:"text-muted-foreground",children:"Pravidla pro vlastnÃky: "}),e.jsxs("a",{href:"/owners/voting-rules",target:"_blank",rel:"noreferrer",className:"text-primary hover:underline inline-flex items-center gap-1",children:["/owners/voting-rules ",e.jsx(Ys,{className:"h-3 w-3"})]})]})]})]})]})}const yn="hausverwaltung_vergleich_2027",St={new:"PÅijato",included:"ZaÅazeno mezi otázky",answered:"OdpovÄzeno",closed:"UzavÅeno"},st=s=>(s==null?void 0:s.full_name)||[s==null?void 0:s.first_name,s==null?void 0:s.last_name].filter(
237Boolean).join(" ")||(s==null?void 0:s.company_name)||(s==null?void 0:s.email)||"â";function xo(){const{user:s}=Ht(),{toast:a}=Re(),[i,y]=t.useState(!0),[E,P]=t.useState(!1),[x,O]=t.useState({owner:!1,beirat:!1,spravce:!1}),[S,N]=t.useState([]),[j,w]=t.useState([]),[M,o]=t.useState([]),[v,u]=t.useState([]),[p,m]=t.useState(""),[$,H]=t.useState({date:new Date().toISOString().slice(0,10),de:"",en:"",cs:"",visibility:"internal",published:!1}),[J,z]=t.useState([]),[h,I]=t.useState("all"),[k,c]=t.useState("all"),[d,T]=t.useState("publish"),r=async(B=!1)=>{B&&y(!0);const[te,xe,de,L]=await Promise.all([g.from("section_visibility").select("visible_to_owner,visible_to_beirat,visible_to_spravce").eq("section_key",yn).single(),g.from("hausverwaltung_update_history").select("*").order("update_date",{ascending:!1}),g.functions.invoke("hausverwaltung-admin",{body:{action:"load"}}),g.functions.invoke("hausverwaltung-admin",{body:{action:"loadFeedback"}})]);te.data&&O({owner:te.data.visible_to_owner,beirat:te.data.visible_to_beirat,spravce:te.data.visible_to_spravce}),u(xe.data||[]),de.data&&(N(de.data.profiles||[]),w(de.data.reviewerIds||[]),o(de.data.visits||[])),L.data&&z(L.data.feedback||[]),(te.error||xe.error||de.error||L.error)&&a({variant:"destructive",title:"Chyba",description:"Äást administrace se nepodaÅilo naÄÃst."}),B&&y(!1)};t.useEffect(()=>{r(!0)},[]);const f=async(B,te)=>{P(!0);const{error:xe}=await g.functions.invoke("hausverwaltung-admin",{body:{action:"updateFeedback",i
237d:B,...te}});xe?a({variant:"destructive",title:"Chyba",description:"Podánà se nepodaÅilo aktualizovat."}):await r(),P(!1)},R=async B=>{if(!B.length)return;P(!0);const{error:te}=await g.functions.invoke("hausverwaltung-admin",{body:{action:"markIncluded",ids:B}});te?a({variant:"destructive",title:"Chyba",description:"Stav se nepodaÅilo zmÄnit."}):(a({title:"Uloženo",description:"Otázky byly oznaÄeny jako pÅedané firmÄ."}),await r()),P(!1)},F=B=>{const te=J.filter(de=>de.provider_id===B&&de.status==="new");if(!te.length)return;const xe=te.map((de,L)=>`${L+1}. ${de.subject||"â"} 238${de.body}`).join(` 239 240`);navigator.clipboard.writeText(xe).then(()=>a({title:"ZkopÃrováno",description:`${te.length} nových podánà â pouze pÅedmÄt a text, bez jmen a internÃch údajů.`}))},ce=async(B,te)=>{const xe={...x,[B]:te};O(xe);const{error:de}=await g.from("section_visibility").update({visible_to_owner:xe.owner,visible_to_beirat:xe.beirat,visible_to_spravce:xe.spravce}).eq("section_key",yn);de?(a({variant:"destructive",title:"Chyba",description:"Viditelnost se nepodaÅilo uložit."}),r()):a({title:"Uloženo",description:"Viditelnost stránky byla aktualizována."})},ie=async(B,te)=>{P(!0);const{error:xe}=await g.functions.invoke("hausverwaltung-admin",{body:{action:te,userId:B}});xe?a({variant:"destructive",title:"Chyba",description:"Review pÅÃstup se nepodaÅilo zmÄnit."}):(a({title:"Uloženo",description:te==="grant"?"Review pÅÃstup byl udÄlen.":"Review pÅÃstup byl odebrán."}),await r()),P(!1)},W=async()=>{if(!$.de.trim()||!$.en.trim()||!$.cs.trim())return;P(!0);const{error:B}=await g.from("hausverwaltung_update_history").insert({update_date:$.date,description_de:$.de.trim(),description_en:$.en.trim(),description_cs:$.cs.trim(),visibility:$.visibility,published:$.published,created_by:s.id});B?a({variant:"destructive",title:"Chyba",description:"Záznam se nepodaÅilo uložit."}):(H({...$,de:"",en:"",cs:""}),await r()),P(!1)},Z=async B=>{await g.from("hausverwaltung_update_history").delete().eq("id",B),await r()},K=t.useMemo(()=>S.filter(B=>`${st(B)} ${B.email||""} ${B.apartments||""}`.toLowerCase().includes(p.toLowerCase())),[S,p]),l=t.useMemo(()=>[...M].sort((B,te)=>new Date(te.lastOpenedAt).getTime()-new Date(B.lastOpenedAt).getTime()),[M]),U=t.useMemo(()=>{const B=new Set(M.map(te=>te.userId));return S.filter(te=>!B.has(te.user_id))},[S,M]),n=t.useMemo(()=>M.reduce((B,te)=>B+te.visitCount,0),[M]),G=t.useMemo(()=>M.filter(B=>B.accessContext==="review").length,[M]),Y=()=>{const B=["Uživatel","E-mail","Apartmán","Prvnà zobrazenÃ","Poslednà zobrazenÃ","NávÅ¡tÄvy","Režim"],te=l.map(re=>{var A,ne;return[st(re.profile),((A=re.profile)==null?void 0:A.email)||"",((ne=re.profile)==null?void 0:ne.apartments)||"",new Date(re.firstOpenedAt).toLocaleString("cs-CZ"),new Date(re.lastOpenedAt).toLocaleString("cs-CZ"),String(re.visitCount),re.accessContext==="review"?"Review pÅÃstup":"Publikovaná stránka"]}),xe=[B,...te].map(re=>re.map(A=>`"${String(A).replace(/"/g,'""')}"`).join(";")).join(` 241`),de=URL.createObjectURL(new Blob(["\uFEFF"+xe],{type:"text/csv;charset=utf-8"})),L=document.createElement("a");L.href=de,L.download=`audit-zobrazeni-hausverwaltung-2027-${new Date().toISOString().slice(0,10)}.csv`,L.click(),URL.revokeObjectURL(de)};if(i)return e.jsx("div",{className:"flex justify-center py-16",children:e.jsx(fe,{className:"h-7 w-7 animate-spin text-primary"})});const pe=async()=>{const B="https://hintermoos.at/hausverwaltungen-2027";try{await navigator.clipboard.writeText(B),a({title:"Odkaz zkopÃrován",description:B})}catch{a({title:"PÅÃmý odkaz",description:B})}};return e.jsxs("div",{className:"mx-auto max-w-6xl space-y-6",children:[e.jsxs("div",{className:"flex flex-col justify-between gap-3 sm:flex-row sm:items-center",children:[e.jsxs("div",{children:[e.jsx("h2",{className:"text-2xl font-semibold",children:"Hausverwaltung 2027"}),e.jsx("p",{className:"text-sm text-muted-foreground",children:"Publikace, ÄasovÄ omezené review pÅÃstupy a audit návÅ¡tÄv."})]}),e.jsxs("div",{className:"flex flex-wrap items-center gap-2",children:[e.jsxs(b,{variant:"outline",onClick:()=>void pe(),children:[e.jsx(Os,{className:"mr-2 h-4 w-4"}),"KopÃrovat pÅÃmý odkaz"]}),e.jsx(b,{asChild:!0,variant:"outline",children:e.jsxs(bn,{to:"/hausverwaltungen-2027?preview=owner",children:["Náhled vlastnÃka",e.jsx(Ys,{className:"ml-2 h-4 w-4"})]})})]})]}),e.jsxs(ks,{value:d,onValueChange:T,children:[e.jsxs(Cs,{children:[e.jsx(We,{value:"publish",children:"Veröffentlichung"}),e.jsx(We,{value:"review",children:"Review & Zugriffe"}),e.jsx(We,{value:"audit",children:"Audit zobrazenÃ"}),e.jsx(We,{value:"feedback",children:"PÅipomÃnky"}),e.jsx(We,{value:"changes",children:"Ãnderungen"})]}),e.jsxs(es,{value:"publish",className:"mt-6 space-y-6",children:[e.jsxs("section",{className:"max-w-2xl rounded-lg border p-5",children:[e.jsx("h3",{className:"font-semibold",children:"Viditelnost stránky podle rolÃ"}),e.jsx("p",{className:"mt-1 text-sm text-muted-foreground",children:"Výchozà stav zůstává vypnutý. Review pÅÃstupy nÞe jsou samostatné pozitivnà výjimky."}
241),e.jsx("div",{className:"mt-5 divide-y",children:[["owner","VlastnÃci"],["beirat","Beirat"],["spravce","Správce"]].map(([B,te])=>e.jsxs("div",{className:"flex items-center justify-between py-3",children:[e.jsx(q,{htmlFor:`visibility-${B}`,children:te}),e.jsx(ss,{id:`visibility-${B}`,checked:x[B],onCheckedChange:xe=>void ce(B,xe)})]},B))})]}),e.jsxs("section",{className:"max-w-2xl border-t pt-5",children:[e.jsx("h3",{className:"font-semibold",children:"Publikovaný obsah"}),e.jsxs("p",{className:"mt-2 text-sm text-muted-foreground",children:["Owner stránka vždy filtruje spoleÄnosti, Åádky, dokumenty, termÃny a Q&A na ",e.jsx("code",{children:"public + published"}),". Pracovnà data nejsou v náhledu zobrazena."]})]})]}),e.jsx(es,{value:"review",className:"mt-6 space-y-8",children:e.jsxs("section",{children:[e.jsxs("div",{className:"mb-4 flex flex-col justify-between gap-3 sm:flex-row",children:[e.jsxs("div",{children:[e.jsx("h3",{className:"font-semibold",children:"Review pÅÃstupy"}),e.jsx("p",{className:"text-sm text-muted-foreground",children:"UdÄlenà vytvoÅà pouze pozitivnà výjimku; odebránà výjimku smaže."})]}),e.jsxs("div",{className:"relative",children:[e.jsx(fs,{className:"absolute left-3 top-2.5 h-4 w-4 text-muted-foreground"}),e.jsx(se,{className:"pl-9",value:p,onChange:B=>m(B.target.value),placeholder:"Hledat úÄet"})]})]}),e.jsx("div",{className:"overflow-x-auto rounded-md border",children:e.jsxs($e,{children:[e.jsx(Be,{children:e.jsxs(Ne,{children:[e.jsx(D,{children:"Uživatel"}),e.jsx(D,{children:"Apartmán"}),e.jsx(D,{children:"Stav"}),e.jsx(D,{className:"text-right",children:"Akce"})]})}),e.jsx(Ue,{children:K.map(B=>{const te=j.includes(B.user_id);return e.jsxs(Ne,{children:[e.jsxs(_,{children:[e.jsx("strong",{children:st(B)}),e.jsx("div",{className:"text-xs text-muted-foreground",children:B.email})]}),e.jsx(_,{children:B.apartments||"â"}),e.jsx(_,{children:te?e.jsx(Q,{children:"Review aktivnÃ"}):e.jsx(Q,{variant:"outline",children:"Bez výjimky"})}),e.jsx(_,{className:"text-right",children:e.jsx(b,{size:"sm",variant:te?"outline":"default",disabled:E,onClick:()=>void ie(B.user_id,te?"revoke":"grant"),children:te?"Odebrat":"UdÄlit"})})]},B.user_id)})})]})})]})}),e.jsxs(es,{value:"audit",className:"mt-6 space-y-6",children:[e.jsx("div",{className:"rounded-lg border bg-muted/40 p-4 text-sm text-muted-foreground",children:"Audit ukazuje, kdo a kdy stránku se srovnánÃm správců otevÅel. Zaznamenává se pouze otevÅenà pÅihlášeným vlastnÃkem nebo osobou s review pÅÃstupem â úÄty administrace se nezapoÄÃtávajÃ. Opakovaná otevÅenà jedné osoby do 30 minut se poÄÃtajà jako jedna návÅ¡tÄva. IP adresa ani zaÅÃzenà se neukládajÃ."}),e.jsx("div",{className:"grid gap-3 sm:grid-cols-2 lg:grid-cols-4",children:[["Zobrazilo stránku",String(M.length)],["Celkem návÅ¡tÄv",String(n)],["ZatÃm neotevÅelo",String(U.length)],["Z toho review pÅÃstup",String(G)]].map(([B,te])=>e.jsxs("div",{className:"rounded-lg border p-4",children:[e.jsx("div",{className:"text-2xl font-semibold",children:te}),e.jsx("div",{className:"mt-1 text-xs text-muted-foreground",children:B})]},B))}),e.jsxs("section",{children:[e.jsxs("div",{className:"mb-3 flex flex-wrap items-center justify-between gap-2",children:[e.jsxs("div",{children:[e.jsx("h3",{className:"font-semibold",children:"Kdo stránku otevÅel"}),e.jsx("p",{className:"text-sm text-muted-foreground",children:"SeÅazeno podle poslednÃho zobrazenÃ."})]}),e.jsxs("div",{className:"flex gap-2",children:[e.jsxs(b,{variant:"outline",size:"sm",disabled:!l.length,onClick:Y,children:[e.jsx(Pt,{className:"mr-2 h-4 w-4"}),"Export CSV"]}),e.jsxs(b,{variant:"ghost",size:"sm",onClick:()=>void r(),children:[e.jsx(Es,{className:"mr-2 h-4 w-4"}),"Obnovit"]})]})]}),e.jsx("div",{className:"overflow-x-auto rounded-md border",children:e.jsxs($e,{children:[e.jsx(Be,{children:e.jsxs(Ne,{children:[e.jsx(D,{children:"Uživatel"}),e.jsx(D,{children:"Apartmán"}),e.jsx(D,{children:"Prvnà zobrazenÃ"}),e.jsx(D,{children:"Poslednà zobrazenÃ"}),e.jsx(D,{children:"NávÅ¡tÄvy"}),e.jsx(D,{children:"Režim"})]})}),e.jsxs(Ue,{children:[l.map(B=>{var te,xe;return e.jsxs(Ne,{children:[e.jsxs(_,{children:[e.jsx("strong",{children:st(B.profile)}),e.jsx("div",{className:"text-xs text-muted-foreground",children:(te=B.profile)==null?void 0:te.email})]}),e.jsx(_,{className:"whitespace-nowrap",children:((xe=B.profile)==null?void 0:xe.apartments)||"â"}),e.jsx(_,{className:"whitespace-nowrap",children:new Date(B.firstOpenedAt).toLocaleStr
241ing("cs-CZ")}),e.jsx(_,{className:"whitespace-nowrap",children:new Date(B.lastOpenedAt).toLocaleString("cs-CZ")}),e.jsx(_,{children:B.visitCount}),e.jsx(_,{className:"whitespace-nowrap",children:B.accessContext==="review"?e.jsx(Q,{variant:"outline",children:"Review pÅÃstup"}):e.jsx(Q,{children:"Publikovaná stránka"})})]},B.userId)}),!l.length&&e.jsx(Ne,{children:e.jsx(_,{colSpan:6,className:"py-8 text-center text-sm text-muted-foreground",children:"Stránku zatÃm nikdo neotevÅel."})})]})]})})]}),e.jsxs("section",{children:[e.jsxs("h3",{className:"font-semibold",children:["ZatÃm neotevÅeli (",U.length,")"]}),e.jsx("p",{className:"mb-3 text-sm text-muted-foreground",children:"VlastnÃci a osoby s review pÅÃstupem, u kterých zatÃm nenà zaznamenané žádné zobrazenÃ."}),e.jsx("div",{className:"overflow-x-auto rounded-md border",children:e.jsxs($e,{children:[e.jsx(Be,{children:e.jsxs(Ne,{children:[e.jsx(D,{children:"Uživatel"}),e.jsx(D,{children:"Apartmán"}),e.jsx(D,{children:"Review pÅÃstup"})]})}),e.jsxs(Ue,{children:[U.map(B=>e.jsxs(Ne,{children:[e.jsxs(_,{children:[e.jsx("strong",{children:st(B)}),e.jsx("div",{className:"text-xs text-muted-foreground",children:B.email})]}),e.jsx(_,{className:"whitespace-nowrap",children:B.apartments||"â"}),e.jsx(_,{children:j.includes(B.user_id)?e.jsx(Q,{variant:"outline",children:"Ano"}):"â"})]},B.user_id)),!U.length&&e.jsx(Ne,{children:e.jsx(_,{colSpan:3,className:"py-8 text-center text-sm text-muted-foreground",children:"VÅ¡ichni už stránku otevÅeli."})})]})]})})]})]}),e.jsxs(es,{value:"feedback",className:"mt-6 space-y-4",children:[e.jsxs("div",{className:"flex flex-col justify-between gap-3 sm:flex-row sm:items-end",children:[e.jsxs("div",{children:[e.jsx("h3",{className:"font-semibold",children:"PÅipomÃnky vlastnÃků"}),e.jsx("p",{className:"text-sm text-muted-foreground",children:'NeveÅejná podánà k nabÃdkám firem. Do textu pro firmu se kopÃruje pouze pÅedmÄt a text podánà ve stavu âPÅijato".'})]}),e.jsxs("div",{className:"flex flex-wrap items-center gap-2",children:[e.jsxs("select",{className:"h-9 rounded-md border bg-background px-3 text-sm",value:h,onChange:B=>I(B.target.value),children:[e.jsx("option",{value:"all",children:"VÅ¡echny firmy"}),Ra.map(B=>e.jsx("option",{value:B.id,children:B.name},B.id))]}),e.jsxs("select",{className:"h-9 rounded-md border bg-background px-3 text-sm",value:k,onChange:B=>c(B.target.value),children:[e.jsx("option",{value:"all",children:"VÅ¡echny stavy"}),Object.keys(St).map(B=>e.jsx("option",{value:B,children:St[B]},B))]}),e.jsxs(b,{variant:"outline",size:"sm",disabled:E||h==="all"||!J.some(B=>B.provider_id===h&&B.status==="new"),onClick:()=>F(h),children:[e.jsx(Os,{className:"mr-2 h-4 w-4"}),"ZkopÃrovat jako otázky"]}),e.jsxs(b,{variant:"outline",size:"sm",disabled:E||h==="all"||!J.some(B=>B.provider_id===h&&B.status==="new"),onClick:()=>void R(J.filter(B=>B.provider_id===h&&B.status==="new").map(B=>B.id)),children:[e.jsx(ps,{className:"mr-2 h-4 w-4"}),"OznaÄit jako pÅedané"]})]})]}),e.jsx("div",{className:"overflow-x-auto rounded-md border",children:e.jsxs($e,{children:[e.jsx(Be,{children:e.jsxs(Ne,{children:[e.jsx(D,{children:"Datum"}),e.jsx(D,{children:"VlastnÃk"}),e.jsx(D,{children:"Firma"}),e.jsx(D,{children:"PÅedmÄt a text"}),e.jsx(D,{children:"Stav"}),e.jsx(D,{children:"Q&A"}),e.jsx(D,{children:"Poznámka"})]})}),e.jsxs(Ue,{children:[J.filter(B=>(h==="all"||B.provider_id===h)&&(k==="all"||B.status===k)).map(B=>{var te,xe;return e.jsxs(Ne,{children:[e.jsx(_,{className:"whitespace-nowrap",children:new Date(B.created_at).toLocaleDateString("cs-CZ")}),e.jsxs(_,{children:[e.jsx("strong",{children:st(B.profile)}),((te=B.profile)==null?void 0:te.apartments)&&e.jsx("div",{className:"text-xs text-muted-foreground",children:B.profile.apartments})]}),e.jsx(_,{className:"whitespace-nowrap",children:((xe=Ra.find(de=>de.id===B.provider_id))==null?void 0:xe.shortName)||B.provider_id}),e.jsxs(_,{className:"max-w-md",children:[e.jsx("p",{className:"text-xs font-semibold",children:B.subject||"â"}),e.jsx("p",{className:"mt-1 text-xs text-muted-foreground",children:B.body}),B.admin_note&&e.jsxs("p",{className:"mt-1 text-[11px] italic text-muted-foreground",children:["InternÃ: ",B.admin_note]})]}),e.jsx(_,{children:e.jsx("select",{className:"h-8 rounded-md border bg-background px-2 text-xs",value:
241B.status,disabled:E,onChange:de=>void f(B.id,{status:de.target.value}),children:Object.keys(St).map(de=>e.jsx("option",{value:de,children:St[de]},de))})}),e.jsx(_,{children:e.jsx(ss,{checked:B.included_in_qa,disabled:E,onCheckedChange:de=>void f(B.id,{included_in_qa:de})})}),e.jsx(_,{children:e.jsx(se,{className:"h-8 w-40 text-xs",defaultValue:B.admin_note||"",placeholder:"Internà poznámka",onBlur:de=>{de.target.value!==(B.admin_note||"")&&f(B.id,{admin_note:de.target.value})}})})]},B.id)}),!J.length&&e.jsx(Ne,{children:e.jsx(_,{colSpan:7,className:"py-8 text-center text-sm text-muted-foreground",children:"ZatÃm žádná podánÃ."})})]})]})})]}),e.jsxs(es,{value:"changes",className:"mt-6 space-y-6",children:[e.jsxs("section",{className:"rounded-lg border p-5",children:[e.jsx("h3",{className:"font-semibold",children:"PÅidat záznam zmÄny"}),e.jsxs("div",{className:"mt-4 grid gap-4",children:[e.jsxs("div",{className:"grid gap-2 sm:grid-cols-3",children:[e.jsxs("div",{children:[e.jsx(q,{children:"Datum"}),e.jsx(se,{type:"date",value:$.date,onChange:B=>H({...$,date:B.target.value})})]}),e.jsxs("div",{children:[e.jsx(q,{children:"Viditelnost"}),e.jsxs("select",{className:"mt-1 h-10 w-full rounded-md border bg-background px-3 text-sm",value:$.visibility,onChange:B=>H({...$,visibility:B.target.value}),children:[e.jsx("option",{value:"internal",children:"InternÃ"}),e.jsx("option",{value:"public",children:"VeÅejná"})]})]}),e.jsxs("div",{className:"flex items-end gap-2 pb-2",children:[e.jsx(ss,{checked:$.published,onCheckedChange:B=>H({...$,published:B})}),e.jsx(q,{children:"Publikováno"})]})]}),e.jsx("div",{className:"grid gap-3 md:grid-cols-3",children:["de","en","cs"].map(B=>e.jsxs("div",{children:[e.jsx(q,{children:B.toUpperCase()}),e.jsx(vs,{className:"mt-1",value:$[B],onChange:te=>H({...$,[B]:te.target.value})})]},B))}),e.jsxs(b,{className:"w-fit",disabled:E,onClick:()=>void W(),children:[e.jsx(Xe,{className:"mr-2 h-4 w-4"}),"PÅidat zmÄnu"]})]})]}),e.jsx("div",{className:"divide-y rounded-lg border",children:v.map(B=>e.jsxs("div",{className:"flex items-start justify-between gap-4 p-4",children:[e.jsxs("div",{children:[e.jsxs("div",{className:"flex gap-2",children:[e.jsx("strong",{children:new Date(B.update_date).toLocaleDateString("cs-CZ")}),e.jsx(Q,{variant:"outline",children:B.visibility}),B.published&&e.jsx(Q,{children:"publikováno"})]}),e.jsx("p",{className:"mt-2 text-sm",children:B.description_de}),e.jsxs("p",{className:"text-xs text-muted-foreground",children:[B.description_en," · ",B.description_cs]})]}),e.jsx(b,{variant:"ghost",size:"icon",onClick:()=>void Z(B.id),children:e.jsx(qe,{className:"h-4 w-4"})})]},B.id))})]})]})]})}const xa={forum:"Fórum",property:"VlastnÃci a apartmány",costs:"Náklady","reserve-fund":"Fond oprav","import-pipeline":"Import & zpracovánÃ",documents:"Dokumenty",announcements:"OznámenÃ",polls:"HlasovánÃ","hausverwaltung-2027":"Hausverwaltung 2027",monitoring:"Monitoring",settings:"NastavenÃ",activity:"Aktivita uživatelů","email-clicks":"Kliknutà v e-mailech","link-audit":"Audit propojenà vlastnÃkâúÄet","invitation-audit":"Audit pozvánek","voting-matrix":"Kdo může hlasovat",users:"PÅÃstupy do portálu"},zt={property:{owners:"VlastnÃci",apartments:"Apartmány","house-contacts":"Kontakty domu"},costs:{categories:"Kategorie nákladů",housecosts:"Domovnà náklady",vendors:"Dodavatelé"},"reserve-fund":{years:"Roky",income:"PÅÃjmy",expenditures:"Výdaje","rf-settings":"Nastavenà fondu"},"import-pipeline":{import:"Import z PDF",mappings:"Pravidla mapovánÃ","ai-prompt":"AI Parser","data-management":"Správa dat","translation-drafts":"Extrakce pÅekladů z PDF"},monitoring:{overview:"PÅehled",points:"Body",measurements:"MÄÅenÃ","mon-import":"Import",floorplan:"Půdorys","monitoring-settings":"Nastavenà monitoringu"},settings:{}},ho=()=>{var u;const s=Ks(),a=Hn(),{isAdmin:i,isLoading:y,loadError:E}=Wn(),P=new URLSearchParams(a.search),[x,O]=t.useState(P.get("section")||"forum"),[S,N]=t.useState(P.get("sub")||"groups"),[j,w]=t.useState(!1);t.useEffect(()=>{const p=new URLSearchParams(a.search),m=p.get("section"),$=p.get("sub");m&&(O(m),$&&N($))},[a.search]),xi(),t.useEffect(()=>{y||E||i||s("/owners",{replace:!0})},[i,y,E,s]);const M=(p,m)=>{O(p);const $={property:"owners",costs:"categories","reserve-fund":"years","import-pipeline":"import",monitoring:"overview"};m?N(m):$[p]?N($[p]):N(void 0),w(!1)},o=()=>{switch(x){case"forum":return e.jsx(vi,{});case"property":return S==="apartments"?e.jsx(Ai,{}):S==="house-contacts"?e.jsx(el,{}):e.jsx(Oi,{});case"costs":switch(S){case"categories":return e.jsx($i,{});case"vendors":return e.jsx(Gi,{});default:return e.jsx(Ri,{})}case"reserve-fund":switch(S){case"years":return e.jsx(Ka,{});case"income":return e.jsx(Mi,{});case"expenditures":return e.jsx(Li,{});case"rf-settings":return e.jsx(Fi,{});default:return e.jsx(Ka,{})}case"import-pipeline":switch(S){case"import":return e.jsx(en,{});case"mappings":return e.jsx(Qi,{});case"ai-prompt":return e.jsx(Hi,{});case"data-management":return e.jsx(Bi,{});case"translation-drafts":return e.jsx(Vi,{});default:return e.jsx(en,{})}case"monitoring":switch(S){case"overview":return e.jsx(jn,{});case"points":return e.jsx(Kl,{});case"measurements":return e.jsx(Zl,{});case"mon-import":return e.jsx(Jl,{});case"floorplan":return e.jsx(Ql,{});case"monitoring-settings":return e.jsx(Wl,{});default:return e.jsx(jn,{})}case"documents":return e.jsx(wi,{});case"announcements":return e.jsx(ki,{});case"polls":return e.jsx(zi,{});case"hausverwaltung-2027":return e.jsx(xo,{});case"settings":return e.jsx(pl,{});case"activity":return e.jsx(Bl,{});case"email-clicks":return e.jsx(Xl,{});case"link-audit":return e.jsx(ao,{});case"invitation-audit":return e.jsx(io,{});case"voting-matrix":return e.jsx(uo,{onNavigate:M});case"users":return e.jsx(yi,{});default:return null}},v=()=>{var m;const p=xa[x]||"Administrace";return S&&((m=zt[x])!=null&&m[S])?`${p} - ${zt[x][S]}`:p};return y?e.jsx(ta,{children:e.jsx("div",{className:"min-h-[60vh] flex items-center justify-center",children:e.jsx(fe,{className:"h-8 w-8 animate-spin text-primary"})})}):E?e.jsx(ta,{children:e.jsxs("div",{className:"min-h-[60vh] flex flex-col items-center justify-center gap-4",children:[e.jsx("p",{className:"text-sm text-muted-foreground",children:"NepodaÅilo se naÄÃst oprávnÄnÃ."}),e.jsx(b,{onClick:()=>window.location.reload(),children:"NaÄÃst znovu"})]})}):i?e.jsx(ta,{children:e.jsxs("div",{className:"flex min-h-[calc(100vh-4rem)]",children:[e.jsx("div",{className:"hidden lg:block",children:e.jsx("div",{className:"sticky top-16 h-[calc(100vh-4rem)]",children:e.jsx(Aa,{activeSection:x,activeSubSection:S,onNavigate:M})})}),e.jsxs("div",{className:"flex-1 flex flex-col min-w-0",children:[e.jsxs("div",{className:"lg:hidden border-b bg-card p-4 flex items-center gap-3",children:[e.jsxs(Yn,{open:j,onOpenChange:w,children:[e.jsx(Qn,{asChild:!0,children:e.jsx(b,{variant:"outline",size:"icon",children:e.jsx(xr,{className:"h-5 w-5"})})}),e.jsx(Xn,{side:"left",className:"p-0 w-64",children:e.jsx(Aa,{activeSection:x,activeSubSection:S,onNavigate:M})})]}),e.jsx("h1",{className:"font-semibold text-lg truncate",children:v()})]}),e.jsxs("div",{className:"hidden lg:block border-b bg-muted/30 px-6 py-4",children:[e.jsx(er,{className:"mb-2",children:e.jsxs(sr,{children:[e.jsx(aa,{children:e.jsxs(Sa,{href:"/",className:"flex items-center gap-1 text-muted-foreground hover:text-foreground",children:[e.jsx(On,{className:"h-3.5 w-3.5"}),e.jsx("span",{children:"Domů"})]})}),e.jsx(za,{children:e.jsx(Ts,{className:"h-3.5 w-3.5"})}),e.jsx(aa,{children:S?e.jsx(Sa,{href:"#",onClick:p=>{p.preventDefault(),M(x)},className:"text-muted-foreground hover:text-foreground",children:xa[x]}):e.jsx(Da,{children:xa[x]})}),S&&((u=zt[x])==null?void 0:u[S])&&e.jsxs(e.Fragment,{children:[e.jsx(za,{children:e.jsx(Ts,{className:"h-3.5 w-3.5"})}),e.jsx(aa,{children:e.jsx(Da,{children:zt[x][S]})})]})]})}),e.jsx("h1",{className:"font-serif text-lg font-bold text-foreground",children:v()})]}),e.jsx("div",{className:"flex-1 p-4 lg:p-6 overflow-auto",children:o()})]})]})}):null},Cd=()=>e.jsx(ho,{});export{Cd 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.