PageSourceSearch

https://hintermoos.at/assets/Admin-CfcrnSCj.js

js hintermoos.at collected 2026-10-09 22:01:57 UTC 566,361 bytes, 241 lines download raw bytes

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&amp;Gesetzesnummer=20001921&amp;
235Paragraf=24" style="color:#1a5276;text-decoration:underline;">Znění zákona (RIS) →</a> &nbsp;·&nbsp; <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&amp;Gesetzesnummer=20001921&amp;
235Paragraf=24" style="color:#1a5276;text-decoration:underline;">Gesetzestext (RIS) →</a> &nbsp;·&nbsp; <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&amp;Gesetzesnummer=20001921&amp;Paragraf=24" style="color:#1a5276;text-decoration:underline;">Text of the law (RIS) →</a> &nbsp;·&nbsp; <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.