PageSourceSearch

https://trips.off-the-path.com/assets/TripDetailPage-C9TdpSUr.js

js off-the-path.com collected 2026-09-24 19:02:00 UTC 541,880 bytes, 159 lines download raw bytes

1const __vite__mapDeps=(i,m=__vite__mapDeps,d=(m.f||(m.f=["assets/index-BKB94GeX.js","assets/react-vendor-oGnIhQt2.js","assets/radix-core-kiNkrX5-.js","assets/index-CTc8Zg3E.css","assets/storageUtils-B99NVakz.js"])))=>i.map(i=>d[i]);
2import{r as t,j as e,f as dt,e as ta,h as oa,u as Ln,L as Yt,o as qn,p as Mn}from"./react-vendor-oGnIhQt2.js";import{p as He,t as Ks,f as ps}from"./dateOnly-qgaHYHLv.js";import{u as Gn}from"./useGenderBalance-BKKLetlf.js";import{B as z,c as Ms,k as tt,t as Ns,x as In,j as Xe,s as _,u as Y,h as $e,G as Ot,X as er,I as te,A as Pt,o as Ft,T as Lt,F as $s,M as Os,m as it,p as Js,q as Xs,r as et,i as Us,l as sr,n as Tt,L as U,_ as Ca,S as za,y as Cr,a as tr,z as Zs,D as On,E as Sr,H as Dr,g as Ut,J as mn,K as aa,N as Er,O as un,Q as Un,v as bt,P as yt,R as hn,C as Ss,e as Rs,b as Mt,d as Gt,f as xn,V as pn,W as gn,Y as fn,Z as ot,$ as Sa,a0 as jn,a1 as Vn,a2 as _n,a3 as Ba,a4 as Ar,a5 as Kn,w as Zn}from"./index-BKB94GeX.js";import{T as ar,a as rr,b as Gs,c as Is}from"./tabs-CA49d49w.js";import{S as Nn,D as Hn,f as Pr}from"./date-range-picker-ClO2CipT.js";import{P as Dt,a as Et,b as At}from"./popover-CVTv06F2.js";import{u as Wn,C as Qn,a as Yn,b as Jn,c as Xn,d as Fr,e as zr,f as ei}from"./useCountries-CQHs-GE2.js";import si from"./chevrons-up-down-woTMjDZ3.js";import{D as We,a as Qe,b as Ye,c as Je,d as Ds,e as gs,f as ua}from"./dialog-BUfcLSZQ.js";import{u as ti,a as ai,b as ri,c as ni,d as ii,e as li}from"./useExpenses-CBnl5tuX.js";import{P as ci}from"./progress-bar-D2wr3mZ9.js";import{u as nr}from"./useTrips-BfB1r5ZX.js";import{T as qs}from"./textarea-2JNRvrIj.js";import{C as qt}from"./calendar-DWh5O53u.js";import{openSignedDocument as La}from"./storageUtils-B99NVakz.js";import{S as Ie,a as Oe,b as Ve,c as Ue,d as O}from"./select-DiGFJ7cc.js";import{A as mt,b as ut,c as ht,d as xt,e as pt,f as gt,g as ft,h as jt,a as oi}from"./alert-dialog-CWEur2G-.js";import wt from"./search-D8yK85og.js";import ra from"./circle-check-Bh4yJa8I.js";import st from"./eye-BXb1jauY.js";import Es from"./plus-D61XoyPZ.js";import bs from"./trash-2-D_Cpvrr2.js";import vt from"./pencil-C0whVfKL.js";import Vt from"./circle-x-BSE_Sd36.js";import Kt from"./credit-card-Crxyvase.js";import kt from"./calendar-CCYM9Ult.js";import wa from"./square-pen-B99V8q1b.js";import Ha from"./file-check-6GnXRsE4.js";import Jt from"./receipt-cTQgphWa.js";import vn from"./chevron-up-Czp8mG4R.js";import Rt from"./sparkles-DTJlEWzQ.js";import _t from"./upload-CdFlrMzI.js";import{c as fs,e as Wa,j as di,p as ka,k as mi,l as ui,g as hi,m as bn}from"./date-fns-DU_j6nL5.js";import{d as Ts}from"./de-Djqs-V1s.js";import{S as ys}from"./switch-hOv0hukA.js";import{u as ir,a as sa,s as lr,K as cr,P as or,D as dr,c as mr,S as ur,v as hr,b as xr,C as pr,d as gr}from"./dnd-_CaPxTQa.js";import Da from"./save-HnsVhFHm.js";import Ra from"./grip-vertical-BitQ--pm.js";import xi from"./message-square-quote-Bq3kmWU8.js";import{B as pi}from"./birthday-picker-C5fzmo0K.js";import{R as fr,a as It}from"./radio-group-80o4oCXK.js";import{L as gi,u as _a}from"./LeadDnaBlock-BIe4qZ71.js";import yn from"./tree-deciduous-hauaiBA2.js";import lt from"./download-57BaKiK5.js";import{s as fi,f as qa,p as ji}from"./profileDataService-CFRT2bHp.js";import Rr from"./clipboard-list-BTDwpi6q.js";import $t from"./plane-N1IZPxav.js";import _i from"./plane-landing-BtWs4RSA.js";import Ni from"./plane-takeoff-D2g2sbwm.js";import vi from"./database-BTElpLuj.js";import wn from"./file-C1ZHz5ZG.js";import Xt from"./link-2-hEqR-ggl.js";import{u as bi}from"./useGuides-D3XDIvhn.js";import Vs from"./clock-Dtubv8qd.js";import Bt from"./send-B_wASXCV.js";import yi from"./scroll-text-CgDowP4s.js";import{C as at,a as rt,b as nt}from"./collapsible-DfKXwtAl.js";import jr from"./file-question-IDvmAMFZ.js";import _r from"./circle-alert-0_TIjeUZ.js";import wi from"./settings-2-DRm4753Y.js";import kn from"./unlink-B2-pa0MG.js";import Zt from"./external-link-BkeWfW6n.js";import Nr from"./cake-BbQLOHPH.js";import ki from"./mail-plus-ChSZfiYz.js";import xa from"./phone-C1yjWOcI.js";import Cn from"./user-CDekFI-y.js";import Sn from"./users-round-Bh7ybuZE.js";import Ci from"./house-CR-OcPRX.js";import{u as Si,a as Di,b as Ei}from"./usePartnerServices-FsHGVuV5.js";import{u as vr}from"./useExchangeRates-CnbIPqrQ.js";import{P as Ai,C as Pi}from"./ContactHistoryDialog-DJ8DSm5E.js";import Ea from"./paperclip-B0wP1PVh.js";import Fi from"./share-2-JLlCYUoY.js";import zi from"./file-image-C49SmEWt.js";import Ri from"./file-spreadsheet-GWPwcMEZ.js";import Ti from"./eye-off-BUyVGJz8.js";import Tr from"./info-C9m1aSaV.js";import $i from"./bell-ring-ohTGaD6r.js";import Ta from"./pen-DVLzerL2.js";import Qa from"./refresh-cw-C-vY9WX3.js";import Bi from"./message-square-C1-dSKnV.js";
2import Dn from"./map-pin-8xFxouSe.js";import Li from"./bed-ovsZOu5Q.js";import qi from"./bus-BTFBObZK.js";import Mi from"./activity-DHlXcd9O.js";import Gi from"./utensils-crossed-DpTM0iCw.js";import Ii from"./earth-BPyVyXcB.js";import pa from"./bed-double-BHztyo9t.js";import{E as Oi,a as Ui}from"./jspdf.plugin.autotable-Cxl38vXQ.js";import Vi from"./table-C5Y1Ie9k.js";import Ki from"./languages-t4Ufx5Ck.js";import En from"./list-Bvuqmz-I.js";import Zi from"./utensils-B-mBUhvb.js";import Hi from"./heart-pulse-BX8uUQ-Z.js";import{T as ga,a as fa,b as ct,c as rs,d as ja,e as ss}from"./table-BwmCMpag.js";import{e as Wi}from"./partnerExport-TG8VoPGS.js";import Qi from"./hotel-DGNQdCog.js";import Yi from"./user-minus-DkrtjZTM.js";import da from"./file-down-Cambvbs_.js";import ma from"./rotate-ccw-BitEzjiJ.js";import Ji from"./history-CtCqSPgF.js";import{h as Ma,p as $r,a as Br}from"./preTripStay-CjljVZ4n.js";import An from"./square-check-big-B-WaTqdC.js";import Xi from"./square-tVoV2Rxr.js";import{A as el}from"./AddonImageUpload-DTH3D_UH.js";import Lr from"./shopping-bag-C4Lx-rHd.js";import Pn from"./ellipsis-gxJPuE3c.js";import Aa from"./circle-check-big-DgB8cS84.js";import Ga from"./bell-PM4Dlvdy.js";import sl from"./circle-user-Bw_JmhdZ.js";import tl from"./bell-off-l4DhCSx4.js";import{S as Pa}from"./skeleton-DeteYSVG.js";import{u as al,a as rl}from"./useLoyaltyTierPipeline-BdCwMkaJ.js";import{T as nl}from"./useTravelIntents-C3gbj_ce.js";import{P as il}from"./progress-D9JUmExy.js";import{s as ll,c as cl}from"./imageCompression-CsTnnJej.js";import Ya from"./camera-DZLHJJrO.js";import ol from"./filter-CISuoAgE.js";import{f as dl}from"./discoverySourceUtils-DFORsckX.js";import{A as ml,a as ul,b as hl,c as xl}from"./accordion-BJW4WjJ0.js";import Fa from"./user-x-B_gJbyNG.js";import Fn from"./circle-arrow-right-DI_7PTdT.js";import{C as pl}from"./country-select-DQoeHZf7.js";import{u as zn}from"./useTripChecklists-CWb8OMQw.js";import gl from"./link-BQbVvInt.js";import{u as fl}from"./useInsuranceCertificates-CIeT6ajq.js";import{u as jl}from"./useTripTemplates-fM87tAWi.js";import{H as _l}from"./HeroFocalPicker-D90YwjOp.js";import Nl from"./image-plus-ZGq0CE5w.js";import vl from"./message-circle-DVyFybcW.js";import qr from"./clipboard-check-DXFI4fZA.js";import{S as Ia}from"./separator-Dr0jxFDQ.js";import bl from"./file-x-i_ScuW5I.js";import{S as yl}from"./slider-B1ogpgvs.js";import{a as wl,p as kl,c as Cl,b as Rn,f as ea}from"./pricingScale-Bjo3CyEW.js";import Sl from"./calculator-xZLwNXhV.js";import Dl from"./arrow-right-BGRfRELI.js";import{R as El,C as Al,X as Pl,Y as Fl,T as zl,L as Rl,a as Mr,b as Gr}from"./generateCategoricalChart-DADrEZKC.js";import{C as Tl}from"./ComposedChart-Cf7rufdg.js";import $l from"./trending-down-C4uCiV9O.js";import Bl from"./arrow-left-D48T8wq1.js";import"./radix-core-kiNkrX5-.js";import"./file-pen-Dn43mabf.js";import"./index.esm-Bh8nfStt.js";import"./travelDnaArchetypes-DeJW1Mde.js";import"./index-DPntC_Uk.js";import"./image-Bf1C1SlN.js";import"./crosshair-DxihnmZN.js";import"./index-CQ81qIb6.js";const Na=["Deutschland","Österreich","Schweiz"];function Ll({value:s,onChange:n,placeholder:a="Land wählen",className:b}){const{countries:f,loading:i}=Wn(),[x,h]=t.useState(!1),c=t.useMemo(()=>{const C=f.filter(v=>Na.includes(v.name)),N=f.filter(v=>!Na.includes(v.name));return C.sort((v,G)=>Na.indexOf(v.name)-Na.indexOf(G.name)),{priority:C,others:N}},[f]),k=C=>{n(s===C?void 0:C),h(!1)};return e.jsxs(Dt,{open:x,onOpenChange:h,children:[e.jsx(Et,{asChild:!0,children:e.jsxs(z,{variant:"outline",role:"combobox","aria-expanded":x,className:Ms("w-full justify-between rounded-xl",b),disabled:i,children:[s||a,e.jsx(si,{className:"ml-2 h-4 w-4 shrink-0 opacity-50"})]})}),e.jsx(At,{className:"w-full min-w-[200px] p-0 z-50 bg-popover",align:"start",children:e.jsxs(Qn,{children:[e.jsx(Yn,{placeholder:"Land suchen..."}),e.jsxs(Jn,{children:[e.jsx(Xn,{children:"Kein Land gefunden."}),c.priority.length>0&&e.jsx(Fr,{children:c.priority.map(C=>e.jsxs(zr,{value:C.name,onSelect:()=>k(C.name),children:[e.jsx(tt,{className:Ms("mr-2 h-4 w-4",s===C.name?"opacity-100":"opacity-0")}),C.name]},C.id))}),c.priority.length>0&&c.others.length>0&&e.jsx(ei,{}),c.others.length>0&&e.jsx(Fr,{children:c.others.map(C=>e.jsxs(zr,{value:C.name,onSelect:()=>k(C.name),children:[e.jsx(tt,{className:Ms("mr-2 h-4 w-4",s===C.name?"opacity-100":"opacity-0")}),C.name]},C.id))})]})]})})]})}function ql({open:s,onOpenChange:n}
2){const a="Lisa",b="Safari im Okavango Delta",f="Botswana",N=`
3    <div style="max-width: 600px; margin: 0 auto; padding: 20px 10px;">
4      <div style="background: linear-gradient(135deg, #C9A227 0%, #8B7355 100%); border-radius: 16px 16px 0 0; padding: 30px 20px; text-align: center;">
5        <h1 style="color: #ffffff; margin: 0; font-size: 24px; font-weight: 700;">
6          🎉 Du bist dabei!
7        </h1>
8      </div>
9      
10      <div style="background-color: #ffffff; padding: 30px 20px; border-radius: 0 0 16px 16px; box-shadow: 0 4px 20px rgba(139, 115, 85, 0.15);">
11        <p style="font-size: 16px; color: #2D2A26; margin: 0 0 16px 0; line-height: 1.6;">
12          Hey ${a}! 🙌
13        </p>
14        
15        <p style="font-size: 14px; color: #5C5650; margin: 0 0 16px 0; line-height: 1.7;">
16          <strong>Großartige Neuigkeiten!</strong> Du wurdest für die Reise nach <strong style="color: #C9A227;">${f}</strong> angemeldet! 
17          Wir freuen uns riesig, dich bald auf diesem unvergesslichen Abenteuer dabei zu haben.
18        </p>
19        
20        <div style="background-color: #FAF6F1; border-radius: 12px; padding: 20px; margin: 20px 0; border: 1px solid #E8E0D5;">
21          <h2 style="color: #2D2A26; font-size: 14px; margin: 0 0 12px 0; text-transform: uppercase; letter-spacing: 1px;">
22            📋 Deine Reisedetails
23          </h2>
24          <table style="width: 100%; border-collapse: collapse;">
25            <tr>
26              <td style="padding: 6px 0; color: #8B7355; font-size: 13px;">Reise:</td>
27              <td style="padding: 6px 0; color: #2D2A26; font-size: 13px; font-weight: 600; text-align: right;">${b}</td>
28            </tr>
29            <tr>
30              <td style="padding: 6px 0; color: #8B7355; font-size: 13px;">Ziel:</td>
31              <td style="padding: 6px 0; color: #2D2A26; font-size: 13px; font-weight: 600; text-align: right;">${f}</td>
32            </tr>
33            <tr>
34              <td style="padding: 6px 0; color: #8B7355; font-size: 13px;">Zeitraum:</td>
35              <td style="padding: 6px 0; color: #2D2A26; font-size: 13px; font-weight: 600; text-align: right;">10. April 2026 - 17. April 2026</td>
36            </tr>
37          </table>
38        </div>
39
40        <h2 style="color: #2D2A26; font-size: 18px; margin: 24px 0 12px 0;">
41          🚀 So geht's weiter
42        </h2>
43        
44        <p style="font-size: 14px; color: #5C5650; margin: 0 0 16px 0; line-height: 1.7;">
45          In deinem persönlichen <strong>Reise-Portal</strong> findest du alles, was du für die Vorbereitung brauchst:
46        </p>
47        
48        <ul style="font-size: 13px; color: #5C5650; line-height: 2; padding-left: 20px; margin: 0 0 20px 0;">
49          <li>✏️ <strong>Reiseformulare</strong> (Passdaten, Ernährung, Notfallkontakt, etc.)</li>
50          <li>✈️ <strong>Flugdaten</strong> - sobald du sie hast</li>
51          <li>💬 <strong>WhatsApp-Gruppe</strong> zum Vernetzen mit der Gruppe</li>
52        </ul>
53        
54        <div style="background-color: #FEF9E7; border-left: 4px solid #C9A227; padding: 14px 16px; margin: 20px 0; border-radius: 0 8px 8px 0;">
55          <p style="font-size: 13px; color: #8B7355; margin: 0; line-height: 1.6;">
56            <strong style="color: #C9A227;">⏰ Keine Eile!</strong> Du kannst alles in deinem eigenen Tempo ausfüllen. 
57            Wichtig ist nur, dass bis spätestens <strong>10. Februar 2026</strong> alles vollständig ist.
58          </p>
59        </div>
60        
61        <div style="text-align: center; margin: 28px 0;">
62          <a href="#" style="display: inline-block; background: linear-gradient(135deg, #C9A227 0%, #A68B1F 100%); color: #ffffff; text-decoration: none; padding: 14px 32px; border-radius: 50px; font-weight: 600; font-size: 14px; box-shadow: 0 4px 15px rgba(201, 162, 39, 0.4);">
63            Zum Portal & Passwort erstellen
64          </a>
65        </div>
66        
67        <p style="font-size: 12px; color: #8B7355; text-align: center; margin: 0 0 20px 0;">
68          Klick auf den Button, um dein Passwort festzulegen!
69        </p>
70
71        <div style="background-color: #E8F5E9; border-radius: 12px; padding: 16px; margin: 24px 0; text-align: center; border: 1px solid #4A7C59;">
72          <p style="font-size: 13px; color: #4A7C59; margin: 0 0 10px 0;">
73            <strong>💬 Tritt unserer WhatsApp-Gruppe bei!</strong>
74          </p>
75          <a href="https://chat.whatsapp.com/example" style="display: inline-block; background-color: #4A7C59; color: #ffffff; text-decoration: none; padding: 10px 20px; border-radius: 25px; font-weight: 600; font-size: 13px;">
76            WhatsApp-Gruppe beitreten
77          </a>
78        </div>
79
80        <hr style="border: none; border-top: 1px solid #E8E0D5; margin: 24px 0;">
81        
82        <p style="font-size: 14px; color: #5C5650; margin: 0 0 8px 0; line-height: 1.7;">
83          Wir können es kaum erwarten, dieses Abenteuer mit dir zu erleben! 🌍✨
84        </p>
85        
86        <p style="font-size: 14px; color: #5C5650; margin: 0; line-height: 1.7;">
87          Liebe Grüße,<br>
88          <strong style="color: #C9A227;">Dein Off The Path Team</strong>
89        </p>
90      </div>
91      
92      <div style="text-align: center; padding: 16px; color: #8B7355; font-size: 11px;">
93        <p style="margin: 0;">
94          Diese E-Mail wurde automatisch versendet. Bei Fragen antworte einfach auf diese Mail.
95        </p>
96      </div>
97    </div>
98  `;return e.jsx(We,{open:s,onOpenChange:n,children:e.jsxs(Qe,{className:"max-h-[90vh] max-w-2xl overflow-y-auto",children:[e.jsx(Ye,{children:e.jsxs("div",{className:"flex items-center gap-3",children:[e.jsx("div",{className:"flex h-10 w-10 items-center justify-center rounded-lg bg-primary/10",children:e.jsx(Ns,{className:"h-5 w-5 text-primary"})}),e.jsxs("div",{children:[e.jsx(Je,{children:"E-Mail Vorschau: Mitreisende"}),e.jsx(Ds,{children:"Diese E-Mail wird an Mitreisende mit E-Mail-Adresse gesendet 
98(ohne Preis/Buchungsnummer)"})]})]})}),e.jsxs("div",{className:"mt-4 space-y-4",children:[e.jsx("div",{className:"rounded-lg border bg-muted/30 p-4",children:e.jsxs("div",{className:"space-y-2",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx("span",{className:"text-sm font-medium text-muted-foreground",children:"An:"}),e.jsx("span",{className:"text-sm",children:"[email protected]"})]}),e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx("span",{className:"text-sm font-medium text-muted-foreground",children:"Betreff:"}),e.jsx("span",{className:"text-sm font-medium",children:"🎉 Du bist dabei: Safari im Okavango Delta"})]})]})}),e.jsx("div",{className:"rounded-lg border bg-[#FAF6F1] overflow-hidden",dangerouslySetInnerHTML:{__html:In.sanitize(N)}}),e.jsx("div",{className:"flex items-center justify-center gap-2 text-center",children:e.jsx(Xe,{variant:"outline",className:"text-xs",children:"Vorschau mit Beispieldaten"})})]})]})})}function na(s){const[n,a]=t.useState([]),[b,f]=t.useState([]),[i,x]=t.useState([]),[h,c]=t.useState([]),[k,C]=t.useState([]),[N,v]=t.useState(!0),[G,T]=t.useState(null),o=t.useCallback(async()=>{v(!0),T(null);try{let g=_.from("bookings").select("*").order("created_at",{ascending:!1});s&&(g=g.eq("trip_id",s));const{data:r,error:m}=await g;if(m)throw m;a(r||[]);const X=r.filter(ne=>ne.status!=="cancelled").map(ne=>ne.id),p=!!s;if(X.length>0||p){let ne=_.from("participants").select("*, wilderness_certificate_url").eq("is_guide",!1);const le=[];X.length>0&&le.push(`booking_id.in.(${X.join(",")})`),p&&le.push(`and(booking_id.is.null,trip_id.eq.${s})`),ne=ne.or(le.join(","));const{data:K,error:M}=await ne;if(M)throw M;const ee=K||[],he=[...new Set(ee.map(qe=>qe.profile_id).filter(Boolean))];if(he.length>0){const{data:qe}=await _.from("participant_profiles").select("id, first_name, last_name, email, phone, date_of_birth, passport_number, dietary_requirements, allergies, emergency_contact, pre_existing_conditions, profile_image, static_questionnaire_data, total_nights_stayed, loyalty_points, loyalty_last_activity, referral_count, billing_street, billing_city, billing_postal_code, billing_country").in("id",he),Be=new Map((qe||[]).map(Ce=>[Ce.id,{first_name:Ce.first_name,last_name:Ce.last_name,email:Ce.email,phone:Ce.phone,date_of_birth:Ce.date_of_birth,passport_number:Ce.passport_number,dietary_requirements:Ce.dietary_requirements,allergies:Ce.allergies,emergency_contact:Ce.emergency_contact,pre_existing_conditions:Ce.pre_existing_conditions,profile_image:Ce.profile_image,static_questionnaire_data:Ce.static_questionnaire_data,total_nights_stayed:Ce.total_nights_stayed,loyalty_points:Ce.loyalty_points,loyalty_last_activity:Ce.loyalty_last_activity,referral_count:Ce.referral_count,billing_street:Ce.billing_street,billing_city:Ce.billing_city,billing_postal_code:Ce.billing_postal_code,billing_country:Ce.billing_country}])),Ke=ee.map(Ce=>{var ms;const xe=Ce.profile_id?Be.get(Ce.profile_id):null;return{...Ce,first_name:(xe==null?void 0:xe.first_name)||Ce.first_name,last_name:(xe==null?void 0:xe.last_name)||Ce.last_name,email:(xe==null?void 0:xe.email)||Ce.email,phone:(xe==null?void 0:xe.phone)||Ce.phone,date_of_birth:(xe==null?void 0:xe.date_of_birth)||Ce.date_of_birth,passport_number:(xe==null?void 0:xe.passport_number)||Ce.passport_number,dietary_requirements:(xe==null?void 0:xe.dietary_requirements)||Ce.dietary_requirements,allergies:(xe==null?void 0:xe.allergies)||Ce.allergies,emergency_contact:(xe==null?void 0:xe.emergency_contact)||Ce.emergency_contact,pre_existing_conditions:(xe==null?void 0:xe.pre_existing_conditions)||null,profile_image:(xe==null?void 0:xe.profile_image)||null,document_expiry_date:((ms=xe==null?void 0:xe.static_questionnaire_data)==null?void 0:ms.Ablaufdatum)||null,static_questionnaire_data:(xe==null?void 0:xe.static_questionnaire_data)||null,wilderness_certificate_url:Ce.wilderness_certificate_url||null,total_nights_stayed:(xe==null?void 0:xe.total_nights_stayed)??Ce.total_nights_stayed??0,loyalty_points:(xe==null?void 0:xe.loyalty_points)??Ce.loyalty_points??0,loyalty_last_activity:(xe==null?void 0:xe.loyalty_last_activity)||Ce.loyalty_last_activity,referral_count:(xe==null?void 0:xe.referral_count)??Ce.referral_count??0,billing_street:(xe==null?void 0:xe.billing_street)||null,billing_city:(xe==null?void 0:xe.billing_city)||null,billing_postal_code:(xe==null?void 0:xe.billing_postal_code)||null,billing_country:(xe==null?void 0:xe.billing_country)||null}});f(Ke)}else f(ee.map(qe=>({...qe,profile_image:null,document_expiry_date:null,pre_existing_conditions:null,wilderness_certificate_url:qe.wilderness_certificate_url||null})));const we=r.map(qe=>qe.id),{data:De,error:_e}=await _.from("booking_documents").select("*").in("booking_id",we);
98if(_e)throw _e;c(De||[]);const{data:J,error:Ae}=await _.from("payments").select("*").in("booking_id",we).order("payment_date",{ascending:!0});if(Ae)throw Ae;C(J||[])}else f([]);if(s){const{data:ne,error:le}=await _.from("participants").select("*, wilderness_certificate_url").eq("trip_id",s).eq("is_guide",!0);if(le)throw le;const K=ne||[],M=[...new Set(K.map(_e=>_e.profile_id).filter(Boolean))];let ee=new Map;if(M.length>0){const{data:_e}=await _.from("participant_profiles").select("id, first_name, last_name, email, phone, date_of_birth, passport_number, dietary_requirements, allergies, emergency_contact, pre_existing_conditions, profile_image, static_questionnaire_data, billing_street, billing_city, billing_postal_code, billing_country").in("id",M);ee=new Map((_e||[]).map(J=>[J.id,{first_name:J.first_name,last_name:J.last_name,email:J.email,phone:J.phone,date_of_birth:J.date_of_birth,passport_number:J.passport_number,dietary_requirements:J.dietary_requirements,allergies:J.allergies,emergency_contact:J.emergency_contact,pre_existing_conditions:J.pre_existing_conditions,profile_image:J.profile_image,static_questionnaire_data:J.static_questionnaire_data,billing_street:J.billing_street,billing_city:J.billing_city,billing_postal_code:J.billing_postal_code,billing_country:J.billing_country}]))}const he=K.filter(_e=>!_e.profile_id);let we=new Map;if(he.length>0){const{data:_e}=await _.from("participant_profiles").select("first_name, last_name, profile_image");(_e||[]).forEach(J=>{const Ae=`${J.first_name}|${J.last_name}`;J.profile_image&&we.set(Ae,{profile_image:J.profile_image})})}const De=K.map(_e=>{var qe,Be;const J=_e.profile_id?ee.get(_e.profile_id):null;let Ae=(J==null?void 0:J.profile_image)||null;return Ae||(Ae=((qe=we.get(`${_e.first_name}|${_e.last_name}`))==null?void 0:qe.profile_image)||null),{..._e,first_name:(J==null?void 0:J.first_name)||_e.first_name,last_name:(J==null?void 0:J.last_name)||_e.last_name,email:(J==null?void 0:J.email)||_e.email,phone:(J==null?void 0:J.phone)||_e.phone,date_of_birth:(J==null?void 0:J.date_of_birth)||_e.date_of_birth,passport_number:(J==null?void 0:J.passport_number)||_e.passport_number,dietary_requirements:(J==null?void 0:J.dietary_requirements)||_e.dietary_requirements,allergies:(J==null?void 0:J.allergies)||_e.allergies,emergency_contact:(J==null?void 0:J.emergency_contact)||_e.emergency_contact,pre_existing_conditions:(J==null?void 0:J.pre_existing_conditions)||null,profile_image:Ae,document_expiry_date:((Be=J==null?void 0:J.static_questionnaire_data)==null?void 0:Be.Ablaufdatum)||null,static_questionnaire_data:(J==null?void 0:J.static_questionnaire_data)||null,wilderness_certificate_url:_e.wilderness_certificate_url||null,billing_street:(J==null?void 0:J.billing_street)||null,billing_city:(J==null?void 0:J.billing_city)||null,billing_postal_code:(J==null?void 0:J.billing_postal_code)||null,billing_country:(J==null?void 0:J.billing_country)||null}});x(De)}}catch(g){console.error("Error fetching bookings:",g),T("Fehler beim Laden der Buchungen. Bitte versuche es erneut.")}finally{v(!1)}},[s]);return t.useEffect(()=>{o()},[o]),{bookings:n,participants:b,guides:i,documents:h,payments:k,isLoading:N,error:G,fetchBookings:o,cancelBooking:async(g,r,m,X)=>{try{const p=n.find(K=>K.id===g),{error:ne}=await _.from("bookings").update({status:"cancelled",cancelled_at:new Date().toISOString(),cancellation_reason:r||null,cancellation_fee:m,refund_amount:X}).eq("id",g);if(ne)throw ne;a(K=>K.map(M=>M.id===g?{...M,status:"cancelled",cancelled_at:new Date().toISOString(),cancellation_reason:r||null,cancellation_fee:m,refund_amount:X}:M)),f(K=>K.filter(M=>M.booking_id!==g));let le=!1;if(p){const{data:K,error:M}=await _.from("trips").select("name, destination, start_date, end_date").eq("id",p.trip_id).maybeSingle();if(M||!K)console.error("Error loading trip data for cancellation email:",M||new Error("Trip not found"));else{const{error:ee}=await _.functions.invoke("send-cancellation-confirmation",{body:{bookingId:g,customerEmail:p.customer_email,customerName:p.customer_name,tripName:K.name,tripDestination:K.destination,tripStartDate:K.start_date,tripEndDate:K.end_date,cancellationFee:m,paidAmount:p.paid_amount,totalAmount:p.total_amount}});
98ee?console.error("Error sending cancellation email:",ee):le=!0}}else console.error("Could not send cancellation email: booking not found in local state",{bookingId:g});if(p!=null&&p.trip_id&&(p==null?void 0:p.participant_count)>0)try{const{data:K}=await _.from("trip_waitlist").select("id").eq("trip_id",p.trip_id).eq("status","waiting").limit(1);if(K&&K.length>0){console.log(`Found waitlist entries for trip ${p.trip_id}, notifying...`);const{error:M}=await _.functions.invoke("notify-waitlist-available",{body:{tripId:p.trip_id,freedSpots:p.participant_count}});M?console.error("Error notifying waitlist:",M):Y.success("Warteliste wurde benachrichtigt")}}catch(K){console.error("Error checking/notifying waitlist:",K)}return Y.success("Buchung storniert",{description:le?`Stornierungsbestätigung wurde an ${p==null?void 0:p.customer_email} gesendet.`:"Stornierung erfolgreich, aber E-Mail konnte nicht gesendet werden."}),!0}catch(p){return console.error("Error cancelling booking:",p),Y.error("Fehler beim Stornieren",{description:"Bitte versuche es erneut."}),!1}},updateCancellation:async(g,r)=>{try{const m=n.find(le=>le.id===g);if(!m)throw new Error("Buchung nicht gefunden");const X=Math.max(0,m.paid_amount-r.cancellationFee),p={cancellation_fee:r.cancellationFee,cancellation_reason:r.cancellationReason||null,refund_amount:X};r.cancelledAt&&(p.cancelled_at=r.cancelledAt);const{error:ne}=await _.from("bookings").update(p).eq("id",g);if(ne)throw ne;return a(le=>le.map(K=>K.id===g?{...K,...p}:K)),Y.success("Stornierung aktualisiert"),!0}catch(m){return console.error("Error updating cancellation:",m),Y.error("Fehler beim Aktualisieren",{description:m==null?void 0:m.message}),!1}},createBooking:async g=>{try{const{data:r,error:m}=await _.from("bookings").insert(g).select().single();if(m)throw m;return a(X=>[r,...X]),Y.success("Buchung erstellt"),r}catch(r){return console.error("Error creating booking:",r),Y.error("Fehler beim Erstellen",{description:"Bitte versuche es erneut."}),null}},updateBooking:async(g,r)=>{try{const{error:m}=await _.from("bookings").update(r).eq("id",g);if(m)throw m;return a(X=>X.map(p=>p.id===g?{...p,...r}:p)),Y.success("Buchung aktualisiert"),!0}catch(m){return console.error("Error updating booking:",m),Y.error("Fehler beim Aktualisieren",{description:"Bitte versuche es erneut."}),!1}},deleteBooking:async g=>{try{const{error:r}=await _.from("participants").delete().eq("booking_id",g);if(r)throw r;const{error:m}=await _.from("payments").delete().eq("booking_id",g);if(m)throw m;const{error:X}=await _.from("booking_documents").delete().eq("booking_id",g);if(X)throw X;const{error:p}=await _.from("bookings").delete().eq("id",g);if(p)throw p;return a(ne=>ne.filter(le=>le.id!==g)),f(ne=>ne.filter(le=>
98le.booking_id!==g)),C(ne=>ne.filter(le=>le.booking_id!==g)),c(ne=>ne.filter(le=>le.booking_id!==g)),Y.success("Buchung gelöscht"),!0}catch(r){return console.error("Error deleting booking:",r),Y.error("Fehler beim Löschen",{description:"Bitte versuche es erneut."}),!1}},addPayment:async(g,r,m,X)=>{const p=n.find(ne=>ne.id===g);if(!p)return!1;try{const{data:ne,error:le}=await _.from("payments").insert({booking_id:g,amount:r,payment_date:m,notes:X||null}).select().single();if(le)throw le;const K=p.paid_amount+r,{error:M}=await _.from("bookings").update({paid_amount:K}).eq("id",g);if(M)throw M;return C(ee=>[...ee,ne]),a(ee=>ee.map(he=>he.id===g?{...he,paid_amount:K}:he)),Y.success("Zahlung erfasst"),!0}catch(ne){return console.error("Error adding payment:",ne),Y.error("Fehler beim Erfassen",{description:"Bitte versuche es erneut."}),!1}},updatePayment:async(g,r)=>{const m=k.find(X=>X.id===g);if(!m)return!1;try{const{error:X}=await _.from("payments").update(r).eq("id",g);if(X)throw X;if(r.amount!==void 0&&r.amount!==m.amount){const p=n.find(ne=>ne.id===m.booking_id);if(p){const ne=r.amount-m.amount,le=p.paid_amount+ne;await _.from("bookings").update({paid_amount:le}).eq("id",m.booking_id),a(K=>K.map(M=>M.id===m.booking_id?{...M,paid_amount:le}:M))}}return C(p=>p.map(ne=>ne.id===g?{...ne,...r}:ne)),Y.success("Zahlung aktualisiert"),!0}catch(X){return console.error("Error updating payment:",X),Y.error("Fehler beim Aktualisieren",{description:"Bitte versuche es erneut."}),!1}},deletePayment:async g=>{const r=k.find(m=>m.id===g);if(!r)return!1;try{const{error:m}=await _.from("payments").delete().eq("id",g);if(m)throw m;const X=n.find(p=>p.id===r.booking_id);if(X){const p=X.paid_amount-r.amount;await _.from("bookings").update({paid_amount:p}).eq("id",r.booking_id),a(ne=>ne.map(le=>le.id===r.booking_id?{...le,paid_amount:p}:le))}return C(p=>p.filter(ne=>ne.id!==g)),Y.success("Zahlung gelöscht"),!0}catch(m){return console.error("Error deleting payment:",m),Y.error("Fehler beim Löschen",{description:"Bitte versuche es erneut."}),!1}},uploadDocument:async(g,r,m)=>{try{const X=r.name.split(".").pop(),p=`${g}/${m}-${Date.now()}.${X}`,{error:ne}=await _.storage.from("booking-documents").upload(p,r);if(ne)throw ne;const{data:le,error:K}=await _.from("booking_documents").insert({booking_id:g,name:r.name,type:m,url:p}).select().single();if(K)throw K;c(M=>[...M,le]);try{const M=[...h,le].filter(we=>we.booking_id===g),ee=M.some(we=>we.type==="invoice"),he=M.some(we=>we.type==="confirmation");if(ee&&he){const{data:we}=await _.from("bookings").select("documents_notified_at").eq("id",g).single();we&&!we.documents_notified_at&&(console.log("Both documents ready, sending customer notification..."),await _.functions.invoke("send-documents-ready",{body:{bookingId:g}}))}}catch(M){console.error("Failed to check/send documents-ready notification:",M)}return Y.success("Dokument hochgeladen"),!0}catch(X){return console.error("Error uploading document:",X),Y.error("Fehler beim Hochladen",{description:"Bitte versuche es erneut."}),!1}},deleteDocument:async g=>{try{const r=h.find(X=>X.id===g);if(r){const X=r.url.split("/booking-documents/");X[1]&&await _.storage.from("booking-documents").remove([X[1]])}const{error:m}=await _.from("booking_documents").delete().eq("id",g);if(m)throw m;return c(X=>X.filter(p=>p.id!==g)),Y.success("Dokument gelöscht"),!0}catch(r){return console.error("Error deleting document:",r),Y.error("Fehler beim Löschen",{description:"Bitte versuche es erneut."}),!1}},getParticipantsForBooking:g=>b.filter(r=>r.booking_id===g),getDocumentsForBooking:g=>h.filter(r=>r.booking_id===g),getPaymentsForBooking:g=>k.filter(r=>r.booking_id===g),updateParticipant:async(g,r)=>{try{const{error:m}=await _.from("participants").update(r).eq("id",g);if(m)throw m;return i.some(p=>p.id===g)?x(p=>p.map(ne=>ne.id===g?{...ne,...r}:ne)):f(p=>p.map(ne=>ne.id===g?{...ne,...r}:ne)),!0}catch(m){return console.error("Error updating participant:",m),Y.error("Fehler beim Aktualisieren",{description:"Bitte versuche es erneut."}),!1}},createGuide:async(g,r)=>{try{let m=null;if(r.email){const{data:le}=await _.from("participant_profiles").select("id").eq("email",r.email).eq("is_guide",!0).maybeSingle();le&&(m=le.id)}if(!m){const{data:le,error:K}
98=await _.from("participant_profiles").insert({first_name:r.first_name,last_name:r.last_name,email:r.email||null,phone:r.phone||null,is_guide:!0}).select().single();if(K)throw K;m=le.id}const{data:X}=await _.from("participants").select("id").eq("profile_id",m).eq("trip_id",g).eq("is_guide",!0).maybeSingle();if(X)return Y.info("Guide ist bereits dieser Reise zugewiesen"),await o(),i.find(le=>le.id===X.id)||null;const{data:p,error:ne}=await _.from("participants").insert({trip_id:g,is_guide:!0,first_name:r.first_name,last_name:r.last_name,email:r.email||null,phone:r.phone||null,profile_id:m,questionnaire_status:"pending",questionnaire_progress:0}).select().single();if(ne)throw ne;return x(le=>[...le,p]),Y.success("Guide hinzugefügt"),p}catch(m){return console.error("Error creating guide:",m),Y.error("Fehler beim Erstellen",{description:"Bitte versuche es erneut."}),null}},assignExistingGuide:async(g,r)=>{try{const{data:m,error:X}=await _.from("participants").insert({trip_id:g,is_guide:!0,first_name:r.first_name,last_name:r.last_name,email:r.email||null,phone:r.phone||null,profile_id:r.profile_id||null,questionnaire_status:"pending",questionnaire_progress:0}).select().single();if(X)throw X;return x(p=>[...p,m]),Y.success("Guide zur Reise hinzugefügt"),m}catch(m){return console.error("Error assigning guide:",m),Y.error("Fehler beim Zuweisen",{description:"Bitte versuche es erneut."}),null}},deleteGuide:async g=>{try{const{error:r}=await _.from("participants").delete().eq("id",g);if(r)throw r;return x(m=>m.filter(X=>X.id!==g)),Y.success("Guide entfernt"),!0}catch(r){return console.error("Error deleting guide:",r),Y.error("Fehler beim Löschen",{description:"Bitte versuche es erneut."}),!1}}}}function Ml({bookingId:s,tripId:n,participantProfileIds:a,onReferralChanged:b}){const[f,i]=t.useState([]),[x,h]=t.useState([]),[c,k]=t.useState(!0),[C,N]=t.useState(!1),[v,G]=t.useState(""),[T,o]=t.useState(!1);t.useEffect(()=>{l()},[s,a]);const l=async()=>{k(!0);try{const{data:y}=await _.from("participant_profiles").select("id, first_name, last_name, email, loyalty_points").order("last_name");if(y){const W=y.filter(j=>!a.includes(j.id));i(W)}if(a.length>0){const{data:W}=await _.from("referrals").select(`
99            id,
100            referrer_profile_id,
101            status,
102            points_awarded,
103            referrer:participant_profiles!referrals_referrer_profile_id_fkey (
104              first_name,
105              last_name
106            )
107          `).in("referred_profile_id",a).eq("booking_id",s);W&&h(W)}}catch(y){console.error("Error fetching referral data:",y)}finally{k(!1)}},V=async()=>{if(!(!v||a.length===0)){o(!0);try{const y=a.map(j=>({referrer_profile_id:v,referred_profile_id:j,booking_id:s,trip_id:n,status:"pending",points_awarded:0})),{error:W}=await _.from("referrals").insert(y);if(W)throw W;Y.success("Empfehlung zugewiesen",{description:`${a.length} Empfehlung(en) wurden erstellt.`}),N(!1),G(""),l(),b==null||b()}catch(y){console.error("Error creating referrals:",y),Y.error("Fehler beim Erstellen der Empfehlung")}finally{o(!1)}}},A=async y=>{try{const{error:W}=await _.from("referrals").delete().eq("id",y);if(W)throw W;Y.success("Empfehlung entfernt"),l(),b==null||b()}catch(W){console.error("Error removing referral:",W),Y.error("Fehler beim Entfernen der Empfehlung")}},q=async(y,W)=>{o(!0);try{const{error:j}=await _.from("referrals").update({status:"completed",points_awarded:100,points_awarded_at:new Date().toISOString()}).eq("id",y);if(j)throw j;const{data:d}=await _.from("participant_profiles").select("loyalty_points, referral_count").eq("id",W).single();d&&await _.from("participant_profiles").update({loyalty_points:(d.loyalty_points||0)+100,referral_count:(d.referral_count||0)+1,loyalty_last_activity:new Date().toISOString()}).eq("id",W),Y.success("100 Punkte vergeben",{description:"Die Empfehlungspunkte wurden gutgeschrieben."}),l(),b==null||b()}catch(j){console.error("Error completing referral:",j),Y.error("Fehler beim Vergeben der Punkte")}finally{o(!1)}};return c?e.jsxs("div",{className:"flex items-center gap-2 text-muted-foreground text-sm",children:[e.jsx($e,{className:"h-4 w-4 animate-spin"}),"Laden..."]}):e.jsxs(e.Fragment,{children:[e.jsx(We,{open:C,onOpenChange:N,children:e.jsxs(Qe,{className:"max-w-md",children:[e.jsxs(Ye,{children:[e.jsxs(Je,{className:"flex items-center gap-2",children:[e.jsx(Ot,{className:"h-5 w-5 text-primary"}),"Empfehlung zuweisen"]}),e.jsx(Ds,{children:"Wählen Sie die Person, die diese Buchung empfohlen hat. Für jeden Teilnehmer wird eine Empfehlung erstellt."})]}),e.jsxs("div",{className:"py-4 space-y-4",children:[e.jsxs("div",{className:"space-y-2",children:[e.jsx("label",{className:"text-sm font-medium",children:"Empfohlen von"}),e.jsxs(Ie,{value:v,onValueChange:G,children:[e.jsx(Oe,{children:e.jsx(Ve,{placeholder:"Profil auswählen..."})}),e.jsx(Ue,{children:f.map(y=>e.jsx(O,{value:y.id,children:e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsxs("span",{children:[y.first_name," ",y.last_name]}),y.email&&e.jsxs("span",{className:"text-muted-foreground text-xs",children:["(",y.email,")"]})]})},y.id))})]})]}),e.jsx("div",{className:"rounded-lg bg-muted/30 p-3 text-sm",children:e.jsxs("p",{className:"text-muted-foreground",children:[e.jsx("strong",{children:a.length})," Empfehlung(en) werden erstellt. Der Empfehler erhält ",e.jsx("strong",{children:"100 Punkte pro Teilnehmer"})," bei Reiseantritt."]})})]}),e.jsxs(gs,{children:[e.jsx(z,{variant:"outline",onClick:()=>N(!1),children:"Abbrechen"}),e.jsx(z,{onClick:V,disabled:!v||T,children:T?"Speichere...":"Empfehlung erstellen"})]})]})}),e.jsxs("div",{className:"space-y-3",children:[e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsxs("div",{className:"flex items-center gap-2 text-sm font-medium",children:[e.jsx(Ot,{className:"h-4 w-4 text-primary"}),"Empfehlung"]}),x.length===0&&a.length>0&&e.jsxs(z,{variant:"outline",size:"sm",onClick:()=>N(!0),className:"h-7 text-xs",children:[e.jsx(Ns,{className:"h-3 w-3 mr-1"}),"Zuweisen"]})]}),x.length>0?e.jsx("div",{className:"space-y-2",children:x.map(y=>e.jsxs("div",{className:`flex items-center justify-between p-2 rounded-lg border text-sm ${y.status==="completed"?"bg-green-50 dark:bg-green-900/20 border-green-200 dark:border-green-800":"bg-amber-50 dark:bg-amber-900/20 border-amber-200 dark:border-amber-800"}`,children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsxs("span",{className:"font-medium",children:[y.referrer.first_name," ",y.referrer.last_name]}),e.jsx(Xe,{variant:y.status==="completed"?"default":"outline",className:y.status==="completed"?"bg-green-600 text-xs":"border-amber-400 text-amber-700 text-xs",children:y.status==="completed"?`+${y.points_awarded} Punkte`:"Ausstehend"})]}),e.jsxs("div",{className:"flex items-center gap-1",children:[y.status==="pending"&&e.jsx(z,{variant:"ghost",size:"icon",className:"h-7 w-7 text-green-600 hover:text-green-700 hover:bg-green-100",onClick:()=>q(y.id,y.referrer_profile_id),disabled:T,title:"Punkte vergeben",children:e.jsx(tt,{className:"h-4 w-4"})}),e.jsx(z,{variant:"ghost",size:"icon",className:"h-7 w-7 text-destructive hover:text-destructive hover:bg-destructive/10",onClick:()=>A(y.id),title:"Empfehlung entfernen",children:e.jsx(er,{className:"h-4 w-4"})})]})]},y.id))}):e.jsx("p",{className:"text-sm text-muted-foreground",children:"Keine Empfehlung zugewiesen"})]})]})}function Gl({value:s,onSave:n}){const[a,b]=t.useState(!1),[f,i]=t.useState(s.toString()),x=k=>new Intl.NumberFormat("de-DE",{style:"currency",currency:"EUR"}).format(k),h=()=>{const k=parseFloat(f.replace(",","."));!isNaN(k)&&k>=0&&(n(k),b(!1))},c=k=>{k.key==="Enter"?h():k.key==="Escape"&&(i(s.toString()),b(!1))};return a?e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(te,{type:"text",value:f,onChange:k=>i(k.target.value),onBlur:h,onKeyDown:c,className:"w-28 h-7 text-right text-sm font-semibold",autoFocus:!0}),e.jsx("span",{className:"text-muted-foreground text-sm",children:"€"})]}):e.jsxs("div",{className:"flex items-center gap-1.5",children:[e.jsx("span",{className:"font-semibold text-foreground",children:x(s)}),e.jsx("button",{onClick:()=>{i(s.toString()),b(!0)},className:"opacity-0 group-hover:opacity-100 transition-opacity p-1 hover:bg-muted rounded",children:e.jsx(vt,{className:"h-3.5 w-3.5 text-muted-foreground"})})]})}function Il({tripId:s}){const[n,a]=t.useState(""),[b,f]=t.useState(null),[i,x]=t.useState(!1),[h,c]=t.useState(!1),[k,C]=t.useState({customer_first_name:"",customer_last_name:"",customer_email:"",customer_phone:"",participant_count:1,price_per_person:0,deposit:0,first_installment_due:null,last_installment_due:null}),[N,v]=t.useState([]),[G,T]=t.useState(null),[o,l]=t.useState([]),[V,A]=t.useState(""),[q,y]=t.useState(!1),[W,j]=t.useState(!1),[d,u]=t.useState(""),[I,E]=t.useState(!1),[$,ge]=t.useState(null);t.useEffect(()=>{(async()=>{const{data:ue}=await _.from("participant_profiles").select("id, first_name, last_name, email, phone, discount_used_at, loyalty_points").order("last_name");ue&&l(ue.map(de=>({id:de.id,first_name:de.first_name,last_name:de.last_name,email:de.email,phone:de.phone,discount_used_at:de.discount_used_at,loyalty_points:de.loyalty_points})))})()},[]);const{trips:be}=nr(),Z=be.find(Q=>Q.id===s),{bookings:H,isLoading:L,cancelBooking:g,updateCancellation:r,createBooking:m,updateBooking:X,deleteBooking:p,addPayment:ne,updatePayment:le,deletePayment:K,uploadDocument:M,deleteDocument:ee,getParticipantsForBooking:he,getDocumentsForBooking:we,getPaymentsForBooking:De,updateParticipant:_e}=na(s),J=H.filter(Q=>Q.customer_name.toLowerCase().includes(n.toLowerCase())).sort((Q,ue)=>
107Q.status==="cancelled"&&ue.status!=="cancelled"?1:Q.status!=="cancelled"&&ue.status==="cancelled"?-1:new Date(ue.created_at).getTime()-new Date(Q.created_at).getTime()),Ae=(Q,ue)=>{const de=Wa(Q,14);let S=null;return ue&&(S=di(He(ue),3),S<=de&&(S=Wa(de,30))),{firstInstallment:de,lastInstallment:S}};t.useEffect(()=>{if(i&&(Z!=null&&Z.startDate)){const Q=new Date,{firstInstallment:ue,lastInstallment:de}=Ae(Q,Z.startDate);C(S=>({...S,first_installment_due:ue,last_installment_due:de}))}},[i,Z==null?void 0:Z.startDate]);const qe=()=>{C({customer_first_name:"",customer_last_name:"",customer_email:"",customer_phone:"",participant_count:1,price_per_person:0,deposit:0,first_installment_due:null,last_installment_due:null}),v([]),T(null),y(!1),A(""),u(""),E(!1),ge(null)},Be=d.length>=2?o.filter(Q=>`${Q.first_name} ${Q.last_name}`.toLowerCase().includes(d.toLowerCase())||Q.email&&Q.email.toLowerCase().includes(d.toLowerCase())).slice(0,5):[],Ke=Q=>{C({...k,customer_first_name:Q.first_name,customer_last_name:Q.last_name,customer_email:Q.email||"",customer_phone:Q.phone||""}),ge({id:Q.id,discount_used_at:Q.discount_used_at||null,loyalty_points:Q.loyalty_points||0}),u(""),E(!1)},Ce=Q=>{const ue=Math.max(1,Q);C({...k,participant_count:ue});const de=ue-1;if(de>N.length){const S=[...N];for(let P=N.length;P<de;P++)S.push({first_name:"",last_name:"",email:""});v(S)}else de<N.length&&v(N.slice(0,de))},xe=(Q,ue,de)=>{const S=[...N];S[Q]={...S[Q],[ue]:de},v(S)},ms=async()=>{if(!k.customer_first_name||!k.customer_last_name||!k.customer_email||!s)return;if(!N.every(S=>S.first_name&&S.last_name)){Y.error("Bitte füllen Sie alle Teilnehmernamen aus");return}c(!0);const ue=`${k.customer_first_name} ${k.customer_last_name}`,de=await m({trip_id:s,customer_name:ue,customer_email:k.customer_email,customer_phone:k.customer_phone||null,billing_address:null,billing_street:null,billing_postal_code:null,billing_city:null,billing_country:null,participant_count:k.participant_count,total_amount:k.price_per_person*k.participant_count,deposit:k.deposit,paid_amount:0,booking_date:fs(new Date,"yyyy-MM-dd"),first_installment_due:k.first_installment_due?fs(k.first_installment_due,"yyyy-MM-dd"):null,last_installment_due:k.last_installment_due?fs(k.last_installment_due,"yyyy-MM-dd"):null,payment_method:null,insurance_certificate_id:null});if(de){const S=[{first_name:k.customer_first_name,last_name:k.customer_last_name,email:k.customer_email,phone:k.customer_phone||null},...N.map(R=>({first_name:R.first_name,last_name:R.last_name,email:R.email||null,phone:null}))],P=[];for(const R of S){let ce=null;if(R.email){const{data:me}=await _.from("participant_profiles").select("id").ilike("email",R.email).maybeSingle();if(me)ce=me.id;else{const{data:Ee}=await _.from("participant_profiles").insert({first_name:R.first_name,last_name:R.last_name,email:R.email,phone:R.phone}).select("id").single();Ee&&(ce=Ee.id)}}else{const{data:me}=await _.from("participant_profiles").insert({first_name:R.first_name,last_name:R.last_name}).select("id").single();me&&(ce=me.id)}const{data:oe}=await _.from("participants").insert({booking_id:de.id,trip_id:s,first_name:R.first_name,last_name:R.last_name,email:R.email,profile_id:ce}).select("id, profile_id").single();oe!=null&&oe.profile_id&&P.push(oe.profile_id)}if(G&&P.length>0){for(const R of P){const{error:ce}=await _.from("referrals").insert({referrer_profile_id:G,referred_profile_id:R,trip_id:s,booking_id:de.id,status:"pending",points_awarded:0});if(!ce&&R===P[0])try{await _.functions.invoke("notify-referral-success",{body:{referrer_profile_id:G,referred_first_name:k.customer_first_name,referred_last_name:k.customer_last_name,trip_name:(Z==null?void 0:Z.name)||"Unbekannte Reise"}})}catch(oe){console.error("Failed to send referral notification:",oe)}}Y.success(`${P.length} Empfehlung(en) erstellt`)}try{const R=k.price_per_person*k.participant_count,{error:ce}=await _.functions.invoke("send-booking-confirmation",{body:{bookingId:de.id,customerEmail:k.customer_email,customerFirstName:k.customer_first_name,customerLastName:k.customer_last_name,tripName:(Z==null?void 0:Z.name)||"Unbekannte Re
107ise",tripDestination:(Z==null?void 0:Z.destination)||"Unbekannt",tripStartDate:(Z==null?void 0:Z.startDate)||"",tripEndDate:(Z==null?void 0:Z.endDate)||"",participantCount:k.participant_count,totalAmount:R,whatsappGroupLink:(Z==null?void 0:Z.whatsappGroupLink)||null}});ce?(console.error("Failed to send confirmation email:",ce),Y.warning("Buchung erstellt, aber E-Mail an Hauptbucher konnte nicht gesendet werden")):Y.success("Buchungsbestätigung an Hauptbucher gesendet")}catch(R){console.error("Email sending error:",R)}const ie=[k.customer_email,...N.filter(R=>{var ce;return(ce=R.email)==null?void 0:ce.trim()}).map(R=>R.email.trim())].filter(Boolean);for(const R of ie)try{await _.functions.invoke("ensure-participant-auth",{body:{email:R}})}catch(ce){console.error(`Failed to ensure auth for ${R}:`,ce)}const Se=N.filter(R=>R.email&&R.email.trim()!=="");if(Se.length>0){let R=0;for(const ce of Se)try{const{error:oe}=await _.functions.invoke("send-participant-confirmation",{body:{participantEmail:ce.email,participantFirstName:ce.first_name,participantLastName:ce.last_name,tripName:(Z==null?void 0:Z.name)||"Unbekannte Reise",tripDestination:(Z==null?void 0:Z.destination)||"Unbekannt",tripStartDate:(Z==null?void 0:Z.startDate)||"",tripEndDate:(Z==null?void 0:Z.endDate)||"",whatsappGroupLink:(Z==null?void 0:Z.whatsappGroupLink)||null}});oe?console.error(`Failed to send confirmation to ${ce.email}:`,oe):R++}catch(oe){console.error(`Email error for ${ce.email}:`,oe)}R>0&&Y.success(`Bestätigung an ${R} Mitreisende gesendet`)}x(!1),qe(),window.location.reload()}c(!1)},us=k.customer_first_name&&k.customer_last_name&&k.customer_email&&k.participant_count>0&&N.every(Q=>Q.first_name&&Q.last_name);return e.jsxs("div",{className:"space-y-6",children:[e.jsx(We,{open:i,onOpenChange:x,children:e.jsxs(Qe,{className:"max-w-lg",children:[e.jsxs(Ye,{children:[e.jsx(Je,{children:"Neue Buchung erstellen"}),e.jsxs(Ds,{children:['Erstellen Sie eine neue Buchung für die Reise "',(Z==null?void 0:Z.name)||"Unbekannt",'".']})]}),e.jsxs("div",{className:"space-y-4 py-4 max-h-[60vh] overflow-y-auto",children:[e.jsxs("div",{className:"space-y-2 pb-3 border-b",children:[e.jsx("label",{className:"text-sm font-medium",children:"Bestehenden Teilnehmer suchen"}),e.jsxs("div",{className:"relative",children:[e.jsx(wt,{className:"absolute left-3 top-1/2 h-4 w-4 -translate-y-1/2 text-muted-foreground"}),e.jsx(te,{value:d,onChange:Q=>{u(Q.target.value),E(!0)},onFocus:()=>E(!0),placeholder:"Name oder E-Mail eingeben...",className:"pl-10"}),I&&Be.length>0&&e.jsx("div",{className:"absolute z-50 w-full mt-1 bg-background border rounded-lg shadow-lg max-h-48 overflow-y-auto",children:Be.map(Q=>e.jsxs("button",{type:"button",onClick:()=>Ke(Q),className:"w-full px-3 py-2 text-left hover:bg-muted flex items-center gap-3 transition-colors",children:[e.jsx(Pt,{className:"h-8 w-8",children:e.jsxs(Ft,{className:"text-xs bg-primary/10 text-primary",children:[Q.first_name[0],Q.last_name[0]]})}),e.jsxs("div",{className:"flex-1 min-w-0",children:[e.jsxs("p",{className:"font-medium text-sm truncate",children:[Q.first_name," ",Q.last_name]}),Q.email&&e.jsx("p",{className:"text-xs text-muted-foreground truncate",children:Q.email})]})]},Q.id))}),I&&d.length>=2&&Be.length===0&&e.jsx("div",{className:"absolute z-50 w-full mt-1 bg-background border rounded-lg shadow-lg p-3",children:e.jsx("p",{className:"text-sm text-muted-foreground text-center",children:"Kein Teilnehmer gefunden"})})]}),e.jsx("p",{className:"text-xs text-muted-foreground",children:"Oder füllen Sie die Felder manuell aus"})]}),($==null?void 0:$.discount_used_at)&&e.jsxs("div",{className:"flex items-start gap-3 p-3 rounded-lg bg-amber-50 dark:bg-amber-950/30 border border-amber-200 dark:border-amber-800",children:[e.jsx(Lt,{className:"h-5 w-5 text-amber-600 dark:text-amber-500 shrink-0 mt-0.5"}),e.jsxs("div",{className:"space-y-1",children:[e.jsx("p",{className:"text-sm font-medium text-amber-800 dark:text-amber-200",children:"Treuerabatt bereits eingelöst"}),e.jsxs("p",{className:"text-xs text-amber-700 dark:text-amber-300",children:["Dieser Teilnehmer hat seinen einmaligen Treuerabatt bereits am ",fs(new Date($.discount_used_at),"dd.MM.yyyy",{locale:Ts})," eingelöst."]})]})]}),$&&!$.discount_used_at&&$.loyalty_points>=100&&e.jsxs("div",{className:"flex items-start gap-3 p-3 rounded-lg bg-green-50 dark:bg-green-950/30 border border-green-200 dark:border-green-800",children:[e.jsx(Ot,{className:"h-5 w-5 text-green-600 dark:text-green-500 shrink-0 mt-0.5"}),e.jsxs("div",{className:"space-y-1",children:[e.jsx("p",{className:"text-sm font-medium text-green-800 dark:text-green-200",children:"Treuerabatt verfügbar"}),e.jsxs("p",{className:"text-xs text-green-700 dark:text-green-300",children:["Dieser Teilnehmer hat ",$.loyalty_points," Punkte und kann seinen einmaligen Treuerabatt (",$.loyalty_points>=500?"10%":"5%",") einlösen."]})]})]}),e.jsxs("div",{className:"grid grid-cols-2 gap-4",children:[e.jsxs("div",{className:"space-y-2",children:[e.jsx("label",{className:"text-sm font-medium",children:"Vorname *"}),e.jsx(te,{value:k.customer_first_name,onChange:Q=>C({...k,customer_first_name:Q.target.value}),placeholder:"Max"})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx("label",{className:"text-sm font-medium",children:"Nachname *"}),e.jsx(te,{value:k.customer_last_name,onChange:Q=>C({...k,customer_last_name:Q.target.value}),placeholder:"Mustermann"})]})]}),e.jsxs("div",{className:"grid grid-cols-2 gap-4",children:[e.jsxs("div",{className:"space-y-2",children:[e.jsx("label",{className:"text-sm font-medium",children:"E-Mail *"}),e.jsx(te,{type:"email",value:k.customer_email,onChange:Q=>C({...k,customer_email:Q.target.value}),placeholder:"[email protected]"})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx("label",{className:"text-sm font-medium",children:"Telefon"}),e.jsx(te,{value:k.customer_phone,onChange:Q=>C({...k,customer_phone:Q.target.value}),placeholder:"+49 170 1234567"})]})]}),e.jsxs("div",{className:"grid grid-cols-2 gap-4",children:[e.jsxs("div",{className:"space-y-2",children:[e.jsx("label",{className:"text-sm font-medium",children:"Anzahl Teilnehmer *"}),e.jsx(te,{type:"number",min:"1",value:k.participant_count,onChange:Q=>Ce(Number(Q.target.value))})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx("label",{className:"text-sm font-medium",children:"Preis pro Person"}),e.jsxs("div",{className:"relative",children:[e.jsx(te,{type:"number",min:"0",value:k.price_per_person,onChange:Q=>C({...k,price_per_person:Number(Q.target.value)}),className:"pr-12"}),e.jsx("span",{className:"absolute right-3 top-1/2 -translate-y-1/2 text-muted-foreground",children:"€"})]}),k.participant_count>1&&k.price_per_person>0&&e.jsxs("p",{className:"text-xs text-muted-foreground",children:["Gesamt: ",(k.price_per_person*k.participant_count).toLocaleStr
107ing("de-DE")," €"]})]})]}),N.length>0&&e.jsxs("div",{className:"space-y-3 pt-2 border-t",children:[e.jsx("label",{className:"text-sm font-medium text-muted-foreground",children:"Weitere Teilnehmer"}),N.map((Q,ue)=>e.jsxs("div",{className:"space-y-2",children:[e.jsxs("div",{className:"grid grid-cols-2 gap-4",children:[e.jsxs("div",{className:"space-y-1",children:[e.jsxs("label",{className:"text-xs text-muted-foreground",children:["Vorname Teilnehmer ",ue+2," *"]}),e.jsx(te,{value:Q.first_name,onChange:de=>xe(ue,"first_name",de.target.value),placeholder:"Vorname"})]}),e.jsxs("div",{className:"space-y-1",children:[e.jsxs("label",{className:"text-xs text-muted-foreground",children:["Nachname Teilnehmer ",ue+2," *"]}),e.jsx(te,{value:Q.last_name,onChange:de=>xe(ue,"last_name",de.target.value),placeholder:"Nachname"})]})]}),e.jsxs("div",{className:"space-y-1",children:[e.jsxs("label",{className:"text-xs text-muted-foreground",children:["E-Mail Teilnehmer ",ue+2," (optional)"]}),e.jsx(te,{type:"email",value:Q.email,onChange:de=>xe(ue,"email",de.target.value),placeholder:"[email protected]"})]})]},ue))]}),e.jsxs("div",{className:"flex items-center justify-between pt-2 border-t",children:[e.jsxs("div",{children:[e.jsx("label",{className:"text-sm font-medium",children:"Empfehlung zuweisen"}),e.jsx("p",{className:"text-xs text-muted-foreground",children:"Wurde diese Buchung von jemandem empfohlen?"})]}),e.jsx(z,{type:"button",variant:q?"default":"outline",size:"sm",onClick:()=>{y(!q),q&&(T(null),A(""))},children:q?"Aktiv":"Hinzufügen"})]}),q&&e.jsxs("div",{className:"space-y-2 p-3 bg-muted/50 rounded-lg border",children:[e.jsxs("div",{className:"relative",children:[e.jsx(wt,{className:"absolute left-3 top-1/2 h-4 w-4 -translate-y-1/2 text-muted-foreground pointer-events-none"}),e.jsx(te,{type:"text",placeholder:"Teilnehmer suchen...",value:V,onChange:Q=>A(Q.target.value),className:"pl-10 bg-background"})]}),e.jsxs("div",{className:"max-h-40 overflow-y-auto border rounded-md bg-background shadow-sm",children:[o.filter(Q=>!V||`${Q.first_name} ${Q.last_name}`.toLowerCase().includes(V.toLowerCase())||Q.email&&Q.email.toLowerCase().includes(V.toLowerCase())).map(Q=>e.jsxs("div",{className:Ms("px-3 py-2 cursor-pointer hover:bg-muted text-sm border-b last:border-b-0",G===Q.id&&"bg-primary/10 font-medium"),onClick:()=>T(Q.id),children:[Q.first_name," ",Q.last_name,Q.email&&e.jsxs("span",{className:"text-muted-foreground ml-2 text-xs",children:["(",Q.email,")"]}),G===Q.id&&e.jsx(ra,{className:"inline-block ml-2 h-4 w-4 text-primary"})]},Q.id)),o.filter(Q=>!V||`${Q.first_name} ${Q.last_name}`.toLowerCase().includes(V.toLowerCase())).length===0&&e.jsx("div",{className:"px-3 py-2 text-sm text-muted-foreground",children:"Keine Teilnehmer gefunden"})]})]})]}),e.jsxs(gs,{className:"flex-col sm:flex-row gap-2",children:[e.jsxs(z,{variant:"ghost",size:"sm",onClick:()=>j(!0),className:"mr-auto",children:[e.jsx(st,{className:"h-4 w-4 mr-2"}),"E-Mail Vorschau"]}),e.jsxs("div",{className:"flex gap-2",children:[e.jsx(z,{variant:"outline",onClick:()=>x(!1),children:"Abbrechen"}),e.jsx(z,{onClick:ms,disabled:!us||h,children:h?"Erstelle...":"Buchung erstellen"})]})]})]})}),e.jsx(ql,{open:W,onOpenChange:j}),e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsxs("div",{className:"relative max-w-md flex-1",children:[e.jsx(wt,{className:"absolute left-3 top-1/2 h-4 w-4 -translate-y-1/2 text-muted-foreground"}),e.jsx(te,{type:"text",placeholder:"Buchung suchen...",value:n,onChange:Q=>a(Q.target.value),className:"pl-10 rounded-xl bg-muted/50 border-0"})]}),e.jsxs(z,{className:"gap-2 rounded-xl",onClick:()=>x(!0),children:[e.jsx(Es,{className:"h-4 w-4"}),"Neue Buchung"]})]}),L&&e.jsxs("div",{className:"glass-card p-12 text-center",children:[e.jsx($e,{className:"mx-auto h-12 w-12 text-muted-foreground animate-spin"}),e.jsx("p",{className:"mt-4 text-muted-foreground",children:"Buchungen werden geladen..."})]}),!L&&e.jsx("div",{className:"space-y-4",children:J.map(Q=>e.jsx(Ol,{booking:Q,tripName:Z==null?void 0:Z.name,tripDestination:Z==null?void 0:Z.destination,tripStartDate:Z==null?void 0:Z.startDate,tripEndDate:Z==null?void 0:Z.endDate,participants:he(Q.id),documents:we(Q.id),payments:De(Q.id),isExpanded:b===Q.id,onToggle:()=>f(b===Q.id?null:Q.id),onCancel:g,onUpdateCancellation:r,onDelete:p,onUpdate:X,onAddPayment:ne,onUpdatePayment:le,onDeletePayment:K,onUploadDocument:M,onDeleteDocument:ee,onUpdateParticipant:_e}
107,Q.id))}),!L&&J.length===0&&e.jsxs("div",{className:"glass-card p-12 text-center",children:[e.jsx($s,{className:"mx-auto h-12 w-12 text-muted-foreground"}),e.jsx("h3",{className:"mt-4 text-lg font-medium text-foreground",children:"Keine Buchungen gefunden"}),e.jsx("p",{className:"mt-1 text-muted-foreground",children:"Erstellen Sie eine neue Buchung für diese Reise."})]})]})}function Ol({booking:s,tripName:n,tripDestination:a,tripStartDate:b,tripEndDate:f,participants:i,documents:x,payments:h,isExpanded:c,onToggle:k,onCancel:C,onUpdateCancellation:N,onDelete:v,onUpdate:G,onAddPayment:T,onUpdatePayment:o,onDeletePayment:l,onUploadDocument:V,onDeleteDocument:A,onUpdateParticipant:q}){const[y,W]=t.useState(!1),[j,d]=t.useState(!1),[u,I]=t.useState(s.cancellation_fee||0),[E,$]=t.useState(s.cancellation_reason||""),[ge,be]=t.useState(s.cancelled_at?s.cancelled_at.slice(0,10):new Date().toISOString().slice(0,10)),[Z,H]=t.useState(!1),[L,g]=t.useState(!1),[r,m]=t.useState(!1),[X,p]=t.useState(!1),[ne,le]=t.useState(!1),[K,M]=t.useState(!1),[ee,he]=t.useState(!1),[we,De]=t.useState(null),[_e,J]=t.useState(null),[Ae,qe]=t.useState(""),[Be,Ke]=t.useState(0),[Ce,xe]=t.useState(!1),[ms,us]=t.useState(!1),[Q,ue]=t.useState(0),[de,S]=t.useState(new Date),[P,ie]=t.useState(""),[Se,R]=t.useState(s.payment_method||""),[ce,oe]=t.useState(!1),[me,Ee]=t.useState(!1),[ze,ns]=t.useState(!1),[Pe,Fe]=t.useState(null),[cs,vs]=t.useState(null),Me=s.billing_street||s.billing_city||s.billing_postal_code||s.billing_country?null:i.find(D=>D.profile_id&&(D.billing_street||D.billing_city||D.billing_postal_code||D.billing_country))||null,[se,Re]=t.useState({customer_name:s.customer_name,customer_email:s.customer_email,customer_phone:s.customer_phone||"",billing_street:s.billing_street||(Me==null?void 0:Me.billing_street)||"",billing_postal_code:s.billing_postal_code||(Me==null?void 0:Me.billing_postal_code)||"",billing_city:s.billing_city||(Me==null?void 0:Me.billing_city)||"",billing_country:s.billing_country||(Me==null?void 0:Me.billing_country)||"",participant_count:s.participant_count,total_amount:s.total_amount}),[ts,hs]=t.useState({first_name:"",last_name:""}),[As,ds]=t.useState(!1),[Ps,Fs]=t.useState(!1),[Hs,Ct]=t.useState(null),[F,re]=t.useState([]);t.useEffect(()=>{if(!c)return;(async()=>{const{data:ye}=await _.from("insurance_certificates").select("id, name").order("valid_until",{ascending:!1});if(ye&&re(ye),s.insurance_certificate_id){const{data:xs}=await _.from("insurance_certificates").select("name").eq("id",s.insurance_certificate_id).single();xs&&Ct(xs.name)}})()},[c,s.insurance_certificate_id]);const{addonPurchases:Ne,stats:as}=ti(c?s.id:null),Ge=Math.round(s.paid_amount/s.total_amount*100),Ze=Math.round((s.total_amount-s.paid_amount)*100)/100,es=Ze===0,Le=s.status==="cancelled",_s=Math.max(0,s.paid_amount-Be),Cs=Math.max(0,Be-s.paid_amount),zs=x.some(D=>D.type==="invoice"),B=x.some(D=>D.type==="confirmation"),ae=D=>D?new Date(D).toLocaleDateString("de-DE"):"–",ve=D=>new Intl.NumberFormat("de-DE",{style:"currency",currency:"EUR"}).format(D),js=D=>!D||es?!1:new Date(D)<new Date,Ws=()=>{if(!n)return{subject:"",body:""};const D=`Stornierungsbestätigung: ${n}`,ye=`Hallo ${s.customer_name.split(" ")[0]||""},
108
109wir bestätigen die Stornierung deiner Buchung für "${n}".
110
111Stornierungsdatum: ${ae(new Date().toISOString())}
112Gesamtbetrag der Reise: ${ve(s.total_amount)}
113Stornierungsgebühr: ${ve(Be)}
114Bereits bezahlt: ${ve(s.paid_amount)}
115${Be>s.paid_amount?`Ausstehender Betrag: ${ve(Be-s.paid_amount)}`:`Rückerstattung: ${ve(_s)}`}
116
117Bei Fragen stehen wir dir gerne zur Verfügung.
118
119Herzliche Grüße
120Off The Path`;return{subject:D,body:ye}},is=async()=>{xe(!0),await C(s.id,Ae,Be,_s),xe(!1),W(!1),qe(""),Ke(0)},ls=async()=>{if(!n||!a||!b||!f){Y.error("Reisedaten fehlen");return}Fs(!0);try{const{error:D}=await _.functions.invoke("send-cancellation-confirmation",{body:{bookingId:s.id,customerEmail:s.customer_email,customerName:s.customer_name,tripName:n,tripDestination:a,tripStartDate:b,tripEndDate:f,cancellationFee:s.cancellation_fee||0,paidAmount:s.paid_amount,totalAmount:s.total_amount}});
120D?(console.error("Error sending cancellation email:",D),Y.error("E-Mail konnte nicht gesendet werden")):Y.success("Stornierungsbestätigung gesendet",{description:`E-Mail an ${s.customer_email} versendet`})}catch(D){console.error("Error:",D),Y.error("E-Mail konnte nicht gesendet werden")}Fs(!1)},ws=async()=>{us(!0),await v(s.id)&&g(!1),us(!1)},Ht=async()=>{if(Q<=0)return;oe(!0);const D=fs(de,"yyyy-MM-dd");await T(s.id,Q,D,P||void 0)&&(Se&&await G(s.id,{payment_method:Se}),p(!1),ue(0),S(new Date),ie(""),R(s.payment_method||"")),oe(!1)},w=D=>{J(D),ue(D.amount),S(He(D.payment_date)),ie(D.notes||""),M(!0)},je=async()=>{if(!_e||Q<=0)return;Ee(!0);const D=fs(de,"yyyy-MM-dd");await o(_e.id,{amount:Q,payment_date:D,notes:P||void 0})&&(M(!1),J(null),ue(0),S(new Date),ie("")),Ee(!1)},pe=async D=>{await l(D)},fe=async()=>{ds(!0),await G(s.id,{customer_name:se.customer_name,customer_email:se.customer_email,customer_phone:se.customer_phone||null,billing_street:se.billing_street||null,billing_postal_code:se.billing_postal_code||null,billing_city:se.billing_city||null,billing_country:se.billing_country||null,participant_count:se.participant_count,total_amount:se.total_amount})&&le(!1),ds(!1)},Te=D=>{La(D,"booking-documents")},ke=async(D,ye)=>{var Ys;const xs=(Ys=ye.target.files)==null?void 0:Ys[0];xs&&(Fe(D),await V(s.id,xs,D),Fe(null),ye.target.value="")},os=async(D,ye)=>{var ia;ye.preventDefault(),ye.stopPropagation(),vs(null);const xs=(ia=ye.dataTransfer.files)==null?void 0:ia[0];if(!xs)return;if(!["application/pdf","application/msword","application/vnd.openxmlformats-officedocument.wordprocessingml.document"].includes(xs.type)){Y.error("Ungültiger Dateityp",{description:"Bitte laden Sie eine PDF oder Word-Datei hoch."});return}Fe(D),await V(s.id,xs,D),Fe(null)},Bs=(D,ye)=>{ye.preventDefault(),ye.stopPropagation(),vs(D)},Qs=D=>{D.preventDefault(),D.stopPropagation(),vs(null)},zt=async(D,ye)=>{ye.stopPropagation(),await A(D)},Ls=D=>{De(D),hs({first_name:D.first_name,last_name:D.last_name}),he(!0)},Nt=async()=>{if(!we)return;ns(!0),await q(we.id,{first_name:ts.first_name,last_name:ts.last_name})&&(Y.success("Name aktualisiert",{description:`${ts.first_name} ${ts.last_name}`}),he(!1),De(null)),ns(!1)};return e.jsxs(e.Fragment,{children:[e.jsx(mt,{open:L,onOpenChange:g,children:e.jsxs(ut,{children:[e.jsxs(ht,{children:[e.jsxs(xt,{className:"flex items-center gap-2 text-destructive",children:[e.jsx(bs,{className:"h-5 w-5"}),"Buchung endgültig löschen?"]}),e.jsxs(pt,{children:["Diese Aktion kann nicht rückgängig gemacht werden. Die Buchung von ",e.jsx("strong",{children:s.customer_name})," sowie alle zugehörigen Teilnehmer, Zahlungen und Dokumente werden unwiderruflich gelöscht."]})]}),e.jsxs(gt,{children:[e.jsx(ft,{children:"Abbrechen"}),e.jsx(jt,{onClick:ws,disabled:ms,className:"bg-destructive text-destructive-foreground hover:bg-destructive/90",children:ms?"Lösche...":"Endgültig löschen"})]})]})}),e.jsx(We,{open:ee,onOpenChange:he,children:e.jsxs(Qe,{className:"max-w-sm",children:[e.jsxs(Ye,{children:[e.jsxs(Je,{className:"flex items-center gap-2",children:[e.jsx(vt,{className:"h-5 w-5"}),"Teilnehmername bearbeiten"]}),e.jsx(Ds,{children:"Ändern Sie den Namen des Teilnehmers. Der offizielle Passname kann abweichen."})]}),e.jsxs("div",{className:"space-y-4 py-4",children:[e.jsxs("div",{className:"space-y-2",children:[e.jsx("label",{className:"text-sm font-medium text-foreground",children:"Vorname"}),e.jsx(te,{value:ts.first_name,onChange:D=>hs(ye=>({...ye,first_name:D.target.value})),placeholder:"Vorname"})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx("label",{className:"text-sm font-medium text-foreground",children:"Nachname"}),e.jsx(te,{value:ts.last_name,onChange:D=>hs(ye=>({...ye,last_name:D.target.value})),placeholder:"Nachname"})]})]}),e.jsxs(gs,{children:[e.jsx(z,{variant:"outline",onClick:()=>he(!1),children:"Abbrechen"}),e.jsx(z,{onClick:Nt,disabled:ze||!ts.first_name.trim()||!ts.last_name.trim(),children:ze?"Speichere...":"Speichern"})]})]})}),e.jsx(We,{open:y,onOpenChange:W,children:e.jsxs(Qe,{className:"max-w-lg",children:[e.jsxs(Ye,{children:[e.jsxs(Je,{className:"flex items-center gap-2 text-destructive",children:[e.jsx(Vt,{className:"h-5 w-5"}),"Buchung stornieren"]}),e.jsxs(Ds,{children:["Stornieren Sie die Buchung von ",s.customer_name,' für die Reise "',n||"Unbekannt",'".']})]}),e.jsxs("div",{className:"space-y-4 py-4",children:[e.jsxs("div",{className:"rounded-lg bg-muted/30 p-4 space-y-2 text-sm",children:[e.jsxs("div",{className:"flex justify-between",children:[e.jsx("span",{className:"text-muted-foreground",children:"Buchungsnummer"}),e.jsx("span",{className:"font-medium",children:s.id})]}),e.jsxs("div",{className:"flex justify-between",children:[e.jsx("span",{className:"text-muted-foreground",children:"Teilnehmer"}),e.jsxs("span",{className:"font-medium",children:[s.participant_count," Personen"]})]}),e.jsxs("div",{className:"flex justify-between",children:[e.jsx("span",{className:"text-muted-foreground",children:"Bezahlter Betrag"}),e.jsx("span",{className:"font-medium text-success",children:ve(s.paid_amount)})]})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx("label",{className:"text-sm font-medium",children:"Stornierungsgrund"}),e.jsx(qs,{placeholder:"Optionaler Stornierungsgrund...",value:Ae,onChange:D=>qe(D.target.value),className:"min-h-[80px]"})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx("label",{className:"text-sm font-medium",children:"Stornierungsgebühr"}),e.jsxs("div",{className:"relative",children:[e.jsx(te,{type:"number",min:"0",max:s.total_amount,value:
120Be,onChange:D=>Ke(Math.min(Number(D.target.value),s.total_amount)),className:"pr-12"}),e.jsx("span",{className:"absolute right-3 top-1/2 -translate-y-1/2 text-muted-foreground",children:"€"})]})]}),e.jsxs("div",{className:"rounded-lg border border-border p-4 space-y-2",children:[e.jsxs("div",{className:"flex justify-between text-sm",children:[e.jsx("span",{className:"text-muted-foreground",children:"Gesamtbetrag der Reise"}),e.jsx("span",{children:ve(s.total_amount)})]}),e.jsxs("div",{className:"flex justify-between text-sm",children:[e.jsx("span",{className:"text-muted-foreground",children:"Stornierungsgebühr"}),e.jsx("span",{className:"text-destructive",children:ve(Be)})]}),e.jsxs("div",{className:"flex justify-between text-sm",children:[e.jsx("span",{className:"text-muted-foreground",children:"Bereits bezahlt"}),e.jsx("span",{children:ve(s.paid_amount)})]}),e.jsx("div",{className:"border-t pt-2 flex justify-between font-medium",children:Cs>0?e.jsxs(e.Fragment,{children:[e.jsx("span",{children:"Ausstehender Betrag"}),e.jsx("span",{className:"text-destructive",children:ve(Cs)})]}):e.jsxs(e.Fragment,{children:[e.jsx("span",{children:"Rückerstattung"}),e.jsx("span",{className:"text-success",children:ve(_s)})]})})]}),e.jsxs(z,{variant:"outline",className:"w-full gap-2",onClick:()=>m(!0),children:[e.jsx(Os,{className:"h-4 w-4"}),"E-Mail-Vorschau anzeigen"]})]}),e.jsxs(gs,{children:[e.jsx(z,{variant:"outline",onClick:()=>W(!1),children:"Abbrechen"}),e.jsx(z,{variant:"destructive",onClick:is,disabled:Ce,children:Ce?"Storniere...":"Buchung stornieren"})]})]})}),e.jsx(We,{open:r,onOpenChange:m,children:e.jsxs(Qe,{className:"max-w-2xl max-h-[80vh] overflow-y-auto",children:[e.jsxs(Ye,{children:[e.jsxs(Je,{className:"flex items-center gap-2",children:[e.jsx(Os,{className:"h-5 w-5"}),"Stornierungsbestätigung - Vorschau"]}),e.jsxs(Ds,{children:["Diese E-Mail wird an ",s.customer_email," gesendet."]})]}),e.jsxs("div",{className:"space-y-4 py-4",children:[e.jsxs("div",{className:"space-y-2",children:[e.jsx("label",{className:"text-xs font-medium text-muted-foreground uppercase",children:"Betreff"}),e.jsx("div",{className:"rounded-lg bg-muted/30 p-3 text-sm font-medium",children:Ws().subject})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx("label",{className:"text-xs font-medium text-muted-foreground uppercase",children:"Inhalt"}),e.jsx("div",{className:"rounded-lg bg-muted/30 p-4 text-sm whitespace-pre-wrap",children:Ws().body})]})]}),e.jsx(gs,{children:e.jsx(z,{variant:"outline",onClick:()=>m(!1),children:"Schließen"})})]})}),e.jsx(We,{open:X,onOpenChange:p,children:e.jsxs(Qe,{className:"max-w-md",children:[e.jsxs(Ye,{children:[e.jsxs(Je,{className:"flex items-center gap-2",children:[e.jsx(Kt,{className:"h-5 w-5"}),"Zahlung hinzufügen"]}),e.jsxs(Ds,{children:["Erfassen Sie eine Zahlung für die Buchung von ",s.customer_name,"."]})]}),e.jsxs("div",{className:"space-y-4 py-4",children:[e.jsxs("div",{className:"rounded-lg bg-muted/30 p-4 space-y-2 text-sm",children:[e.jsxs("div",{className:"flex justify-between",children:[e.jsx("span",{className:"text-muted-foreground",children:"Gesamtbetrag"}),e.jsx("span",{className:"font-medium",children:ve(s.total_amount)})]}),e.jsxs("div",{className:"flex justify-between",children:[e.jsx("span",{className:"text-muted-foreground",children:"Bereits bezahlt"}),e.jsx("span",{className:"font-medium text-success",children:ve(s.paid_amount)})]}),e.jsxs("div",{className:"flex justify-between",children:[e.jsx("span",{className:"text-muted-foreground",children:"Offener Betrag"}),e.jsx("span",{className:"font-medium text-warning",children:ve(Ze)})]})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsx("label",{className:"text-sm font-medium",children:"Zahlungsbetrag"}),e.jsxs("div",{className:"flex gap-1",children:[e.jsx(z,{type:"button",variant:"outline",size:"sm",className:"h-6 px-2 text-xs",onClick:()=>ue(Math.round(s.total_amount*.25*100)/100),children:"25%"}),e.jsx(z,{type:"button",variant:"outline",size:"sm",className:"h-6 px-2 text-xs",onClick:()=>ue(Math.round(s.total_amount*.75*100)/100),children:"75%"})]})]}),e.jsxs("div",{className:"relative",children:[e.jsx(te,{type:"number",min:"0",step:"0.01",max:Ze,value:Q,onChange:D=>{const ye=D.target.value===""?0:Number(D.target.value),xs=Math.round((Number.isFinite(ye)?ye:0)*100)/100;ue(Math.min(xs,Ze))},className:"pr-12"}),e.jsx("span",{className:"absolute right-3 top-1/2 -translate-y-1/2 text-muted-foreground",children:"€"})]})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx("label",{className:"text-sm font-medium",children:"Zahlungsdatum"}),e.jsxs(Dt,{children:[e.jsx(Et,{asChild:!0,children:e.jsxs(z,{variant:"outline",className:Ms("w-full justify-start text-left font-normal",!de&&"text-muted-foreground"),children:[e.jsx(kt,{className:"mr-2 h-4 w-4"}),de?fs(de,"PPP",{locale:Ts}):e.jsx("span",{children:"Datum wählen"})]})}),e.jsx(At,{className:"w-auto p-0",align:"start",children:e.jsx(qt,{mode:"single",selected:de,onSelect:D=>D&&S(D),initialFocus:!0,className:Ms("p-3 pointer-events-auto")})})]})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx("label",{className:"text-sm font-medium",children:"Zahlungsart"}),e.jsxs("select",{value:Se,onChange:D=>R(D.target.value),className:"w-full text-sm font-medium bg-background border border-input rounded-md px-3 py-2 text-foreground focus:outline-none focus:ring-2 focus:ring-primary",children:[e.jsx("option",{value:"",children:"Zahlungsart wählen..."}),e.jsx("option",{value:"bank_transfer",children:"Überweisung"}),e.jsx("option",{value:"cash",children:"Barzahlung"}),e.jsx("option",{value:"credit_card",children:"Kreditkarte"}),e.jsx("option",{value:"paypal",children:"PayPal"}),e.jsx("option",{value:"stripe",children:"Stripe"})]})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx("label",{className:"text-sm font-medium",children:"Notizen (optional)"}),e.jsx(te,{placeholder:"z.B. Rechnungsnummer, Verwendungszweck...",value:P,onChange:D=>ie(D.target.value)})]})]}),e.jsxs(gs,{children:[e.jsx(z,{variant:"outline",onClick:()=>p(!1),children:"Abbrechen"}),e.jsx(z,{onClick:Ht,disabled:ce||Q<=0,children:ce?"Speichern...":"Zahlung erfassen"})]})]})}),e.jsx(We,{open:K,onOpenChange:M,children:e.jsxs(Qe,{className:"max-w-md",children:[e.jsxs(Ye,{children:[e.jsxs(Je,{className:"flex items-center gap-2",children:[e.jsx(vt,{className:"h-5 w-5"}),"Zahlung bearbeiten"]}),e.jsx(Ds,{children:"Bearbeiten Sie die Zahlungsdetails."})]}),e.jsxs("div",{className:"space-y-4 py-4",children:[e.jsxs("div",{className:"space-y-2",children:[e.jsx("label",{className:"text-sm font-medium",children:"Zahlungsbetrag"}),e.jsxs("div",{className:"relative",children:[e.jsx(te,{type:"number",min:"0",step:"0.01",value:Q,onChange:D=>{const ye=D.target.value===""?0:Number(D.target.value);ue(Math.round((Number.isFinite(ye)?ye:0)*100)/100)},className:"pr-12"}),e.jsx("span",{className:"absolute right-3 top-1/2 -translate-y-1/2 text-muted-foreground",children:"€"})]})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx("label",{className:"text-sm font-medium",children:"Zahlungsdatum"}),e.jsxs(Dt,{children:[e.jsx(Et,{asChild:!0,children:e.jsxs(z,{variant:"outline",className:Ms("w-full justify-start text-left font-normal",!de&&"text-muted-foreground"),children:[e.jsx(kt,{className:"mr-2 h-4 w-4"}),de?fs(de,"PPP",{locale:Ts}):e.jsx("span",{children:"Datum wählen"})]})}),e.jsx(At,{className:"w-auto p-0",align:"start",children:e.jsx(qt,{mode:"single",selected:de,onSelect:D=>D&&S(D),initialFocus:!0,className:Ms("p-3 pointer-events-auto")})})]})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx("label",{className:"text-sm font-medium",children:"Notizen (optional)"}),e.jsx(te,{placeholder:"z.B. Überweisung, Barzahlung...",value:P,onChange:D=>ie(D.target.value)})]})]}),e.jsxs(gs,{children:[e.jsx(z,{variant:"outline",onClick:()=>M(!1),children:"Abbrechen"}),e.jsx(z,{onClick:je,disabled:me||Q<=0,children:me?"Speichern...":"Speichern"})]})]})}),e.jsx(We,{open:ne,onOpenChange:le,children:e.jsxs(Qe,{className:"max-w-md",children:[e.jsxs(Ye,{children:[e.jsxs(Je,{className:"flex items-center gap-2",children:[e.jsx(wa,{className:"h-5 w-5"}),"Buchung bearbeiten"]}),e.jsx(Ds,{children:"Bearbeiten Sie die Buchungsdetails."})]}),e.jsxs("div",{className:"space-y-4 py-4",children:[e.jsxs("div",{className:"space-y-2",children:[e.jsx("label",{className:"text-sm font-medium",children:"Name"}),e.jsx(te,{value:se.customer_name,onChange:D=>Re({...se,customer_name:D.target.value})})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx("label",{className:"text-sm font-medium",children:"E-Mail"}),e.jsx(te,{type:"email",value:se.customer_email,onChange:D=>Re({...se,customer_email:D.target.value})})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx("label",{className:"text-sm font-medium",children:"Telefon"}),e.jsx(te,{value:se.customer_phone,onChange:D=>Re({...se,customer_phone:D.target.value})})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx("label",{className:"text-sm font-medium",children:"Straße + Hausnummer"}),e.jsx(te,{placeholder:"Musterstraße 123",value:se.billing_street,onChange:D=>Re({...se,billing_street:D.target.value})})]}),e.jsxs("div",{className:"grid grid-cols-2 gap-3",children:[e.jsxs("div",{className:"space-y-2",children:[e.jsx("label",{className:"text-sm font-medium",children:"PLZ"}),e.jsx(te,{placeholder:"12345",value:se.billing_postal_code,onChange:D=>Re({...se,billing_postal_code:D.target.value})})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx("label",{className:"text-sm font-medium",children:"Ort"}),e.jsx(te,{placeholder:"Berlin",value:se.billing_city,onChange:D=>Re({...se,billing_city:D.target.value})})]})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx("label",{className:"text-sm font-medium",children:"Land"}),e.jsx(Ll,{value:se.billing_country,onChange:D=>Re({...se,billing_country:D||""})})]}),e.jsxs("div",{className:"grid grid-cols-2 gap-4",children:[e.jsxs("div",{className:"space-y-2",children:[e.jsx("label",{className:"text-sm font-medium",children:"Teilnehmer"}),e.jsx(te,{type:"number",min:"1",value:se.participant_count,onChange:D=>Re({...se,participant_count:Number(D.target.value)})})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx("label",{className:"text-sm font-medium",children:"Gesamtbetrag"}),e.jsxs("div",{className:"relative",children:[e.jsx(te,{type:"number",min:"0",value:se.total_amount,onChange:D=>Re({...se,total_amount:Number(D.target.value)}),className:"pr-12"}),e.jsx("span",{className:"absolute right-3 top-1/2 -translate-y-1/2 text-muted-foreground",children:"€"})]})]})]})]}),e.jsxs(gs,{children:[e.jsx(z,{variant:"outline",onClick:()=>le(!1),children:"Abbrechen"}),e.jsx(z,{onClick:fe,disabled:As,children:As?"Speichern...":"Speichern"})]})]})}),e.jsx(We,{open:j,onOpenChange:d,children:e.jsxs(Qe,{children:[e.jsxs(Ye,{children:[e.jsx(Je,{children:"Stornierung bearbeiten"}),e.jsx(Ds,{children:"Passe Stornogebühr, Grund und Datum nachträglich an. Rückerstattung bzw. offener Betrag werden automatisch neu berechnet."})]}),e.jsxs("div",{className:"space-y-4 py-2",children:[e.jsxs("div",{children:[e.jsx("label",{className:"text-sm font-medium",children:"Stornogebühr (EUR)"}
120),e.jsx(te,{type:"number",min:0,step:.01,value:u,onChange:D=>I(parseFloat(D.target.value)||0)})]}),e.jsxs("div",{children:[e.jsx("label",{className:"text-sm font-medium",children:"Storno-Datum"}),e.jsx(te,{type:"date",value:ge,onChange:D=>be(D.target.value)})]}),e.jsxs("div",{children:[e.jsx("label",{className:"text-sm font-medium",children:"Stornogrund"}),e.jsx(qs,{rows:3,value:E,onChange:D=>$(D.target.value),placeholder:"z.B. Krankheit, Kulanz, Umbuchung..."})]}),e.jsxs("div",{className:"rounded-lg bg-muted/40 p-3 text-sm space-y-1",children:[e.jsxs("div",{className:"flex justify-between",children:[e.jsx("span",{className:"text-muted-foreground",children:"Bereits bezahlt"}),e.jsx("span",{className:"font-medium",children:ve(s.paid_amount)})]}),e.jsxs("div",{className:"flex justify-between",children:[e.jsx("span",{className:"text-muted-foreground",children:"Stornogebühr"}),e.jsx("span",{className:"font-medium",children:ve(u)})]}),u>s.paid_amount?e.jsxs("div",{className:"flex justify-between text-destructive",children:[e.jsx("span",{children:"Offener Betrag"}),e.jsx("span",{className:"font-medium",children:ve(u-s.paid_amount)})]}):e.jsxs("div",{className:"flex justify-between text-success",children:[e.jsx("span",{children:"Rückerstattung"}),e.jsx("span",{className:"font-medium",children:ve(s.paid_amount-u)})]})]})]}),e.jsxs(gs,{children:[e.jsx(z,{variant:"outline",onClick:()=>d(!1),disabled:Z,children:"Abbrechen"}),e.jsxs(z,{onClick:async()=>{H(!0);const D=await N(s.id,{cancellationFee:u,cancellationReason:E,cancelledAt:ge?new Date(ge).toISOString():void 0});H(!1),D&&d(!1)},disabled:Z,children:[Z?e.jsx($e,{className:"h-4 w-4 animate-spin mr-2"}):null,"Speichern"]})]})]})}),e.jsxs("div",{className:"glass-card overflow-hidden",children:[Le&&e.jsxs("div",{className:"bg-destructive/10 px-5 py-2 flex items-center gap-2 text-destructive",children:[e.jsx(Lt,{className:"h-4 w-4"}),e.jsxs("span",{className:"text-sm font-medium",children:["Storniert am ",s.cancelled_at?ae(s.cancelled_at):"–",s.cancellation_reason&&` – ${s.cancellation_reason}`]})]}),e.jsxs("div",{className:"flex cursor-pointer items-center justify-between p-5 transition-colors hover:bg-muted/20",onClick:k,children:[e.jsxs("div",{className:"flex items-center gap-4",children:[e.jsx("div",{className:`flex h-12 w-12 items-center justify-center rounded-xl text-lg font-semibold ${Le?"bg-destructive/10 text-destructive":"bg-primary/10 text-primary"}`,children:Le?e.jsx(Vt,{className:"h-6 w-6"}):s.customer_name.charAt(0)}),e.jsxs("div",{children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx("h3",{className:`font-semibold ${Le?"text-muted-foreground line-through":"text-foreground"}`,children:s.customer_name}),Le&&e.jsx(Xe,{variant:"destructive",className:"text-xs",children:"Storniert"})]}),e.jsxs("p",{className:"text-sm text-muted-foreground",children:[s.participant_count," Personen • Buchung vom ",ae(s.booking_date)]})]})]}),e.jsxs("div",{className:"flex items-center gap-6",children:[e.jsx(it,{children:e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsxs(Js,{children:[e.jsx(Xs,{asChild:!0,children:e.jsx("div",{className:`flex items-center justify-center h-8 w-8 rounded-lg transition-colors ${B?"bg-success/10 text-success":"bg-destructive/10 text-destructive"}`,children:e.jsx(Ha,{className:"h-4 w-4"})})}),e.jsx(et,{children:e.jsx("p",{children:B?"Buchungsbestätigung vorhanden":"Buchungsbestätigung fehlt"})})]}),e.jsxs(Js,{children:[e.jsx(Xs,{asChild:!0,children:e.jsx("div",{className:`flex items-center justify-center h-8 w-8 rounded-lg transition-colors ${zs?"bg-success/10 text-success":"bg-destructive/10 text-destructive"}`,children:e.jsx(Jt,{className:"h-4 w-4"})})}),e.jsx(et,{children:e.jsx("p",{children:zs?"Rechnung vorhanden":"Rechnung fehlt"})})]})]})}),e.jsx("div",{className:"w-48",children:e.jsx(ci,{value:s.paid_amount,max:s.total_amount})}),e.jsxs("div",{className:"text-right",children:[e.jsx("p",{className:"font-semibold text-foreground",children:ve(s.total_amount)}),!Le&&!es&&s.last_installment_due&&e.jsxs("p",{className:`text-sm ${js(s.last_installment_due)?"text-destructive":"text-muted-foreground"}`,children:["Letzte Rate: ",ae(s.last_installment_due)]}),!Le&&es&&e.jsx("p",{className:"text-sm text-success",children:"Vollständig bezahlt"})]}),e.jsx("button",{className:"rounded-lg p-2 transition-colors hover:bg-muted",children:c?e.jsx(vn,{className:"h-5 w-5 text-muted-foreground"}):e.jsx(Us,{className:"h-5 w-5 text-muted-foreground"})})]})]}),c&&e.jsxs("div",{className:"border-t border-border bg-muted/10 p-5 animate-fade-in",children:[e.jsxs("div",{className:"grid gap-6 lg:grid-cols-2",children:[e.jsxs("div",{className:"space-y-6",children:[e.jsxs("div",{className:"space-y-4",children:[e.jsxs("h4",{className:"font-medium text-foreground flex items-center gap-2",children:[e.jsx(kt,{className:"h-4 w-4"}),"Zahlungsübersicht"]}),e.jsxs("div",{className:"grid gap-3 text-sm rounded-xl bg-muted/30 p-4",children:[e.jsxs("div",{className:"flex justify-between items-center",children:[e.jsx("span",{className:"text-muted-foreground",children:"Buchungsdatum"}),e.jsxs("div",{className:"flex items-center gap-1",children:[e.jsx("span",{className:"text-foreground font-medium",children:ae(s.booking_date)}),e.jsxs(Dt,{children:[e.jsx(Et,{asChild:!0,children:e.jsx(z,{variant:"ghost",size:"icon",className:"h-6 w-6",children:e.jsx(vt,{className:"h-3 w-3"})})}),e.jsx(At,{className:"w-auto p-0",align:"end",children:e.jsx(qt,{mode:"single",selected:s.booking_date?He(s.booking_date):void 0,onSelect:D=>{if(D){const ye=Wa(D,14);G(s.id,{booking_date:fs(D,"yyyy-MM-dd"),first_installment_due:fs(ye,"yyyy-MM-dd")})}},locale:Ts,className:Ms("p-3 pointer-events-auto")})})]})]})]}),e.jsxs("div",{className:"flex justify-between items-center",children:[e.jsx("span",{className:"text-muted-foreground",children:"Fälligkeit 1. Rate"}),e.jsxs("div",{className:"flex items-center gap-1",children:[e.jsx("span",{className:`font-medium ${s.first_installment_due&&js(s.first_installment_due)&&s.paid_amount<s.deposit?"text-destructive":"text-foreground"}`,children:ae(s.first_installment_due||"")}),e.jsxs(Dt,{children:[e.jsx(Et,{asChild:!0,children:e.jsx(z,{variant:"ghost",size:"icon",className:"h-6 w-6",children:e.jsx(vt,{className:"h-3 w-3"})})}),e.jsx(At,{className:"w-auto p-0",align:"end",children:e.jsx(qt,{mode:"single",selected:s.first_installment_due?He(s.first_installment_due):void 0,onSelect:D=>{D&&G(s.id,{first_installment_due:fs(D,"yyyy-MM-dd")})},locale:Ts,className:Ms("p-3 pointer-events-auto")})})]})]})]}),e.jsxs("div",{className:"flex justify-between items-center",children:[e.jsx("span",{className:"text-muted-foreground",children:"Fälligkeit letzte Rate"}),e.jsxs("div",{className:"flex items-center gap-1",children:[e.jsx("span",{className:`font-medium ${s.last_installment_due&&js(s.last_installment_due)&&!es?"text-destructive":"text-foreground"}`,children:ae(s.last_installment_due||"")}),e.jsxs(Dt,{children:[e.jsx(Et,{asChild:!0,children:e.jsx(z,{variant:"ghost",size:"icon",className:"h-6 w-6",children:e.jsx(vt,{className:"h-3 w-3"})})}),e.jsx(At,{className:"w-auto p-0",align:"end",children:e.jsx(qt,{mode:"single",selected:s.last_installment_due?He(s.last_installment_due):void 0,onSelect:D=>{D&&G(s.id,{last_installment_due:fs(D,"yyyy-MM-dd")})},locale:Ts,className:Ms("p-3 pointer-events-auto")})})]})]})]}),e.jsx("div",{className:"border-t border-border pt-3 mt-2",children:e.jsxs("div",{className:"flex justify-between items-center group",children:[e.jsx("span",{className:"text-muted-foreground",children:"Gesamtbetrag"}),e.jsx(Gl,{value:s.total_amount,onSave:D=>G(s.id,{total_amount:D})})]})}),e.jsxs("div",{className:"flex justify-between",children:[e.jsx("span",{className:"text-muted-foreground",children:"Bezahlt"}),e.jsxs("span",{className:"text-success font-medium",children:[ve(s.paid_amount)," (",Ge,"%)"]})]}),e.jsxs("div",{className:"flex justify-between",children:[e.jsx("span",{className:"text-muted-foreground",children:"Restbetrag"}),e.jsx("span",{className:`font-semibold ${Ze>0?"text-warning":"text-success"}`,children:ve(Ze)})]})]}),e.jsxs("div",{className:"rounded-xl bg-muted/30 p-4",children:[e.jsxs("div",{className:"flex justify-between text-sm mb-2",children:[e.jsx("span",{className:"text-muted-foreground",children:"Zahlungsfortschritt"}),e.jsxs("span",{className:"font-medium text-foreground",children:[Ge,"%"]})]}),e.jsx("div",{className:"h-3 rounded-full bg-muted overflow-hidden",children:e.jsx("div",{className:`h-full rounded-full transition-all duration-500 ${Ge===100?"bg-success":"bg-primary"}`,style:{width:`${Ge}%`}})})]}),(h.length>0||Ne.length>0)&&e.jsxs("div",{className:"space-y-3",children:[e.jsxs("h4",{className:"font-medium text-foreground flex items-center gap-2",children:[e.jsx(Kt,{className:"h-4 w-4"}),"Zahlungshistorie"]}),e.jsxs("div",{className:"space-y-2",children:[h.map(D=>e.jsxs("div",{className:"flex items-center justify-between rounded-lg bg-muted/30 px-3 py-2",children:[e.jsx("div",{className:"flex items-center gap-3",children:e.jsxs("div",{className:"text-left",children:[e.jsx("p",{className:"text-sm font-medium text-foreground",children:ve(D.amount)}),e.jsxs("p",{className:"text-xs text-muted-foreground",children:[ae(D.payment_date),D.notes&&` • ${D.notes}`]})]})}),e.jsxs("div",{className:"flex gap-1",children:[e.jsx("button",{className:"rounded p-1.5 transition-colors hover:bg-muted",onClick:ye=>{ye.stopPropagation(),w(D)},children:e.jsx(vt,{className:"h-4 w-4 text-muted-foreground"})}),e.jsx("button",{className:"rounded p-1.5 transition-colors hover:bg-destructive/10",onClick:ye=>{ye.stopPropagation(),pe(D.id)},children:e.jsx(bs,{className:"h-4 w-4 text-destructive"})})]})]},D.id)),Ne.filter(D=>D.payment_status==="paid").map(D=>e.jsxs("div",{className:"flex items-center justify-between rounded-lg bg-primary/5 border border-primary/20 px-3 py-2",children:[e.jsxs("div",{className:"flex items-center gap-3",children:[e.jsx(Rt,{className:"h-4 w-4 text-primary"}),e.jsxs("div",{className:"text-left",children:[e.jsxs("p",{className:"text-sm font-medium text-foreground",children:[ve(D.total_price),e.jsxs("span",{className:"text-xs text-muted-foreground ml-2",children:["Add-on: ",D.addon_name]})]}),e.jsxs("p",{className:"text-xs text-muted-foreground",children:[ae(D.purchased_at||D.created_at)," • ",D.participant_name]})]})]}),D.invoice_url&&e.jsx("button",{className:"rounded p-1.5 transition-colors hover:bg-muted",onClick:ye=>{ye.stopPropagation(),La(D.invoice_url,"booking-documents")},title:"Rechnung öffnen",children:e.jsx(st,{className:"h-4 w-4 text-muted-foreground"})})]},`addon-${D.id}`)),Ne.filter(D=>D.payment_status==="pending").length>0&&e.jsxs(e.Fragment,{children:[e.jsx("p",{className:"text-xs font-medium text-muted-foreground uppercase tracking-wide mt-3",children:"Ausstehende Add-ons"}),Ne.filter(D=>D.payment_status==="pending").map(D=>e.jsx("div",{className:"flex items-center justify-between rounded-lg bg-amber-500/5 border border-amber-500/20 px-3 py-2",children:e.jsxs("div",{className:"flex items-center gap-3",children:[e.jsx(Rt,{className:"h-4 w-4 text-amber-500"}),e.jsxs("div",{className:"text-left",children:[e.jsxs("p",{className:"text-sm font-medium text-foreground",children:[ve(D.total_price),e.jsx("span",{className:"text-xs text-muted-foreground ml-2",children:D.addon_name})]}),e.jsxs("p",{className:"text-xs text-amber-500",children:["Zahlung ausstehend • ",D.participant_name]})]})]})},`addon-pending-${D.id}`))]})]})]})]}),e.jsxs("div",{className:"space-y-3",children:[e.jsx("h4",{className:"font-medium text-foreground",children:"Kontaktdaten"}),e.jsxs("div",{className:"grid gap-2 text-sm",children:[e.jsxs("div",{className:"flex justify-between",children:[e.jsx("span",{className:"text-muted-foreground",children:"E-Mail"}),e.jsx("span",{className:"text-foreground",children:s.customer_email})]}),e.jsxs("div",{className:"flex justify-between",children:[e.jsx("span",{className:"text-muted-foreground",children:"Telefon"}),e.jsx("span",{className:"text-foreground",children:s.customer_phone||"–"})]}),e.jsxs("div",{className:"pt-2 border-t border-border mt-2",children:[e.jsx("span",{className:"text-muted-foreground text-xs uppercase tracking-wide",children:"Rechnungsadresse"}),(()=>{const D=s.billing_street||s.billing_city||s.billing_postal_code||s.billing_country,ye=D?null:i.find(Ys=>Ys.profile_id&&(Ys.billing_street||Ys.billing_city||Ys.billing_postal_code||Ys.billing_country)),xs=D?{street:s.billing_street,postal:s.billing_postal_code,city:s.billing_city,country:s.billing_country}:ye?{street:ye.billing_street,postal:ye.billing_postal_code,city:ye.billing_city,country:ye.billing_country}:null;return xs?e.jsxs("div",{className:"text-foreground text-sm mt-1 
120space-y-0.5",children:[xs.street&&e.jsx("p",{children:xs.street}),(xs.postal||xs.city)&&e.jsx("p",{children:[xs.postal,xs.city].filter(Boolean).join(" ")}),xs.country&&e.jsx("p",{children:xs.country}),!D&&e.jsx("span",{className:"text-xs text-muted-foreground italic",children:"(aus Profil)"})]}):e.jsx("p",{className:"text-muted-foreground text-sm mt-1",children:"–"})})()]})]})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsxs("h4",{className:"font-medium text-foreground flex items-center gap-2",children:[e.jsx(sr,{className:"h-4 w-4"}),"Sicherungsschein"]}),e.jsxs("select",{className:"w-full rounded-lg border border-border bg-background px-3 py-2 text-sm text-foreground",value:s.insurance_certificate_id||"",onChange:async D=>{const ye=D.target.value||null;await G(s.id,{insurance_certificate_id:ye})&&Y.success("Sicherungsschein aktualisiert")},children:[e.jsx("option",{value:"",children:"– Kein Sicherungsschein –"}),F.map(D=>e.jsx("option",{value:D.id,children:D.name},D.id))]})]}),e.jsxs("div",{children:[e.jsxs("h4",{className:"mb-3 font-medium text-foreground",children:["Teilnehmer (",i.length,")"]}),e.jsx("div",{className:"space-y-2",children:i.map(D=>e.jsxs("div",{className:"flex items-center justify-between rounded-lg bg-muted/30 px-3 py-2 group",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsxs(Pt,{className:"h-7 w-7",children:[e.jsx(Tt,{src:D.profile_image||void 0,alt:`${D.first_name} ${D.last_name}`}),e.jsxs(Ft,{className:"text-xs bg-primary/10 text-primary",children:[D.first_name[0],D.last_name[0]]})]}),e.jsxs("span",{className:"text-sm text-foreground",children:[D.first_name," ",D.last_name]}),e.jsx("button",{onClick:ye=>{ye.stopPropagation(),Ls(D)},className:"opacity-0 group-hover:opacity-100 transition-opacity p-1 hover:bg-muted rounded",title:"Namen bearbeiten",children:e.jsx(vt,{className:"h-3 w-3 text-muted-foreground"})})]}),e.jsxs("span",{className:`text-xs ${D.questionnaire_status==="completed"?"text-success":D.questionnaire_status==="pending"?"text-warning":"text-destructive"}`,children:[D.questionnaire_status==="completed"&&"Fragebogen ✓",D.questionnaire_status==="pending"&&"Ausstehend",D.questionnaire_status==="incomplete"&&"Unvollständig"]})]},D.id))})]}),e.jsx("div",{className:"pt-4 border-t border-border",children:e.jsx(Ml,{bookingId:s.id,tripId:s.trip_id,participantProfileIds:i.filter(D=>D.profile_id).map(D=>D.profile_id)})})]}),e.jsxs("div",{className:"space-y-6",children:[e.jsxs("div",{className:"space-y-4",children:[e.jsx("div",{className:"flex items-center justify-between",children:e.jsxs("h4",{className:"font-medium text-foreground flex items-center gap-2",children:[e.jsx(Ha,{className:"h-4 w-4"}),"Reisebestätigung"]})}),(()=>{const D=x.find(ye=>ye.type==="confirmation");return D?e.jsxs("div",{className:"rounded-xl border border-border p-4 flex items-center justify-between",children:[e.jsxs("div",{className:"flex items-center gap-3",children:[e.jsx($s,{className:"h-8 w-8 text-primary"}),e.jsxs("div",{className:"text-left",children:[e.jsx("p",{className:"text-sm font-medium text-foreground",children:D.name}),e.jsxs("p",{className:"text-xs text-muted-foreground",children:["Hochgeladen am ",ae(D.uploaded_at)]})]})]}),e.jsxs("div",{className:"flex gap-1",children:[e.jsx("button",{className:"rounded p-1.5 transition-colors hover:bg-muted",onClick:ye=>{ye.stopPropagation(),Te(D.url)},children:e.jsx(st,{className:"h-4 w-4 text-muted-foreground"})}),e.jsx("button",{className:"rounded p-1.5 transition-colors hover:bg-destructive/10",onClick:ye=>zt(D.id,ye),children:e.jsx(bs,{className:"h-4 w-4 text-destructive"})})]})]}):e.jsxs("label",{className:`rounded-xl border-2 border-dashed p-6 text-center transition-all cursor-pointer block ${cs==="confirmation"?"border-primary bg-primary/5 scale-[1.02]":"border-border hover:border-primary/50"}`,onDragOver:ye=>Bs("confirmation",ye),onDragLeave:Qs,onDrop:ye=>os("confirmation",ye),children:[e.jsx("input",{type:"file",accept:".pdf,.doc,.docx",className:"hidden",onChange:ye=>ke("confirmation",ye),disabled:Pe==="confirmation"}),Pe==="confirmation"?e.jsx($e,{className:"mx-auto h-8 w-8 text-primary animate-spin"}):e.jsx(_t,{className:`mx-auto h-8 w-8 transition-colors ${cs==="confirmation"?"text-primary":"text-muted-foreground"}`}),e.jsx("p",{className:`mt-2 text-sm transition-colors ${cs==="confirmation"?"text-primary font-medium":"text-muted-foreground"}`,children:Pe==="confirmation"?"Wird hochgeladen...":cs==="confirmation"?"Datei hier ablegen":"PDF hierher ziehen oder klicken"})]})})()]}),e.jsxs("div",{className:"space-y-4",children:[e.jsx("div",{className:"flex items-center justify-between",children:e.jsxs("h4",{className:"font-medium text-foreground flex items-center gap-2",children:[e.jsx(Jt,{className:"h-4 w-4"}),"Rechnung"]})}),(()=>{const D=x.find(ye=>ye.type==="invoice");return D?e.jsxs("div",{className:"rounded-xl border border-border p-4 flex items-center justify-between",children:[e.jsxs("div",{className:"flex items-center gap-3",children:[e.jsx($s,{className:"h-8 w-8 text-primary"}),e.jsxs("div",{className:"text-left",children:[e.jsx("p",{className:"text-sm font-medium text-foreground",children:D.name}),e.jsxs("p",{className:"text-xs text-muted-foreground",children:["Hochgeladen am ",ae(D.uploaded_at)]})]})]}),e.jsxs("div",{className:"flex gap-1",children:[e.jsx("button",{className:"rounded p-1.5 transition-colors hover:bg-muted",onClick:ye=>{ye.stopPropagation(),Te(D.url)},children:e.jsx(st,{className:"h-4 w-4 text-muted-foreground"})}),e.jsx("button",{className:"rounded p-1.5 transition-colors hover:bg-destructive/10",onClick:ye=>zt(D.id,ye),children:e.jsx(bs,{className:"h-4 w-4 text-destructive"})})]})]}):e.jsxs("label",{className:`rounded-xl border-2 border-dashed p-6 text-center transition-all cursor-pointer block ${cs==="invoice"?"border-primary bg-primary/5 scale-[1.02]":"border-border hover:border-primary/50"}`,onDragOver:ye=>Bs("invoice",ye),onDragLeave:Qs,onDrop:ye=>os("invoice",ye),children:[e.jsx("input",{type:"file",accept:".pdf,.doc,.docx",className:"hidden",onChange:ye=>ke("invoice",ye),disabled:Pe==="invoice"}),Pe==="invoice"?e.jsx($e,{className:"mx-auto h-8 w-8 text-primary animate-spin"}):e.jsx(_t,{className:`mx-auto h-8 w-8 transition-colors ${cs==="invoice"?"text-primary":"text-muted-foreground"}`}),e.jsx("p",{className:`mt-2 text-sm transition-colors ${cs==="invoice"?"text-primary font-medium":"text-muted-foreground"}`,children:Pe==="invoice"?"Wird hochgeladen...":cs==="invoice"?"Datei hier ablegen":"PDF hierher ziehen oder klicken"})]})})()]}),e.jsxs("div",{className:"space-y-4",children:[e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsx("h4",{className:"font-medium text-foreground",children:"Weitere Dokumente"}),e.jsxs("label",{children:[e.jsx("input",{type:"file",accept:".pdf,.doc,.docx,.jpg,.jpeg,.png",className:"hidden",onChange:D=>ke("other",D),disabled:Pe==="other"}),e.jsx(z,{variant:"outline",size:"sm",className:"gap-2 rounded-lg",asChild:!0,children:e.jsxs("span",{children:[Pe==="other"?e.jsx($e,{className:"h-4 w-4 animate-spin"}):e.jsx(_t,{className:"h-4 w-4"}),Pe==="other"?"Lädt...":"Hochladen"]})})]})]}),e.jsxs("div",{className:"space-y-2",children:[x.filter(D=>D.type==="other").map(D=>e.jsxs("div",{className:"flex items-center justify-between rounded-lg bg-muted/30 px-3 py-2",children:[e.jsxs("div",{className:"flex items-center gap-3",children:[e.jsx($s,{className:"h-4 w-4 text-muted-foreground"}),e.jsxs("div",{children:[e.jsx("p",{className:"text-sm font-medium text-foreground",children:D.name}),e.jsx("p",{className:"text-xs text-muted-foreground",children:ae(D.uploaded_at)})]})]}),e.jsxs("div",{className:"flex gap-1",children:[e.jsx("button",{className:"rounded p-1.5 transition-colors hover:bg-muted",onClick:ye=>{ye.stopPropagation(),Te(D.url)},children:e.jsx(st,{className:"h-4 w-4 text-muted-foreground"})}),e.jsx("button",{className:"rounded p-1.5 transition-colors hover:bg-destructive/10",onClick:ye=>zt(D.id,ye),children:e.jsx(bs,{className:"h-4 w-4 text-destructive"})})]})]},D.id)),x.filter(D=>D.type==="other").length===0&&Ne.filter(D=>D.invoice_url).length===0&&e.jsx("p",{className:"py-2 text-center text-sm text-muted-foreground",children:"Keine weiteren Dokumente"}),Ne.filter(D=>D.invoice_url).length>0&&e.jsxs(e.Fragment,{children:[e.jsxs("p",{className:"text-xs font-medium text-muted-foreground uppercase tracking-wide mt-3 mb-2 flex items-center gap-1",children:[e.jsx(Rt,{className:"h-3 w-3 text-primary"}
120),"Add-on-Rechnungen"]}),Object.entries(Ne.filter(D=>D.invoice_url).reduce((D,ye)=>{const xs=ye.participant_name||"Unbekannt";return(D[xs]||(D[xs]=[])).push(ye),D},{})).map(([D,ye])=>e.jsxs("div",{className:"space-y-2 mb-2",children:[e.jsxs("p",{className:"text-xs font-semibold text-primary flex items-center gap-1",children:[e.jsx(Ns,{className:"h-3 w-3"}),D]}),ye.map(xs=>e.jsxs("div",{className:"flex items-center justify-between rounded-lg bg-primary/5 border border-primary/20 px-3 py-2",children:[e.jsxs("div",{className:"flex items-center gap-3",children:[e.jsx(Rt,{className:"h-4 w-4 text-primary"}),e.jsxs("div",{children:[e.jsx("p",{className:"text-sm font-medium text-foreground",children:xs.addon_name}),e.jsx("p",{className:"text-xs text-muted-foreground",children:ve(xs.total_price)})]})]}),e.jsx("button",{className:"rounded p-1.5 transition-colors hover:bg-muted",onClick:Ys=>{Ys.stopPropagation(),La(xs.invoice_url,"booking-documents")},title:"Rechnung öffnen",children:e.jsx(st,{className:"h-4 w-4 text-muted-foreground"})})]},`addon-doc-${xs.id}`))]},`addon-group-${D}`))]})]})]})]})]}),e.jsxs("div",{className:"mt-6 flex justify-end gap-3 border-t border-border pt-4",children:[!Le&&e.jsxs(e.Fragment,{children:[e.jsx(z,{variant:"outline",size:"icon",className:"rounded-xl text-destructive hover:bg-destructive/10 hover:text-destructive",onClick:D=>{D.stopPropagation(),g(!0)},children:e.jsx(bs,{className:"h-4 w-4"})}),e.jsxs(z,{variant:"outline",className:"rounded-xl gap-2 text-destructive hover:bg-destructive/10 hover:text-destructive",onClick:D=>{D.stopPropagation(),W(!0)},children:[e.jsx(Vt,{className:"h-4 w-4"}),"Stornieren"]}),e.jsxs(z,{variant:"outline",className:"rounded-xl gap-2",onClick:D=>{D.stopPropagation(),p(!0)},children:[e.jsx(Kt,{className:"h-4 w-4"}),"Zahlung hinzufügen"]}),e.jsxs(z,{className:"rounded-xl gap-2",onClick:D=>{D.stopPropagation(),Re({customer_name:s.customer_name,customer_email:s.customer_email,customer_phone:s.customer_phone||"",billing_street:s.billing_street||(Me==null?void 0:Me.billing_street)||"",billing_postal_code:s.billing_postal_code||(Me==null?void 0:Me.billing_postal_code)||"",billing_city:s.billing_city||(Me==null?void 0:Me.billing_city)||"",billing_country:s.billing_country||(Me==null?void 0:Me.billing_country)||"",participant_count:s.participant_count,total_amount:s.total_amount}),le(!0)},children:[e.jsx(wa,{className:"h-4 w-4"}),"Buchung bearbeiten"]})]}),Le&&e.jsxs("div",{className:"flex flex-wrap gap-2 items-center",children:[e.jsxs("div",{className:"text-sm text-muted-foreground mr-auto",children:["Storno-Gebühr: ",e.jsx("span",{className:"font-medium text-foreground",children:ve(s.cancellation_fee||0)})," • ",(s.cancellation_fee||0)>s.paid_amount?e.jsxs(e.Fragment,{children:["Offen: ",e.jsx("span",{className:"font-medium text-destructive",children:ve((s.cancellation_fee||0)-s.paid_amount)})]}):e.jsxs(e.Fragment,{children:["Rückerstattung: ",e.jsx("span",{className:"font-medium text-success",children:ve(s.paid_amount-(s.cancellation_fee||0))})]})]}),e.jsxs(z,{variant:"outline",className:"rounded-xl gap-2",onClick:D=>{D.stopPropagation(),I(s.cancellation_fee||0),$(s.cancellation_reason||""),be(s.cancelled_at?s.cancelled_at.slice(0,10):new Date().toISOString().slice(0,10)),d(!0)},children:[e.jsx(wa,{className:"h-4 w-4"}),"Storno bearbeiten"]}),e.jsxs(z,{variant:"outline",className:"rounded-xl gap-2",onClick:D=>{D.stopPropagation(),ls()},disabled:Ps,children:[Ps?e.jsx($e,{className:"h-4 w-4 animate-spin"}):e.jsx(Os,{className:"h-4 w-4"}),Ps?"Sende...":"Stornierungsmail senden"]}),e.jsx(Xe,{variant:"outline",className:"text-destructive border-destructive/30",children:"Storniert"})]})]})]})]})]})}function Ir({progress:s,className:n}){return s===0?e.jsx("span",{className:Ms("inline-flex items-center px-2.5 py-0.5 rounded-full text-xs font-medium bg-warning/10 text-warning",n),children:"Ausstehend"}):s===100?e.jsx("span",{className:Ms("inline-flex items-center px-2.5 py-0.5 rounded-full text-xs font-medium bg-success/10 text-success",n),children:"Abgeschlossen"}):e.jsxs("div",{className:Ms("flex items-center gap-2",n),children:[e.jsx("div",{className:"w-16 h-2 rounded-full bg-muted overflow-hidden",children:e.jsx("div",{className:"h-full rounded-full bg-primary transition-all duration-300",style:{width:`${s}%`}})}),e.jsxs("span",{className:"text-xs font-medium text-primary",children:[s,"%"]})]})}function $a(s){const[n,a]=t.useState([]),[b,f]=t.useState([]),[i,x]=t.useState(!0),h=async()=>{try{let T=null;if(s){const{data:A,error:q}=await _.from("questionnaires").select("*").eq("trip_id",s).eq("is_template",!1).maybeSingle();if(q)throw q;A&&(T={id:A.id,name:A.name,description:A.description||void 0,fields:A.fields||[],isTemplate:A.is_template,createdAt:A.created_at})}const{data:o,error:l}=await _.from("questionnaires").select("*").eq("is_template",!0).order("created_at",{ascending:!1});if(l)throw l;const V=(o||[]).map(A=>({id:A.id,name:A.name,description:A.description||void 0,fields:A.fields||[],isTemplate:A.is_template,createdAt:A.created_at}));a(T?[T]:[]),f(V)}catch(T){console.error("Error fetching questionnaires:",T),Y.error("Fehler beim Laden der Fragebögen")}
120finally{x(!1)}};t.useEffect(()=>{h()},[s]);const c=async(T,o)=>{try{const l={name:T.name,description:T.description||null,fields:T.fields,is_template:T.isTemplate,trip_id:T.isTemplate?null:s};if(o){const{error:V}=await _.from("questionnaires").update(l).eq("id",o);if(V)throw V;Y.success("Fragebogen aktualisiert")}else{const{error:V}=await _.from("questionnaires").insert({name:l.name,description:l.description,fields:l.fields,is_template:l.is_template,trip_id:l.trip_id});if(V)throw V;Y.success("Fragebogen gespeichert")}return await h(),!0}catch(l){return console.error("Error saving questionnaire:",l),Y.error("Fehler beim Speichern des Fragebogens"),!1}},k=async T=>{try{const{error:o}=await _.from("questionnaires").delete().eq("id",T);if(o)throw o;return Y.success("Fragebogen gelöscht"),await h(),!0}catch(o){return console.error("Error deleting questionnaire:",o),Y.error("Fehler beim Löschen des Fragebogens"),!1}},C=async T=>{try{const{data:o,error:l}=await _.from("questionnaires").select("*").eq("template_id",T).maybeSingle();if(l)throw l;return o?{id:o.id,name:o.name,description:o.description||void 0,fields:o.fields||[],isTemplate:o.is_template,createdAt:o.created_at}:null}catch(o){return console.error("Error fetching template questionnaire:",o),null}},N=async(T,o)=>{try{const{data:l,error:V}=await _.from("questionnaires").select("*").eq("trip_id",T).eq("is_template",!1).maybeSingle();if(V)throw V;if(!l)return!1;const{data:A}=await _.from("questionnaires").select("id").eq("template_id",o).maybeSingle();if(A){const{error:q}=await _.from("questionnaires").update({name:l.name,description:l.description,fields:l.fields,is_template:!0}).eq("id",A.id);if(q)throw q}else{const{error:q}=await _.from("questionnaires").insert({name:l.name,description:l.description,fields:l.fields,is_template:!0,template_id:o,trip_id:null});if(q)throw q}return!0}catch(l){return console.error("Error copying questionnaire to template:",l),!1}},v=async(T,o)=>{try{const{data:l,error:V}=await _.from("questionnaires").select("*").eq("template_id",T).maybeSingle();if(V)throw V;if(!l)return!1;const{error:A}=await _.from("questionnaires").insert({name:l.name,description:l.description,fields:l.fields,is_template:!1,template_id:null,trip_id:o});if(A)throw A;return!0}catch(l){return console.error("Error copying questionnaire from template:",l),!1}},G=n.find(T=>!T.isTemplate)||null;return{questionnaires:n,templates:b,tripQuestionnaire:G,loading:i,saveQuestionnaire:c,deleteQuestionnaire:k,refetch:h,fetchTemplateQuestionnaire:C,copyQuestionnaireToTemplate:N,copyQuestionnaireFromTemplate:v}}const Ul={text:"Text",dropdown:"Dropdown",checkbox:"Checkbox",number:"Zahl",date:"Datum",radio:"Radiobuttons",file:"Datei-Upload"},Vl={id:"geburtstag",label:"Geburtstag",type:"date",required:!0,placeholder:"Geburtsdatum auswählen"};function Kl({tripId:s,templateId:n,templateName:a,onSave:b}){const{tripQuestionnaire:f,loading:i,saveQuestionnaire:x,copyQuestionnaireToTemplate:h}=$a(s),[c,k]=t.useState(!1),[C,N]=t.useState(""),[v,G]=t.useState(""),[T,o]=t.useState([]),[l,V]=t.useState(!1),[A,q]=t.useState(!1),y=async()=>{if(!(!n||!f)){q(!0);try{if(await h(s,n)){const{toast:$}=await Ca(async()=>{const{toast:ge}=await import("./index-BKB94GeX.js").then(be=>be.bH);return{toast:ge}},__vite__mapDeps([0,1,2,3]));$.success(`Fragebogen zur Vorlage "${a||"Template"}" hinzugefügt`)}}catch(E){console.error("Error syncing to template:",E);const{toast:$}=await Ca(async()=>{const{toast:ge}=await import("./index-BKB94GeX.js").then(be=>be.bH);return{toast:ge}},__vite__mapDeps([0,1,2,3]));$.error("Fehler beim Synchronisieren zur Vorlage")}finally{q(!1)}}};t.useEffect(()=>{c&&(f?(N(f.name),G(f.description||""),o(f.fields)):T.length===0&&o([{...Vl,id:`geburtstag_${Date.now()}`}]))},[f,c]);const W=()=>{const E={id:`field_${Date.now()}`,label:"",type:"text",required:!1,placeholder:""};o([...T,E])},j=(E,$)=>{o(T.map(ge=>ge.id===E?{...ge,...$}:ge))},d=E=>{o(T.filter($=>$.id!==E))},u=async()=>{if(V(!0),await x({name:C,description:v,fields:T,isTemplate:!1},f==null?void 0:f.id)){const $={id:(f==null?void 0:f.id)||`q_${Date.now()}`,name:C,description:v,fields:T,isTemplate:!1,createdAt:new Date().toISOString()};b==null||b($),k(!1),I()}V(!1)},I=()=>{N(""),G(""),o([])};return i?e.jsx("div",{className:"flex items-center justify-center py-8",children:e.jsx($e,{className:"h-6 w-6 animate-spin text-muted-foreground"})}):e.jsxs("div",{className:"space-y-4",children:[f&&e.jsxs("div",{className:"glass-card p-4",children:[e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsxs("div",{className:"flex items-center gap-3",children:[e.jsx("div",{className:"flex h-10 w-10 items-center justify-center rounded-xl bg-primary/10",children:e.jsx($s,{className:"h-5 w-5 text-primary"})}),e.jsxs("div",{children:[e.jsx("h4",{className:"font-medium text-foreground",children:f.name}),e.jsxs("p",{className:"text-sm text-muted-foreground",children:[f.fields.length," Felder"]})]})]}),e.jsxs("div",{className:"flex items-center gap-2",children:[n&&e.jsxs(z,{variant:"outline",className:"rounded-xl gap-2",onClick:y,disabled:A,children:[A?e.jsx($e,{className:"h-4 w-4 animate-spin"}):e.jsx(_t,{className:"h-4 w-4"}),e.jsx("span",{className:"hidden sm:inline",children:"Zur Vorlage"})]}),e.jsxs(We,{open:c,onOpenChange:k,children:[e.jsx(ua,{asChild:!0,children:e.jsx(z,{variant:"outline",className:"rounded-xl",children:"Bearbeiten"})}),e.jsx(Or,{name:C,setName:N,description:v,setDescription:G,fields:T,setFields:o,addField:W,updateField:j,removeField:d,handleSave:u,onClose:()=>k(!1),isSaving:l})]})]})]}),n&&e.jsxs("p",{className:"text-xs text-muted-foreground mt-2 ml-13",children:["Verknüpft mit Vorlage: ",a||"Template"]})]}),!f&&e.jsxs(We,{open:c,onOpenChange:k,children:[e.jsx(ua,{asChild:!0,children:e.jsxs(z,{className:"gap-2 rounded-xl",children:[e.jsx(Es,{className:"h-4 w-4"}),"Fragebogen erstellen"]})}),e.jsx(Or,{name:C,setName:N,description:v,setDescription:G,fields:T,setFields:o,addField:W,updateField:j,removeField:d,handleSave:u,onClose:()=>k(!1),isSaving:l})]})]})}function Or({name:s,setName:n,description:a,setDescription:b,fields:f,setFields:i,addField:x,updateField:h,removeField:c,handleSave:k,onClose:C,isSaving:N}){const v=ir(sa(or),sa(cr,{coordinateGetter:lr})),G=T=>{const{active:o,over:l}=T;if(l&&o.id!==l.id){const V=f.findIndex(q=>q.id===o.id),A=f.findIndex(q=>q.id===l.id);i(gr(f,V,A))}};return e.jsxs(Qe,{className:"glass-modal sm:max-w-2xl max-h-[85vh] overflow-y-auto",children:[e.jsx(Ye,{children:e.jsx(Je,{children:"Fragebogen erstellen"})}),e.jsxs("div",{className:"space-y-6 mt-4",children:[e.jsxs("div",{className:"space-y-4",children:[e.jsxs("div",{className:"space-y-2",children:[e.jsx(U,{children:"Name des Fragebogens"}),e.jsx(te,{value:s,onChange:T=>n(T.target.value),placeholder:"z.B. Reisefragebogen Toskana",className:"rounded-xl"})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(U,{children:"Beschreibung (optional)"}),e.jsx(qs,{value:a,onChange:T=>b(T.target.value),placeholder:"Kurze Beschreibung des Fragebogens",className:"rounded-xl"})]})]}),e.jsxs("div",{className:"space-y-4",children:[e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsx(U,{children:"Felder"}),e.jsxs(z,{variant:"outline",size:"sm",className:"gap-2 rounded-lg",onClick:x,children:[e.jsx(Es,{className:"h-4 w-4"}),"Feld hinzufügen"]})]}),e.jsx(dr,{sensors:v,collisionDetection:mr,onDragEnd:G,children:e.jsx(ur,{items:f.map(T=>T.id),strategy:hr,children:e.jsx("div",{className:"space-y-3",children:f.map((T,o)=>e.jsx(Zl,{field:T,index:o,totalFields:f.length,allFields:f,onUpdate:l=>h(T.id,l),onRemove:()=>c(T.id)},T.id))})})}),f.length===0&&e.jsxs("div",{className:"rounded-xl border-2 border-dashed border-border p-8 text-center",children:[e.jsx("p",{className:"text-muted-foreground",children:"Noch keine Felder hinzugefügt"}),e.jsxs(z,{variant:"outline",size:"sm",className:"mt-3 gap-2 rounded-lg",onClick:x,children:[e.jsx(Es,{className:"h-4 w-4"}),"Erstes Feld hinzufügen"]})]})]}),e.jsxs("div",{className:"flex justify-end gap-3 pt-4 border-t border-border",children:[e.jsx(z,{variant:"outline",className:"rounded-xl",onClick:C,disabled:N,children:"Abbrechen"}),e.jsxs(z,{className:"gap-2 rounded-xl",onClick:k,disabled:!s||f.length===0||N,children:[N?e.jsx($e,{className:"h-4 w-4 animate-spin"}):e.jsx(Da,{className:"h-4 w-4"}),"Speichern"]})]})]})]})}function Zl({field:s,index:n,totalFields:a,allFields:b,onUpdate:f,onRemove:i}){var y,W,j,d,u,I;const{attributes:x,listeners:h,setNodeRef:c,transform:k,transition:C,isDragging:N}=xr({id:s.id}),v={transform:pr.Transform.toString(k),transition:C,opacity:N?.5:1},[G,T]=t.useState(((y=s.options)==null?void 0:y.join(`
121`))||""),[o,l]=t.useState(!!s.condition),V=E=>{T(E);const $=E.split(`
122`).filter(ge=>ge.trim());f({options:$})},A=b.slice(0,n).filter(E=>E.type==="checkbox"||E.type==="radio"||E.type==="dropdown"),q=A.find(E=>{var $;return E.id===(($=s.condition)==null?void 0:$.fieldId)});return e.jsxs("div",{ref:c,style:v,className:"rounded-xl border border-border bg-card p-4 space-y-4",children:[e.jsxs("div",{className:"flex items-start justify-between",children:[e.jsxs("div",{...x,...h,className:"flex items-center gap-2 cursor-grab active:cursor-grabbing p-1 rounded hover:bg-muted/50 transition-colors",children:[e.jsx(Ra,{className:"h-5 w-5 text-muted-foreground"}),e.jsxs("span",{className:"text-xs text-muted-foreground font-medium",children:["Feld ",n+1]})]}),e.jsx("button",{className:"p-1.5 rounded hover:bg-destructive/10",onClick:i,children:e.jsx(bs,{className:"h-4 w-4 text-destructive"})})]}),e.jsxs("div",{className:"grid gap-4 sm:grid-cols-2",children:[e.jsxs("div",{className:"space-y-2",children:[e.jsx(U,{children:"Feldbezeichnung"}),e.jsx(te,{value:s.label,onChange:E=>f({label:E.target.value}),placeholder:"z.B. Ernährungsform",className:"rounded-lg"})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(U,{children:"Feldtyp"}),e.jsxs(Ie,{value:s.type,onValueChange:E=>f({type:E}
122),children:[e.jsx(Oe,{className:"rounded-lg",children:e.jsx(Ve,{})}),e.jsx(Ue,{children:Object.entries(Ul).map(([E,$])=>e.jsx(O,{value:E,children:$},E))})]})]})]}),(s.type==="dropdown"||s.type==="radio")&&e.jsxs("div",{className:"space-y-2",children:[e.jsx(U,{children:"Optionen (eine pro Zeile)"}),e.jsx(qs,{value:G,onChange:E=>V(E.target.value),placeholder:`Option 1
123Option 2
124Option 3`,className:"rounded-lg",rows:4})]}),(s.type==="text"||s.type==="number")&&e.jsxs("div",{className:"space-y-2",children:[e.jsx(U,{children:"Platzhalter (optional)"}),e.jsx(te,{value:s.placeholder||"",onChange:E=>f({placeholder:E.target.value}),placeholder:"Hinweistext für das Eingabefeld",className:"rounded-lg"})]}),s.type==="file"&&e.jsxs("div",{className:"space-y-2",children:[e.jsx(U,{children:"Akzeptierte Dateitypen (optional)"}),e.jsx(te,{value:((W=s.acceptedFileTypes)==null?void 0:W.join(", "))||"",onChange:E=>f({acceptedFileTypes:E.target.value.split(",").map($=>$.trim()).filter(Boolean)}),placeholder:"z.B. image/*, .pdf, .docx",className:"rounded-lg"}),e.jsx("p",{className:"text-xs text-muted-foreground",children:"Kommagetrennt, z.B.: image/*, .pdf, .docx"})]}),e.jsxs("div",{className:"flex flex-wrap items-center gap-4",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(ys,{id:`required-${s.id}`,checked:s.required,onCheckedChange:E=>f({required:E})}),e.jsx(U,{htmlFor:`required-${s.id}`,children:"Pflichtfeld"})]}),e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(ys,{id:`static-${s.id}`,checked:s.isStatic||!1,onCheckedChange:E=>f({isStatic:E})}),e.jsxs(U,{htmlFor:`static-${s.id}`,className:"flex items-center gap-1",children:["Statisches Feld",e.jsx("span",{className:"text-xs text-muted-foreground",children:"(Im Profil speichern)"})]})]})]}),n>0&&A.length>0&&e.jsxs("div",{className:"border-t border-border pt-4 space-y-3",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(ys,{id:`condition-${s.id}`,checked:o,onCheckedChange:E=>{l(E),E||f({condition:void 0})}}),e.jsx(U,{htmlFor:`condition-${s.id}`,children:"Bedingt anzeigen"})]}),o&&e.jsxs("div",{className:"grid gap-3 sm:grid-cols-2 pl-4 border-l-2 border-primary/30",children:[e.jsxs("div",{className:"space-y-2",children:[e.jsx(U,{className:"text-sm",children:"Wenn Feld"}),e.jsxs(Ie,{value:((j=s.condition)==null?void 0:j.fieldId)||"",onValueChange:E=>{var $;return f({condition:{fieldId:E,value:(($=s.condition)==null?void 0:$.value)||""}})},children:[e.jsx(Oe,{className:"rounded-lg",children:e.jsx(Ve,{placeholder:"Feld auswählen..."})}),e.jsx(Ue,{children:A.map(E=>e.jsx(O,{value:E.id,children:E.label||`Feld ${b.indexOf(E)+1}`},E.id))})]})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(U,{className:"text-sm",children:"den Wert hat"}),(q==null?void 0:q.type)==="checkbox"?e.jsxs(Ie,{value:((d=s.condition)==null?void 0:d.value)||"",onValueChange:E=>{var $;return f({condition:{fieldId:(($=s.condition)==null?void 0:$.fieldId)||"",value:E}})},children:[e.jsx(Oe,{className:"rounded-lg",children:e.jsx(Ve,{placeholder:"Wert wählen..."})}),e.jsxs(Ue,{children:[e.jsx(O,{value:"true",children:"Ja (angehakt)"}),e.jsx(O,{value:"false",children:"Nein (nicht angehakt)"})]})]}):q!=null&&q.options&&q.options.length>0?e.jsxs(Ie,{value:((u=s.condition)==null?void 0:u.value)||"",onValueChange:E=>{var $;return f({condition:{fieldId:(($=s.condition)==null?void 0:$.fieldId)||"",value:E}})},children:[e.jsx(Oe,{className:"rounded-lg",children:e.jsx(Ve,{placeholder:"Wert wählen..."})}),e.jsx(Ue,{children:q.options.map(E=>e.jsx(O,{value:E,children:E},E))})]}):e.jsx(te,{value:((I=s.condition)==null?void 0:I.value)||"",onChange:E=>{var $;return f({condition:{fieldId:(($=s.condition)==null?void 0:$.fieldId)||"",value:E.target.value}})},placeholder:"Erwarteter Wert",className:"rounded-lg"})]})]})]})]})}function Hl({open:s,onOpenChange:n,participants:a}){const b=a.filter(i=>i.icebreakerAnswer),f=a.filter(i=>!i.icebreakerAnswer);return e.jsx(We,{open:s,onOpenChange:n,children:e.jsxs(Qe,{className:"sm:max-w-lg max-h-[85vh]",children:[e.jsxs(Ye,{children:[e.jsxs(Je,{className:"flex items-center gap-2",children:[e.jsx(xi,{className:"h-5 w-5 text-primary"}),"Icebreaker-Antworten"]}),e.jsx(Ds,{children:'„Worauf freust du dich am meisten?"'})]}),e.jsx(za,{className:"max-h-[60vh] pr-4 -mr-4",children:e.jsxs("div",{className:"space-y-4",children:[b.length>0?b.map(i=>e.jsxs("div",{className:"flex gap-3 p-3 rounded-xl bg-muted/30",children:[e.jsxs(Pt,{className:"h-10 w-10 shrink-0",children:[e.jsx(Tt,{src:i.profileImage||void 0}),e.jsxs(Ft,{className:"bg-primary/10 text-primary",children:[i.firstName[0],i.lastName[0]]})]}),e.jsxs("div",{className:"min-w-0 flex-1",children:[e.jsxs("p",{className:"font-medium text-sm text-foreground",children:[Cr(i.firstName)," ",i.lastName[0],"."]}),e.jsxs("p",{className:"text-sm text-muted-foreground mt-0.5 italic",children:["„",i.icebreakerAnswer,'"']})]})]},i.id)):e.jsx("p",{className:"text-center text-muted-foreground py-4",children:"Noch keine Antworten vorhanden."}),f.length>0&&e.jsxs(e.Fragment,{children:[e.jsxs("div",{className:"flex items-center gap-2 pt-2",children:[e.jsx("div",{className:"h-px flex-1 bg-border"}),e.jsxs("span",{className:"text-xs text-muted-foreground px-2",children:["Noch keine Antwort (",f.length,")"]}),e.jsx("div",{className:"h-px flex-1 bg-border"})]}),e.jsx("div",{className:"flex flex-wrap gap-2",children:f.map(i=>e.jsxs("div",{className:"flex items-center gap-2 px-3 py-1.5 rounded-full bg-muted/50",children:[e.jsxs(Pt,{className:"h-6 w-6",children:[e.jsx(Tt,{src:i.profileImage||void 0}),e.jsxs(Ft,{className:"text-xs bg-muted",children:[i.firstName[0],i.lastName[0]]})]}),e.jsxs("span",{className:"text-sm text-muted-foreground",children:[Cr(i.firstName)," ",i.lastName[0],"."]})]},i.id))})]})]})})]})})}function Wl({participant:s,onCertificateUpdated:n}){const[a,b]=t.useState(!1),[f,i]=t.useState(!1),[x,h]=t.useState(!1),[c,k]=t.useState(!1),C=t.useRef(null),N=s.wildernessCertificateUrl,v=async y=>{if(y.type!=="application/pdf"){Y.error("Nur PDF-Dateien erlaubt");return}b(!0);try{const W=Date.now(),j=`${s.id}/${W}.pdf`,{error:d}=await _.storage.from("wilderness-certificates").upload(j,y);if(d)throw d;const{error:u}=await _.from("participants").update({wilderness_certificate_url:j}).eq("id",s.id);if(u)throw u;Y.success("Urkunde hochgeladen"),n()}catch(W){console.error("Upload error:",W),Y.error("Fehler beim Hochladen")}finally{b(!1),C.current&&(C.current.value="")}},G=async y=>{var j;const W=(j=y.target.files)==null?void 0:j[0];W&&await v(W)},T=y=>{y.preventDefault(),y.stopPropagation()},o=y=>{y.preventDefault(),y.stopPropagation(),k(!0)},l=y=>{y.preventDefault(),y.stopPropagation(),k(!1)},V=async y=>{var j;y.preventDefault(),y.stopPropagation(),k(!1);const W=(j=y.dataTransfer.files)==null?void 0:j[0];W&&await v(W)},A=async()=>
124{if(N){h(!0);try{const{data:y,error:W}=await _.storage.from("wilderness-certificates").createSignedUrl(N,3600);if(W)throw W;window.open(y.signedUrl,"_blank")}catch(y){console.error("Download error:",y),Y.error("Fehler beim Herunterladen")}finally{h(!1)}}},q=async()=>{if(N){i(!0);try{const{error:y}=await _.storage.from("wilderness-certificates").remove([N]);if(y)throw y;const{error:W}=await _.from("participants").update({wilderness_certificate_url:null}).eq("id",s.id);if(W)throw W;Y.success("Urkunde gelöscht"),n()}catch(y){console.error("Delete error:",y),Y.error("Fehler beim Löschen")}finally{i(!1)}}};return e.jsxs("div",{className:"space-y-6",children:[e.jsx("div",{className:"rounded-xl bg-gradient-to-br from-green-50 to-emerald-50 dark:from-green-950/30 dark:to-emerald-950/30 p-6 border border-green-200/50 dark:border-green-800/50",children:e.jsxs("div",{className:"flex items-start gap-4",children:[e.jsx("div",{className:"p-3 rounded-xl bg-green-100 dark:bg-green-900/50",children:e.jsx(yn,{className:"h-8 w-8 text-green-600 dark:text-green-400"})}),e.jsxs("div",{children:[e.jsx("h4",{className:"font-semibold text-lg text-foreground",children:"Wilderness International"}),e.jsx("p",{className:"text-sm text-muted-foreground mt-1",children:"64 m² Regenwald im Off The Path Wald geschützt"})]})]})}),e.jsx("input",{ref:C,type:"file",accept:".pdf",onChange:G,className:"hidden"}),N?e.jsx("div",{className:"border rounded-xl p-6 bg-card",children:e.jsxs("div",{className:"flex items-center gap-4",children:[e.jsx("div",{className:"p-3 rounded-xl bg-green-100 dark:bg-green-900/50",children:e.jsx($s,{className:"h-8 w-8 text-green-600 dark:text-green-400"})}),e.jsxs("div",{className:"flex-1 min-w-0",children:[e.jsx("p",{className:"font-medium text-foreground",children:"Wilderness Urkunde"}),e.jsx("p",{className:"text-sm text-muted-foreground truncate",children:N.split("/").pop()})]}),e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsxs(z,{variant:"outline",size:"sm",className:"rounded-xl gap-2",onClick:A,disabled:x,children:[e.jsx(lt,{className:"h-4 w-4"}),x?"Lädt...":"Öffnen"]}),e.jsxs(mt,{children:[e.jsx(oi,{asChild:!0,children:e.jsx(z,{variant:"outline",size:"sm",className:"rounded-xl text-destructive hover:text-destructive",disabled:f,children:e.jsx(bs,{className:"h-4 w-4"})})}),e.jsxs(ut,{children:[e.jsxs(ht,{children:[e.jsx(xt,{children:"Urkunde löschen?"}),e.jsx(pt,{children:"Die Wilderness International Urkunde wird unwiderruflich gelöscht."})]}),e.jsxs(gt,{children:[e.jsx(ft,{className:"rounded-xl",children:"Abbrechen"}),e.jsx(jt,{onClick:q,className:"rounded-xl bg-destructive text-destructive-foreground hover:bg-destructive/90",children:"Löschen"})]})]})]})]})]})}):e.jsxs("div",{onClick:()=>{var y;return(y=C.current)==null?void 0:y.click()},onDragOver:T,onDragEnter:o,onDragLeave:l,onDrop:V,className:`border-2 border-dashed rounded-xl p-8 text-center cursor-pointer transition-all ${c?"border-primary bg-primary/10":"border-muted-foreground/25 hover:border-primary/50 hover:bg-muted/30"}`,children:[e.jsx(_t,{className:`h-12 w-12 mx-auto ${c?"text-primary":"text-muted-foreground/50"}`}),e.jsx("p",{className:"mt-4 font-medium text-foreground",children:a?"Wird hochgeladen...":c?"Datei hier ablegen":"Urkunde hochladen"}),e.jsx("p",{className:"text-sm text-muted-foreground mt-1",children:"PDF-Datei auswählen oder hierher ziehen"}),e.jsxs(z,{variant:"outline",className:"mt-4 rounded-xl",disabled:a,children:[e.jsx(_t,{className:"h-4 w-4 mr-2"}),"Datei auswählen"]})]}),e.jsx("p",{className:"text-xs text-muted-foreground",children:'Die Urkunde wird dem Teilnehmer im Portal unter "Zahlungen & Dokumente" angezeigt.'})]})}
124function Ql({participant:s,tripId:n,open:a,onOpenChange:b,onParticipantUpdated:f}){const[i,x]=t.useState("questionnaire"),[h,c]=t.useState(s.questionnaireResponses||{}),[k,C]=t.useState({}),[N,v]=t.useState({arrival_flight_number:"",arrival_date:"",departure_flight_number:"",departure_date:""}),G=t.useRef(!1),T=t.useRef(s.id),o=t.useRef(s.questionnaireResponses||{}),{bookings:l,updateParticipant:V}=na(n),{tripQuestionnaire:A,loading:q}=$a(n),{profile:y}=tr(),W=l.find(K=>K.id===s.bookingId),j=A,d=!s.bookingId;t.useEffect(()=>{(async()=>{if(!s.profileId)return;const M=await qa(s.profileId);M&&C(M.staticQuestionnaireData)})()},[s.profileId]),t.useEffect(()=>{const M=(s.questionnaireResponses||{})._travel_form;v(M?{arrival_flight_number:M.arrival_flight_number||"",arrival_date:M.arrival_date||"",departure_flight_number:M.departure_flight_number||"",departure_date:M.departure_date||""}:{arrival_flight_number:"",arrival_date:"",departure_flight_number:"",departure_date:""})},[s.id,s.questionnaireResponses]),t.useEffect(()=>{if(T.current!==s.id&&(G.current=!1,T.current=s.id,o.current=s.questionnaireResponses||{}),G.current)return;(async()=>{const M=s.questionnaireResponses||{};if(j!=null&&j.fields&&s.profileId){const ee=await qa(s.profileId);if(ee){const he=ji(ee,j.fields,M);c(he),C(ee.staticQuestionnaireData)}else c(M)}else c(M)})()},[s.id,s.profileId,j==null?void 0:j.fields]);const u=(j==null?void 0:j.fields.length)||0,I=(j==null?void 0:j.fields.filter(K=>{const M=h[K.id];return K.type==="checkbox"?M!==void 0:M!==void 0&&M!==""}).length)||0,E=u>0?Math.round(I/u*100):0,[$,ge]=t.useState(!1),be=t.useCallback(async K=>{if(!s.profileId||!(j!=null&&j.fields))return;if(await fi(s.profileId,j.fields,K)){const ee=await qa(s.profileId);ee&&C(ee.staticQuestionnaireData)}},[s.profileId,j==null?void 0:j.fields]),[Z,H]=t.useState("");t.useEffect(()=>{(async()=>{const{data:M}=await _.from("trips").select("name").eq("id",n).single();M&&H(M.name)})()},[n]),t.useEffect(()=>{if(JSON.stringify(h)===JSON.stringify(o.current))return;const M=setTimeout(async()=>{ge(!0);try{const ee=E===100?"completed":E>0?"incomplete":"pending";await V(s.id,{questionnaire_responses:h,questionnaire_status:ee,questionnaire_progress:E})&&(o.current=h,await be(h),s.profileId&&(y!=null&&y.email)&&await On(s.profileId,Z||"Unbekannte Reise",E,y.email,y.full_name||void 0),f())}catch(ee){console.error("Error saving questionnaire:",ee),Y.error("Fehler beim Speichern")}finally{ge(!1)}},800);return()=>clearTimeout(M)},[h,s.profileId,y,Z,E]);const L=(K,M)=>{G.current=!0,c({...h,[K]:M})},[g,r]=t.useState(!1),m=t.useRef(null);t.useEffect(()=>{if(m.current===null){m.current=N;return}if(JSON.stringify(N)===JSON.stringify(m.current))return;const M=setTimeout(async()=>{r(!0);try{const he={...s.questionnaireResponses||{},_travel_form:N};await V(s.id,{questionnaire_responses:he})&&(m.current=N,f())}catch(ee){console.error("Error saving travel form:",ee),Y.error("Fehler beim Speichern")}finally{r(!1)}},800);return()=>clearTimeout(M)},[N,s.id,s.questionnaireResponses,V,f]);const X=(K,M)=>{v(ee=>({...ee,[K]:M}))},p=[N.arrival_flight_number,N.arrival_date,N.departure_flight_number,N.departure_date],ne=p.filter(K=>K&&K.trim()!=="").length,le=Math.round(ne/p.length*100);return!d&&!W?null:(W&&Math.round(Number(W.paid_amount)/Number(W.total_amount)*100),e.jsx(We,{open:a,onOpenChange:b,children:e.jsxs(Qe,{className:"glass-modal sm:max-w-3xl max-h-[90vh] overflow-hidden flex flex-col",children:[e.jsxs(Ye,{className:"pb-4 border-b border-border",children:[e.jsxs("div",{className:"flex items-center gap-4",children:[e.jsxs(Pt,{className:"h-14 w-14",children:[e.jsx(Tt,{src:s.profileImage,alt:`${s.firstName} ${s.lastName}`}),e.jsxs(Ft,{className:"bg-primary/10 text-xl font-semibold text-primary",children:[s.firstName.charAt(0),s.lastName.charAt(0)]})]}),e.jsxs("div",{children:[e.jsxs(Je,{className:"text-xl",children:[s.firstName," ",s.lastName]}),e.jsxs("p",{className:"text-sm text-muted-foreground mt-1",children:[s.email||"Keine E-Mail"," ",d?"• Guide":`• Buchung: ${(W==null?void 0:W.customer_name)||"Unbekannt"}`]}),(k.Geschlecht||k.Kleidergröße)&&e.jsxs("p",{className:"text-xs text-muted-foreground mt-0.5",children:[k.Geschlecht&&e.jsx("span",{children:k.Geschlecht}),k.Geschlecht&&k.Kleidergröße&&" • ",k.Kleidergröße&&e.jsxs("span",{children:["Größe: ",k.Kleidergröße]})]})]})]}),s.email&&e.jsx("div",{className:"mt-3",children:e.jsx(gi,{email:s.email})})]}),e.jsxs(ar,{value:i,onValueChange:x,className:"flex-1 overflow-hidden flex flex-col",children:[e.jsxs(rr,{className:"grid w-full grid-cols-3 rounded-xl bg-muted/30 p-1",children:[e.jsxs(Gs,{value:"questionnaire",className:"rounded-lg gap-2 data-[state=active]:bg-background",children:[e.jsx(Rr,{className:"h-4 w-4"}),e.jsx("span",{className:"hidden sm:inline",children:"Fragebogen"}),E>0&&E<100&&e.jsxs("span",{className:"ml-1 text-xs text-primary",children:[E,"%"]}),E===100&&e.jsx(tt,{className:"h-3 w-3 text-success"})]}),e.jsxs(Gs,{value:"flights",className:"rounded-lg gap-2 data-[state=active]:bg-background",children:[e.jsx($t,{className:"h-4 w-4"}),e.jsx("span",{className:"hidden sm:inline",children:"Flugdaten"}),le>0&&le<100&&e.jsxs("span",{className:"ml-1 text-xs text-primary",children:[le,"%"]}),le===100&&e.jsx(tt,{className:"h-3 w-3 text-success"})]}),e.jsxs(Gs,{value:"certificate",className:"rounded-lg gap-2 data-[state=active]:bg-background",children:[e.jsx(yn,{className:"h-4 w-4"}),e.jsx("span",{className:"hidden sm:inline",children:"Urkunde"}),s.wildernessCertificateUrl&&e.jsx(tt,{className:"h-3 w-3 text-success"})]})]}),e.jsxs("div",{className:"flex-1 overflow-y-auto mt-4",children:[e.jsx(Is,{value:"questionnaire",className:"space-y-6 mt-0",children:j?e.jsxs(e.Fragment,{children:[e.jsxs("div",{className:"rounded-xl bg-muted/30 p-4",children:[e.jsxs("div",{className:"flex justify-between items-center mb-2",children:[e.jsxs("div",{children:[e.jsx("h4",{className:"font-medium text-foreground",children:j.name}),j.description&&e.jsx("p",{className:"text-sm text-muted-foreground",children:j.description})]}),e.jsx("div",{className:"flex items-center gap-2",children:E===100?e.jsx("span",{className:"px-3 py-1 rounded-full bg-success/20 text-success text-sm font-medium",children:"Abgeschlossen"}):e.jsxs("span",{className:"text-sm text-muted-foreground",children:[I," / ",u," Felder"]})})]}),e.jsx("div",{className:"h-2 rounded-full bg-muted overflow-hidden",children:e.jsx("div",{className:`h-full rounded-full transition-all duration-300 ${E===100?"bg-success":"bg-primary"}`,style:{width:`${E}%`}})}),e.jsxs("p",{className:"text-xs text-muted-foreground mt-2 flex items-center gap-1",children:[e.jsx(Da,{className:`h-3 w-3 ${$?"animate-pulse":""}`}),$?"Speichert...":"Wird automatisch gespeichert"]})]}),e.jsx("div",{className:"space-y-4",children:j.fields.filter(K=>{if(!K.condition)return!0;const M=h[K.condition.fieldId];return typeof M=="boolean"?M.toString()===K.condition.value:M===K.condition.value}).map(K=>e.jsx(Yl,{field:K,value:h[K.id],onChange:M=>L(K.id,M),participantId:s.id},K.id))})]}):e.jsxs("div",{className:"text-center py-12",children:[e.jsx(Rr,{className:"mx-auto h-12 w-12 text-muted-foreground"}),e.jsx("h3",{className:"mt-4 text-lg font-medium text-foreground",children:"Kein Fragebogen"}),e.jsx("p",{className:"mt-1 text-muted-foreground",children:"Für diese Reise wurde noch kein Fragebogen erstellt."})]})}),e.jsxs(Is,{value:"flights",className:"space-y-6 mt-0",children:[e.jsxs("div",{className:"rounded-xl bg-muted/30 p-4",children:[e.jsxs("div",{className:"flex justify-between items-center mb-2",children:[e.jsxs("div",{children:[e.jsx("h4",{className:"font-medium text-foreground",children:"An- & Abreise"}),e.jsx("p",{className:"text-sm text-muted-foreground",children:"Flugdaten des Teilnehmers"})]}),e.jsx("div",{className:"flex items-center gap-2",children:le===100?e.jsx("span",{className:"px-3 py-1 rounded-full bg-success/20 text-success text-sm font-medium",children:"Vollständig"}):e.jsxs("span",{className:"text-sm text-muted-foreground",children:[ne," / 4 Felder"]})})]}),e.jsx("div",{className:"h-2 rounded-full bg-muted overflow-hidden",children:e.jsx("div",{className:`h-full rounded-full transition-all duration-300 ${le===100?"bg-success":"bg-primary"}`,style:{width:`${le}%`}})})]}),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(_i,{className:"h-4 w-4"}),e.jsx("span",{children:"Anreise"})]}),e.jsxs("div",{className:"grid gap-4 sm:grid-cols-2",children:[e.jsxs("div",{className:"space-y-2",children:[e.jsx(U,{htmlFor:"arrival_flight",children:"Flugnummer"}),e.jsx(te,{id:"arrival_flight",placeholder:"z.B. LH1234",value:N.arrival_flight_number,onChange:K=>X("arrival_flight_number",K.target.value),className:"rounded-xl"})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(U,{htmlFor:"arrival_date",children:"Ankunftsdatum"}),e.jsx(te,{id:"arrival_date",type:"date",value:N.arrival_date,onChange:K=>X("arrival_date",K.target.value),className:"rounded-xl"})]})]})]}),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(Ni,{className:"h-4 w-4"}),e.jsx("span",{children:"Abreise"})]}),e.jsxs("div",{className:"grid gap-4 sm:grid-cols-2",children:[e.jsxs("div",{className:"space-y-2",children:[e.jsx(U,{htmlFor:"departure_flight",children:"Flugnummer"}),e.jsx(te,{id:"departure_flight",placeholder:"z.B. LH1235",value:N.departure_flight_number,onChange:K=>X("departure_flight_number",K.target.value),className:"rounded-xl"})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(U,{htmlFor:"departure_date",children:"Abflugdatum"}),e.jsx(te,{id:"departure_date",type:"date",value:N.departure_date,onChange:K=>X("departure_date",K.target.value),className:"rounded-xl"})]})]})]}),e.jsxs("p",{className:"text-xs text-muted-foreground mt-2 flex items-center gap-1",children:[e.jsx(Da,{className:`h-3 w-3 ${g?"animate-pulse":""}`}),g?"Speichert...":"Wird automatisch gespeichert"]})]}),e.jsx(Is,{value:"certificate",className:"space-y-6 mt-0",children:e.jsx(Wl,{participant:s,onCertificateUpdated:f})})]})]})]})}))}function Yl({field:s,value:n,onChange:a,participantId:b}){var C;const f=t.useRef(null),[i,x]=t.useState(!1),h=async N=>{var G;const v=(G=N.target.files)==null?void 0:G[0];if(v){x(!0);try{const T=v.name.split(".").pop(),o=`${b}/${s.id}_${Date.now()}.${T}`,{data:l,error:V}=await _.storage.from("questionnaire-files").upload(o,v);if(V)throw V;a({fileName:v.name,url:o,path:o}),Y.success("Datei hochgeladen")}catch(T){console.error("Upload error:",T),Y.error("Fehler beim Hochladen")}finally{x(!1)}}},c=async()=>
124{if(n!=null&&n.path)try{await _.storage.from("questionnaire-files").remove([n.path])}catch(N){console.error("Delete error:",N)}a(null)},k=s.isStatic;return e.jsxs("div",{className:"space-y-2",children:[e.jsxs(U,{className:"flex items-center gap-2",children:[s.label,s.required&&e.jsx("span",{className:"text-destructive",children:"*"}),k&&e.jsx(it,{children:e.jsxs(Js,{children:[e.jsx(Xs,{asChild:!0,children:e.jsx(vi,{className:"h-3.5 w-3.5 text-primary"})}),e.jsx(et,{children:e.jsx("p",{children:"Wird im Profil gespeichert & bei neuen Reisen vorausgefüllt"})})]})})]}),s.type==="text"&&e.jsx(qs,{value:n||"",onChange:N=>a(N.target.value),placeholder:s.placeholder,className:"rounded-xl resize-none",rows:2}),s.type==="number"&&e.jsx(te,{type:"number",value:n||"",onChange:N=>a(N.target.value?Number(N.target.value):""),placeholder:s.placeholder,className:"rounded-xl"}),s.type==="dropdown"&&s.options&&e.jsxs(Ie,{value:n||"",onValueChange:a,children:[e.jsx(Oe,{className:"rounded-xl",children:e.jsx(Ve,{placeholder:"Auswählen..."})}),e.jsx(Ue,{children:s.options.map(N=>e.jsx(O,{value:N,children:N},N))})]}),s.type==="checkbox"&&e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(Zs,{checked:n||!1,onCheckedChange:a}),e.jsx("span",{className:"text-sm text-muted-foreground",children:"Ja"})]}),s.type==="radio"&&s.options&&e.jsx(fr,{value:n||"",onValueChange:a,className:"space-y-2",children:s.options.map(N=>e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(It,{value:N,id:`${s.id}-${N}`}),e.jsx(U,{htmlFor:`${s.id}-${N}`,className:"font-normal cursor-pointer",children:N})]},N))}),s.type==="date"&&e.jsx(pi,{value:n?new Date(n):void 0,onChange:N=>a(N?N.toISOString():""),placeholder:"Datum wählen..."}),s.type==="file"&&e.jsxs("div",{className:"space-y-2",children:[e.jsx("input",{ref:f,type:"file",accept:((C=s.acceptedFileTypes)==null?void 0:C.join(","))||"*",onChange:h,className:"hidden"}),n!=null&&n.url?e.jsxs("div",{className:"flex items-center gap-2 rounded-xl border border-border p-3 bg-muted/30",children:[e.jsx(wn,{className:"h-5 w-5 text-primary"}),e.jsx("span",{className:"flex-1 text-sm truncate",children:n.fileName}),e.jsx(z,{type:"button",variant:"ghost",size:"sm",onClick:()=>{Ca(async()=>{const{openSignedDocument:N}=await import("./storageUtils-B99NVakz.js");return{openSignedDocument:N}},__vite__mapDeps([4,0,1,2,3])).then(({openSignedDocument:N})=>{N(n.url,"questionnaire-files")})},children:e.jsx(st,{className:"h-4 w-4"})}),e.jsx(z,{type:"button",variant:"ghost",size:"sm",onClick:c,children:e.jsx(bs,{className:"h-4 w-4 text-destructive"})})]}):e.jsx(z,{type:"button",variant:"outline",className:"w-full rounded-xl gap-2",onClick:()=>{var N;return(N=f.current)==null?void 0:N.click()},disabled:i,children:i?e.jsx(e.Fragment,{children:"Wird hochgeladen..."}):e.jsxs(e.Fragment,{children:[e.jsx(_t,{className:"h-4 w-4"}),"Datei auswählen"]})}),s.acceptedFileTypes&&s.acceptedFileTypes.length>0&&e.jsxs("p",{className:"text-xs text-muted-foreground",children:["Erlaubte Dateitypen: ",s.acceptedFileTypes.join(", ")]})]})]})}function Jl({participant:s,open:n,onOpenChange:a,onLinked:b}){const[f,i]=t.useState(s.email||""),[x,h]=t.useState(!1),[c,k]=t.useState(!1),[C,N]=t.useState(null),[v,G]=t.useState(!1);t.useEffect(()=>{n&&(i(s.email||""),N(null),G(!1))},[n,s.email]),t.useEffect(()=>{if(!f||!f.includes("@")){N(null),G(!1);return}const o=setTimeout(async()=>{h(!0);try{const{data:l}=await _.from("participant_profiles").select("id, first_name, last_name, email, phone, loyalty_points, total_nights_stayed, profile_image").eq("email",f.toLowerCase().trim()).maybeSingle();N(l),G(!0)}catch(l){console.error("Error checking profile:",l)}finally{h(!1)}},500);return()=>clearTimeout(o)},[f]);const T=async()=>{var o,l,V;if(!f||!f.includes("@")){Y.error("Bitte gib eine gültige E-Mail-Adresse ein");return}k(!0);try{const A=f.toLowerCase().trim();if(C){const q=s.profileId?await _.from("participant_profiles").select("loyalty_points, total_nights_stayed, referral_count").eq("id",s.profileId).maybeSingle():null,y=C.loyalty_points+(((o=q==null?void 0:q.data)==null?void 0:o.loyalty_points)||0),W=C.total_nights_stayed+(((l=q==null?void 0:q.data)==null?void 0:l.total_nights_stayed)||0),j=((V=q==null?void 0:q.data)==null?void 0:V.referral_count)||0;if(await _.from("participant_profiles").update({loyalty_points:y,total_nights_stayed:W,referral_count:(C.loyalty_points>0,j),loyalty_last_activity:new Date().toISOString()}).eq("id",C.id),await _.from("participants").update({email:A,profile_id:C.id}).eq("id",s.id),s.profileId&&s.profileId!==C.id){const{data:d}=await _.from("participants").select("id").eq("profile_id",s.profileId).neq("id",s.id);(!d||d.length===0)&&await _.from("participant_profiles").delete().eq("id",s.profileId)}Y.success(`${s.firstName} wurde mit dem Profil von ${C.first_name} ${C.last_name} verknüpft`,{description:"Treuepunkte wurden zusammengeführt"})}else await _.from("participants").update({email:A}).eq("id",s.id),s.profileId&&await _.from("participant_profiles").update({email:A}).eq("id",s.profileId),Y.success("E-Mail-Adresse wurde gespeichert");b(),a(!1)}catch(A){console.error("Error linking email:",A),Y.error("Fehler beim Speichern")}finally{k(!1)}};return e.jsx(We,{open:n,onOpenChange:a,children:e.jsxs(Qe,{className:"sm:max-w-md",children:[e.jsxs(Ye,{children:[e.jsxs(Je,{className:"flex items-center gap-2",children:[e.jsx(Os,{className:"h-5 w-5"}),"E-Mail zuweisen"]}),e.jsxs(Ds,{children:["Füge eine E-Mail-Adresse hinzu, um ",s.firstName," mit einem Profil zu verknüpfen."]})]}),e.jsxs("div",{className:"space-y-4 py-4",children:[e.jsxs("div",{className:"flex items-center gap-3 p-3 rounded-lg bg-muted/50",children:[e.jsxs(Pt,{className:"h-10 w-10",children:[e.jsx(Tt,{src:s.profileImage}),e.jsxs(Ft,{className:"bg-primary/10 text-primary",children:[s.firstName.charAt(0),s.lastName.charAt(0)]})]}),e.jsxs("div",{children:[e.jsxs("p",{className:"font-medium",children:[s.firstName," ",s.lastName]}),e.jsx("p",{className:"text-sm text-muted-foreground",children:s.email||"Keine E-Mail hinterlegt"})]})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(U,{htmlFor:"email",children:"E-Mail-Adresse"}),e.jsxs("div",{className:"relative",children:[e.jsx(te,{id:"email",type:"email",value:f,onChange:o=>i(o.target.value),placeholder:"[email protected]",className:"pr-10"}),x&&e.jsx($e,{className:"absolute right-3 top-1/2 -translate-y-1/2 h-4 w-4 animate-spin text-muted-foreground"})]})]}),v&&C&&e.jsxs(Sr,{className:"border-primary/50 bg-primary/5",children:[e.jsx(Xt,{className:"h-4 w-4"}),e.jsxs(Dr,{children:[e.jsxs("div",{className:"flex items-center gap-3 mt-1",children:[e.jsxs(Pt,{className:"h-8 w-8",children:[e.jsx(Tt,{src:C.profile_image||void 0}),e.jsxs(Ft,{className:"bg-primary/10 text-primary text-xs",children:[C.first_name.charAt(0),C.last_name.charAt(0)]})]}),e.jsxs("div",{className:"flex-1",children:[e.jsx("p",{className:"font-medium text-sm",children:"Bestehendes Profil gefunden"}),e.jsxs("p",{className:"text-xs text-muted-foreground",children:[C.first_name," ",C.last_name," • ",C.loyalty_points," Punkte • ",C.total_nights_stayed," Nächte"]})]})]}),e.jsxs("p",{className:"mt-2 text-xs",children:[s.firstName," wird mit diesem Profil verknüpft und die Treuepunkte werden zusammengeführt."]})]})]}),v&&!C&&f.includes("@")&&e.jsxs(Sr,{children:[e.jsx(ra,{className:"h-4 w-4"}),e.jsx(Dr,{children:e.jsx("p",{className:"text-sm",children:"Kein bestehendes Profil mit dieser E-Mail gefunden. Die E-Mail wird dem aktuellen Profil hinzugefügt."})})]})]}),e.jsxs(gs,{children:[e.jsx(z,{variant:"outline",onClick:()=>a(!1),children:"Abbrechen"}),e.jsx(z,{onClick:T,disabled:!f.includes("@")||c||x,children:c?e.jsxs(e.Fragment,{children:[e.jsx($e,{className:"mr-2 h-4 w-4 animate-spin"}),"Speichern..."]}):C?e.jsxs(e.Fragment,{children:[e.jsx(Xt,{className:"mr-2 h-4 w-4"}),"Verknüpfen"]}):"Speichern"})]})]})})}function Xl(s){return dt({queryKey:["trip-guide-assignments",s],enabled:!!s,queryFn:async()=>{const{data:n,error:a}=await _.from("participants").select("id, first_name, last_name, email, profile_id, guide_assignment_status, guide_requested_at, guide_responded_at, guide_decline_reason, guide_reminder_sent_at, guide_request_sent_count").eq("trip_id",s).eq("is_guide",!0);if(a)throw a;return n??[]}})}function ec(s){const n=ta();return oa({mutationFn:async a=>{const{data:b,error:f}=await _.functions.invoke("send-guide-assignment-request",{body:{mode:"request",participant_id:a}});if(f)throw f;return b},onSuccess:()=>{n.invalidateQueries({queryKey:["trip-guide-assignments",s]}),Y.success("Anfrage an Guide versendet")},onError:a=>Y.error((a==null?void 0:a.message)||"Anfrage konnte nicht versendet werden")})}function sc(s,n=!0){return dt({queryKey:["guide-assignment-log",s??null],enabled:n,queryFn:async()=>{const{data:a,error:b}=await _.rpc("admin_get_guide_assignment_log",{p_profile_id:s??void 0});if(b)throw b;return a??[]}})}const tc={requested:"Anfrage versendet",reminded:"Erinnerung versendet",accepted:"Guide hat zugesagt",declined:"Guide hat abgesagt",assigned:"Guide zugewiesen",legacy_import:"Altbestand übernommen"};function ac({assignment:s}){const n=s.guide_assignment_status;return n==="accepted"||n==="legacy_accepted"?e.jsxs(Xe,{variant:"outline",className:"gap-1 border-safari-green/40 text-safari-green text-[10px]",children:[e.jsx(ra,{className:"h-3 w-3"}),n==="accepted"?"Zugesagt":"Bestand"]}):n==="declined"?e.jsxs(Xe,{variant:"outline",className:"gap-1 border-destructive/40 text-destructive text-[10px]",children:[e.jsx(Vt,{className:"h-3 w-3"})," Abgesagt"]}):e.jsxs(Xe,{variant:"outline",className:"gap-1 border-amber-500/40 text-amber-600 text-[10px]",children:[e.jsx(Vs,{className:"h-3 w-3"}),s.guide_requested_at?"Antwort offen":"Nicht angefragt"]})}
124function rc({assignment:s,tripId:n}){const[a,b]=t.useState(!1),f=ec(n),{data:i=[],isLoading:x}=sc(s.profile_id??void 0,a),h=s.guide_assignment_status==="pending";return e.jsxs("div",{className:"flex items-center gap-1",onClick:c=>c.stopPropagation(),children:[h&&e.jsx(z,{variant:"ghost",size:"icon",className:"h-6 w-6",title:s.guide_requested_at?"Anfrage erneut senden":"Anfrage senden",disabled:f.isPending,onClick:()=>f.mutate(s.id),children:e.jsx(Bt,{className:"h-3 w-3 text-primary"})}),e.jsx(z,{variant:"ghost",size:"icon",className:"h-6 w-6",title:"Nachweis-Protokoll",onClick:()=>b(!0),children:e.jsx(yi,{className:"h-3 w-3 text-muted-foreground"})}),e.jsx(We,{open:a,onOpenChange:b,children:e.jsxs(Qe,{className:"sm:max-w-lg",children:[e.jsxs(Ye,{children:[e.jsx(Je,{children:"Nachweis-Protokoll"}),e.jsxs(Ds,{children:[s.first_name," ",s.last_name," · unveränderliche Historie aller Zuweisungen und Entscheidungen"]})]}),s.guide_decline_reason&&e.jsxs("p",{className:"text-xs rounded-md bg-muted/50 p-3",children:["Absage-Grund: ",s.guide_decline_reason]}),e.jsx("div",{className:"max-h-80 overflow-y-auto space-y-2",children:x?e.jsx("p",{className:"text-sm text-muted-foreground",children:"Lade…"}):i.length===0?e.jsx("p",{className:"text-sm text-muted-foreground",children:"Noch keine Einträge."}):i.map(c=>e.jsxs("div",{className:"rounded-lg border p-3 text-xs space-y-1",children:[e.jsxs("div",{className:"flex items-center justify-between gap-2",children:[e.jsx("span",{className:"font-medium",children:tc[c.event]??c.event}),e.jsx("span",{className:"text-muted-foreground",children:fs(ka(c.created_at),"d. MMM yyyy, HH:mm",{locale:Ts})})]}),e.jsx("div",{className:"text-muted-foreground",children:c.trip_name}),c.reason&&e.jsxs("div",{children:["Grund: ",c.reason]}),c.decision_text&&e.jsxs("div",{className:"italic",children:["„",c.decision_text,"“"]}),c.actor&&e.jsxs("div",{className:"text-muted-foreground",children:["Ausgelöst von: ",c.actor]})]},c.id))})]})})]})}const Ur=["#8B5CF6","#EC4899","#F59E0B","#10B981","#3B82F6","#EF4444","#14B8A6","#F97316"],Vr=(s,n)=>{const a=He(s),b=He(n);let f=b.getFullYear()-a.getFullYear();const i=b.getMonth()-a.getMonth();return(i<0||i===0&&b.getDate()<a.getDate())&&f--,f},nc=(s,n)=>{if(!s||!n)return null;const a=new Date(s),b=He(n),f=new Date;if(b<f)return null;const i=a<f,x=Math.floor((a.getTime()-b.getTime())/(1e3*60*60*24*30));return i||x<6?{isExpiring:!0,isExpired:i,monthsBeforeTrip:x}:null},Oa=s=>s||null,ic=(s,n,a)=>{if(!s)return{hasBirthday:!1,formattedDate:""};const b=He(s),f=He(n),i=He(a),x=new Date(f.getFullYear(),b.getMonth(),b.getDate()),h=new Date(f.getFullYear()+1,b.getMonth(),b.getDate()),c=k=>k>=f&&k<=i;return c(x)?{hasBirthday:!0,formattedDate:x.toLocaleDateString("de-DE",{day:"2-digit",month:"2-digit"})}:c(h)?{hasBirthday:!0,formattedDate:h.toLocaleDateString("de-DE",{day:"2-digit",month:"2-digit"})}:{hasBirthday:!1,formattedDate:""}},la=[{id:"group",label:"Gruppe",field:"group",visible:!0,isDefault:!1},{id:"name",label:"Teilnehmer",field:"name",visible:!0,isDefault:!0},{id:"contact",label:"Kontakt",field:"contact",visible:!0,isDefault:!0},{id:"age",label:"Alter (bei Reise)",field:"age",visible:!0,isDefault:!1},{id:"booking",label:"Buchung",field:"booking",visible:!0,isDefault:!0},{id:"questionnaire",label:"Fragebogen",field:"questionnaireStatus",visible:!0,isDefault:!0}],Kr="participantsTab_columnVisibility";function lc({tripId:s,groups:n,onGroupsChange:a}){var Ct;const b=Ln(),[f,i]=t.useState(""),[x,h]=t.useState(()=>{const F=localStorage.getItem(Kr);if(F)try{const re=JSON.parse(F);return la.map(Ne=>({...Ne,visible:re[Ne.id]??Ne.visible}))}catch{return la}return la}),[c,k]=t.useState("all"),[C,N]=t.useState(null),[v,G]=t.useState(!1),[T,o]=t.useState([]),[l,V]=t.useState(!1),[A,q]=t.useState(""),[y,W]=t.useState("couple"),[j,d]=t.useState(null),[u,I]=t.useState(""),[E,$]=t.useState(null),[ge,be]=t.useState(!1),[Z,H]=t.useState(!1),{bookings:L,participants:g,guides:r,isLoading:m,fetchBookings:X,createGuide:p,assignExistingGuide:ne,deleteGuide:le}=na(s),{trips:K}=nr(),{tripQuestionnaire:M}=$a(s),{data:ee,isLoading:he}=bi(),we=ta(),{data:De=[]}=Xl(s),_e=t.useMemo(()=>new Map(De.map(F=>[F.id,F])),[De]),[J,Ae]=t.useState(!1),[qe,Be]=t.useState(!1),[Ke,Ce]=t.useState(!1),[xe,ms]=t.useState("existing"),[us,Q]=t.useState({first_name:"",last_name:"",email:"",ph
124one:""}),[ue,de]=t.useState(null),[S,P]=t.useState(""),ie=K.find(F=>F.id===s);t.useEffect(()=>{if(M&&M.fields.length>0){const F=M.fields.map(re=>({id:`q_${re.id}`,label:re.label,field:`questionnaire_${re.id}`,visible:!1,isDefault:!1,isQuestionnaireField:!0}));h(re=>{const Ne=la.map(Ge=>{const Ze=re.find(es=>es.id===Ge.id);return Ze?{...Ge,visible:Ze.visible}:Ge}),as=F.map(Ge=>{const Ze=re.find(es=>es.id===Ge.id);return Ze?{...Ge,visible:Ze.visible}:Ge});return[...Ne,...as]})}else h(F=>la.map(re=>{const Ne=F.find(as=>as.id===re.id);return Ne?{...re,visible:Ne.visible}:re}))},[M]);const Se=t.useMemo(()=>{const F=new Set(L.filter(re=>re.status!=="cancelled").map(re=>re.id));return g.filter(re=>!re.booking_id||F.has(re.booking_id)).map(re=>(L.find(Ne=>Ne.id===re.booking_id),{id:re.id,bookingId:re.booking_id||"",firstName:re.first_name,lastName:re.last_name,email:re.email||"",phone:re.phone||"",dateOfBirth:re.date_of_birth||"",passportNumber:re.passport_number||"",dietaryRequirements:re.dietary_requirements||"",allergies:re.allergies||"",emergencyContact:re.emergency_contact||"",questionnaireStatus:re.questionnaire_status||"pending",questionnaireProgress:re.questionnaire_progress||0,questionnaireResponses:re.questionnaire_responses||{},roomAssignment:re.room_assignment||void 0,groupId:re.group_id||void 0,loyaltyPoints:re.loyalty_points||0,loyaltyLastActivity:re.loyalty_last_activity||void 0,referralCount:re.referral_count||0,totalNightsStayed:re.total_nights_stayed||0,profileId:re.profile_id||void 0,profileImage:re.profile_image||void 0,documentExpiryDate:re.document_expiry_date||void 0,wildernessCertificateUrl:re.wilderness_certificate_url||void 0,icebreakerAnswer:re.icebreaker_answer||void 0}))},[g,L]),R=t.useMemo(()=>r.map(F=>({id:F.id,bookingId:"",firstName:F.first_name,lastName:F.last_name,email:F.email||"",phone:F.phone||"",dateOfBirth:F.date_of_birth||"",passportNumber:F.passport_number||"",dietaryRequirements:F.dietary_requirements||"",allergies:F.allergies||"",emergencyContact:F.emergency_contact||"",questionnaireStatus:F.questionnaire_status||"pending",questionnaireProgress:F.questionnaire_progress||0,questionnaireResponses:F.questionnaire_responses||{},roomAssignment:F.room_assignment||void 0,groupId:F.group_id||void 0,loyaltyPoints:F.loyalty_points||0,loyaltyLastActivity:F.loyalty_last_activity||void 0,referralCount:F.referral_count||0,totalNightsStayed:F.total_nights_stayed||0,profileId:F.profile_id||void 0,profileImage:F.profile_image||void 0,isGuide:!0,wildernessCertificateUrl:F.wilderness_certificate_url||void 0})),[r]),ce=F=>n.find(re=>re.participantIds.includes(F)),oe=Se.filter(F=>F.firstName.toLowerCase().includes(f.toLowerCase())||F.lastName.toLowerCase().includes(f.toLowerCase())||F.email.toLowerCase().includes(f.toLowerCase())?c==="all"?!0:F.questionnaireStatus===c:!1).sort((F,re)=>{const Ne=ce(F.id),as=ce(re.id);return Ne&&!as?-1:!Ne&&as?1:Ne&&as&&Ne.id!==as.id?Ne.name.localeCompare(as.name,"de"):F.lastName.localeCompare(re.lastName,"de")}),me=x.filter(F=>F.visible),Ee=!((Ct=x.find(F=>F.id==="group"))!=null&&Ct.visible),ze=F=>{const re=x.map(as=>as.id===F?{...as,visible:!as.visible}:as);h(re);const Ne={};re.forEach(as=>{Ne[as.id]=as.visible}),localStorage.setItem(Kr,JSON.stringify(Ne))},ns=()=>{if(C){const F=r.find(Ne=>Ne.id===C.id),re=g.find(Ne=>Ne.id===C.id);F?N(Ne=>Ne?{...Ne,questionnaireResponses:F.questionnaire_responses||{},questionnaireProgress:F.questionnaire_progress||0,questionnaireStatus:F.questionnaire_status||"pending"}:null):re&&N(Ne=>Ne?{...Ne,questionnaireResponses:re.questionnaire_responses||{},questionnaireProgress:re.questionnaire_progress||0,questionnaireStatus:re.questionnaire_status||"pending"}:null)}},Pe=(F,re)=>{re.stopPropagation(),T.includes(F)?o(T.filter(Ne=>Ne!==F)):o([...T,F])},Fe=()=>{if(T.length<2)return;const F=Ur[n.length%Ur.length],re=T.map(Ze=>{const es=Se.find(Le=>Le.id===Ze);return es?es.lastName:""});let Ne=A;Ne||(y==="couple"?Ne=`Paar ${re[0]}`:y==="friends"?Ne=`Freunde ${re[0]}`:y==="family"?Ne=`Familie ${re[0]}`:Ne=`${re[0]} & ${re.length>2?"Gruppe":re[1]}`);const as={id:`g${Date.now()}`,tripId:s,name:Ne,color:F,participantIds:T,category:y},Ge=n.map(Ze=>({...Ze,participantIds:Ze.participantIds.filter(es=>!T.includes(es))}
124)).filter(Ze=>Ze.participantIds.length>0);a([...Ge,as]),o([]),G(!1),V(!1),q(""),W("couple")},cs=(F,re)=>{if(!re.trim())return;const Ne=n.map(as=>as.id===F?{...as,name:re.trim()}:as);a(Ne),d(null),I("")},vs=(F,re)=>{re.stopPropagation();const Ne=n.map(as=>({...as,participantIds:as.participantIds.filter(Ge=>Ge!==F)})).filter(as=>as.participantIds.length>1);a(Ne)},Me=()=>{const F=me.map(Ze=>Ze.label),re=oe.map(Ze=>me.map(es=>{var Le,_s;if(es.field.startsWith("questionnaire_")){const Cs=es.field.replace("questionnaire_",""),zs=(Le=Ze.questionnaireResponses)==null?void 0:Le[Cs];return zs==null||zs===""?"":typeof zs=="boolean"?zs?"Ja":"Nein":Array.isArray(zs)?zs.join(", "):String(zs)}switch(es.field){case"group":{const Cs=ce(Ze.id);return(Cs==null?void 0:Cs.name)||""}case"name":return`${Ze.firstName} ${Ze.lastName}`;case"contact":return Ze.email||Ze.phone||"";case"age":{const Cs=Oa(Ze.dateOfBirth);return ie&&Cs?Vr(Cs,ie.startDate).toString():""}case"booking":return((_s=L.find(Cs=>Cs.id===Ze.bookingId))==null?void 0:_s.customer_name)||"";case"questionnaireStatus":return Ze.questionnaireProgress===100?"Abgeschlossen":Ze.questionnaireProgress===0?"Ausstehend":`${Ze.questionnaireProgress}%`;default:return""}})),Ne=[F,...re].map(Ze=>Ze.map(es=>`"${es}"`).join(",")).join(`
125`),as=new Blob([Ne],{type:"text/csv;charset=utf-8;"}),Ge=document.createElement("a");Ge.href=URL.createObjectURL(as),Ge.download=`teilnehmer_${(ie==null?void 0:ie.name)||"export"}.csv`,Ge.click()},se={completed:Se.filter(F=>F.questionnaireStatus==="completed").length,pending:Se.filter(F=>F.questionnaireStatus==="pending").length,incomplete:Se.filter(F=>F.questionnaireStatus==="incomplete").length},Re=F=>{k(c===F?"all":F)},ts=t.useMemo(()=>{if(!ee)return[];const F=r.map(re=>`${re.first_name}-${re.last_name}-${re.email||""}`);return ee.filter(re=>{const Ne=`${re.first_name}-${re.last_name}-${re.email||""}`;return(S===""||`${re.first_name} ${re.last_name}`.toLowerCase().includes(S.toLowerCase())||re.email&&re.email.toLowerCase().includes(S.toLowerCase()))&&!F.includes(Ne)})},[ee,r,S]),hs=async F=>{if(F)try{const{data:re}=await _.from("participants").select("id, guide_assignment_status, guide_requested_at").eq("trip_id",s).eq("is_guide",!0).eq("email",F).maybeSingle();if(!re||re.guide_assignment_status!=="pending"||re.guide_requested_at)return;await _.functions.invoke("send-guide-assignment-request",{body:{mode:"request",participant_id:re.id}}),Y.success("Anfrage zur Zu-/Absage an den Guide versendet")}catch(re){console.error("guide request failed",re)}finally{we.invalidateQueries({queryKey:["trip-guide-assignments",s]})}},As=async()=>{!us.first_name||!us.last_name||(await p(s,us),await hs(us.email),Q({first_name:"",last_name:"",email:"",phone:""}),Ce(!1),ms("existing"))},ds=async()=>{ue&&(await ne(s,{first_name:ue.first_name,last_name:ue.last_name,email:ue.email,phone:ue.phone,profile_id:ue.profile_id}),await hs(ue.email),de(null),Ce(!1),P(""))},Ps=async F=>{await le(F)},Fs=()=>{Ce(!1),ms("existing"),Q({first_name:"",last_name:"",email:"",phone:""}),de(null),P("")},Hs=async()=>{if(se.pending+se.incomplete===0){Y.info("Alle Teilnehmer haben ihre Formulare bereits ausgefüllt");return}H(!0);try{const{data:re,error:Ne}=await _.functions.invoke("send-form-reminder",{body:{tripId:s}});if(Ne)throw Ne;(re==null?void 0:re.sent)>0?Y.success("Formular-Erinnerungen versendet",{description:`${re.sent} von ${re.total} E-Mails gesendet`}):Y.info("Keine Teilnehmer zum Erinnern gefunden")}catch(re){console.error("Error sending form reminders:",re),Y.error("Fehler beim Versenden",{description:"Bitte versuche es erneut."})}finally{H(!1)}};return e.jsxs("div",{className:"space-y-4",children:[e.jsxs("div",{className:"grid gap-4 sm:grid-cols-2",children:[e.jsx(at,{open:J,onOpenChange:Ae,children:e.jsxs("div",{className:"glass-card overflow-hidden",children:[e.jsx(rt,{asChild:!0,children:e.jsxs("button",{className:"w-full p-4 flex items-center justify-between hover:bg-muted/20 transition-colors",children:[e.jsxs("div",{className:"flex items-center gap-3",children:[e.jsx("div",{className:"flex h-9 w-9 items-center justify-center rounded-xl bg-primary/10",children:e.jsx(Ut,{className:"h-4 w-4 text-primary"})}),e.jsxs("div",{className:"text-left",children:[e.jsx("h3",{className:"font-semibold text-foreground",children:"Guides"}),e.jsxs("p",{className:"text-xs text-muted-foreground",children:[R.length," Guide",R.length!==1?"s":""]})]})]}),e.jsx(Us,{className:`h-4 w-4 text-muted-foreground transition-transform duration-200 ${J?"rotate-180":""}`})]})}),e.jsx(nt,{children:e.jsxs("div",{className:"px-4 pb-4 space-y-3",children:[R.length>0?e.jsx("div",{className:"space-y-2",children:R.map(F=>e.jsxs("div",{className:"flex items-center gap-3 p-2 rounded-lg bg-muted/30 hover:bg-muted/50 transition-colors cursor-pointer group",onClick:()=>N(F),children:[e.jsxs(Pt,{className:"h-8 w-8",children:[e.jsx(Tt,{src:F.profileImage,alt:`${F.firstName} ${F.lastName}`}),e.jsxs(Ft,{className:"bg-primary/20 text-primary text-xs",children:[F.firstName.charAt(0),F.lastName.charAt(0)]})]}),e.jsx("div",{className:"flex-1 min-w-0",children:e.jsxs("p",{className:"text-sm font-medium text-foreground truncate",children:[F.firstName," ",F.lastName]})}),_e.get(F.id)&&e.jsx(ac,{assignment:_e.get(F.id)}),e.jsx(Ir,{progress:F.questionnaireProgress}),_e.get(F.id)&&e.jsx(rc,{assignment:_e.get(F.id),tripId:s}),e.jsx(z,{variant:"ghost",size:"icon",className:"h-6 w-6 opacity-0 group-hover:opacity-100 transition-opacity",onClick:re=>{re.stopPropagation(),Ps(F.id)},children:e.jsx(bs,{className:"h-3 w-3 text-destructive"})})]},F.id))}):e.jsx("p",{className:"text-sm text-muted-foreground text-center py-2",children:"Keine Guides"}),e.jsxs(z,{className:"w-full gap-2 rounded-lg",size:"sm",variant:"outline",onClick:F=>{F.stopPropagation(),Ce(!0)},children:[e.jsx(Es,{className:"h-3 w-3"}),"Guide hinzufügen"]})]})})]})}),e.jsx(at,{open:qe,onOpenChange:Be,children:e.jsxs("div",{className:"glass-card overflow-hidden",children:[e.jsx(rt,{asChild:!0,children:e.jsxs("button",{className:"w-full p-4 flex items-center justify-between hover:bg-muted/20 transition-colors",children:[e.jsxs("div",{className:"flex items-center gap-3",children:[e.jsx("div",{className:"flex h-9 w-9 items-center justify-center rounded-xl bg-primary/10",children:e.jsx(jr,{className:"h-4 w-4 text-primary"})}),e.jsxs("div",{className:"text-left",children:[e.jsx("h3",{className:"font-semibold text-foreground",children:"Fragebogen"}),e.jsxs("p",{className:"text-xs text-muted-foreground",children:[(M==null?void 0:M.fields.length)||0," Felder"]})]})]}),e.jsx(Us,{className:`h-4 w-4 text-muted-foreground transition-transform duration-200 ${qe?"rotate-180":""}`})]})}),e.jsx(nt,{children:e.jsx("div",{className:"px-4 pb-4",children:e.jsx(Kl,{tripId:s,templateId:ie==null?void 0:ie.templateId,templateName:ie==null?void 0:ie.name})})})]})})]}),m&&e.jsxs("div",{className:"glass-card p-12 text-center",children:[e.jsx($e,{className:"mx-auto h-12 w-12 text-muted-foreground animate-spin"}),e.jsx("p",{className:"mt-4 text-muted-foreground",children:"Teilnehmer werden geladen..."})]}),!m&&e.jsxs(e.Fragment,{children:[e.jsxs("div",{className:"grid gap-4 sm:grid-cols-3",children:[e.jsxs("button",{onClick:()=>Re("completed"),className:`glass-card p-4 flex items-center gap-4 text-left transition-all ${c==="completed"?"ring-2 ring-success":"hover:bg-muted/30"}`,children:[e.jsx("div",{className:"flex h-10 w-10 items-center justify-center rounded-xl bg-success/10",children:e.jsx(Ha,{className:"h-5 w-5 text-success"})}),e.jsxs("div",{children:[e.jsx("p",{className:"text-2xl font-bold text-foreground",children:se.completed}),e.jsx("p",{className:"text-sm text-muted-foreground",children:"Fragebögen komplett"})]})]}),e.jsxs("button",{onClick:()=>Re("pending"),className:`glass-card p-4 flex items-center gap-4 text-left transition-all ${c==="pending"?"ring-2 ring-warning":"hover:bg-muted/30"}`,children:[e.jsx("div",{className:"flex h-10 w-10 items-center justify-center rounded-xl bg-warning/10",children:e.jsx(Vs,{className:"h-5 w-5 text-warning"})}),e.jsxs("div",{children:[e.jsx("p",{className:"text-2xl font-bold text-foreground",children:se.pending}),e.jsx("p",{className:"text-sm text-muted-foreground",children:"Ausstehend"})]})]}),e.jsxs("button",{onClick:()=>Re("incomplete"),className:`glass-card p-4 flex items-center gap-4 text-left transition-all ${c==="incomplete"?"ring-2 ring-destructive":"hover:bg-muted/30"}`,children:[e.jsx("div",{className:"flex h-10 w-10 items-center justify-center rounded-xl bg-destructive/10",children:e.jsx(_r,{className:"h-5 w-5 text-destructive"})}),e.jsxs("div",{children:[e.jsx("p",{className:"text-2xl font-bold text-foreground",children:se.incomplete}),e.jsx("p",{className:"text-sm text-muted-foreground",children:"Unvollständig"})]})]})]}),c!=="all"&&e.jsxs("div",{className:"flex items-center gap-2 text-sm",children:[e.jsx("span",{className:"text-muted-foreground",children:"Filter aktiv:"}),e.jsx("span",{className:`px-2 py-1 rounded-lg font-medium ${c==="completed"?"bg-success/10 text-success":c==="pending"?"bg-warning/10 text-warning":"bg-destructive/10 text-destructive"}`,children:c==="completed"?"Abgeschlossen":c==="pending"?"Ausstehend":"Unvollständig"}),e.jsx(z,{variant:"ghost",size:"sm",className:"h-6 px-2 text-xs",onClick:()=>k("all"),children:"Filter entfernen"})]}),e.jsxs("div",{className:"flex items-center justify-between gap-4",children:[e.jsxs("div",{className:"relative max-w-md flex-1",children:[e.jsx(wt,{className:"absolute left-3 top-1/2 h-4 w-4 -translate-y-1/2 text-muted-foreground"}),e.jsx(te,{type:"text",placeholder:"Teilnehmer suchen...",value:f,onChange:F=>i(F.target.value),className:"pl-10 rounded-xl bg-muted/50 border-0"})]}),e.jsxs("div",{className:"flex gap-2",children:[e.jsx(it,{children:e.jsxs(Js,{children:[e.jsx(Xs,{asChild:!0,children:e.jsxs(z,{variant:v?"default":"outline",className:"gap-2 rounded-xl",onClick:()=>{G(!v),o([])},children:[e.jsx(Xt,{className:"h-4 w-4"}),e.jsx("span",{className:"hidden sm:inline",children:"Verknüpfen"})]})}),e.jsx(et,{children:e.jsx("p",{children:"Teilnehmer zu Gruppen verbinden (z.B. Paare, Freunde)"})})]})}),e.jsxs(Dt,{children:[e.jsx(Et,{asChild:!0,children:e.jsxs(z,{variant:"outline",className:"gap-2 rounded-xl",children:[e.jsx(wi,{className:"h-4 w-4"}),e.jsx("span",{className:"hidden sm:inline",children:"Spalten"})]})}),e.jsxs(At,{className:"w-64 p-4",align:"end",children:[e.jsx("h4",{className:"font-medium text-foreground mb-3",children:"Sichtbare Spalten"}),e.jsx("div",{className:"space-y-2",children:x.filter(F=>!F.isQuestionnaireField).map(F=>e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(Zs,{id:F.id,checked:F.visible,onCheckedChange:()=>ze(F.id)}),e.jsx(U,{htmlFor:F.id,className:"text-sm cursor-pointer",children:F.label})]},F.id))}),x.some(F=>F.isQuestionnaireField)&&e.jsxs(e.Fragment,{children:[e.jsx("div",{className:"my-3 border-t border-border"}),e.jsx("h4",{className:"font-medium text-foreground mb-3 text-sm",children:"Fragebogen-Felder"}),e.jsx("div",{className:"space-y-2",children:x.filter(F=>F.isQuestionnaireField).map(F=>e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(Zs,{id:F.id,checked:F.visible,onCheckedChange:()=>ze(F.id)}),e.jsx(U,{htmlFor:F.id,className:"text-sm cursor-pointer",children:F.label})]},F.id))})]})]})]}),e.jsx(it,{children:e.jsxs(Js,{children:[e.jsx(Xs,{asChild:!0,children:e.jsxs(z,{variant:"outline",className:"gap-2 rounded-xl",onClick:()=>be(!0),children:[e.jsx(Rt,{className:"h-4 w-4"}),e.jsx("span",{className:"hidden sm:inline",children:"Icebreaker"})]})}),e.jsx(et,{children:e.jsx("p",{children:"Icebreaker-Antworten der Teilnehmer anzeigen"})})]})}),e.jsxs(z,{variant:"outline",className:"gap-2 rounded-xl",onClick:Me,children:[e.jsx(lt,{className:"h-4 w-4"}),e.jsx("span",{className:"hidden sm:inline",children:"CSV Export"})]}),e.jsx(it,{children:e.jsxs(Js,{children:[e.jsx(Xs,{asChild:!0,children:e.jsxs(z,{variant:"outline",className:"gap-2 rounded-xl",onClick:Hs,disabled:Z||se.pending+se.incomplete===0,children:[Z?e.jsx($e,{className:"h-4 w-4 animate-spin"}):e.jsx(Bt,{className:"h-4 w-4"}),e.jsx("span",{className:"hidden sm:inline",children:"Erinnern"})]})}),e.jsx(et,{children:e.jsxs("p",{children:["Formular-Erinnerungen an ",se.pending+se.incomplete," Teilnehmer senden"]})})]})})]})]}),v&&e.jsxs("div",{className:"glass-card p-4 flex items-center justify-between bg-primary/5 border-primary/20",children:[e.jsxs("div",{className:"flex items-center gap-3",children:[e.jsx(Ns,{className:"h-5 w-5 text-primary"}),e.jsxs("div",{children:[e.jsx("p",{className:"font-medium text-foreground",children:"Verknüpfungsmodus aktiv"}),e.jsx("p",{className:"text-sm text-muted-foreground",children:T.length===0?"Wähle mindestens 2 Teilnehmer aus, die zusammengehören":`${T.length} Teilnehmer ausgewählt`})]})]}),e.jsxs("div",{className:"flex gap-2",children:[e.jsx(z,{variant:"outline",size:"sm",className:"rounded-xl",onClick:()=>{G(!1),o([])},children:"Abbrechen"}),e.jsx(z,{size:"sm",className:"rounded-xl",disabled:T.length<2,onClick:()=>V(!0),children:"Gruppe erstellen"})]})]}),n.length>0&&e.jsx("div",{className:"flex flex-wrap gap-2",children:n.map(F=>e.jsxs("div",{className:"flex items-center gap-2 px-3 py-1.5 rounded-full text-sm cursor-pointer",style:{backgroundColor:`${F.color}20`,color:F.color},onClick:()=>{d(F.id),I(F.name)},children:[e.jsx(Ns,{className:"h-3.5 w-3.5"}),j===F.id?e.jsx("input",{autoFocus:!0,className:"bg-transparent border-none outline-none font-medium w-24 text-sm",style:{color:F.color},value:u,onChange:re=>I(re.target.value),onKeyDown:re=>{re.key==="Enter"&&cs(F.id,u),re.key==="Escape"&&(d(null),I(""))},onBlur:()=>cs(F.id,u),onClick:re=>re.stopPropagation()}):e.jsx("span",{className:"font-medium",children:F.name}),e.jsxs("span",{className:"opacity-60",children:["(",F.participantIds.length,")"]})]},F.id))}),e.jsx("div",{className:"glass-card overflow-hidden",children:e.jsx("div",{className:"overflow-x-auto",children:e.jsxs("table",{className:"w-full",children:[e.jsx("thead",{children:e.jsxs("tr",{className:"border-b border-border bg-muted/30",children:[v&&e.jsx("th",{className:"px-3 py-4 w-12"}),me.map(F=>e.jsx("th",{className:"px-5 py-4 text-left text-sm font-medium text-muted-foreground",children:F.label}
125,F.id))]})}),e.jsx("tbody",{children:oe.map(F=>{const re=L.find(es=>es.id===F.bookingId),Ne=Oa(F.dateOfBirth),as=ie&&Ne?Vr(Ne,ie.startDate):null,Ge=ce(F.id),Ze=T.includes(F.id);return e.jsxs("tr",{className:`group/row border-b border-border/50 transition-colors cursor-pointer ${Ze?"bg-primary/10":"hover:bg-muted/20"}`,onClick:es=>{v?Pe(F.id,es):N(F)},children:[v&&e.jsx("td",{className:"px-3 py-4",children:e.jsx(Zs,{checked:Ze,onCheckedChange:()=>{o(Ze?T.filter(es=>es!==F.id):[...T,F.id])}})}),me.map(es=>e.jsxs("td",{className:"px-5 py-4",children:[es.field==="group"&&e.jsx("div",{className:"flex items-center gap-2",children:Ge?e.jsx(it,{children:e.jsxs(Js,{children:[e.jsx(Xs,{asChild:!0,children:e.jsxs("div",{className:"flex items-center gap-1.5 px-2 py-1 rounded-full text-xs font-medium cursor-pointer group/badge",style:{backgroundColor:`${Ge.color}20`,color:Ge.color},onClick:Le=>{Le.stopPropagation(),d(Ge.id),I(Ge.name)},children:[e.jsx(Ns,{className:"h-3 w-3"}),j===Ge.id?e.jsx("input",{autoFocus:!0,className:"bg-transparent border-none outline-none w-20 text-xs font-medium",style:{color:Ge.color},value:u,onChange:Le=>I(Le.target.value),onKeyDown:Le=>{Le.stopPropagation(),Le.key==="Enter"&&cs(Ge.id,u),Le.key==="Escape"&&(d(null),I(""))},onBlur:()=>cs(Ge.id,u),onClick:Le=>Le.stopPropagation()}):e.jsx("span",{children:Ge.name}),e.jsx("button",{onClick:Le=>vs(F.id,Le),className:"opacity-0 group-hover/badge:opacity-100 transition-opacity ml-1 hover:text-destructive",children:e.jsx(kn,{className:"h-3 w-3"})})]})}),e.jsx(et,{children:e.jsx("p",{children:"Automatische Zimmerzuteilung mit Gruppe"})})]})}):e.jsx("span",{className:"text-sm text-muted-foreground",children:"–"})}),es.field==="name"&&e.jsxs("div",{className:"flex items-center gap-3",children:[Ee&&Ge?e.jsx(it,{children:e.jsxs(Js,{children:[e.jsx(Xs,{asChild:!0,children:e.jsxs("div",{className:"flex h-10 w-10 items-center justify-center rounded-full text-sm font-medium cursor-default",style:{backgroundColor:`${Ge.color}20`,color:Ge.color,borderWidth:"2px",borderColor:Ge.color},children:[F.firstName.charAt(0),F.lastName.charAt(0)]})}),e.jsx(et,{children:e.jsxs("div",{className:"flex items-center gap-1.5",children:[e.jsx(Ns,{className:"h-3 w-3"}),e.jsx("span",{children:Ge.name})]})})]})}):e.jsxs("div",{className:"flex h-10 w-10 items-center justify-center rounded-full text-sm font-medium",style:{backgroundColor:Ge?`${Ge.color}20`:"hsl(var(--primary) / 0.1)",color:Ge?Ge.color:"hsl(var(--primary))",borderWidth:Ge?"2px":"0",borderColor:Ge==null?void 0:Ge.color},children:[F.firstName.charAt(0),F.lastName.charAt(0)]}),e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx("div",{children:e.jsxs("div",{className:"flex items-center gap-1.5",children:[e.jsxs("p",{className:"font-medium text-foreground",children:[F.firstName," ",F.lastName]}),F.profileId&&e.jsx(it,{children:e.jsxs(Js,{children:[e.jsx(Xs,{asChild:!0,children:e.jsx("button",{onClick:Le=>{Le.stopPropagation(),b(`/admin/participants/${F.profileId}`)},className:"opacity-0 group-hover/row:opacity-100 transition-opacity text-muted-foreground hover:text-primary",children:e.jsx(Zt,{className:"h-3.5 w-3.5"})})}),e.jsx(et,{children:"Profil öffnen"})]})})]})}),(()=>{const Le=Oa(F.dateOfBirth);if(ie&&Le){const _s=ic(Le,ie.startDate,ie.endDate);if(_s.hasBirthday)return e.jsx(it,{children:e.jsxs(Js,{children:[e.jsx(Xs,{asChild:!0,children:e.jsx("div",{className:"flex-shrink-0 text-amber-500",children:e.jsx(Nr,{className:"h-4 w-4"})})}),e.jsx(et,{children:e.jsxs("p",{children:["Hat am ",_s.formattedDate," Geburtstag während der Reise 🎂"]})})]})})}return null})(),(()=>{const Le=nc(F.documentExpiryDate,ie==null?void 0:ie.startDate);return Le?e.jsx(it,{children:e.jsxs(Js,{children:[e.jsx(Xs,{asChild:!0,children:e.jsx("div",{className:`flex-shrink-0 ${Le.isExpired?"text-destructive":"text-amber-500"}`,children:e.jsx(Lt,{className:"h-4 w-4"})})}),e.jsx(et,{children:e.jsx("p",{children:Le.isExpired?"Dokument ist abgelaufen!":Le.monthsBeforeTrip<0?"Dokument läuft vor Reisebeginn ab!":`Dokument läuft nur ${Le.monthsBeforeTrip} ${Le.monthsBeforeTrip===1?"Monat":"Monate"} vor Reisebeginn ab`})})]})}):null})()]})]}),es.field==="contact"&&e.jsxs("div",{className:"space-y-1",children:[F.email?e.jsxs("div",{className:"flex items-center gap-2 text-sm text-muted-foreground",children:[e.jsx(Os,{className:"h-3 w-3"}),F.email]}):e.jsxs(z,{variant:"ghost",size:"sm",className:"h-6 px-2 text-xs text-muted-foreground hover:text-primary gap-1",onClick:Le=>{Le.stopPropagation(),$(F)},children:[e.jsx(ki,{className:"h-3 w-3"}),"E-Mail hinzufügen"]}),F.phone&&e.jsxs("div",{className:"flex items-center gap-2 text-sm text-muted-foreground",children:[e.jsx(xa,{
125className:"h-3 w-3"}),F.phone]})]}),es.field==="age"&&e.jsx("span",{className:"text-sm text-foreground font-medium",children:as!==null?`${as} Jahre`:"–"}),es.field==="booking"&&e.jsx("span",{className:"text-sm text-muted-foreground",children:(re==null?void 0:re.customer_name)||"–"}),es.field==="questionnaireStatus"&&e.jsx(Ir,{progress:F.questionnaireProgress||0}),es.field.startsWith("questionnaire_")&&e.jsx("span",{className:"text-sm text-foreground",children:(()=>{var Cs;const Le=es.field.replace("questionnaire_",""),_s=(Cs=F.questionnaireResponses)==null?void 0:Cs[Le];return _s==null||_s===""?"–":typeof _s=="boolean"?_s?"Ja":"Nein":Array.isArray(_s)?_s.join(", "):String(_s)})()})]},es.id))]},F.id)})})]})})}),oe.length===0&&e.jsxs("div",{className:"glass-card p-12 text-center",children:[e.jsx(Cn,{className:"mx-auto h-12 w-12 text-muted-foreground"}),e.jsx("h3",{className:"mt-4 text-lg font-medium text-foreground",children:"Keine Teilnehmer gefunden"}),e.jsx("p",{className:"mt-1 text-muted-foreground",children:c!=="all"?"Keine Teilnehmer mit diesem Fragebogen-Status.":"Es wurden noch keine Teilnehmer für diese Reise erfasst."}),c!=="all"&&e.jsx(z,{variant:"outline",className:"mt-4 rounded-xl",onClick:()=>k("all"),children:"Filter entfernen"})]}),e.jsx(We,{open:l,onOpenChange:V,children:e.jsxs(Qe,{className:"glass-modal sm:max-w-md",children:[e.jsx(Ye,{children:e.jsx(Je,{children:"Gruppe erstellen"})}),e.jsxs("div",{className:"space-y-4 py-4",children:[e.jsxs("div",{className:"space-y-3",children:[e.jsx(U,{children:"Art der Verknüpfung"}),e.jsxs(fr,{value:y,onValueChange:F=>W(F),className:"grid grid-cols-2 gap-3",children:[e.jsxs(U,{htmlFor:"cat-couple",className:`flex items-center gap-3 p-3 rounded-xl border-2 cursor-pointer transition-colors ${y==="couple"?"border-primary bg-primary/5":"border-muted hover:border-muted-foreground/30"}`,children:[e.jsx(It,{value:"couple",id:"cat-couple",className:"sr-only"}),e.jsx(mn,{className:`h-5 w-5 ${y==="couple"?"text-primary":"text-muted-foreground"}`}),e.jsx("span",{className:y==="couple"?"font-medium":"",children:"Paar"})]}),e.jsxs(U,{htmlFor:"cat-friends",className:`flex items-center gap-3 p-3 rounded-xl border-2 cursor-pointer transition-colors ${y==="friends"?"border-primary bg-primary/5":"border-muted hover:border-muted-foreground/30"}`,children:[e.jsx(It,{value:"friends",id:"cat-friends",className:"sr-only"}),e.jsx(Sn,{className:`h-5 w-5 ${y==="friends"?"text-primary":"text-muted-foreground"}`}),e.jsx("span",{className:y==="friends"?"font-medium":"",children:"Freunde"})]}),e.jsxs(U,{htmlFor:"cat-family",className:`flex items-center gap-3 p-3 rounded-xl border-2 cursor-pointer transition-colors ${y==="family"?"border-primary bg-primary/5":"border-muted hover:border-muted-foreground/30"}`,children:[e.jsx(It,{value:"family",id:"cat-family",className:"sr-only"}),e.jsx(Ci,{className:`h-5 w-5 ${y==="family"?"text-primary":"text-muted-foreground"}`}),e.jsx("span",{className:y==="family"?"font-medium":"",children:"Familie"})]}),e.jsxs(U,{htmlFor:"cat-other",className:`flex items-center gap-3 p-3 rounded-xl border-2 cursor-pointer transition-colors ${y==="other"?"border-primary bg-primary/5":"border-muted hover:border-muted-foreground/30"}`,children:[e.jsx(It,{value:"other",id:"cat-other",className:"sr-only"}),e.jsx(Ns,{className:`h-5 w-5 ${y==="other"?"text-primary":"text-muted-foreground"}`}),e.jsx("span",{className:y==="other"?"font-medium":"",children:"Andere"})]})]})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(U,{children:"Gruppenname (optional)"}),e.jsx(te,{placeholder:y==="couple"?"z.B. Paar Müller":y==="friends"?"z.B. Freunde Berlin":"z.B. Familie Müller",value:A,onChange:F=>q(F.target.value),className:"rounded-xl"}),e.jsx("p",{className:"text-xs text-muted-foreground",children:"Wenn leer, wird automatisch ein Name generiert"})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(U,{children:"Ausgewählte Teilnehmer"}),e.jsx("div",{className:"flex flex-wrap gap-2",children:T.map(F=>{const re=Se.find(Ne=>Ne.id===F);return re?e.jsxs("span",{className:"px-2 py-1 rounded-lg bg-muted text-sm",children:[re.firstName," ",re.lastName]},F):null})})]}),e.jsx("div",{className:"rounded-xl bg-muted/30 p-3",children:e.jsxs("p",{className:"text-sm text-muted-foreground flex items-center gap-2",children:[e.jsx(tt,{className:"h-4 w-4 text-success"}),"Diese Teilnehmer werden automatisch zusammen in Zimmerlisten eingetragen"]})})]}),e.jsxs(gs,{children:[e.jsx(z,{variant:"outline",onClick:()=>V(!1),className:"rounded-xl",children:"Abbrechen"}),e.jsx(z,{onClick:Fe,className:"rounded-xl",children:"Gruppe erstellen"})]})]})}),e.jsx(We,{open:Ke,onOpenChange:Fs,children:e.jsxs(Qe,{className:"glass-modal sm:max-w-lg",children:[e.jsx(Ye,{children:e.jsx(Je,{children:"Guide hinzufügen"})}),e.jsxs(ar,{value:xe,onValueChange:F=>ms(F),children:[e.jsxs(rr,{className:"grid w-full grid-cols-2",children:[e.jsx(Gs,{value:"existing",children:"Bestehender Guide"}),e.jsx(Gs,{value:"new",children:"Neuer Guide"})]}),e.jsxs(Is,{value:"existing",className:"mt-4 space-y-4",children:[e.jsxs("div",{className:"space-y-2",children:[e.jsx(U,{children:"Guide suchen"}),e.jsxs("div",{className:"relative",children:[e.jsx(wt,{className:"absolute left-3 top-1/2 h-4 w-4 -translate-y-1/2 text-muted-foreground"}),e.jsx(te,{placeholder:"Name oder E-Mail...",value:S,onChange:F=>P(F.target.value),className:"rounded-xl pl-9"})]})]}),e.jsx(za,{className:"h-[250px] rounded-xl border",children:he?e.jsx("div",{className:"flex items-center justify-center py-8",children:e.jsx($e,{className:"h-6 w-6 animate-spin text-muted-foreground"})}):ts.length>0?e.jsx("div",{className:"p-2 space-y-1",children:ts.map(F=>e.jsxs("div",{className:`flex items-center gap-3 p-3 rounded-lg cursor-pointer transition-colors ${(ue==null?void 0:ue.id)===F.id?"bg-primary/10 border border-primary/30":"hover:bg-muted/50"}`,onClick:()=>de(F),children:[e.jsxs(Pt,{className:"h-10 w-10",children:[e.jsx(Tt,{src:F.profile_image||void 0,alt:`${F.first_name} ${F.last_name}`}),e.jsxs(Ft,{className:"bg-primary/20 text-primary",children:[F.first_name[0],F.last_name[0]]})]}),e.jsxs("div",{className:"flex-1 min-w-0",children:[e.jsxs("p",{className:"font-medium text-foreground",children:[F.first_name," ",F.last_name]}),e.jsxs("p",{className:"text-xs text-muted-foreground truncate",children:[F.email||"Keine E-Mail"," • ",F.trips.length," Reise",F.trips.length!==1?"n":""]})]}),(ue==null?void 0:ue.id)===F.id&&e.jsx(tt,{className:"h-5 w-5 text-primary"})]},F.id))}):e.jsxs("div",{className:"flex flex-col items-center justify-center py-8 text-muted-foreground",children:[e.jsx(Ut,{className:"h-8 w-8 mb-2 opacity-50"}),e.jsx("p",{className:"text-sm",children:(ee==null?void 0:ee.length)===0?"Noch keine Guides vorhanden":S?"Keine passenden Guides gefunden":"Alle Guides sind bereits die
125ser Reise zugewiesen"})]})}),e.jsxs(gs,{children:[e.jsx(z,{variant:"outline",onClick:Fs,className:"rounded-xl",children:"Abbrechen"}),e.jsx(z,{onClick:ds,className:"rounded-xl",disabled:!ue,children:"Guide zuweisen"})]})]}),e.jsxs(Is,{value:"new",className:"mt-4 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(U,{children:"Vorname *"}),e.jsx(te,{placeholder:"Max",value:us.first_name,onChange:F=>Q({...us,first_name:F.target.value}),className:"rounded-xl"})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(U,{children:"Nachname *"}),e.jsx(te,{placeholder:"Mustermann",value:us.last_name,onChange:F=>Q({...us,last_name:F.target.value}),className:"rounded-xl"})]})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(U,{children:"E-Mail"}),e.jsx(te,{type:"email",placeholder:"[email protected]",value:us.email,onChange:F=>Q({...us,email:F.target.value}),className:"rounded-xl"})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(U,{children:"Telefon"}),e.jsx(te,{placeholder:"+49 123 456789",value:us.phone,onChange:F=>Q({...us,phone:F.target.value}),className:"rounded-xl"})]}),e.jsx("div",{className:"rounded-xl bg-primary/5 p-3 border border-primary/10",children:e.jsxs("p",{className:"text-sm text-muted-foreground flex items-center gap-2",children:[e.jsx(Ut,{className:"h-4 w-4 text-primary"}),"Guides erscheinen in allen Listen (Zimmer, Essen) und können Fragebögen ausfüllen"]})}),e.jsxs(gs,{children:[e.jsx(z,{variant:"outline",onClick:Fs,className:"rounded-xl",children:"Abbrechen"}),e.jsx(z,{onClick:As,className:"rounded-xl",disabled:!us.first_name||!us.last_name,children:"Guide erstellen"})]})]})]})]})}),C&&e.jsx(Ql,{participant:C,tripId:s,open:!!C,onOpenChange:F=>!F&&N(null),onParticipantUpdated:ns}),E&&e.jsx(Jl,{participant:E,open:!!E,onOpenChange:F=>!F&&$(null),onLinked:()=>{X(),$(null)}}),e.jsx(Hl,{open:ge,onOpenChange:be,participants:Se})]})]})}const Zr={booking_confirmation:"Buchungsbestätigung",invoice:"Rechnung",contract:"Vertrag",correspondence:"Korrespondenz",other:"Sonstiges"};function cc(s,n){const[a,b]=t.useState([]),[f,i]=t.useState(!0),[x,h]=t.useState(!1),{toast:c}=aa(),k=t.useCallback(async()=>{if(!s||!n){b([]),i(!1);return}try{const{data:o,error:l}=await _.from("trip_partner_documents").select("*").eq("partner_id",s).eq("trip_id",n).order("created_at",{ascending:!1});if(l)throw l;const V=(o||[]).map(A=>({id:A.id,partnerId:A.partner_id,tripId:A.trip_id,fileName:A.file_name,filePath:A.file_path,fileType:A.file_type,fileSize:A.file_size,notes:A.notes||void 0,uploadedBy:A.uploaded_by||void 0,uploadedByRole:A.uploaded_by_role||"admin",sharedWithPartner:A.shared_with_partner??!0,reviewStatus:A.review_status||"accepted",reviewNote:A.review_note||void 0,createdAt:A.created_at}));b(V)}catch(o){console.error("Error fetching partner documents:",o),c({title:"Fehler beim Laden der Dokumente",description:"Bitte versuche es erneut.",variant:"destructive"})}finally{i(!1)}},[s,n,c]);t.useEffect(()=>{k()},[k]);const C=t.useCallback(async(o,l="other",V)=>{if(!s||!n)return null;h(!0);try{const A=Date.now(),q=o.name.replace(/[^a-zA-Z0-9.-]/g,"_"),y=`${n}/${s}/${A}_${q}`,{error:W}=await _.storage.from("partner-documents").upload(y,o);if(W)throw W;const{data:{user:j}}=await _.auth.getUser(),{data:d,error:u}=await _.from("trip_partner_documents").insert({partner_id:s,trip_id:n,file_name:o.name,file_path:y,file_type:l,file_size:o.size,notes:V||null,uploaded_by:(j==null?void 0:j.id)||null}).select().single();if(u)throw u;const I={id:d.id,partnerId:d.partner_id,tripId:d.trip_id,fileName:d.file_name,filePath:d.file_path,fileType:d.file_type,fileSize:d.file_size,notes:d.notes||void 0,uploadedBy:d.uploaded_by||void 0,uploadedByRole:d.uploaded_by_role||"admin",sharedWithPartner:d.shared_with_partner??!0,reviewStatus:d.review_status||"accepted",reviewNote:d.review_note||void 0,createdAt:d.created_at};return b(E=>[I,...E]),c({title:"Dokument hochgeladen",description:`"${o.name}" wurde erfolgreich gespeichert.`}),I}catch(A){return console.error("Error uploading document:",A),c({title:"Fehler beim Hochladen",description:"Bitte versuche es erneut.",variant:"destructive"}),null}finally{h(!1)}},[s,n,c]),N=t.useCallback(async o=>{try{const{error:l}=await _.storage.from("partner-documents").remove([o.filePath]);l&&console.warn("Storage delete warning:",l);const{error:V}
125=await _.from("trip_partner_documents").delete().eq("id",o.id);if(V)throw V;b(A=>A.filter(q=>q.id!==o.id)),c({title:"Dokument gelöscht",description:`"${o.fileName}" wurde entfernt.`})}catch(l){console.error("Error deleting document:",l),c({title:"Fehler beim Löschen",description:"Bitte versuche es erneut.",variant:"destructive"})}},[c]),v=t.useCallback(async o=>{try{const{data:l,error:V}=await _.storage.from("partner-documents").createSignedUrl(o,3600);if(V)throw V;return l.signedUrl}catch(l){return console.error("Error getting download URL:",l),c({title:"Fehler beim Download",description:"Bitte versuche es erneut.",variant:"destructive"}),null}},[c]),G=t.useCallback(async(o,l,V)=>{try{const{data:{user:A}}=await _.auth.getUser(),{error:q}=await _.from("trip_partner_documents").update({review_status:l,review_note:V||null,reviewed_at:new Date().toISOString(),reviewed_by:(A==null?void 0:A.id)||null}).eq("id",o);if(q)throw q;b(y=>y.map(W=>W.id===o?{...W,reviewStatus:l,reviewNote:V||void 0}:W)),c({title:l==="accepted"?"Dokument angenommen":"Dokument abgelehnt"})}catch(A){console.error("Error reviewing document:",A),c({title:"Fehler",description:"Bitte versuche es erneut.",variant:"destructive"})}},[c]),T=t.useCallback(async(o,l)=>{try{const{error:V}=await _.from("trip_partner_documents").update({shared_with_partner:l}).eq("id",o);if(V)throw V;b(A=>A.map(q=>q.id===o?{...q,sharedWithPartner:l}:q))}catch(V){console.error("Error updating sharing:",V),c({title:"Fehler",description:"Bitte versuche es erneut.",variant:"destructive"})}},[c]);return{documents:a,loading:f,uploading:x,uploadDocument:C,deleteDocument:N,getDownloadUrl:v,reviewDocument:G,setShared:T,refetch:k}}function oc(s,n){const[a,b]=t.useState({}),[f,i]=t.useState(!0),x=t.useCallback(async()=>{if(!s||n.length===0){b({}),i(!1);return}try{const{data:h,error:c}=await _.from("trip_partner_documents").select("partner_id").eq("trip_id",s).in("partner_id",n);if(c)throw c;const k={};(h||[]).forEach(C=>{k[C.partner_id]=(k[C.partner_id]||0)+1}),b(k)}catch(h){console.error("Error fetching document counts:",h)}finally{i(!1)}},[s,n.join(",")]);return t.useEffect(()=>{x()},[x]),{counts:a,loading:f,refetch:x}}function dc(s){if(s===0)return"0 B";const n=1024,a=["B","KB","MB","GB"],b=Math.floor(Math.log(s)/Math.log(n));return parseFloat((s/Math.pow(n,b)).toFixed(1))+" "+a[b]}function mc(s){var a;const n=(a=s.split(".").pop())==null?void 0:a.toLowerCase();return n==="pdf"?$s:["jpg","jpeg","png","webp","gif"].includes(n||"")?zi:["doc","docx"].includes(n||"")?$s:["xls","xlsx"].includes(n||"")?Ri:wn}function uc({partnerId:s,tripId:n,onDocumentChange:a}){const{documents:b,loading:f,uploading:i,uploadDocument:x,deleteDocument:h,getDownloadUrl:c,reviewDocument:k,setShared:C}=cc(s,n),[N,v]=t.useState("booking_confirmation"),[G,T]=t.useState(!1),[o,l]=t.useState(null),V=t.useRef(null),A=u=>{u.preventDefault(),u.stopPropagation(),u.type==="dragenter"||u.type==="dragover"?T(!0):u.type==="dragleave"&&T(!1)},q=async u=>{u.preventDefault(),u.stopPropagation(),T(!1),u.dataTransfer.files&&u.dataTransfer.files[0]&&await y(u.dataTransfer.files[0])},y=async u=>{if(u.size>10*1024*1024){alert("Die Datei ist zu groß. Maximale Größe: 10 MB");return}await x(u,N)&&a&&a()},W=async u=>{u.target.files&&u.target.files[0]&&(await y(u.target.files[0]),u.target.value="")},j=async u=>{l(u.id);try{const I=await c(u.filePath);if(I){const E=document.createElement("a");E.href=I,E.download=u.fileName,document.body.appendChild(E),E.click(),document.body.removeChild(E)}}finally{l(null)}},d=async u=>{confirm(`Möchten Sie "${u.fileName}" wirklich löschen?`)&&(await h(u),a&&a())};return f?e.jsx("div",{className:"flex items-center justify-center py-8",children:e.jsx($e,{className:"h-6 w-6 animate-spin text-muted-foreground"})}):e.jsxs("div",{className:"space-y-4",children:[e.jsx("div",{className:"flex items-center justify-between",children:e.jsxs("h4",{className:"font-medium text-foreground flex items-center gap-2",children:[e.jsx(Ea,{className:"h-4 w-4"}),"Dokumente (",b.length,")"]})}),e.jsxs("div",{className:"space-y-3",children:[e.jsx("div",{className:"flex gap-2",children:e.jsxs("div",{className:"flex-1",children:[e.jsx(U,{className:"text-xs text-muted-foreground mb-1 block",children:"Dokumenttyp"}),e.jsxs(Ie,{value:N,onValueChange:u=>v(u),children:[e.jsx(Oe,{className:"rounded-lg h-9",children:e.jsx(Ve,{})}),e.jsx(Ue,{children:Object.entries(Zr).map(([u,I])=>e.jsx(O,{value:u,children:I},u))})]})]})}),e.jsxs("div",{className:Ms("relative rounded-xl border-2 border-dashed p-6 transition-colors",G?"border-primary bg-primary/5":"border-muted-foreground
125/25 hover:border-muted-foreground/50",i&&"pointer-events-none opacity-50"),onDragEnter:A,onDragLeave:A,onDragOver:A,onDrop:q,children:[e.jsx("input",{ref:V,type:"file",className:"hidden",accept:".pdf,.jpg,.jpeg,.png,.webp,.doc,.docx",onChange:W}),e.jsxs("div",{className:"flex flex-col items-center gap-2 text-center",children:[i?e.jsx($e,{className:"h-8 w-8 animate-spin text-primary"}):e.jsx(_t,{className:"h-8 w-8 text-muted-foreground"}),e.jsxs("div",{children:[e.jsx("p",{className:"text-sm font-medium text-foreground",children:i?"Wird hochgeladen...":"Datei hierher ziehen"}),e.jsxs("p",{className:"text-xs text-muted-foreground mt-1",children:["oder"," ",e.jsx("button",{type:"button",className:"text-primary hover:underline",onClick:()=>{var u;return(u=V.current)==null?void 0:u.click()},disabled:i,children:"Datei auswählen"})]})]}),e.jsx("p",{className:"text-xs text-muted-foreground",children:"PDF, Bilder, Word-Dokumente (max. 10 MB)"})]})]})]}),b.length>0?e.jsx("div",{className:"space-y-2",children:b.map(u=>{const I=mc(u.fileName),E=u.uploadedByRole==="partner",$=E&&u.reviewStatus==="pending";return e.jsxs("div",{className:Ms("flex items-center gap-3 p-3 rounded-lg transition-colors group",$?"bg-amber-500/10 ring-1 ring-amber-500/30":"bg-muted/30 hover:bg-muted/50"),children:[e.jsx("div",{className:"flex h-10 w-10 items-center justify-center rounded-lg bg-primary/10",children:e.jsx(I,{className:"h-5 w-5 text-primary"})}),e.jsxs("div",{className:"flex-1 min-w-0",children:[e.jsx("p",{className:"text-sm font-medium text-foreground truncate",children:u.fileName}),e.jsxs("div",{className:"flex flex-wrap items-center gap-2 text-xs text-muted-foreground",children:[e.jsx("span",{children:Zr[u.fileType]||"Sonstiges"}),e.jsx("span",{children:"•"}),e.jsx("span",{children:dc(u.fileSize)}),e.jsx("span",{children:"•"}),e.jsx("span",{children:new Date(u.createdAt).toLocaleDateString("de-DE")}),e.jsx(Xe,{variant:"outline",className:"text-[10px] font-normal",children:E?"Vom Partner":"Von uns"}),E&&u.reviewStatus==="accepted"&&e.jsxs(Xe,{variant:"outline",className:"gap-1 border-emerald-500/40 text-emerald-600 text-[10px] font-normal",children:[e.jsx(ra,{className:"h-3 w-3"})," Angenommen"]}),E&&u.reviewStatus==="rejected"&&e.jsxs(Xe,{variant:"outline",className:"gap-1 border-destructive/40 text-destructive text-[10px] font-normal",title:u.reviewNote,children:[e.jsx(Vt,{className:"h-3 w-3"})," Abgelehnt"]}),$&&e.jsxs(Xe,{variant:"outline",className:"gap-1 border-amber-500/40 text-amber-600 text-[10px] font-normal",children:[e.jsx(Vs,{className:"h-3 w-3"})," Eingereicht"]})]}),!E&&e.jsxs("label",{className:"mt-1.5 flex items-center gap-2 text-xs text-muted-foreground",children:[e.jsx(ys,{checked:u.sharedWithPartner,onCheckedChange:ge=>C(u.id,ge),className:"scale-75"}),e.jsx(Fi,{className:"h-3 w-3"})," ",u.sharedWithPartner?"Mit Partner geteilt":"Nur intern"]})]}),e.jsxs("div",{className:"flex items-center gap-1",children:[$&&e.jsxs(e.Fragment,{children:[e.jsx(z,{variant:"ghost",size:"icon",className:"h-8 w-8 text-emerald-600 hover:text-emerald-600",title:"Annehmen",onClick:()=>k(u.id,"accepted"),children:e.jsx(tt,{className:"h-4 w-4"})}),e.jsx(z,{variant:"ghost",size:"icon",className:"h-8 w-8 text-destructive hover:text-destructive",title:"Ablehnen",onClick:()=>k(u.id,"rejected"),children:e.jsx(er,{className:"h-4 w-4"})})]}),e.jsx(z,{variant:"ghost",size:"icon",className:"h-8 w-8",onClick:()=>j(u),disabled:o===u.id,children:o===u.id?e.jsx($e,{className:"h-4 w-4 animate-spin"}):e.jsx(lt,{className:"h-4 w-4"})}),e.jsx(z,{variant:"ghost",size:"icon",className:"h-8 w-8 text-destructive hover:text-destructive",onClick:()=>d(u),children:e.jsx(bs,{className:"h-4 w-4"})})]})]},u.id)})}):e.jsxs("div",{className:"text-center py-6 text-muted-foreground",children:[e.jsx(Ea,{className:"mx-auto h-8 w-8 mb-2 opacity-50"}),e.jsx("p",{className:"text-sm",children:"Noch keine Dokumente vorhanden"}),e.jsx("p",{className:"text-xs",children:"Laden Sie Buchungsbestätigungen, Rechnungen oder Verträge hoch"})]})]})}function hc(s,n){if(!s.accessActive)return!1;const a=s.hasService||s.hasTripPartner;return n?s.templateGranted?s.templateAllTrips||a:!1:a}async function xc(s){const{data:n,error:a}=await _.from("trips").select("id, name, template_id, start_date, end_date").eq("id",s).maybeSingle();if(a)throw a;const[b,f,i,x]=await Promise.all([_.from("trip_partners").select("partner_id").eq("trip_id",s),_.from("trip_partner_services").select("partner_service_id").eq("trip_id",s),_.from("partner_access").select("partner_id, is_active"),_.from("partners").select("id, name").order("name")]),h=(f.data??[]).map(A=>
125A.partner_service_id).filter(Boolean);let c=[];if(h.length){const{data:A}=await _.from("partner_services").select("id, partner_id").in("id",h);c=[...new Set((A??[]).map(q=>q.partner_id))]}let k=[];if(n!=null&&n.template_id){const{data:A}=await _.from("partner_template_access").select("partner_id, all_trips").eq("template_id",n.template_id);k=A??[]}const C=!!(n!=null&&n.template_id),N=new Map((i.data??[]).map(A=>[A.partner_id,A])),v=new Map(k.map(A=>[A.partner_id,A])),G=new Set((b.data??[]).map(A=>A.partner_id)),T=new Set(c),o=[...new Set([...G,...T])],l={};for(const A of x.data??[]){const q=N.get(A.id),y=v.get(A.id),W={partnerId:A.id,accessActive:!!(q!=null&&q.is_active),hasAccessRow:!!q,hasService:T.has(A.id),hasTripPartner:G.has(A.id),templateGranted:!!y,templateAllTrips:!!(y!=null&&y.all_trips)};l[A.id]={...W,visible:hc(W,C)}}const V=(x.data??[]).filter(A=>{var q;return((q=N.get(A.id))==null?void 0:q.is_active)&&!o.includes(A.id)});return{trip:n,hasTemplate:C,byPartner:l,assignable:V,attachedPartnerIds:o}}function br(s){return dt({queryKey:["trip-partner-portal",s],queryFn:()=>xc(s),staleTime:3e4})}function Tn(s){const n=ta(),[a,b]=t.useState(!1),f=()=>n.invalidateQueries({queryKey:["trip-partner-portal",s]});return{busy:a,assign:async(c,k)=>{if(k){b(!0);try{const{error:C}=await _.from("trip_partners").insert({partner_id:c,trip_id:s,start_date:k.start_date,end_date:k.end_date,price_type:"per_person",price:0,status:"requested",last_contact_date:new Date().toISOString().slice(0,10)});if(C)throw C;Y.success("Reise im Portal freigegeben"),f()}catch(C){Y.error("Freigabe fehlgeschlagen",{description:C.message})}finally{b(!1)}}},unassign:async c=>{b(!0);try{const{error:k}=await _.from("trip_partners").delete().eq("trip_id",s).eq("partner_id",c);if(k)throw k;Y.success("Freigabe entfernt"),f()}catch(k){Y.error("Entfernen fehlgeschlagen",{description:k.message})}finally{b(!1)}},notifyChange:async(c,k)=>{b(!0);try{const{error:C}=await _.from("partner_relevant_events").insert({trip_id:s,event_type:"participant_added",title:`Trip assigned: ${k}`.trim(),metadata:{source:"manual_trip_assignment",partner_id:c}});if(C)throw C;Y.success('Änderung gemeldet – erscheint im Portal unter „What’s new"')}catch(C){Y.error("Meldung fehlgeschlagen",{description:C.message})}finally{b(!1)}}}}function Hr({tripId:s,partnerId:n,partnerName:a,onOpenEmailDialog:b}){var V;const[f,i]=t.useState(!1),{data:x,isLoading:h}=br(s),{busy:c,assign:k,unassign:C,notifyChange:N}=Tn(s),v=(V=x==null?void 0:x.byPartner)==null?void 0:V[n],G=!!(x!=null&&x.hasTemplate);if(h||!v)return e.jsxs(z,{variant:"outline",size:"sm",className:"gap-2 rounded-lg",disabled:!0,children:[e.jsx($e,{className:"h-3.5 w-3.5 animate-spin"}),"Portal"]});const T=!v.hasAccessRow||!v.accessActive,o=T?"Kein Portal-Zugang":v.visible?"Portal: sichtbar":"Portal: nicht freigegeben",l=T?Er:v.visible?st:Ti;return e.jsxs(e.Fragment,{children:[e.jsxs(z,{variant:"outline",size:"sm",className:Ms("gap-2 rounded-lg",T&&"border-amber-500/40 text-amber-600 hover:text-amber-600",!T&&v.visible&&"border-emerald-500/40 text-emerald-600 hover:text-emerald-600",!T&&!v.visible&&"text-muted-foreground"),onClick:()=>i(!0),children:[e.jsx(l,{className:"h-3.5 w-3.5"}),o]}),e.jsx(We,{open:f,onOpenChange:i,children:e.jsxs(Qe,{className:"max-w-lg",children:[e.jsxs(Ye,{children:[e.jsxs(Je,{children:["Portal-Sichtbarkeit – ",a]}),e.jsx(Ds,{children:T?"Dieser Partner hat noch keinen aktiven Portal-Zugang und sieht deshalb keine Reisen.":v.visible?"Dieser Partner sieht diese Reise aktuell in seinem Portal.":"Dieser Partner hat Portal-Zugang, sieht diese Reise aber nicht."})]}),e.jsx("div",{className:"space-y-4",children:T?e.jsxs("div",{className:"flex items-start gap-2 rounded-lg border border-amber-500/30 bg-amber-500/10 p-3 text-xs text-amber-700",children:[e.jsx(Er,{className:"mt-0.5 h-3.5 w-3.5 shrink-0"}),e.jsxs("div",{className:"space-y-2",children:[e.jsx("p",{children:"Richte zuerst den Portal-Zugang in der Partner-Verwaltung ein (Rechte, Einladung). Danach kannst du hier die Reise freigeben."}),e.jsx(z,{asChild:!0,variant:"outline",size:"sm",className:"gap-1.5 rounded-lg",children:e.jsxs(Yt,{to:"/admin/partners",children:[e.jsx(Zt,{className:"h-3.5 w-3.5"})," Partner-Verwaltung öffnen"]})})]})]}):e.jsxs(e.Fragment,{children:[e.jsxs("div",{className:"flex items-start justify-between gap-4 roun
125ded-xl border border-border/60 bg-muted/30 p-3",children:[e.jsxs("div",{className:"space-y-1",children:[e.jsx(U,{htmlFor:"portal-visibility",className:"text-sm",children:"Diese Reise im Portal freigeben"}),e.jsx("p",{className:"text-xs text-muted-foreground",children:v.hasService?"Sichtbarkeit kommt über die Dienstleistung dieser Reise – dort entfernen.":"Weist die Reise direkt diesem Partner zu."})]}),e.jsx(ys,{id:"portal-visibility",checked:v.hasService||v.hasTripPartner,disabled:c||v.hasService,onCheckedChange:A=>A?k(n,(x==null?void 0:x.trip)??null):C(n)})]}),G&&!v.templateGranted&&e.jsxs("div",{className:"flex items-start gap-2 rounded-lg border border-amber-500/30 bg-amber-500/10 p-3 text-xs text-amber-700",children:[e.jsx(Tr,{className:"mt-0.5 h-3.5 w-3.5 shrink-0"}),e.jsxs("div",{className:"space-y-2",children:[e.jsx("p",{children:"Für die Reisevorlage fehlt die Freigabe – ohne sie bleibt die Reise im Portal unsichtbar."}),e.jsx(z,{asChild:!0,variant:"outline",size:"sm",className:"gap-1.5 rounded-lg",children:e.jsxs(Yt,{to:"/admin/partners",children:[e.jsx(Zt,{className:"h-3.5 w-3.5"})," Portal-Zugang des Partners öffnen"]})})]})]}),!G&&e.jsxs("p",{className:"flex items-start gap-2 rounded-lg bg-muted/40 p-3 text-xs text-muted-foreground",children:[e.jsx(Tr,{className:"mt-0.5 h-3.5 w-3.5 shrink-0"}),"Individuelle Reise ohne Vorlage: Die Sichtbarkeit wird ausschließlich hier gesteuert. Es gelten die Konto-Standardrechte des Partners, Add-ons bleiben ausgeblendet."]})]})}),e.jsxs(gs,{className:"gap-2 sm:justify-between",children:[e.jsxs(z,{variant:"outline",size:"sm",className:"gap-1.5 rounded-lg",disabled:c||!v.visible,onClick:()=>{var A;return N(n,((A=x==null?void 0:x.trip)==null?void 0:A.name)??"")},children:[e.jsx($i,{className:"h-3.5 w-3.5"})," Änderung melden"]}),b&&e.jsxs(z,{size:"sm",className:"gap-1.5 rounded-lg",disabled:!v.visible,onClick:()=>{i(!1),b()},children:[e.jsx(Os,{className:"h-3.5 w-3.5"})," Bestätigung senden"]})]})]})})]})}function pc({tripId:s}){const[n,a]=t.useState(!1),[b,f]=t.useState(""),{data:i}=br(s),{busy:x,assign:h}=Tn(s),c=(i==null?void 0:i.assignable)??[];return e.jsxs(e.Fragment,{children:[e.jsxs(z,{variant:"outline",className:"gap-2 rounded-xl",onClick:()=>a(!0),children:[e.jsx(st,{className:"h-4 w-4"}),"Partner im Portal freigeben"]}),e.jsx(We,{open:n,onOpenChange:a,children:e.jsxs(Qe,{className:"max-w-md",children:[e.jsxs(Ye,{children:[e.jsx(Je,{children:"Partner im Portal freigeben"}),e.jsx(Ds,{children:"Der Partner sieht diese Reise danach in seinem Portal – auch ohne eingetragene Dienstleistung."})]}),c.length===0?e.jsx("p",{className:"text-sm text-muted-foreground",children:"Alle Partner mit aktivem Portal-Zugang sind dieser Reise bereits zugeordnet."}):e.jsxs(Ie,{value:b,onValueChange:f,children:[e.jsx(Oe,{className:"rounded-lg",children:e.jsx(Ve,{placeholder:"Partner mit Portal-Zugang wählen…"})}),e.jsx(Ue,{children:c.map(k=>e.jsx(O,{value:k.id,children:k.name},k.id))})]}),e.jsxs(gs,{children:[e.jsx(z,{variant:"outline",className:"rounded-lg",onClick:()=>a(!1),children:"Abbrechen"}),e.jsxs(z,{className:"gap-1.5 rounded-lg",disabled:!b||x,onClick:async()=>{await h(b,(i==null?void 0:i.trip)??null),f(""),a(!1)},children:[e.jsx(Es,{className:"h-3.5 w-3.5"})," Freigeben"]})]})]})})]})}const va={hotel:"Hotel",guide:"Reiseleiter",transport:"Transport",activity:"Aktivität",donation:"Spende",catering:"Verpflegung",dmc:"DMC"},Ua={hotel:{bg:"bg-blue-500/15",text:"text-blue-500",iconBg:"bg-blue-500"},guide:{bg:"bg-purple-500/15",text:"text-purple-500",iconBg:"bg-purple-500"},transport:{bg:"bg-orange-500/15",text:"text-orange-500",iconBg:"bg-orange-500"},activity:{bg:"bg-emerald-500/15",text:"text-emerald-500",iconBg:"bg-emerald-500"},donation:{bg:"bg-pink-500/15",text:"text-pink-500",iconBg:"bg-pink-500"},catering:{bg:"bg-amber-500/15",text:"text-amber-500",iconBg:"bg-amber-500"},dmc:{bg:"bg-teal-500/15",text:"text-teal-500",iconBg:"bg-teal-500"}},Wr={hotel:Li,guide:Ns,transport:qi,activity:Mi,donation:mn,catering:Gi,dmc:Ii},Qr=[{value:"requested",label:"Angefragt"},{value:"provisional",label:"Vorläufig"},{value:"confirmed",label:"Bestätigt"}];function gc({tripId:s,tripCountry:n,onOpenEmailDialog:a}){var Ps,Fs,Hs,Ct,F,re,Ne,as,Ge,Ze,es,Le,_s,Cs,zs;const[b,f]=t.useState(""),{partners:i,loading:x,updatePartner:h,addPartner:c,addContactEntry:k}=un(),{services:C,loading:N,refetch:v}=Si(),{tripServices:G,loading:T,addTripService:o,updateTripService:l,deleteTripService:V}=Di(s),{tripPartners:A,loading:q,updateTripPartner:y}=Un(s),{convertToEUR:W}=vr(),j=t.useMemo(()=>{const B=new Set;return G.forEach(ae=>{const ve=C.find(js=>js.id===ae.partnerServiceId);ve&&B.add(ve.partnerId)}),Array.from(B)},[G,C]),{counts:d,refetch:u}=oc(s,j),{data:I}=br(s),E=t.useMemo(()=>((I==null?void 0:I.attachedPartnerIds)??[]).filter(ae=>!j.includes(ae)).map(ae=>i.find(ve=>ve.id===ae)).filter(ae=>!!ae).sort((ae,ve)=>ae.name.localeCompare(ve.name)),[I,j,i]),[$,ge]=t.useState(null),[be,Z]=t.useState(null),[H,L]=t.useState(!1),[g,r]=t.useState(!1),[m,X]=t.useState(!1),[p,ne]=t.useState(null),[le,K]=t.useState(!1),[M,ee]=t.useState(!1),[he,we]=t.useState(void 0),[De,_e]=t.useState(null),[J,Ae]=t.useState({name:"",type:"activity",country:n||"",contactPerson:"",email:"",ph
125one:""}),[qe,Be]=t.useState({name:"",description:"",defaultPrice:0,priceType:"per_person",currency:"EUR"}),[Ke,Ce]=t.useState({partnerId:"",partnerServiceId:"",startDate:"",endDate:"",price:0,priceType:"per_person"}),[xe,ms]=t.useState({name:"",description:"",defaultPrice:0,priceType:"per_person",currency:"EUR"}),us=x||N||T||q,Q=t.useMemo(()=>G.map(B=>{const ae=C.find(js=>js.id===B.partnerServiceId),ve=ae?i.find(js=>js.id===ae.partnerId):null;return{tripService:B,partnerService:ae,partner:ve}}).filter(B=>B.partnerService&&B.partner),[G,C,i]),ue=t.useMemo(()=>$&&Q.find(B=>B.tripService.id===$)||null,[$,Q]),de=t.useMemo(()=>ue?ue.partner:null,[ue]),S=Q.filter(({partner:B,partnerService:ae})=>(B==null?void 0:B.name.toLowerCase().includes(b.toLowerCase()))||(ae==null?void 0:ae.name.toLowerCase().includes(b.toLowerCase()))),P=t.useMemo(()=>{const B={};return S.forEach(ae=>{var js;const ve=(js=ae.partner)==null?void 0:js.id;ve&&(B[ve]||(B[ve]=[]),B[ve].push(ae))}),B},[S]),ie=async B=>{await l(B,{lastContactDate:Ks()})},Se=async(B,ae)=>{await l(B,{status:ae})},R=async B=>{await h(B)},ce=async B=>{de&&(await k(de.id,B),ue&&await ie(ue.tripService.id))},oe=B=>{ge(B)},me=()=>{ge(null)},Ee=t.useMemo(()=>{const B=G.map(ae=>ae.partnerServiceId);return C.filter(ae=>!B.includes(ae.id))},[C,G]),ze=t.useMemo(()=>he?i.filter(B=>B.country===he):i,[i,he]),ns=t.useMemo(()=>{const B={};return Ee.forEach(ae=>{const ve=ze.find(js=>js.id===ae.partnerId);ve&&(B[ve.id]||(B[ve.id]={partner:ve,services:[]}),B[ve.id].services.push(ae))}),B},[Ee,ze]),Pe=async()=>{if(Ke.partnerServiceId){K(!0);try{const B=C.find(ae=>ae.id===Ke.partnerServiceId);await o({tripId:s,partnerServiceId:Ke.partnerServiceId,startDate:Ke.startDate||Ks(),endDate:Ke.endDate||Ks(),price:Ke.price||(B==null?void 0:B.defaultPrice)||0,priceType:Ke.priceType,status:"requested",lastContactDate:Ks()}),r(!1),Ce({partnerId:"",partnerServiceId:"",startDate:"",endDate:"",price:0,priceType:"per_person"}),ee(!1),Ae({name:"",type:"activity",country:n||"",contactPerson:"",email:"",phone:""}),Be({name:"",description:"",defaultPrice:0,priceType:"per_person",currency:"EUR"})}finally{K(!1)}}},Fe=async()=>{if(!(!J.name||!J.email||!J.contactPerson||!qe.name)){K(!0);try{const B={id:`partner-${Date.now()}`,name:J.name,type:J.type,country:J.country,contactPerson:J.contactPerson,email:J.email,phone:J.phone,costType:"per_person",costAmount:0,notes:"",contactHistory:[]};await c(B);const{data:ae}=await _.from("partners").select("id").eq("email",J.email).order("created_at",{ascending:!1}).limit(1).maybeSingle();if(!ae)throw new Error("Partner konnte nicht gefunden werden");const{data:ve,error:js}=await _.from("partner_services").insert({partner_id:ae.id,name:qe.name,description:qe.description||null,default_price:qe.defaultPrice,price_type:qe.priceType,currency:qe.currency}).select().single();if(js)throw js;await o({tripId:s,partnerServiceId:ve.id,startDate:Ke.startDate||Ks(),endDate:Ke.endDate||Ks(),price:qe.defaultPrice,priceType:qe.priceType,status:"requested",lastContactDate:Ks()}),r(!1),ee(!1),Ae({name:"",type:"activity",country:n||"",contactPerson:"",email:"",phone:""}),Be({name:"",description:"",defaultPrice:0,priceType:"per_person",currency:"EUR"}),Ce({partnerId:"",partnerServiceId:"",startDate:"",endDate:"",price:0,priceType:"per_person"}),await v()}finally{K(!1)}}},cs=async B=>{await V(B),ge(null)},{addService:vs,deleteService:Me}=Ei(p==null?void 0:p.id),se=async()=>{if(!(!p||!xe.name)){K(!0);try{await vs({partnerId:p.id,name:xe.name,description:xe.description||void 0,defaultPrice:xe.defaultPrice,priceType:xe.priceType,currency:xe.currency}),ms({name:"",description:"",defaultPrice:0,priceType:"per_person",currency:"EUR"}),await v()}finally{K(!1)}}},Re=async B=>{await Me(B),await v()},ts=B=>{const ae=C.find(ve=>ve.id===B);Ce(ve=>({...ve,partnerServiceId:B,price:(ae==null?void 0:ae.defaultPrice)||0,priceType:(ae==null?void 0:ae.priceType)||"per_person"}))},hs=B=>B?new Date(B).toLocaleDateString("de-DE"):"–",As=(B,ae)=>{const ve=new Date(B),js=new Date(ae);return ve.getTime()===js.getTime()?hs(B):`${hs(B)} – ${hs(ae)}`},ds=B=>{const ae=new Date(B),js=new Date().getTime()-ae.getTime(),Ws=Math.floor(js/(1e3*60*60*24));return Ws===0?"Heute":Ws===1?"Gestern":`vor ${Ws} Tagen`};return us?e.jsx("div",{className:"flex min-h-[200px] items-center justify-center",children:e.jsx($e,{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",{className:"relative max-w-md flex-1",children:[e.jsx(wt,{className:"absolute left-3 top-1/2 h-4 w-4 -translate-y-1/2 text-muted-foreground"}),e.jsx(te,{type:"text",placeholder:"Partner oder Dienstleistung suchen...",value:b,onChange:B=>f(B.target.value),className:"pl-10 rounded-xl bg-muted/50 border-0"})]}),e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(pc,{tripId:s}),e.jsxs(z,{className:"gap-2 rounded-xl",onClick:()=>r(!0),children:[e.jsx(Es,{className:"h-4 w-4"}),"Dienstleistung hinzufügen"]})]})]}),Object.keys(P).length>0?e.jsx("div",{className:"space-y-6",children:Object.entries(P).map(([B,ae])=>{var Ws;const ve=(Ws=ae[0])==null?void 0:Ws.partner;if(!ve)return null;const js={};
125return ae.forEach(({tripService:is,partnerService:ls})=>{const ws=(ls==null?void 0:ls.currency)||"EUR";js[ws]=(js[ws]||0)+is.price}),e.jsxs("div",{className:"glass-card overflow-hidden",children:[e.jsxs("div",{className:"flex items-center justify-between p-5 border-b border-border bg-muted/30",children:[e.jsxs("div",{className:"flex items-center gap-3",children:[(()=>{const is=Wr[ve.type]||bt,ls=Ua[ve.type]||{bg:"bg-primary/15",text:"text-primary",iconBg:"bg-primary"};return e.jsx("div",{className:`flex h-10 w-10 items-center justify-center rounded-xl ${ls.iconBg}`,children:e.jsx(is,{className:"h-5 w-5 text-white"})})})(),e.jsxs("div",{children:[e.jsx("p",{className:"font-medium text-foreground",children:ve.name}),e.jsxs("div",{className:"flex items-center gap-2",children:[(()=>{const is=Ua[ve.type]||{bg:"bg-primary/15",text:"text-primary",iconBg:"bg-primary"};return e.jsx("span",{className:`text-xs font-medium rounded-full px-2.5 py-0.5 ${is.bg} ${is.text}`,children:va[ve.type]||ve.type})})(),e.jsxs("span",{className:"text-xs text-muted-foreground",children:[ae.length," Dienstleistung",ae.length!==1?"en":""]})]})]}),(()=>{const is=A.find(ls=>ls.partnerId===B);return e.jsx("div",{className:"ml-4",children:e.jsx(te,{type:"text",placeholder:"Buchungsnr.",defaultValue:(is==null?void 0:is.partnerBookingNumber)||"",className:"rounded-lg h-8 w-40 text-xs",onClick:ls=>ls.stopPropagation(),onBlur:ls=>{const ws=ls.target.value;is&&ws!==(is.partnerBookingNumber||"")&&y(is.id,{partnerBookingNumber:ws})}})})})()]}),e.jsxs("div",{className:"flex items-center gap-4",children:[e.jsx(Hr,{tripId:s,partnerId:ve.id,partnerName:ve.name,onOpenEmailDialog:a}),e.jsxs(z,{variant:"outline",size:"sm",className:"gap-2 rounded-lg",onClick:()=>_e(ve),children:[e.jsx(Ea,{className:"h-4 w-4"}),"Dokumente",d[ve.id]>0&&e.jsx("span",{className:"rounded-full bg-primary/10 text-primary px-2 py-0.5 text-xs font-medium",children:d[ve.id]})]}),e.jsxs("div",{className:"text-right",children:[e.jsx("p",{className:"text-sm text-muted-foreground",children:"Gesamt"}),e.jsx("div",{className:"flex flex-col items-end gap-0.5",children:Object.entries(js).map(([is,ls])=>{const ws=is==="EUR",Ht=W(ls,is);return e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx("p",{className:"font-semibold text-foreground",children:new Intl.NumberFormat("de-DE",{style:"currency",currency:is}).format(ls)}),!ws&&e.jsxs("span",{className:"text-xs text-muted-foreground",children:["≈ ",new Intl.NumberFormat("de-DE",{style:"currency",currency:"EUR"}).format(Ht)]})]},is)})})]}),e.jsx(z,{variant:"ghost",size:"icon",className:"rounded-lg",onClick:()=>{ne(ve),X(!0)},children:e.jsx(Ta,{className:"h-4 w-4"})})]})]}),e.jsx("div",{className:"overflow-x-auto",children:e.jsxs("table",{className:"w-full",children:[e.jsx("thead",{children:e.jsxs("tr",{className:"border-b border-border/50 bg-muted/10",children:[e.jsx("th",{className:"px-5 py-3 text-left text-sm font-medium text-muted-foreground",children:"Dienstleistung"}),e.jsx("th",{className:"px-5 py-3 text-left text-sm font-medium text-muted-foreground",children:"Zeitraum"}),e.jsx("th",{className:"px-5 py-3 text-left text-sm font-medium text-muted-foreground",children:"Preis"}),e.jsx("th",{className:"px-5 py-3 text-left text-sm font-medium text-muted-foreground",children:"Status"}),e.jsx("th",{className:"px-5 py-3 text-left text-sm font-medium text-muted-foreground",children:"Letzter Kontakt"})]})}),e.jsx("tbody",{children:ae.map(({tripService:is,partnerService:ls})=>e.jsxs("tr",{className:"border-b border-border/50 transition-colors hover:bg-muted/20 cursor-pointer",onClick:()=>oe(is.id),children:[e.jsx("td",{className:"px-5 py-4",children:e.jsxs("div",{className:"flex items-center gap-3",children:[e.jsx("div",{className:"flex h-8 w-8 items-center justify-center rounded-lg bg-accent/10",children:e.jsx(yt,{className:"h-4 w-4 text-accent-foreground"})}),e.jsxs("div",{children:[e.jsx("p",{className:"font-medium text-foreground",children:ls==null?void 0:ls.name}),(ls==null?void 0:ls.description)&&e.jsx("p",{className:"text-xs text-muted-foreground line-clamp-1",children:ls.description})]})]})}),e.jsx("td",{className:"px-5 py-4",children:e.jsxs("div",{className:"flex items-center gap-2 text-sm text-foreground",children:[e.jsx(kt,{className:"h-4 w-4 text-muted-foreground"}),As(is.startDate,is.endDate)]})}),e.jsx("td",{className:"px-5 py-4",children:e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx("span",{className:"font-semibold text-foreground",children:new Intl.NumberFormat("de-DE",{style:"currency",currency:(ls==null?void 0:ls.currency)||"EUR"}).format(is.price)}),e.jsx("span",{className:"text-xs text-muted-foreground",children:is.priceType==="per_person"?"/ Person":"/ Buchung"})]})}),e.jsx("td",{className:"px-5 py-4",onClick:ws=>ws.stopPropagation(),children:e.jsxs(Ie,{value:is.status,onValueChange:ws=>Se(is.id,ws),children:[e.jsx(Oe,{className:"w-32 rounded-lg border-0 bg-transparent p-0 h-auto",children:e.jsx(Nn,{status:is.status})}),e.jsx(Ue,{children:Qr.map(ws=>e.jsx(O,{value:ws.value,children:ws.label},ws.value))})]})}),e.jsx("td",{className:"px-5 py-4",children:e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsxs("div",{children:[e.jsx("p",{className:"text-sm text-foreground",children:hs(is.lastContactDate)}),e.jsx("p",{className:"text-xs text-muted-foreground",children:ds(is.lastContactDate)})]}),e.jsx(z,{variant:"ghost",size:"icon",className:"h-8 w-8 rounded-lg",onClick:ws=>{ws.stopPropagation(),ie(is.id)},children:e.jsx(Qa,{className:"h-4 w-4"})})]})})]},is.id))})]})})]},B)})}):e.jsxs("div",{className:"glass-card p-12 text-center",children:[e.jsx(yt,{className:"mx-auto h-12 w-12 text-muted-foreground"}),e.jsx("h3",{className:"mt-4 text-lg font-medium text-foreground",children:"Keine Dienstleistungen für diese Reise"}),e.jsx("p",{className:"mt-1 text-muted-foreground",children:"Fügen Sie Dienstleistungen von Ihren Partnern hinzu."})]}),E.length>0&&e.jsxs("div",{className:"glass-card overflow-hidden",children:[e.jsxs("div",{className:"border-b border-border bg-muted/30 px-5 py-3",children:[e.jsx("p",{className:"text-sm font-medium text-foreground",children:"Nur der Reise zugewiesen"}),e.jsx("p",{className:"text-xs text-muted-foreground",children:"Diese Partner hängen ohne Dienstleistung an der Reise – z. B. rein für die Portal-Sichtbarkeit."})]}),e.jsx("div",{className:"divide-y divide-border/50",children:E.map(B=>{const ae=Wr[B.type]||bt,ve=Ua[B.type]||{bg:"bg-primary/15",text:"text-primary",iconBg:"bg-primary"};return e.jsxs("div",{className:"flex flex-wrap items-center justify-between gap-3 px-5 py-4",children:[e.jsxs("div",{className:"flex items-center gap-3",children:[e.jsx("div",{className:`flex h-9 w-9 items-center justify-center rounded-xl ${ve.iconBg}`,children:e.jsx(ae,{className:"h-4 w-4 text-white"})}),e.jsxs("div",{children:[e.jsx("p",{className:"text-sm font-medium text-foreground",children:B.name}),e.jsx("span",{className:`text-xs font-medium rounded-full px-2.5 py-0.5 ${ve.bg} ${ve.text}`,children:va[B.type]||B.type})]})]}),e.jsx(Hr,{tripId:s,partnerId:B.id,partnerName:B.name,onOpenEmailDialog:a})]},B.id)})})]}),ue&&e.jsx(We,{open:!!ue,onOpenChange:me,children:e.jsxs(Qe,{className:"glass-modal sm:max-w-lg",children:[e.jsx(Ye,{children:e.jsx(Je,{className:"flex items-center justify-between",children:e.jsxs("div",{className:"flex items-center gap-3",children:[e.jsx("div",{className:"flex h-10 w-10 items-center justify-center rounded-xl bg-primary/10",children:e.jsx(yt,{className:"h-5 w-5 text-primary"})}),e.jsxs("div",{children:[e.jsx("p",{className:"text-lg font-semibold",children:(Ps=ue.partnerService)==null?void 0:Ps.name}),e.jsx("p",{className:"text-sm text-muted-foreground",children:(Fs=ue.partner)==null?void 0:Fs.name})]})]})})}),e.jsxs("div",{className:"mt-4 space-y-6",children:[e.jsxs("div",{className:"flex items-center justify-between rounded-xl bg-muted/30 p-4",children:[e.jsx("span",{className:"text-muted-foreground",children:"Status"}),e.jsxs(Ie,{value:ue.tripService.status,onValueChange:B=>Se(ue.tripService.id,B),children:[e.jsx(Oe,{className:"w-40 rounded-lg",children:e.jsx(Ve,{})}),e.jsx(Ue,{children:Qr.map(B=>e.jsx(O,{value:B.value,children:B.label},B.value))})]})]}),e.jsxs("div",{className:"space-y-3",children:[e.jsx("h4",{className:"font-medium text-foreground",children:"Kontaktdaten"}),e.jsxs("div",{className:"space-y-2 text-sm",children:[e.jsxs("div",{className:"flex items-center gap-3 text-muted-foreground",children:[e.jsx(Cn,{className:"h-4 w-4"}),(Hs=ue.partner)==null?void 0:Hs.contactPerson]}),e.jsxs("div",{className:"flex items-center gap-3 text-muted-foreground",children:[e.jsx(Os,{className:"h-4 w-4"}),e.jsx("a",{href:`mailto:${(Ct=ue.partner)==null?void 0:Ct.email}`,className:"hover:text-primary",children:(F=ue.partner)==null?void 0:F.email})]}),e.jsxs("div",{className:"flex items-center gap-3 text-muted-foreground",children:[e.jsx(xa,{
125className:"h-4 w-4"}),e.jsx("a",{href:`tel:${(re=ue.partner)==null?void 0:re.phone}`,className:"hover:text-primary",children:(Ne=ue.partner)==null?void 0:Ne.phone})]})]})]}),e.jsxs("div",{className:"space-y-3",children:[e.jsx("h4",{className:"font-medium text-foreground",children:"Buchungsdetails bearbeiten"}),e.jsxs("div",{className:"grid gap-4 text-sm rounded-xl bg-muted/30 p-4",children:[e.jsxs("div",{className:"space-y-2",children:[e.jsx("span",{className:"text-muted-foreground text-xs",children:"Zeitraum"}),e.jsxs("div",{className:"flex gap-2",children:[e.jsxs("div",{className:"flex-1",children:[e.jsx(U,{className:"text-xs text-muted-foreground mb-1 block",children:"Startdatum"}),e.jsxs(Dt,{children:[e.jsx(Et,{asChild:!0,children:e.jsxs(z,{variant:"outline",className:"w-full justify-start text-left font-normal rounded-lg h-9",children:[e.jsx(kt,{className:"mr-2 h-4 w-4"}),hs(ue.tripService.startDate)]})}),e.jsx(At,{className:"w-auto p-0 z-50",align:"start",children:e.jsx(qt,{mode:"single",selected:He(ue.tripService.startDate),onSelect:B=>{B&&l(ue.tripService.id,{startDate:fs(B,"yyyy-MM-dd")})},initialFocus:!0,className:"pointer-events-auto"})})]})]}),e.jsxs("div",{className:"flex-1",children:[e.jsx(U,{className:"text-xs text-muted-foreground mb-1 block",children:"Enddatum"}),e.jsxs(Dt,{children:[e.jsx(Et,{asChild:!0,children:e.jsxs(z,{variant:"outline",className:"w-full justify-start text-left font-normal rounded-lg h-9",children:[e.jsx(kt,{className:"mr-2 h-4 w-4"}),hs(ue.tripService.endDate)]})}),e.jsx(At,{className:"w-auto p-0 z-50",align:"start",children:e.jsx(qt,{mode:"single",selected:He(ue.tripService.endDate),onSelect:B=>{B&&l(ue.tripService.id,{endDate:fs(B,"yyyy-MM-dd")})},initialFocus:!0,className:"pointer-events-auto"})})]})]})]})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx("span",{className:"text-muted-foreground text-xs",children:"Preis"}),e.jsxs("div",{className:"flex gap-2",children:[e.jsx("div",{className:"flex-1",children:e.jsx(te,{type:"number",step:"0.01",min:"0",defaultValue:ue.tripService.price,className:"rounded-lg h-9",onBlur:B=>{const ae=parseFloat(B.target.value);!isNaN(ae)&&ae!==ue.tripService.price&&l(ue.tripService.id,{price:ae})}})}),e.jsxs(Ie,{value:((as=ue.partnerService)==null?void 0:as.currency)||"EUR",onValueChange:async B=>{var ae;if((ae=ue.partnerService)!=null&&ae.id){const{error:ve}=await _.from("partner_services").update({currency:B}).eq("id",ue.partnerService.id);ve||v()}},children:[e.jsx(Oe,{className:"w-24 rounded-lg h-9",children:e.jsx(Ve,{})}),e.jsxs(Ue,{children:[e.jsx(O,{value:"EUR",children:"EUR"}),e.jsx(O,{value:"USD",children:"USD"}),e.jsx(O,{value:"CAD",children:"CAD"}),e.jsx(O,{value:"GBP",children:"GBP"}),e.jsx(O,{value:"CHF",children:"CHF"}),e.jsx(O,{value:"AUD",children:"AUD"}),e.jsx(O,{value:"NZD",children:"NZD"}),e.jsx(O,{value:"ISK",children:"ISK"}),e.jsx(O,{value:"NOK",children:"NOK"}),e.jsx(O,{value:"SEK",children:"SEK"}),e.jsx(O,{value:"DKK",children:"DKK"}),e.jsx(O,{value:"CZK",children:"CZK"}),e.jsx(O,{value:"PLN",children:"PLN"}),e.jsx(O,{value:"JPY",children:"JPY"}),e.jsx(O,{value:"ZAR",children:"ZAR"}),e.jsx(O,{value:"NAD",children:"NAD"}),e.jsx(O,{value:"BWP",children:"BWP"}),e.jsx(O,{value:"UGX",children:"UGX"}),e.jsx(O,{value:"CRC",children:"CRC"}),e.jsx(O,{value:"MXN",children:"MXN"}),e.jsx(O,{value:"BRL",children:"BRL"}),e.jsx(O,{value:"MAD",children:"MAD"}),e.jsx(O,{value:"TRY",children:"TRY"}),e.jsx(O,{value:"THB",children:"THB"}),e.jsx(O,{value:"IDR",children:"IDR"}),e.jsx(O,{value:"INR",children:"INR"})]})]}),e.jsxs(Ie,{value:ue.tripService.priceType,onValueChange:B=>l(ue.tripService.id,{priceType:B}),children:[e.jsx(Oe,{className:"w-32 rounded-lg h-9",children:e.jsx(Ve,{})}),e.jsxs(Ue,{children:[e.jsx(O,{value:"per_person",children:"Pro Person"}),e.jsx(O,{value:"flat",children:"Pauschal"})]})]})]}),e.jsxs("div",{className:"flex justify-between text-xs pt-1",children:[e.jsx("span",{className:"text-muted-foreground",children:"Standardpreis"}),e.jsx("span",{className:"text-muted-foreground",children:new Intl.NumberFormat("de-DE",{style:"currency",currency:((Ge=ue.partnerService)==null?void 0:Ge.currency)||"EUR"}).format(((Ze=ue.partnerService)==null?void 0:Ze.defaultPrice)||0)})]})]})]})]}),e.jsxs("div",{className:"space-y-3",children:[e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsx("h4",{className:"font-medium text-foreground",children:"Letzter Kontakt"}),e.jsxs(z,{variant:"outline",size:"sm",className:"gap-2 rounded-lg",onClick:()=>ie(ue.tripService.id),children:[e.jsx(Qa,{className:"h-4 w-4"}),"Aktualisieren"]})]}),e.jsxs("div",{className:"rounded-xl bg-muted/30 p-4",children:[e.jsx("p",{className:"text-foreground",children:hs(ue.tripService.last
125ContactDate)}),e.jsx("p",{className:"text-sm text-muted-foreground",children:ds(ue.tripService.lastContactDate)})]})]}),e.jsxs("div",{className:"space-y-3",children:[e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsxs("h4",{className:"font-medium text-foreground",children:["Kontakthistorie (",((es=ue.partner)==null?void 0:es.contactHistory.length)||0,")"]}),e.jsxs(z,{variant:"outline",size:"sm",className:"gap-2 rounded-lg",onClick:()=>L(!0),children:[e.jsx(Bi,{className:"h-4 w-4"}),"Verwalten"]})]}),(((Le=ue.partner)==null?void 0:Le.contactHistory.length)||0)>0?e.jsx("div",{className:"space-y-2",children:(_s=ue.partner)==null?void 0:_s.contactHistory.slice(-2).reverse().map(B=>e.jsxs("div",{className:"rounded-lg bg-muted/30 p-3",children:[e.jsx("p",{className:"text-sm text-muted-foreground",children:hs(B.date)}),e.jsx("p",{className:"mt-1 text-sm text-foreground",children:B.note})]},B.id))}):e.jsx("p",{className:"text-sm text-muted-foreground",children:"Keine Einträge vorhanden"})]}),e.jsxs(z,{variant:"destructive",className:"w-full gap-2 rounded-xl",onClick:()=>{cs(ue.tripService.id)},children:[e.jsx(bs,{className:"h-4 w-4"}),"Dienstleistung entfernen"]})]})]})}),e.jsx(Ai,{partner:be,open:!!be,onOpenChange:B=>!B&&Z(null),onSave:R}),de&&e.jsx(Pi,{partnerName:de.name,contactHistory:de.contactHistory,open:H,onOpenChange:L,onAddEntry:ce}),e.jsx(We,{open:g,onOpenChange:B=>{r(B),B||(ee(!1),Ce({partnerId:"",partnerServiceId:"",startDate:"",endDate:"",price:0,priceType:"per_person"}),we(void 0))},children:e.jsxs(Qe,{className:"glass-modal sm:max-w-lg max-h-[85vh] overflow-y-auto",children:[e.jsx(Ye,{children:e.jsxs(Je,{className:"flex items-center gap-3",children:[e.jsx("div",{className:"flex h-10 w-10 items-center justify-center rounded-xl bg-primary/10",children:e.jsx(Es,{className:"h-5 w-5 text-primary"})}),"Dienstleistung hinzufügen"]})}),e.jsxs("div",{className:"mt-4 space-y-6",children:[e.jsxs("div",{className:"flex gap-2",children:[e.jsx(z,{variant:M?"outline":"default",className:"flex-1 rounded-xl",onClick:()=>ee(!1),children:"Bestehender Partner"}),e.jsx(z,{variant:M?"default":"outline",className:"flex-1 rounded-xl",onClick:()=>ee(!0),children:"Neuer Partner"})]}),M?e.jsxs("div",{className:"space-y-6",children:[e.jsxs("div",{className:"rounded-xl bg-muted/30 p-4 space-y-4",children:[e.jsx("h4",{className:"font-medium text-foreground",children:"Partner-Informationen"}),e.jsxs("div",{className:"grid grid-cols-2 gap-4",children:[e.jsxs("div",{className:"space-y-2 col-span-2",children:[e.jsx(U,{children:"Partnername *"}),e.jsx(te,{placeholder:"z.B. Ruka Experiences Oy",value:J.name,onChange:B=>Ae(ae=>({...ae,name:B.target.value})),className:"rounded-xl"})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(U,{children:"Typ"}),e.jsxs(Ie,{value:J.type,onValueChange:B=>Ae(ae=>({...ae,type:B})),children:[e.jsx(Oe,{className:"rounded-xl",children:e.jsx(Ve,{})}),e.jsxs(Ue,{children:[e.jsx(O,{value:"hotel",children:"Hotel"}),e.jsx(O,{value:"guide",children:"Reiseleiter"}),e.jsx(O,{value:"transport",children:"Transport"}),e.jsx(O,{value:"activity",children:"Aktivität"}),e.jsx(O,{value:"donation",children:"Spende"}),e.jsx(O,{value:"catering",children:"Verpflegung"}),e.jsx(O,{value:"dmc",children:"DMC"})]})]})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(U,{children:"Land"}),e.jsx(te,{placeholder:"z.B. Finnland",value:J.country,onChange:B=>Ae(ae=>({...ae,country:B.target.value})),className:"rounded-xl"})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(U,{children:"Ansprechpartner *"}),e.jsx(te,{placeholder:"Name",value:J.contactPerson,onChange:B=>Ae(ae=>({...ae,contactPerson:B.target.value})),className:"rounded-xl"})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(U,{children:"E-Mail *"}),e.jsx(te,{type:"email",placeholder:"[email protected]",value:J.email,onChange:B=>Ae(ae=>({...ae,email:B.target.value})),className:"rounded-xl"})]}),e.jsxs("div",{className:"space-y-2 col-span-2",children:[e.jsx(U,{children:"Telefon"}),e.jsx(te,{placeholder:"+358...",value:J.phone,onChange:B=>Ae(ae=>({...ae,phone:B.target.value})),className:"rounded-xl"})]})]})]}),e.jsxs("div",{className:"rounded-xl bg-muted/30 p-4 space-y-4",children:[e.jsx("h4",{className:"font-medium text-foreground",children:"Erste Dienstleistung"}),e.jsxs("div",{className:"space-y-4",children:[e.jsxs("div",{className:"space-y-2",children:[e.jsx(U,{children:"Name der Dienstleistung *"}),e.jsx(te,{placeholder:"z.B. Arctic River Floating",value:qe.name,onChange:B=>Be(ae=>({...ae,name:B.target.value})),className:"rounded-xl"})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(U,{children:"Beschreibung (optional)"}),e.jsx(qs,{placeholder:"Kurze Beschreibung...",value:qe.description,onChange:B=>Be(ae=>({...ae,description:B.target.value})),className:"rounded-xl",rows:2})]}),e.jsxs("div",{className:"grid grid-cols-3 gap-4",children:[e.jsxs("div",{className:"space-y-2",children:[e.jsx(U,{children:"Preis"}),e.jsx(te,{type:"number",min:"0",step:"0.01",value:qe.defaultPrice||"",onChange:B=>Be(ae=>
125({...ae,defaultPrice:parseFloat(B.target.value)||0})),className:"rounded-xl"})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(U,{children:"Währung"}),e.jsxs(Ie,{value:qe.currency,onValueChange:B=>Be(ae=>({...ae,currency:B})),children:[e.jsx(Oe,{className:"rounded-xl",children:e.jsx(Ve,{})}),e.jsxs(Ue,{children:[e.jsx(O,{value:"EUR",children:"EUR (€)"}),e.jsx(O,{value:"USD",children:"USD ($)"}),e.jsx(O,{value:"CAD",children:"CAD (C$)"}),e.jsx(O,{value:"GBP",children:"GBP (£)"}),e.jsx(O,{value:"CHF",children:"CHF"}),e.jsx(O,{value:"AUD",children:"AUD (A$)"}),e.jsx(O,{value:"NZD",children:"NZD (NZ$)"}),e.jsx(O,{value:"ISK",children:"ISK (kr)"}),e.jsx(O,{value:"NOK",children:"NOK (kr)"}),e.jsx(O,{value:"SEK",children:"SEK (kr)"}),e.jsx(O,{value:"DKK",children:"DKK (kr)"}),e.jsx(O,{value:"CZK",children:"CZK (Kč)"}),e.jsx(O,{value:"PLN",children:"PLN (zł)"}),e.jsx(O,{value:"JPY",children:"JPY (¥)"}),e.jsx(O,{value:"ZAR",children:"ZAR (R)"}),e.jsx(O,{value:"NAD",children:"NAD (N$)"}),e.jsx(O,{value:"BWP",children:"BWP (P)"}),e.jsx(O,{value:"UGX",children:"UGX (USh)"}),e.jsx(O,{value:"CRC",children:"CRC (₡)"}),e.jsx(O,{value:"MXN",children:"MXN ($)"}),e.jsx(O,{value:"BRL",children:"BRL (R$)"}),e.jsx(O,{value:"MAD",children:"MAD (DH)"}),e.jsx(O,{value:"TRY",children:"TRY (₺)"}),e.jsx(O,{value:"THB",children:"THB (฿)"}),e.jsx(O,{value:"IDR",children:"IDR (Rp)"}),e.jsx(O,{value:"INR",children:"INR (₹)"})]})]})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(U,{children:"Preisart"}),e.jsxs(Ie,{value:qe.priceType,onValueChange:B=>Be(ae=>({...ae,priceType:B})),children:[e.jsx(Oe,{className:"rounded-xl",children:e.jsx(Ve,{})}),e.jsxs(Ue,{children:[e.jsx(O,{value:"per_person",children:"Pro Person"}),e.jsx(O,{value:"flat",children:"Pauschal"})]})]})]})]})]})]}),e.jsxs("div",{className:"grid grid-cols-2 gap-4",children:[e.jsxs("div",{className:"space-y-2",children:[e.jsx(U,{children:"Startdatum"}),e.jsx(te,{type:"date",value:Ke.startDate,onChange:B=>Ce(ae=>({...ae,startDate:B.target.value})),className:"rounded-xl"})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(U,{children:"Enddatum"}),e.jsx(te,{type:"date",value:Ke.endDate,onChange:B=>Ce(ae=>({...ae,endDate:B.target.value})),className:"rounded-xl"})]})]})]}):e.jsx(e.Fragment,{children:Object.keys(ns).length>0||i.length>0?e.jsxs(e.Fragment,{children:[e.jsxs("div",{className:"space-y-3",children:[e.jsxs(U,{className:"flex items-center gap-2",children:[e.jsx(Dn,{className:"h-4 w-4 text-muted-foreground"}),"Nach Land filtern"]}),e.jsxs("div",{className:"flex gap-2",children:[e.jsx("div",{className:"flex-1",children:e.jsxs(Ie,{value:he||"all",onValueChange:B=>{we(B==="all"?void 0:B),Ce(ae=>({...ae,partnerId:"",partnerServiceId:""}))},children:[e.jsx(Oe,{className:"rounded-xl",children:e.jsx(Ve,{placeholder:"Alle Länder"})}),e.jsxs(Ue,{children:[e.jsx(O,{value:"all",children:"Alle Länder"}),[...new Set(i.map(B=>B.country).filter(Boolean))].sort().map(B=>e.jsx(O,{value:B,children:B},B))]})]})}),he&&e.jsx(z,{variant:"ghost",size:"icon",className:"shrink-0",onClick:()=>{we(void 0),Ce(B=>({...B,partnerId:"",partnerServiceId:""}))},children:e.jsx(bs,{className:"h-4 w-4"})})]})]}),e.jsxs("div",{className:"space-y-3",children:[e.jsx(U,{children:"Partner auswählen"}),e.jsxs(Ie,{value:Ke.partnerId,onValueChange:B=>Ce(ae=>({...ae,partnerId:B,partnerServiceId:""})),children:[e.jsx(Oe,{className:"rounded-xl",children:e.jsx(Ve,{placeholder:"Partner auswählen..."})}),e.jsx(Ue,{children:ze.map(B=>e.jsxs(O,{value:B.id,children:[B.name," (",va[B.type],B.country?` • ${B.country}`:"",")"]},B.id))})]}),he&&ze.length===0&&e.jsx("p",{className:"text-sm text-muted-foreground",children:"Keine Partner für dieses Land gefunden."})]}),Ke.partnerId&&e.jsxs("div",{className:"space-y-3",children:[e.jsx(U,{children:"Dienstleistung auswählen"}),((Cs=ns[Ke.partnerId])==null?void 0:Cs.services.length)>0?e.jsxs(Ie,{value:Ke.partnerServiceId,onValueChange:ts,children:[e.jsx(Oe,{className:"rounded-xl",children:e.jsx(Ve,{placeholder:"Dienstleistung auswählen..."})}),e.jsx(Ue,{children:(zs=ns[Ke.partnerId])==null?void 0:zs.services.map(B=>
125e.jsxs(O,{value:B.id,children:[B.name," (",new Intl.NumberFormat("de-DE",{style:"currency",currency:B.currency||"EUR"}).format(B.defaultPrice),")"]},B.id))})]}):e.jsxs("div",{className:"rounded-xl bg-muted/50 p-4 text-center",children:[e.jsx("p",{className:"text-sm text-muted-foreground mb-3",children:"Keine verfügbaren Dienstleistungen für diesen Partner."}),e.jsxs(z,{variant:"outline",size:"sm",className:"gap-2 rounded-lg",onClick:()=>{ne(i.find(B=>B.id===Ke.partnerId)||null),X(!0)},children:[e.jsx(Es,{className:"h-4 w-4"}),"Dienstleistung erstellen"]})]})]}),Ke.partnerServiceId&&e.jsxs("div",{className:"space-y-4",children:[e.jsx("h4",{className:"font-medium text-foreground",children:"Buchungsdetails"}),e.jsxs("div",{className:"grid grid-cols-2 gap-4",children:[e.jsxs("div",{className:"space-y-2",children:[e.jsx(U,{children:"Startdatum"}),e.jsx(te,{type:"date",value:Ke.startDate,onChange:B=>Ce(ae=>({...ae,startDate:B.target.value})),className:"rounded-xl"})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(U,{children:"Enddatum"}),e.jsx(te,{type:"date",value:Ke.endDate,onChange:B=>Ce(ae=>({...ae,endDate:B.target.value})),className:"rounded-xl"})]})]}),e.jsxs("div",{className:"grid grid-cols-2 gap-4",children:[e.jsxs("div",{className:"space-y-2",children:[e.jsx(U,{children:"Saisonaler Preis"}),e.jsx(te,{type:"number",min:"0",step:"0.01",value:Ke.price||"",onChange:B=>Ce(ae=>({...ae,price:parseFloat(B.target.value)||0})),className:"rounded-xl"})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(U,{children:"Preisart"}),e.jsxs(Ie,{value:Ke.priceType,onValueChange:B=>Ce(ae=>({...ae,priceType:B})),children:[e.jsx(Oe,{className:"rounded-xl",children:e.jsx(Ve,{})}),e.jsxs(Ue,{children:[e.jsx(O,{value:"per_person",children:"Pro Person"}),e.jsx(O,{value:"flat",children:"Pauschal"})]})]})]})]})]})]}):e.jsxs("div",{className:"text-center py-6",children:[e.jsx(bt,{className:"mx-auto h-12 w-12 text-muted-foreground"}),e.jsx("p",{className:"mt-4 text-muted-foreground",children:"Keine Partner vorhanden."}),e.jsxs(z,{variant:"outline",className:"mt-4 gap-2 rounded-xl",onClick:()=>ee(!0),children:[e.jsx(Es,{className:"h-4 w-4"}),"Neuen Partner erstellen"]})]})})]}),e.jsxs(gs,{className:"mt-6 gap-2",children:[e.jsx(z,{variant:"outline",className:"rounded-xl",onClick:()=>{r(!1),ee(!1)},disabled:le,children:"Abbrechen"}),M?e.jsx(z,{className:"gap-2 rounded-xl",onClick:Fe,disabled:le||!J.name||!J.email||!J.contactPerson||!qe.name,children:le?e.jsxs(e.Fragment,{children:[e.jsx($e,{className:"h-4 w-4 animate-spin"}),"Wird erstellt..."]}):"Partner & Service erstellen"}):e.jsx(z,{className:"gap-2 rounded-xl",onClick:Pe,disabled:le||!Ke.partnerServiceId,children:le?e.jsxs(e.Fragment,{children:[e.jsx($e,{className:"h-4 w-4 animate-spin"}),"Wird hinzugefügt..."]}):"Hinzufügen"})]})]})}),e.jsx(We,{open:m,onOpenChange:X,children:e.jsxs(Qe,{className:"glass-modal sm:max-w-lg max-h-[80vh] overflow-y-auto",children:[e.jsx(Ye,{children:e.jsxs(Je,{className:"flex items-center gap-3",children:[e.jsx("div",{className:"flex h-10 w-10 items-center justify-center rounded-xl bg-primary/10",children:e.jsx(bt,{className:"h-5 w-5 text-primary"})}),e.jsxs("div",{children:[e.jsx("p",{children:"Dienstleistungen verwalten"}),p&&e.jsx("p",{className:"text-sm font-normal text-muted-foreground",children:p.name})]})]})}),e.jsxs("div",{className:"mt-4 space-y-6",children:[e.jsxs("div",{className:"space-y-2",children:[e.jsx(U,{children:"Partner"}),e.jsxs(Ie,{value:(p==null?void 0:p.id)||"",onValueChange:B=>ne(i.find(ae=>ae.id===B)||null),children:[e.jsx(Oe,{className:"rounded-xl",children:e.jsx(Ve,{placeholder:"Partner auswählen..."})}),e.jsx(Ue,{children:i.map(B=>e.jsxs(O,{value:B.id,children:[B.name," (",va[B.type],")"]},B.id))})]})]}),p&&e.jsxs(e.Fragment,{children:[e.jsxs("div",{className:"space-y-3",children:[e.jsx("h4",{className:"font-medium text-foreground",children:"Bestehende Dienstleistungen"}),C.filter(B=>B.partnerId===p.id).length>0?e.jsx("div",{className:"space-y-2",children:C.filter(B=>B.partnerId===p.id).map(B=>{const ae=G.some(ve=>ve.partnerServiceId===B.id);return e.jsxs("div",{className:"flex items-center justify-between rounded-xl bg-muted/30 p-4",children:[e.jsxs("div",{children:[e.jsx("p",{className:"font-medium text-foreground",children:B.name}),e.jsxs("p",{className:"text-sm text-muted-foreground",children:[new Intl.NumberFormat("de-DE",{style:"currency",currency:"EUR"}).format(B.defaultPrice)," ","(",B.priceType==="per_person"?"pro Person":"pro Buchung",")"]})]}),e.jsxs("div",{className:"flex items-center gap-2",children:[ae?e.jsx("span",{className:"text-xs text-muted-foreground bg-muted px-2 py-1 rounded-lg",children:"Bereits hinzugefügt"}):e.jsxs(z,{variant:"outline",size:"sm",className:"gap-1 rounded-lg",onClick:async()=>{K(!0);
125try{await o({tripId:s,partnerServiceId:B.id,startDate:Ks(),endDate:Ks(),price:B.defaultPrice,priceType:B.priceType,status:"requested",lastContactDate:Ks()})}finally{K(!1)}},disabled:le,children:[e.jsx(Es,{className:"h-3 w-3"}),"Zur Reise"]}),e.jsx(z,{variant:"ghost",size:"icon",className:"h-8 w-8 text-destructive hover:text-destructive rounded-lg",onClick:()=>Re(B.id),children:e.jsx(bs,{className:"h-4 w-4"})})]})]},B.id)})}):e.jsx("p",{className:"text-sm text-muted-foreground",children:"Keine Dienstleistungen vorhanden"})]}),e.jsxs("div",{className:"space-y-4 border-t border-border pt-4",children:[e.jsx("h4",{className:"font-medium text-foreground",children:"Neue Dienstleistung hinzufügen"}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(U,{children:"Name"}),e.jsx(te,{placeholder:"z.B. Arctic River Floating",value:xe.name,onChange:B=>ms(ae=>({...ae,name:B.target.value})),className:"rounded-xl"})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(U,{children:"Beschreibung (optional)"}),e.jsx(qs,{placeholder:"Beschreibung der Dienstleistung...",value:xe.description,onChange:B=>ms(ae=>({...ae,description:B.target.value})),className:"rounded-xl resize-none",rows:2})]}),e.jsxs("div",{className:"grid grid-cols-3 gap-4",children:[e.jsxs("div",{className:"space-y-2",children:[e.jsx(U,{children:"Standardpreis"}),e.jsx(te,{type:"number",min:"0",step:"0.01",value:xe.defaultPrice||"",onChange:B=>ms(ae=>({...ae,defaultPrice:parseFloat(B.target.value)||0})),className:"rounded-xl"})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(U,{children:"Währung"}),e.jsxs(Ie,{value:xe.currency||"EUR",onValueChange:B=>ms(ae=>({...ae,currency:B})),children:[e.jsx(Oe,{className:"rounded-xl",children:e.jsx(Ve,{})}),e.jsxs(Ue,{children:[e.jsx(O,{value:"EUR",children:"EUR (€)"}),e.jsx(O,{value:"USD",children:"USD ($)"}),e.jsx(O,{value:"GBP",children:"GBP (£)"}),e.jsx(O,{value:"CHF",children:"CHF"}),e.jsx(O,{value:"CAD",children:"CAD ($)"}),e.jsx(O,{value:"AUD",children:"AUD ($)"}),e.jsx(O,{value:"NZD",children:"NZD ($)"}),e.jsx(O,{value:"ZAR",children:"ZAR (R)"}),e.jsx(O,{value:"NAD",children:"NAD (N$)"}),e.jsx(O,{value:"BWP",children:"BWP (P)"}),e.jsx(O,{value:"UGX",children:"UGX (USh)"}),e.jsx(O,{value:"CRC",children:"CRC (₡)"}),e.jsx(O,{value:"JPY",children:"JPY (¥)"}),e.jsx(O,{value:"CNY",children:"CNY (¥)"}),e.jsx(O,{value:"INR",children:"INR (₹)"}),e.jsx(O,{value:"BRL",children:"BRL (R$)"}),e.jsx(O,{value:"MXN",children:"MXN ($)"}),e.jsx(O,{value:"SEK",children:"SEK (kr)"}),e.jsx(O,{value:"NOK",children:"NOK (kr)"}),e.jsx(O,{value:"DKK",children:"DKK (kr)"}),e.jsx(O,{value:"PLN",children:"PLN (zł)"}),e.jsx(O,{value:"CZK",children:"CZK (Kč)"}),e.jsx(O,{value:"HUF",children:"HUF (Ft)"}),e.jsx(O,{value:"THB",children:"THB (฿)"}),e.jsx(O,{value:"SGD",children:"SGD ($)"}),e.jsx(O,{value:"HKD",children:"HKD ($)"}),e.jsx(O,{value:"KRW",children:"KRW (₩)"}),e.jsx(O,{value:"TRY",children:"TRY (₺)"}),e.jsx(O,{value:"MAD",children:"MAD (د.م.)"})]})]})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(U,{children:"Preisart"}),e.jsxs(Ie,{value:xe.priceType,onValueChange:B=>ms(ae=>({...ae,priceType:B})),children:[e.jsx(Oe,{className:"rounded-xl",children:e.jsx(Ve,{})}),e.jsxs(Ue,{children:[e.jsx(O,{value:"per_person",children:"Pro Person"}),e.jsx(O,{value:"flat",children:"Pauschal"})]})]})]})]}),e.jsx(z,{className:"w-full gap-2 rounded-xl",onClick:se,disabled:le||!xe.name,children:le?e.jsxs(e.Fragment,{children:[e.jsx($e,{className:"h-4 w-4 animate-spin"}),"Wird hinzugefügt..."]}):e.jsxs(e.Fragment,{children:[e.jsx(Es,{className:"h-4 w-4"}),"Dienstleistung hinzufügen"]})})]})]})]})]})}),e.jsx(We,{open:!!De,onOpenChange:B=>!B&&_e(null),children:e.jsxs(Qe,{className:"glass-modal sm:max-w-lg max-h-[85vh] overflow-y-auto",children:[e.jsx(Ye,{children:e.jsxs(Je,{className:"flex items-center gap-3",children:[e.jsx("div",{className:"flex h-10 w-10 items-center justify-center rounded-xl bg-primary/10",children:e.jsx(Ea,{className:"h-5 w-5 text-primary"})}),"Dokumente für ",De==null?void 0:De.name]})}),De&&e.jsx(uc,{partnerId:De.id,tripId:s,onDocumentChange:u})]})})]})}const Yr=[{id:"fullName",label:"Name",category:"Stammdaten"},{id:"firstName",label:"Vorname",category:"Stammdaten"},{id:"lastName",label:"Nachname",category:"Stammdaten"},{id:"email",label:"E-Mail",category:"Kontakt"},{id:"phone",label:"Telefon",category:"Kontakt"},{id:"dateOfBirth",label:"Geburtsdatum",category:"Stammdaten"},{id:"passportNumber",label:"Passnummer",category:"Dokumente"},{id:"dietaryRequirements",label:"Ernährung",category:"Präferenzen"},{id:"allergies",label:"Allergien",category:"Präferenzen"},{id:"foodDislikes",label:"No-Gos beim Essen",category:"Präferenzen"},{id:"emergencyContact",label:"Notfallkontakt",category:"Kontakt"},{id:"roomAssignment",label:"Zimmer",category:"Zimmerzuteilung"},{id:"bookingName",label:"Buchung",category:"Buchung"}];function fc({list:s,onSave:n,onClose:a}){const[b,f]=t.useState(s.name),[i,x]=t.useState(s.description||""),[h,c]=t.useState(s.enableRoomAssignment),[k,C]=t.useState(s.visibleToGuides??!1),[N,v]=t.useState(s.visibleToPartnerIds??[]),[G,T]=t.useState([]),[o,l]=t.useState(s.columns);t.useEffect(()=>{(async()=>{const{data:u}=await _.from("partner_access").select("partner_id, partners(id, name)").eq("is_active",!0),I=(u??[]).map(E=>E.partners?{id:E.partners.id,name:E.partners.name}
125:null).filter(Boolean);I.sort((E,$)=>E.name.localeCompare($.name)),T(I)})()},[]);const V=u=>{v(I=>I.includes(u)?I.filter(E=>E!==u):[...I,u])},A=o.map(u=>u.sourceField),q=u=>{if(A.includes(u))l(o.filter(I=>I.sourceField!==u));else{const I=Yr.find(E=>E.id===u);l([...o,{id:`col_${Date.now()}`,label:I.label,sourceField:I.id,visible:!0}])}},y=u=>{l(o.filter(I=>I.id!==u))},W=(u,I)=>{l(o.map(E=>E.id===u?{...E,label:I}:E))},j=()=>{let u=[...o];h&&!A.includes("roomAssignment")&&u.push({id:`col_${Date.now()}_room`,label:"Zimmer",sourceField:"roomAssignment",visible:!0});const I={...s,name:b,description:i,columns:u,enableRoomAssignment:h,visibleToGuides:k,visibleToPartnerIds:N};n(I)},d=Yr.reduce((u,I)=>(u[I.category]||(u[I.category]=[]),u[I.category].push(I),u),{});return e.jsxs(Qe,{className:"glass-modal sm:max-w-2xl max-h-[85vh] overflow-y-auto",children:[e.jsx(Ye,{children:e.jsx(Je,{children:"Liste bearbeiten"})}),e.jsxs("div",{className:"space-y-6 mt-4",children:[e.jsxs("div",{className:"grid gap-4 sm:grid-cols-2",children:[e.jsxs("div",{className:"space-y-2",children:[e.jsx(U,{children:"Name der Liste"}),e.jsx(te,{value:b,onChange:u=>f(u.target.value),placeholder:"z.B. Küchenliste",className:"rounded-xl"})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(U,{children:"Beschreibung (optional)"}),e.jsx(te,{value:i,onChange:u=>x(u.target.value),placeholder:"Kurze Beschreibung",className:"rounded-xl"})]})]}),e.jsxs("div",{className:"flex items-center justify-between rounded-xl bg-muted/30 p-4",children:[e.jsxs("div",{className:"flex items-center gap-3",children:[e.jsx(pa,{className:"h-5 w-5 text-primary"}),e.jsxs("div",{children:[e.jsx("p",{className:"font-medium text-foreground",children:"Zimmerzuteilung aktivieren"}),e.jsx("p",{className:"text-sm text-muted-foreground",children:"Ermöglicht manuelle Zimmerzuweisung"})]})]}),e.jsx(ys,{checked:h,onCheckedChange:c})]}),e.jsxs("div",{className:"flex items-center justify-between rounded-xl bg-muted/30 p-4",children:[e.jsxs("div",{className:"flex items-center gap-3",children:[e.jsx(st,{className:"h-5 w-5 text-primary"}),e.jsxs("div",{children:[e.jsx("p",{className:"font-medium text-foreground",children:"Im Guide-Portal anzeigen"}),e.jsx("p",{className:"text-sm text-muted-foreground",children:"Diese Liste erscheint in der Reise-Detailansicht deiner Guides"})]})]}),e.jsx(ys,{checked:k,onCheckedChange:C})]}),G.length>0&&e.jsxs("div",{className:"rounded-xl bg-muted/30 p-4 space-y-3",children:[e.jsxs("div",{className:"flex items-center gap-3",children:[e.jsx(bt,{className:"h-5 w-5 text-primary"}),e.jsxs("div",{children:[e.jsx("p",{className:"font-medium text-foreground",children:"Im Partner-Portal anzeigen"}),e.jsx("p",{className:"text-sm text-muted-foreground",children:"Wähle, welche Partner diese Liste sehen dürfen."})]})]}),e.jsx("div",{className:"grid grid-cols-1 sm:grid-cols-2 gap-2",children:G.map(u=>{const I=N.includes(u.id);return e.jsxs("div",{className:`flex items-center gap-2 rounded-lg p-2 cursor-pointer transition-colors ${I?"bg-primary/10 border border-primary/30":"bg-background/50 hover:bg-muted/50"}`,onClick:()=>V(u.id),children:[e.jsx(Zs,{checked:I}),e.jsx("span",{className:"text-sm",children:u.name})]},u.id)})})]}),e.jsxs("div",{className:"space-y-3",children:[e.jsxs(U,{children:["Aktive Spalten (",o.length,")"]}),e.jsx("div",{className:"space-y-2 rounded-xl bg-muted/20 p-4",children:o.length===0?e.jsx("p",{className:"text-sm text-muted-foreground text-center py-2",children:"Keine Spalten ausgewählt. Wählen Sie unten Spalten hinzu."}):o.map((u,I)=>e.jsxs("div",{className:"flex items-center gap-3 rounded-lg bg-background/50 px-3 py-2",children:[e.jsx(Ra,{className:"h-4 w-4 text-muted-foreground"}),e.jsxs("span",{className:"text-sm text-muted-foreground w-6",children:[I+1,"."]}),e.jsx(te,{value:u.label,onChange:E=>W(u.id,E.target.value),className:"h-8 flex-1 rounded-lg"}),e.jsx("span",{className:"text-xs text-muted-foreground px-2 py-1 rounded bg-muted",children:u.sourceField}),e.jsx(z,{variant:"ghost",size:"icon",className:"h-8 w-8 rounded-lg text-destructive hover:bg-destructive/10",onClick:()=>y(u.id),children:e.jsx(bs,{className:"h-4 w-4"})})]},u.id))})]}),e.jsxs("div",{className:"space-y-3",children:[e.jsx(U,{children:"Spalten hinzufügen"}),Object.entries(d).map(([u,I])=>e.jsxs("div",{className:"space-y-2",children:[e.jsx("p",{className:"text-xs font-medium text-muted-foreground uppercase tracking-wider",children:u}),e.jsx("div",{className:"grid grid-cols-2 sm:grid-cols-3 gap-2",children:I.map(E=>{const $=A.includes(E.id);return e.jsxs("div",{className:`flex items-center gap-2 rounded-lg p-2 cursor-pointer transition-colors ${$?"bg-primary/10 border border-primary/30":"bg-muted/30 hover:bg-muted/50"}`,onClick:()=>q(E.id),children:[e.jsx(Zs,{checked:$}),e.jsx("span",{className:"text-sm",children:E.label})]},E.id)})})]},u))]}),e.jsxs("div",{className:"flex justify-end gap-3 pt-4 border-t border-border",children:[e.jsx(z,{variant:"outline",className:"rounded-xl",onClick:a,children:"Abbrechen"}),e.jsx(z,{className:"rounded-xl",onClick:j,disabled:!b||o.length===0,children:"Änderungen speichern"})]})]})]})}const jc={Name:{de:"Name",en:"Name"},Vorname:{de:"Vorname",en:"First Name"},Nachname:{de:"Nachname",en:"Last Name"},"E-Mail":{de:"E-Mail",en:"Email"},Telefon:{de:"Telefon",en:"Phone"},Geburtsdatum:{de:"Geburtsdatum",en:"Date of Birth"},Alter:{de:"Alter",en:"Age"},Nationalität:{de:"Nationalität",en:"Nationality"},Passnummer:{de:"Passnummer",en:"Passport Number"},Ernährungsform:{de:"Ernährungsform",en:"Dietary Requirements"},Allergien:{de:"Allergien",en:"Allergies"},Notfallkontakt:{de:"Notfallkontakt",en:"Emergency Contact"}
125,Zimmer:{de:"Zimmer",en:"Room"},Buchung:{de:"Buchung",en:"Booking"},"Anreise Flugnummer":{de:"Anreise Flugnummer",en:"Arrival Flight Number"},"Anreise Datum":{de:"Anreise Datum",en:"Arrival Date"},Ankunftszeit:{de:"Ankunftszeit",en:"Arrival Time"},"Anreise Route":{de:"Anreise Route",en:"Arrival Route"},"Abreise Flugnummer":{de:"Abreise Flugnummer",en:"Departure Flight Number"},"Abreise Datum":{de:"Abreise Datum",en:"Departure Date"},Abflugzeit:{de:"Abflugzeit",en:"Departure Time"},"Abreise Route":{de:"Abreise Route",en:"Departure Route"},Schuhgröße:{de:"Schuhgröße",en:"Shoe Size"},Kopfumfang:{de:"Kopfumfang",en:"Head Circumference"},"Overall Größe":{de:"Overall Größe",en:"Overall Size"},Kleidergröße:{de:"Kleidergröße",en:"Clothing Size"},Größe:{de:"Größe",en:"Size"},Körpergröße:{de:"Körpergröße",en:"Height"},Gewicht:{de:"Gewicht",en:"Weight"},Geschlecht:{de:"Geschlecht",en:"Gender"}},_c=(s,n)=>{const a=jc[s];return a?a[n]:s},Nc=["fullName","firstName","lastName","email","phone","dateOfBirth","age","passportNumber","roomAssignment","bookingName","billingStreet","billingCity","billingPostalCode","billingCountry","fullAddress","arrivalFlightNumber","arrivalDate","arrivalTime","departureFlightNumber","departureDate","departureTime"],Jr=s=>!Nc.includes(s);function vc({open:s,onClose:n,list:a,participants:b,getParticipantValue:f,trip:i,companySettings:x,groups:h=[]}){const[c,k]=t.useState("csv"),[C,N]=t.useState("de"),[v,G]=t.useState(!1),T=a.columns.filter(Z=>Z.visible),o=a.enableRoomAssignment&&h.length>0,l=t.useMemo(()=>{const Z=new Map;for(const H of h)for(const L of H.participantIds)Z.set(L,H);return Z},[h]),V=t.useMemo(()=>{if(!o)return b;const Z=new Map;return h.forEach((H,L)=>Z.set(H.id,L)),[...b].sort((H,L)=>{const g=l.get(H.id),r=l.get(L.id),m=g?Z.get(g.id):Number.MAX_SAFE_INTEGER,X=r?Z.get(r.id):Number.MAX_SAFE_INTEGER;return m!==X?m-X:b.indexOf(H)-b.indexOf(L)})},[b,h,o,l]),A=/\b(auto|car|fahrzeug|vehicle)/i.test(a.name),q=Z=>{const H=_c(Z,C);return A&&(H==="Zimmer"||H==="Room")?C==="en"?"Car":"Auto":H},y=C==="en"?"Group":"Gruppe",W=Z=>{const H=Z.replace("#","").match(/^([0-9a-f]{6})$/i);if(!H)return[240,240,240];const L=parseInt(H[1],16);return[L>>16&255,L>>8&255,L&255]},j=Z=>[Math.round(Z[0]*.1+255*(1-.1)),Math.round(Z[1]*.1+255*(1-.1)),Math.round(Z[2]*.1+255*(1-.1))],d=()=>{const Z=new Set;for(const H of b)for(const L of T)if(Jr(L.sourceField)){const g=String(f(H,L.sourceField)??"");g&&g!=="–"&&g.trim()&&Z.add(g)}return Array.from(Z)},u=async Z=>{if(Z.length===0)return new Map;try{const{data:H,error:L}=await _.functions.invoke("translate-list-content",{body:{texts:Z,sourceLanguage:"de",targetLanguage:"en"}});if(L)throw console.error("Translation error:",L),L;const g=new Map,r=(H==null?void 0:H.translations)||[];return Z.forEach((m,X)=>{g.set(m,r[X]||m)}),g}catch(H){console.error("AI translation failed:",H);const L=new Map;return Z.forEach(g=>L.set(g,g)),L}},I=async()=>{G(!0);try{let Z=new Map;if(C==="en"){const H=d();H.length>0&&(Y.info("Übersetze Inhalte mit KI..."),Z=await u(H))}c==="csv"?ge(Z):be(Z),Y.success("Export erfolgreich!"),n()}catch(Z){console.error("Export error:",Z);const H=Z instanceof Error?Z.message:String(Z);Y.error(`Export fehlgeschlagen: ${H}`)}finally{G(!1)}},E=(Z,H,L)=>{const g=String(f(Z,H.sourceField)??"");return C==="en"&&Jr(H.sourceField)&&L.get(g)||g},$=()=>{if(!i)return"";const Z=C==="en"?mi:Ts,H=He(i.startDate),L=He(i.endDate),g=fs(H,"dd.MM.yyyy",{locale:Z}),r=fs(L,"dd.MM.yyyy",{locale:Z});return`${g} - ${r}`},ge=Z=>{var we;const H="\uFEFF",L=[];if(x!=null&&x.companyName&&L.push(`"${x.companyName}"`),i&&(L.push(`"${i.name}"`),L.push(`"${$()}"`)),x!=null&&x.companyEmail||x!=null&&x.companyPhone){const De=[x.companyEmail,x.companyPhone].filter(Boolean).join(" | ");L.push(`"${De}"`)}L.push("");const g=T.map(De=>q(De.label)),r=o?[y,...g]:g,m=De=>{const _e=T.map(Ae=>E(De,Ae,Z));if(!o)return _e;const J=l.get(De.id);return[(J==null?void 0:J.name)||"",..._e]},X=[];if(o){const De=new Map;for(const _e of V){const J=((we=l.get(_e.id))==null?void 0:we.id)||"__none__";De.has(J)||De.set(J,[]),De.get(J).push(_e)}for(const _e of De.values())X.push(_e.map(m))}else X.push(V.map(m));const p=r.map(()=>""),ne=[r];
125X.forEach((De,_e)=>{_e>0&&ne.push(p),ne.push(...De)});const le=ne.map(De=>De.map(_e=>`"${String(_e??"").replace(/"/g,'""')}"`).join(",")).join(`
126`),K=[...L,le].join(`
127`),M=new Blob([H+K],{type:"text/csv;charset=utf-8;"}),ee=document.createElement("a");ee.href=URL.createObjectURL(M);const he=C==="en"?"_EN":"_DE";ee.download=`${a.name.replace(/\s+/g,"_")}${he}.csv`,ee.click()},be=Z=>{const H=new Oi({orientation:b.length>10||T.length>6?"landscape":"portrait",unit:"mm",format:"a4"});let L=15;if(x!=null&&x.companyName&&(H.setFontSize(18),H.setFont("helvetica","bold"),H.text(x.companyName,14,L),L+=8),x!=null&&x.companyEmail||x!=null&&x.companyPhone){H.setFontSize(9),H.setFont("helvetica","normal");const M=[x.companyEmail,x.companyPhone].filter(Boolean).join(" | ");H.text(M,14,L),L+=8}if(H.setDrawColor(200,200,200),H.line(14,L,H.internal.pageSize.width-14,L),L+=8,i){H.setFontSize(14),H.setFont("helvetica","bold"),H.text(i.name,14,L),L+=6,H.setFontSize(10),H.setFont("helvetica","normal");const M=C==="en"?"Date: ":"Datum: ";H.text(M+$(),14,L),L+=6}H.setFontSize(11),H.setFont("helvetica","bold"),H.text(a.name,14,L),L+=5,H.setFontSize(9),H.setFont("helvetica","normal");const g=C==="en"?`${b.length} Participants`:`${b.length} Teilnehmer`;H.text(g,14,L),L+=8;const r=T.map(M=>q(M.label)),m=o?[y,...r]:r,X=[],p=[],ne=V.map(M=>{const ee=T.map(we=>E(M,we,Z)),he=l.get(M.id);return X.push((he==null?void 0:he.color)||null),p.push((he==null?void 0:he.id)||null),o?[(he==null?void 0:he.name)||"",...ee]:ee});Ui(H,{head:[m],body:ne,startY:L,styles:{fontSize:9,cellPadding:3},headStyles:{fillColor:[59,130,246],textColor:255,fontStyle:"bold"},alternateRowStyles:o?{}:{fillColor:[245,247,250]},margin:{left:14,right:14},didParseCell:M=>{if(!o||M.section!=="body")return;const ee=X[M.row.index];ee&&(M.cell.styles.fillColor=j(W(ee)))},didDrawCell:M=>{if(!o||M.section!=="body"||M.column.index!==0)return;const ee=M.row.index,he=p[ee],we=ee+1<p.length?p[ee+1]:void 0;if(we!==void 0&&he!==we){const De=M.table.settings.margin.left,_e=H.internal.pageSize.width-M.table.settings.margin.right,J=M.cell.y+M.cell.height;H.setDrawColor(120,120,120),H.setLineWidth(.4),H.line(De,J,_e,J)}}});const le=H.getNumberOfPages();for(let M=1;M<=le;M++){H.setPage(M),H.setFontSize(8),H.setFont("helvetica","normal");const ee=new Date().toLocaleDateString(C==="en"?"en-US":"de-DE"),he=C==="en"?"Exported: ":"Exportiert: ";H.text(`${he}${ee} | ${C==="en"?"Page":"Seite"} ${M}/${le}`,14,H.internal.pageSize.height-10)}const K=C==="en"?"_EN":"_DE";H.save(`${a.name.replace(/\s+/g,"_")}${K}.pdf`)};return e.jsx(We,{open:s,onOpenChange:n,children:e.jsxs(Qe,{className:"sm:max-w-md",children:[e.jsx(Ye,{children:e.jsxs(Je,{className:"flex items-center gap-2",children:[e.jsx(lt,{className:"h-5 w-5"}),"Liste exportieren"]})}),e.jsxs("div",{className:"space-y-6 py-4",children:[e.jsxs("div",{className:"space-y-3",children:[e.jsx(U,{className:"text-sm font-medium",children:"Format"}),e.jsxs(fr,{value:c,onValueChange:Z=>k(Z),className:"grid grid-cols-2 gap-4",children:[e.jsxs("div",{className:"flex items-center space-x-2",children:[e.jsx(It,{value:"csv",id:"csv"}),e.jsxs(U,{htmlFor:"csv",className:"flex items-center gap-2 cursor-pointer",children:[e.jsx(Vi,{className:"h-4 w-4 text-muted-foreground"}),"CSV (Excel)"]})]}),e.jsxs("div",{className:"flex items-center space-x-2",children:[e.jsx(It,{value:"pdf",id:"pdf"}),e.jsxs(U,{htmlFor:"pdf",className:"flex items-center gap-2 cursor-pointer",children:[e.jsx($s,{className:"h-4 w-4 text-muted-foreground"}),"PDF"]})]})]})]}),e.jsxs("div",{className:"space-y-3",children:[e.jsxs(U,{className:"text-sm font-medium flex items-center gap-2",children:[e.jsx(Ki,{className:"h-4 w-4"}),"Sprache"]}),e.jsxs(Ie,{value:C,onValueChange:Z=>N(Z),children:[e.jsx(Oe,{children:e.jsx(Ve,{})}),e.jsxs(Ue,{children:[e.jsx(O,{value:"de",children:"🇩🇪 Deutsch"}),e.jsx(O,{value:"en",children:"🇬🇧 English (KI-Übersetzung)"})]})]}),e.jsx("p",{className:"text-xs text-muted-foreground",children:C==="en"?"Alle Freitext-Inhalte werden kontextbasiert mit KI übersetzt.":"All free-text content will be translated contextually using AI."})]}),e.jsx("div",{className:"bg-muted/50 rounded-lg p-3",children:e.jsxs("p",{className:"text-sm text-muted-foreground",children:[e.jsx("strong",{children:a.name}),e.jsx("br",{}),b.length," ",C==="en"?"participants":"Teilnehmer"," • ",T.length," ",C==="en"?"columns":"Spalten",i&&e.jsxs(e.Fragment,{children:[e.jsx("br",{}
127),i.name," (",$(),")"]})]})})]}),e.jsxs(gs,{children:[e.jsx(z,{variant:"outline",onClick:n,disabled:v,children:"Abbrechen"}),e.jsx(z,{onClick:I,disabled:v,className:"gap-2",children:v?e.jsxs(e.Fragment,{children:[e.jsx($e,{className:"h-4 w-4 animate-spin"}),"Exportiere..."]}):e.jsxs(e.Fragment,{children:[e.jsx(lt,{className:"h-4 w-4"}),"Exportieren"]})})]})]})})}function bc({listId:s,partnerIds:n}){const[a,b]=t.useState([]),[f,i]=t.useState({});if(t.useEffect(()=>{let h=!0;return(async()=>{if(n.length===0){b([]);return}const[{data:c},{data:k}]=await Promise.all([_.from("partner_list_acknowledgements").select("partner_id, acknowledged_at, content_hash").eq("list_id",s),_.from("partners").select("id, name").in("id",n)]);if(!h)return;const C={};(k||[]).forEach(N=>{C[N.id]=N.name}),i(C),b(c||[])})(),()=>{h=!1}},[s,n.join(",")]),n.length===0)return null;const x=new Map(a.map(h=>[h.partner_id,h]));return e.jsxs("div",{className:"flex flex-wrap items-center gap-1.5 px-4 py-2 text-xs",children:[e.jsx("span",{className:"text-muted-foreground",children:"Partner-Bestätigung:"}),n.map(h=>{const c=x.get(h),k=f[h]||"Partner";return c?e.jsxs(Xe,{variant:"outline",className:"gap-1 border-emerald-500/40 text-emerald-600 font-normal",children:[e.jsx(ra,{className:"h-3 w-3"})," ",k," · ",new Date(c.acknowledged_at).toLocaleDateString("de-DE")]},h):e.jsxs(Xe,{variant:"outline",className:"gap-1 text-muted-foreground font-normal",children:[e.jsx(Vs,{className:"h-3 w-3"})," ",k," · offen"]},h)})]})}const $n=[{id:"fullName",label:"Name",category:"Stammdaten"},{id:"firstName",label:"Vorname",category:"Stammdaten"},{id:"lastName",label:"Nachname",category:"Stammdaten"},{id:"email",label:"E-Mail",category:"Kontakt"},{id:"phone",label:"Telefon",category:"Kontakt"},{id:"dateOfBirth",label:"Geburtsdatum",category:"Stammdaten"},{id:"age",label:"Alter",category:"Stammdaten"},{id:"nationality",label:"Nationalität",category:"Stammdaten"},{id:"passportNumber",label:"Passnummer",category:"Dokumente"},{id:"dietaryRequirements",label:"Ernährungsform",category:"Präferenzen"},{id:"allergies",label:"Allergien",category:"Präferenzen"},{id:"foodDislikes",label:"No-Gos beim Essen",category:"Präferenzen"},{id:"preExistingConditions",label:"Vorerkrankungen",category:"Präferenzen"},{id:"emergencyContact",label:"Notfallkontakt",category:"Kontakt"},{id:"roomAssignment",label:"Zimmer",category:"Zimmerzuteilung"},{id:"bookingName",label:"Buchung",category:"Buchung"},{id:"billingStreet",label:"Straße",category:"Adresse"},{id:"billingCity",label:"Stadt",category:"Adresse"},{id:"billingPostalCode",label:"PLZ",category:"Adresse"},{id:"billingCountry",label:"Land",category:"Adresse"},{id:"fullAddress",label:"Vollständige Adresse",category:"Adresse"},{id:"arrivalFlightNumber",label:"Anreise Flugnummer",category:"An- und Abreise"},{id:"arrivalDate",label:"Anreise Datum",category:"An- und Abreise"},{id:"arrivalTime",label:"Ankunftszeit",category:"An- und Abreise"},{id:"arrivalRoute",label:"Anreise Route",category:"An- und Abreise"},{id:"departureFlightNumber",label:"Abreise Flugnummer",category:"An- und Abreise"},{id:"departureDate",label:"Abreise Datum",category:"An- und Abreise"},{id:"departureTime",label:"Abflugzeit",category:"An- und Abreise"},{id:"departureRoute",label:"Abreise Route",category:"An- und Abreise"}],Xr=[{id:"template_dietary",name:"Ernährungseinstellungen",description:"Liste mit Ernährungsform, Allergien und No-Gos aller Teilnehmer",icon:Zi,columns:["firstName","lastName","dietaryRequirements","allergies","foodDislikes"],enableRoomAssignment:!1},{id:"template_rooms",name:"Zimmerzuteilung",description:"Zimmerliste mit Nationalität, Alter und Ernährungsinfos",icon:pa,columns:["firstName","lastName","roomAssignment","nationality","age","dietaryRequirements","allergies","foodDislikes"],enableRoomAssignment:!0},{id:"template_flights",name:"An- und Abreise",description:"Fluginformationen mit automatischer Routenabfrage",icon:$t,columns:["firstName","lastName","arrivalFlightNumber","arrivalDate","arrivalTime","arrivalRoute","departureFlightNumber","departureDate","departureTime","departureRoute"],enableRoomAssignment:!1},{id:"template_medical",name:"Medizinische Informationen",description:"Wichtige Gesundheitsdaten und Notfallkontakte",icon:Hi,columns:["fullName","dateOfBirth","dietaryRequirements","preExistingConditions","allergies","foodDislikes","emergencyContact"],enableRoomAssignment:!1}],yc=(s,n)=>{for(const a of n)if(s[a])return s[a];for(const a of Object.keys(s)){const b=a.toLowerCase().replace(/[_\s-]/g,"");for(const f of n){const i=f.toLowerCase().replace(/[_\s-]/g,"");if(b.includes(i)||i.includes(b))return s[a]}}},en=s=>{if(!(s==null||s===""))return Array.isArray(s)?s.join(", "):typeof s=="object"?JSON.stringify(s):String(s)},Wt=(s,n,a)=>{for(const b of n){const f=b.label.toLowerCase().replace(/[_\s-]/g,"");for(const i of a){const x=i.toLowerCase().replace(/[_\s-]/g,"");if((f.includes(x)||x.includes(f))&&s[b.id])return en(s[b.id])}}return en(yc(s,a))},Ja=s=>{if(!s)return null;const n=String(s).trim(),a=n.match(/^(\d{1,2})\.(\d{1,2})\.(\d{4})/);if(a){const[,f,i,x]=a,h=new Date(Number(x),Number(i)-1,Number(f));return isNaN(h.getTime())?null:h}const b=new Date(n);return isNaN(b.getTime())?null:b},wc=(s,n)=>{const a=Ja(s);if(!a)return null;const b=n?Ja(n):new Date;if(!b)return null;let f=b.getFullYear()-a.getFullYear();const i=b.getMonth()-a.getMonth();return(i<0||i===0&&b.getDate()<a.getDate())&&f--,Number.isFinite(f)&&f>=0&&f<120?f:null};function kc({tripId:s,trip:n,groups:a,onGroupsChange:b,onUpdateParticipant:f}){const[i,x]=t.useState(""),[h,c]=t.useState([]),[k,C]=t.useState(!1),[N,v]=t.useState(null),[G,T]=t.useState(null),[o,l]=t.useState(!0),{bookings:V,participants:A,guides:q}=na(s),{tripQuestionnaire:y}=$a(s),{settings:W}=hn(),j=(y==null?void 0:y.fields)||[],d=t.useCallback(async()=>{try{const{data:g,error:r}=await _.from("custom_lists").select("*").eq("trip_id",s).order("created_at",{ascending:!0});if(r)throw r;const m=(g||[]).map(X=>({id:X.id,tripId:X.trip_id,name:X.name,description:X.description||void 0,columns:X.columns||[],enableRoomAssignment:X.enable_room_assignment,visibleToGuides:X.visible_to_guides??!1,visibleToPartnerIds:X.visible_to_partner_ids??[],createdAt:X.created_at}));c(m)}catch(g){console.error("Error fetching lists:",g)}finally{l(!1)}},[s]);t.useEffect(()=>{d()},[d]);const u=async g=>{try{const{error:r}=await _.from("custom_lists").insert({id:g.id,trip_id:g.tripId,name:g.name,description:g.description||null,columns:g.columns,enable_room_assignment:g.enableRoomAssignment,visible_to_guides:g.visibleToGuides??!1,visible_to_partner_ids:g.visibleToPartnerIds??[]});if(r)throw r;return!0}catch(r){return console.error("Error saving list:",r),!1}},I=async g=>{try{const{error:r}=await _.from("custom_lists").update({name:g.name,description:g.description||null,columns:g.columns,enable_room_assignment:g.enableRoomAssignment,visible_to_guides:g.visibleToGuides??!1,visible_to_partner_ids:g.visibleToPartnerIds??[]}).eq("id",g.id);if(r)throw r;return!0}catch(r){return console.error("Error updating list:",r),!1}},E=async g=>{try{const{error:r}=await _.from("custom_lists").delete().eq("id",g);if(r)throw r;return!0}catch(r){return console.error("Error deleting list:",r),!1}},$=t.useMemo(()=>{const g=A.map(m=>({id:m.id,bookingId:m.booking_id||"",firstName:m.first_name,lastName:m.last_name,email:m.email||"",phone:m.phone||"",dateOfBirth:m.date_of_birth||"",passportNumber:m.passport_number||"",questionnaireStatus:m.questionnaire_status,questionnaireProgress:m.questionnaire_progress||0,questionnaireResponses:m.questionnaire_responses||{},dietaryRequirements:m.dietary_requirements||"",allergies:m.allergies||"",foodDislikes:m.food_dislikes||"",emergencyContact:m.emergency_contact||"",preExistingConditions:m.pre_existing_conditions||"",roomAssignment:m.room_assignment||"",loyaltyPoints:m.loyalty_points||0,loyaltyLastActivity:m.loyalty_last_activity||"",referralCount:m.referral_count||0,totalNightsStayed:m.total_nights_stayed||0,staticQuestionnaireData:m.static_questionnaire_data||{},isGuide:!1,wildernessCertificateUrl:m.wilderness_certificate_url||void 0,billing_street:m.billing_street||null,billing_city:m.billing_city||null,billing_postal_code:m.billing_postal_code||null,billing_country:m.billing_country||null}));return[...q.map(m=>({id:m.id,bookingId:"",firstName:m.first_name,lastName:m.last_name,email:m.email||"",phone:m.phone||"",dateOfBirth:m.date_of_birth||"",passportNumber:m.passport_number||"",questionnaireStatus:m.questionnaire_status,questionnaireProgress:m.questionnaire_progress||0,questionnaireResponses:m.questionnaire_responses||{},dietaryRequirements:m.dietary_requirements||"",allergies:m.allergies||"",foodDislikes:m.food_dislikes||"",emergencyContact:m.emergency_contact||"",preExistingConditions:m.pre_existing_conditions||"",roomAssignment:m.room_assignment||"",loyaltyPoints:m.loyalty_points||0,loyaltyLastActivity:m.loyalty_last_activity||"",referralCount:m.referral_count||0,totalNightsStayed:m.total_nights_stayed||0,staticQuestionnaireData:m.static_questionnaire_data||{},isGuide:!0,wildernessCertificateUrl:m.wilderness_certificate_url||void 0,billing_street:m.billing_street||null,billing_city:m.billing_city||null,billing_postal_code:m.billing_postal_code||null,billing_country:m.billing_country||null})),...g]},[A,q]),ge=async g=>{const r=Xr.find(le=>le.id===g);if(!r||h.find(le=>le.name===r.name))return;const X=r.columns.map((le,K)=>{const M=$n.find(ee=>ee.id===le);return{id:`col_${Date.now()}_${K}`,label:M.label,sourceField:M.id,visible:!0}}),p={id:crypto.randomUUID(),tripId:s,name:r.name,description:r.description,columns:X,enableRoomAssignment:r.enableRoomAssignment,createdAt:new Date().toISOString()};await u(p)&&c(le=>[...le,p])},be=h.filter(g=>g.name.toLowerCase().includes(i.toLowerCase())),Z=async g=>{await I(g)&&c(h.map(m=>m.id===g.id?g:m)),v(null)},H=async g=>
127{await E(g)&&c(h.filter(m=>m.id!==g))},L=async g=>{await u(g)&&(c([...h,g]),C(!1))};return e.jsxs("div",{className:"space-y-6",children:[e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsxs("div",{className:"relative max-w-md flex-1",children:[e.jsx(wt,{className:"absolute left-3 top-1/2 h-4 w-4 -translate-y-1/2 text-muted-foreground"}),e.jsx(te,{type:"text",placeholder:"Liste suchen...",value:i,onChange:g=>x(g.target.value),className:"pl-10 rounded-xl bg-muted/50 border-0"})]}),e.jsxs(We,{open:k,onOpenChange:C,children:[e.jsx(ua,{asChild:!0,children:e.jsxs(z,{className:"gap-2 rounded-xl",children:[e.jsx(Es,{className:"h-4 w-4"}),"Neue Liste"]})}),e.jsx(Sc,{tripId:s,questionnaireFields:j,onSave:L,onClose:()=>C(!1)})]})]}),!o&&h.length===0&&e.jsxs("div",{className:"space-y-4",children:[e.jsx("h3",{className:"text-sm font-medium text-muted-foreground",children:"Schnellstart mit Vorlagen"}),e.jsx("div",{className:"grid grid-cols-1 md:grid-cols-3 gap-4",children:Xr.map(g=>{const r=g.icon;return e.jsx("div",{className:"glass-card p-5 cursor-pointer hover:bg-muted/30 transition-colors group",onClick:()=>ge(g.id),children:e.jsxs("div",{className:"flex items-start gap-4",children:[e.jsx("div",{className:"flex h-12 w-12 items-center justify-center rounded-xl bg-primary/10 group-hover:bg-primary/20 transition-colors",children:e.jsx(r,{className:"h-5 w-5 text-primary"})}),e.jsxs("div",{className:"flex-1",children:[e.jsx("h4",{className:"font-semibold text-foreground",children:g.name}),e.jsx("p",{className:"text-sm text-muted-foreground mt-1",children:g.description}),e.jsxs("p",{className:"text-xs text-muted-foreground mt-2",children:[g.columns.length," Spalten"]})]})]})},g.id)})})]}),o&&e.jsx("div",{className:"flex items-center justify-center py-12",children:e.jsx($e,{className:"h-6 w-6 animate-spin text-muted-foreground"})}),e.jsx("div",{className:"space-y-4",children:be.map(g=>{var r;return e.jsxs("div",{className:"space-y-0",children:[e.jsx(Cc,{list:g,participants:$,groups:a,bookings:V,questionnaireFields:j,isExpanded:G===g.id,onToggle:()=>T(G===g.id?null:g.id),onUpdate:Z,onEdit:()=>v(g),onDelete:()=>H(g.id),onGroupsChange:b,tripId:s,trip:n,companySettings:W,onUpdateParticipant:f}),(((r=g.visibleToPartnerIds)==null?void 0:r.length)??0)>0&&e.jsx(bc,{listId:g.id,partnerIds:g.visibleToPartnerIds??[]})]},g.id)})}),be.length===0&&h.length>0&&e.jsxs("div",{className:"glass-card p-12 text-center",children:[e.jsx(wt,{className:"mx-auto h-12 w-12 text-muted-foreground"}),e.jsx("h3",{className:"mt-4 text-lg font-medium text-foreground",children:"Keine Listen gefunden"}),e.jsx("p",{className:"mt-1 text-muted-foreground",children:"Keine Listen entsprechen Ihrer Suche."})]}),N&&e.jsx(We,{open:!!N,onOpenChange:g=>!g&&v(null),children:e.jsx(fc,{list:N,onSave:Z,onClose:()=>v(null)})})]})}function Cc({list:s,participants:n,groups:a,bookings:b,questionnaireFields:f,isExpanded:i,onToggle:x,onUpdate:h,onEdit:c,onDelete:k,onGroupsChange:C,tripId:N,trip:v,companySettings:G,onUpdateParticipant:T}){const[o,l]=t.useState({}),[V,A]=t.useState(!1),[q,y]=t.useState([]),[W,j]=t.useState(!1);t.useEffect(()=>{if(!s.enableRoomAssignment||!i)return;(async()=>{try{const{data:ce,error:oe}=await _.from("custom_list_groups").select("id, name, color").eq("list_id",s.id);if(oe)throw oe;if(!ce||ce.length===0){if(a.length>0){const Pe=[];for(const Fe of a){const{data:cs,error:vs}=await _.from("custom_list_groups").insert({list_id:s.id,name:Fe.name,color:Fe.color}).select("id").single();if(vs||!cs)continue;const Me=Fe.participantIds.map(se=>({group_id:cs.id,participant_id:se}));Me.length>0&&await _.from("custom_list_group_members").insert(Me),Pe.push({id:cs.id,tripId:N,name:Fe.name,color:Fe.color,participantIds:Fe.participantIds})}y(Pe)}else y([]);j(!0);return}const me=ce.map(Pe=>Pe.id),{data:Ee,error:ze}=await _.from("custom_list_group_members").select("group_id, participant_id").in("group_id",me);if(ze)throw ze;const ns=ce.map(Pe=>({id:Pe.id,tripId:N,name:Pe.name,color:Pe.color,participantIds:(Ee||[]).filter(Fe=>Fe.group_id===Pe.id).map(Fe=>Fe.participant_id)}));y(ns),j(!0)}catch(ce){console.error("Error loading list groups:",ce)}})()},[s.id,s.enableRoomAssignment,i,N]),t.useEffect(()=>{if(!s.enableRoomAssignment||!i)return;(async()=>{try{const{data:ce,error:oe}=await _.from("custom_list_assignments").select("participant_id, assignment_value").eq("list_id",s.id);if(oe)throw oe;const me={};
127(ce||[]).forEach(Ee=>{me[Ee.participant_id]=Ee.assignment_value}),l(me),A(!0)}catch(ce){console.error("Error loading list assignments:",ce)}})()},[s.id,s.enableRoomAssignment,i]);const[d,u]=t.useState({}),[I,E]=t.useState(!1),[$,ge]=t.useState(!1),be=t.useRef(!1),[Z,H]=t.useState(!1),[L,g]=t.useState(null),[r,m]=t.useState([]),[X,p]=t.useState(""),[ne,le]=t.useState(!1),[K,M]=t.useState(null),[ee,he]=t.useState(!1),we=["#8B5CF6","#EC4899","#F59E0B","#10B981","#3B82F6","#EF4444","#14B8A6","#F97316"],De=s.enableRoomAssignment?q:a,_e=R=>R?R.replace(/\s+/g,"").toUpperCase().replace(/^([A-Z0-9]{2})0+(\d+)$/,"$1$2"):"",J=R=>(R==null?void 0:R.split("T")[0])||"",Ae=t.useMemo(()=>{const R=new Map;for(const ce of n){const me=(ce.questionnaireResponses||{})._travel_form||{},Ee=(ze,ns,Pe)=>{const Fe=_e(ze);if(!Fe)return;const cs=J(ns),vs=`${Fe}_${cs}`,Me=R.get(vs);if(Me){Me.participantTargets.push({participantId:ce.id,type:Pe});return}R.set(vs,{requestKey:vs,flightNumber:Fe,date:cs,participantTargets:[{participantId:ce.id,type:Pe}]})};Ee(me.arrival_flight_number,me.arrival_date,"arrival"),Ee(me.departure_flight_number,me.departure_date,"departure")}return Array.from(R.values())},[n]),qe=t.useMemo(()=>Ae.map(R=>R.requestKey).sort().join("|"),[Ae]);t.useEffect(()=>{u({}),ge(!1),E(!1),be.current=!1},[qe,s.id]);const Be=t.useMemo(()=>n.filter(R=>!De.some(oe=>oe.participantIds.includes(R.id))),[n,De]),Ke=R=>{g(R),m([R]),H(!0)},Ce=async()=>{if(r.length<2)return;const R=we[De.length%we.length],ce=r.map(me=>{const Ee=n.find(ze=>ze.id===me);return Ee?Ee.lastName:""}),oe=X||`${ce[0]} & ${ce.length>2?"Gruppe":ce[1]}`;try{const{data:me,error:Ee}=await _.from("custom_list_groups").insert({list_id:s.id,name:oe,color:R}).select("id").single();if(Ee)throw Ee;const ze=r.map(cs=>({group_id:me.id,participant_id:cs})),{error:ns}=await _.from("custom_list_group_members").insert(ze);if(ns)throw ns;const Pe={id:me.id,tripId:N,name:oe,color:R,participantIds:r};y(cs=>[...cs,Pe]);const Fe=o[r[0]]||"";if(Fe){const cs={...o};r.forEach(vs=>{cs[vs]=Fe}),l(cs)}}catch(me){console.error("Error creating list group:",me)}H(!1),g(null),m([]),p("")},xe=t.useMemo(()=>{const R=ce=>De.find(oe=>oe.participantIds.includes(ce));return[...n].sort((ce,oe)=>{const me=R(ce.id),Ee=R(oe.id),ze=ce.isGuide&&!me,ns=oe.isGuide&&!Ee;if(ze&&!ns)return-1;if(!ze&&ns)return 1;if(ze&&ns)return`${ce.lastName} ${ce.firstName}`.localeCompare(`${oe.lastName} ${oe.firstName}`);if(me&&Ee)return me.id!==Ee.id?me.name.localeCompare(Ee.name):`${ce.lastName} ${ce.firstName}`.localeCompare(`${oe.lastName} ${oe.firstName}`);if(me&&!Ee)return-1;if(!me&&Ee)return 1;const Pe=o[ce.id]||"",Fe=o[oe.id]||"";return Pe&&!Fe?-1:!Pe&&Fe?1:Pe&&Fe&&Pe!==Fe?Pe.localeCompare(Fe):`${ce.lastName} ${ce.firstName}`.localeCompare(`${oe.lastName} ${oe.firstName}`)})},[n,De,o]),ms=s.columns.filter(R=>R.visible),us=ms.some(R=>["arrivalTime","arrivalRoute","departureTime","departureRoute"].includes(R.sourceField)),Q=t.useCallback(async()=>{if(!us||$||be.current)return;if(Ae.length===0){ge(!0);return}be.current=!0,E(!0);const R={};try{for(let ce=0;ce<Ae.length;ce++){const oe=Ae[ce];ce>0&&await new Promise(ze=>setTimeout(ze,1500));const{data:me,error:Ee}=await _.functions.invoke("get-flight-info",{body:{flightNumber:oe.flightNumber,date:oe.date}});if(Ee||!me||me.error){const ze=(Ee==null?void 0:Ee.message)||(me==null?void 0:me.error)||"Unknown flight lookup error";if(console.warn(`Flight lookup skipped for ${oe.flightNumber}: ${ze}`),ze.includes("429")||ze.toLowerCase().includes("rate limit"))break;continue}oe.participantTargets.forEach(({participantId:ze,type:ns})=>{R[`${ze}_${ns}`]=me})}u(R),ge(!0)}catch(ce){console.error("Error fetching flight data:",ce),ge(!0)}finally{be.current=!1,E(!1)}},[$,Ae,us]);t.useEffect(()=>{!i||!us||$||Q()},[i,us,Q,$]);const ue=R=>De.find(ce=>ce.participantIds.includes(R)),de=(R,ce)=>{var ze,ns;const oe=R.questionnaireResponses||{},me=d[`${R.id}_arrival`],Ee=d[`${R.id}_departure`];switch(ce){case"fullName":return`${R.firstName} ${R.lastName}`;case"firstName":return R.firstName;case"lastName":return R.lastName;case"email":return R.email||"–";case"phone":return R.phone||"–";case"dateOfBirth":return R.dateOfBirth&&((ze=Ja(R.dateOfBirth))==null?void 0:ze.toLocaleDateString("de-DE"))||"–";case"age":{const Pe=R.dateOfBirth?wc(R.dateOfBirth,v==null?void 0:v.startDate):null;return Pe!==null?Pe.toString():"–"}case"nationality":{const Pe=R.staticQuestionnaireData||{},Fe=Pe.nationality||Pe.Nationalität||Pe.nationalität;return Fe||Wt(oe,f,["nationalität","nationality","staatsangehörigkeit"])||"–"}case"passportNumber":return R.passportNumber||"–";case"dietaryRequirements":return R.dietaryRequirements||Wt(oe,f,["ernährung","ernährungsform","dietary","diet"])||"–";case"allergies":return R.allergies||Wt(oe,f,["allergien","allergies","allergie"])||"–";case"foodDislikes":return R.foodDislikes||Wt(oe,f,["no-gos","no gos","food dislikes","no-gos beim essen"])||"–";case"emergencyContact":return R.emergencyContact||Wt(oe,f,["notfallkontakt","emergency contact","notfall"])||"–";case"preExistingConditions":return R.preExistingConditions||Wt(oe,f,["vorerkrankungen","pre-existing conditions","erkrankungen"])||"–";case"roomAssignment":return o[R.id]||"–";case"bookingName":return((ns=b.find(Pe=>Pe.id===R.bookingId))==null?void 0:ns.customer_name)||"–";case"billingStreet":return R.billing_street||"–";case"billingCity":return R.billing_city||"–";case"billingPostalCode":return R.billing_postal_code||"–";case"billingCountry":return R.billing_country||"–";case"fullAddress":{const Pe=[R.billing_street,[R.billing_postal_code,R.billing_city].filter(
127Boolean).join(" "),R.billing_country].filter(Boolean);return Pe.length>0?Pe.join(", "):"–"}case"arrivalFlightNumber":return(oe._travel_form||{}).arrival_flight_number||"–";case"arrivalDate":{const Fe=(oe._travel_form||{}).arrival_date;return Fe?He(Fe).toLocaleDateString("de-DE"):"–"}case"arrivalTime":return me!=null&&me.arrivalTime?new Date(me.arrivalTime).toLocaleTimeString("de-DE",{hour:"2-digit",minute:"2-digit",timeZone:me.arrivalTimezone||void 0}):I?"...":"–";case"arrivalRoute":return me?`${me.departureCity} → ${me.arrivalCity}`:I?"...":"–";case"departureFlightNumber":return(oe._travel_form||{}).departure_flight_number||"–";case"departureDate":{const Fe=(oe._travel_form||{}).departure_date;return Fe?He(Fe).toLocaleDateString("de-DE"):"–"}case"departureTime":return Ee!=null&&Ee.departureTime?new Date(Ee.departureTime).toLocaleTimeString("de-DE",{hour:"2-digit",minute:"2-digit",timeZone:Ee.departureTimezone||void 0}):I?"...":"–";case"departureRoute":return Ee?`${Ee.departureCity} → ${Ee.arrivalCity}`:I?"...":"–";default:{if(ce.startsWith("questionnaire_")){const Pe=ce.replace("questionnaire_",""),Fe=oe[Pe];return Fe==null||Fe===""?"–":Array.isArray(Fe)?Fe.join(", "):typeof Fe=="object"?JSON.stringify(Fe):String(Fe)}return"–"}}},S=async(R,ce)=>{const oe=ue(R),me=oe&&s.enableRoomAssignment?oe.participantIds:[R],Ee={...o};me.forEach(ze=>{Ee[ze]=ce}),l(Ee);for(const ze of me)try{const{error:ns}=await _.from("custom_list_assignments").upsert({list_id:s.id,participant_id:ze,assignment_value:ce,updated_at:new Date().toISOString()},{onConflict:"list_id,participant_id"});ns&&console.error("Error saving assignment:",ns)}catch(ns){console.error("Error saving assignment:",ns)}},P=R=>{M(R),le(!0)},ie=async()=>{if(!K)return;const R=ue(K);if(R){try{await _.from("custom_list_group_members").delete().eq("group_id",R.id).eq("participant_id",K);const ce=R.participantIds.filter(oe=>oe!==K);ce.length<2?(await _.from("custom_list_group_members").delete().eq("group_id",R.id),await _.from("custom_list_groups").delete().eq("id",R.id),y(oe=>oe.filter(me=>me.id!==R.id))):y(oe=>oe.map(me=>me.id===R.id?{...me,participantIds:ce}:me))}catch(ce){console.error("Error unlinking participant:",ce)}le(!1),M(null)}},Se=(R,ce)=>de(R,ce);return e.jsxs("div",{className:"glass-card overflow-hidden",children:[e.jsxs("div",{className:"flex cursor-pointer items-center justify-between p-5 transition-colors hover:bg-muted/20",onClick:x,children:[e.jsxs("div",{className:"flex items-center gap-4",children:[e.jsx("div",{className:"flex h-12 w-12 items-center justify-center rounded-xl bg-primary/10",children:s.enableRoomAssignment?e.jsx(pa,{className:"h-5 w-5 text-primary"}):e.jsx(En,{className:"h-5 w-5 text-primary"})}),e.jsxs("div",{children:[e.jsx("h3",{className:"font-semibold text-foreground",children:s.name}),e.jsxs("p",{className:"text-sm text-muted-foreground",children:[n.length," Teilnehmer • ",ms.length," Spalten",s.enableRoomAssignment&&" • Zimmerzuteilung aktiv"]})]})]}),e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(z,{variant:"ghost",size:"icon",className:"rounded-lg",onClick:R=>{R.stopPropagation(),c()},children:e.jsx(wa,{className:"h-4 w-4"})}),e.jsx(z,{variant:"ghost",size:"icon",className:"rounded-lg",onClick:R=>{R.stopPropagation(),he(!0)},children:e.jsx(lt,{className:"h-4 w-4"})}),e.jsx(z,{variant:"ghost",size:"icon",className:"rounded-lg",onClick:R=>{R.stopPropagation(),k()},children:e.jsx(bs,{className:"h-4 w-4 text-destructive"})}),e.jsx("button",{className:"rounded-lg p-2 transition-colors hover:bg-muted",children:i?e.jsx(vn,{className:"h-5 w-5 text-muted-foreground"}):e.jsx(Us,{className:"h-5 w-5 text-muted-foreground"})})]})]}),i&&e.jsx("div",{className:"border-t border-border bg-muted/10 animate-fade-in",children:e.jsx("div",{className:"overflow-x-auto",children:e.jsxs("table",{className:"w-full",children:[e.jsx("thead",{children:e.jsx("tr",{className:"border-b border-border bg-muted/30",children:ms.map(R=>e.jsx("th",{className:"px-5 py-3 text-left text-sm font-medium text-muted-foreground",children:R.label},R.id))})}),e.jsx("tbody",{children:xe.map((R,ce)=>{const oe=ue(R.id),me=ce>0?xe[ce-1]:null,Ee=me?ue(me.id):null,ze=R.isGuide&&!oe,ns=me?me.isGuide&&!Ee:null,Pe=ze&&(ce===0||!ns),Fe=!ze&&s.enableRoomAssignment&&(oe&&(!Ee||Ee.id!==oe.id||ns)||!oe&&(Ee||ns)),cs=Pe||Fe;return e.jsxs(e.Fragment,{children:[cs&&e.jsx("tr",{className:"bg-muted/40",children:e.jsx("td",{colSpan:ms.length,className:"px-5 py-2 text-xs font-medium text-muted-foreground uppercase tracking-wider",children:ze?e.jsxs("span",{className:"flex items-center gap-2",children:[e.jsx("div",{className:"w-2 h-2 rounded-full bg-primary"}),"Guides"]}):oe?e.jsxs("span",{className:"flex items-center gap-2",children:[e.jsx("div",{className:"w-2 h-2 rounded-full",style:{backgroundColor:oe.color}}),oe.name]}):e.jsxs("span",{className:"flex items-center gap-2",children:[e.jsx(Ns,{className:"h-3 w-3"}),"Einzelpersonen (ohne Verknüpfung)"]})})},`section-${R.id}`),e.jsx("tr",{className:"border-b border-border/50 hover:bg-muted/20",style:ze?{borderLeftWidth:"3px",borderLeftColor:"hsl(var(--primary))"}:oe?{borderLeftWidth:"3px",borderLeftColor:oe.color}:void 0,children:ms.map(vs=>e.jsx("td",{className:"px-5 py-3 text-sm text-foreground",children:vs.sourceField==="roomAssignment"&&s.enableRoomAssignment?e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(te,{value:o[R.id]||"",onChange:Me=>S(R.id,Me.target.value),placeholder:"Zimmer...",className:"h-8 w-28 rounded-lg bg-muted/50 border-0",onClick:Me=>Me.stopPropagation()}),oe?e.jsxs("div",{className:"flex items-center gap-1",children:[e.jsx(it,{children:e.jsxs(Js,{children:[e.jsx(Xs,{asChild:!0,children:e.jsxs("div",{className:"flex items-center gap-1 px-2 py-0.5 rounded-full text-xs cursor-default",style:{backgroundColor:`${oe.color}20`,color:oe.color},children:[e.jsx(Ns,{className:"h-3 w-3"}),e.jsx("span",{children:oe.participantIds.length})]})}),e.jsx(et,{children:e.jsxs("p",{children:["Zimmer wird automatisch für ",oe.name," gesetzt"]})})]})}),s.enableRoomAssignment&&e.jsx(it,{children:e.jsxs(Js,{children:[e.jsx(Xs,{asChild:!0,children:e.jsx(z,{variant:"ghost",size:"sm",className:"h-6 w-6 p-0 text-muted-foreground hover:text-destructive hover:bg-destructive/10",onClick:Me=>{Me.stopPropagation(),P(R.id)},children:e.jsx(kn,{className:"h-3 w-3"})})}),e.jsx(et,{children:e.jsx("p",{children:"Verknüpfung auflösen"})})]})})]}):ze?s.enableRoomAssignment?e.jsxs(z,{variant:"ghost",size:"sm",className:"h-6 px-2 text-xs text-primary hover:bg-primary/10",onClick:Me=>{Me.stopPropagation(),Ke(R.id)},children:[e.jsx(Xt,{className:"h-3 w-3 mr-1"}),"Guide"]}):e.jsx("span",{className:"text-xs text-primary font-medium",children:"Guide"}):s.enableRoomAssignment?e.jsxs(z,{variant:"ghost",size:"sm",className:"h-6 px-2 text-xs text-muted-foreground hover:text-foreground hover:bg-muted",onClick:Me=>{Me.stopPropagation(),Ke(R.id)},children:[e.jsx(Xt,{className:"h-3 w-3 mr-1"}),"Verknüpfen"]}):e.jsx("span",{className:"text-xs text-muted-foreground",children:"Einzelperson"})]}):vs.sourceField==="fullName"?e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx("span",{children:de(R,vs.sourceField)}),ze&&e.jsx("div",{className:"flex items-center gap-1 px-2 py-0.5 rounded-full text-xs bg-primary/10 text-primary",children:e.jsx("span",{children:"Guide"})}),oe&&!ze&&e.jsxs("div",{className:"flex items-center gap-1 px-2 py-0.5 rounded-full text-xs",style:{backgroundColor:`${oe.color}20`,color:oe.color},children:[e.jsx(Ns,{className:"h-3 w-3"}),e.jsx("span",{children:oe.name})]})]}):de(R,vs.sourceField)},vs.id))},R.id)]})})})]})})}),e.jsx(We,{open:Z,onOpenChange:R=>{R||(H(!1),g(null),m([]),p(""))},children:e.jsxs(Qe,{className:"sm:max-w-md",children:[e.jsx(Ye,{children:e.jsxs(Je,{className:"flex items-center gap-2",children:[e.jsx(Xt,{className:"h-5 w-5 text-primary"}),"Teilnehmer verknüpfen"]})}),e.jsxs("div",{className:"space-y-4 py-4",children:[e.jsx("p",{className:"text-sm text-muted-foreground",children:"Wählen Sie Teilnehmer aus, die sich ein Zimmer teilen sollen. Die Verknüpfung gilt für diese Reise."}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(U,{children:"Gruppenname (optional)"}),e.jsx(te,{value:X,onChange:R=>p(R.target.value),placeholder:"z.B. Paar Müller, Freunde Schmidt",className:"rounded-lg"})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(U,{children:"Teilnehmer auswählen"}),e.jsx(za,{className:"h-[200px] rounded-lg border border-border p-2",children:e.jsx("div",{className:"space-y-1",children:Be.map(R=>{const ce=r.includes(R.id),oe=R.id===L,me=R.isGuide;return e.jsxs("div",{className:`flex items-center gap-3 p-2 rounded-lg cursor-pointer transition-colors ${ce?"bg-primary/10 border border-primary/30":"hover:bg-muted/50"}`,onClick:()=>{oe||m(ce?Ee=>Ee.filter(ze=>ze!==R.id):Ee=>[...Ee,R.id])},children:[e.jsx(Zs,{checked:ce,disabled:oe}),e.jsxs("div",{className:"flex-1",children:[e.jsxs("p",{className:"text-sm font-medium",children:[R.firstName," ",R.lastName,oe&&e.jsx("span",{className:"text-xs text-muted-foreground ml-2",children:"(ausgewählt)"})]}),me&&e.jsx("span",{className:"text-xs text-primary",children:"Guide"})]})]},R.id)})})})]})]}),e.jsxs(gs,{children:[e.jsx(z,{variant:"outline",onClick:()=>H(!1),children:"Abbrechen"}),e.jsxs(z,{onClick:Ce,disabled:r.length<2,className:"gap-2",children:[e.jsx(Ns,{className:"h-4 w-4"}),r.length," Personen verknüpfen"]})]})]})}),e.jsx(mt,{open:ne,onOpenChange:le,children:e.jsxs(ut,{children:[e.jsxs(ht,{children:[e.jsx(xt,{children:"Verknüpfung auflösen?"}),e.jsx(pt,{children:"Möchten Sie diese Person wirklich aus der Gruppe entfernen? Sie kann danach einem anderen Zimmer zugewiesen werden."})]}),e.jsxs(gt,{children:[e.jsx(ft,{onClick:()=>M(null),children:"Abbrechen"}),e.jsx(jt,{onClick:ie,children:"Auflösen"})]})]})}),e.jsx(vc,{open:ee,onClose:()=>he(!1),list:s,participants:xe,getParticipantValue:Se,trip:v,companySettings:G,groups:De})]})}function Sc({tripId:s,questionnaireFields:n=[],onSave:a,onClose:b}){const[f,i]=t.useState(""),[x,h]=t.useState(""),[c,k]=t.useState(!1),[C,N]=t.useState(["fullName"]),[v,G]=t.useState(!1),[T,o]=t.useState([]),[l,V]=t.useState([]);t.useEffect(()=>{(async()=>{const{data:d}=await _.from("partner_access").select("partner_id, partners(id, name)").eq("is_active",!0),u=(d??[]).map(I=>I.partners?{id:I.partners.id,name:I.partners.name}
127:null).filter(Boolean);u.sort((I,E)=>I.name.localeCompare(E.name)),V(u)})()},[]);const A=d=>{o(u=>u.includes(d)?u.filter(I=>I!==d):[...u,d])},q=t.useMemo(()=>{const d=n.filter(u=>u.type!=="file").map(u=>({id:`questionnaire_${u.id}`,label:u.label,category:"Fragebogen"}));return[...$n,...d]},[n]),y=d=>{C.includes(d)?N(C.filter(u=>u!==d)):N([...C,d])},W=()=>{const d=C.map((I,E)=>{const $=q.find(ge=>ge.id===I);return{id:`col_${Date.now()}_${E}`,label:($==null?void 0:$.label)||I,sourceField:I,visible:!0}});c&&!C.includes("roomAssignment")&&d.push({id:`col_${Date.now()}_room`,label:"Zimmer",sourceField:"roomAssignment",visible:!0});const u={id:crypto.randomUUID(),tripId:s,name:f,description:x,columns:d,enableRoomAssignment:c,visibleToGuides:v,visibleToPartnerIds:T,createdAt:new Date().toISOString()};a(u)},j=q.reduce((d,u)=>(d[u.category]||(d[u.category]=[]),d[u.category].push(u),d),{});return e.jsxs(Qe,{className:"glass-modal sm:max-w-lg max-h-[85vh] overflow-y-auto",children:[e.jsx(Ye,{children:e.jsx(Je,{children:"Neue Liste erstellen"})}),e.jsxs("div",{className:"space-y-6 mt-4",children:[e.jsxs("div",{className:"space-y-2",children:[e.jsx(U,{children:"Name der Liste"}),e.jsx(te,{value:f,onChange:d=>i(d.target.value),placeholder:"z.B. Küchenliste, Zimmerliste Hotel XY",className:"rounded-xl"})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(U,{children:"Beschreibung (optional)"}),e.jsx(te,{value:x,onChange:d=>h(d.target.value),placeholder:"Kurze Beschreibung",className:"rounded-xl"})]}),e.jsxs("div",{className:"flex items-center justify-between rounded-xl bg-muted/30 p-4",children:[e.jsxs("div",{className:"flex items-center gap-3",children:[e.jsx(pa,{className:"h-5 w-5 text-primary"}),e.jsxs("div",{children:[e.jsx("p",{className:"font-medium text-foreground",children:"Zimmerzuteilung aktivieren"}),e.jsx("p",{className:"text-sm text-muted-foreground",children:"Ermöglicht manuelle Zimmerzuweisung"})]})]}),e.jsx(ys,{checked:c,onCheckedChange:k})]}),e.jsxs("div",{className:"flex items-center justify-between rounded-xl bg-muted/30 p-4",children:[e.jsxs("div",{className:"flex items-center gap-3",children:[e.jsx(st,{className:"h-5 w-5 text-primary"}),e.jsxs("div",{children:[e.jsx("p",{className:"font-medium text-foreground",children:"Im Guide-Portal anzeigen"}),e.jsx("p",{className:"text-sm text-muted-foreground",children:"Diese Liste erscheint in der Reise-Detailansicht deiner Guides"})]})]}),e.jsx(ys,{checked:v,onCheckedChange:G})]}),l.length>0&&e.jsxs("div",{className:"rounded-xl bg-muted/30 p-4 space-y-3",children:[e.jsxs("div",{className:"flex items-center gap-3",children:[e.jsx(bt,{className:"h-5 w-5 text-primary"}),e.jsxs("div",{children:[e.jsx("p",{className:"font-medium text-foreground",children:"Im Partner-Portal anzeigen"}),e.jsx("p",{className:"text-sm text-muted-foreground",children:"Wähle, welche Partner diese Liste sehen dürfen."})]})]}),e.jsx("div",{className:"grid grid-cols-1 sm:grid-cols-2 gap-2",children:l.map(d=>{const u=T.includes(d.id);return e.jsxs("div",{className:`flex items-center gap-2 rounded-lg p-2 cursor-pointer transition-colors ${u?"bg-primary/10 border border-primary/30":"bg-background/50 hover:bg-muted/50"}`,onClick:()=>A(d.id),children:[e.jsx(Zs,{checked:u}),e.jsx("span",{className:"text-sm",children:d.name})]},d.id)})})]}),e.jsxs("div",{className:"space-y-3",children:[e.jsx(U,{children:"Spalten auswählen"}),Object.entries(j).map(([d,u])=>e.jsxs("div",{className:"space-y-2",children:[e.jsx("p",{className:"text-xs font-medium text-muted-foreground uppercase tracking-wider",children:d}),e.jsx("div",{className:"grid grid-cols-2 gap-2",children:u.map(I=>e.jsxs("div",{className:`flex items-center gap-2 rounded-lg p-2 cursor-pointer transition-colors ${C.includes(I.id)?"bg-primary/10 border border-primary/30":"bg-muted/30 hover:bg-muted/50"}`,onClick:()=>y(I.id),children:[e.jsx(Zs,{checked:C.includes(I.id)}),e.jsx("span",{className:"text-sm",children:I.label})]},I.id))})]},d))]}),e.jsxs("div",{className:"flex justify-end gap-3 pt-4 border-t border-border",children:[e.jsx(z,{variant:"outline",className:"rounded-xl",onClick:b,children:"Abbrechen"}),e.jsx(z,{className:"rounded-xl",onClick:W,disabled:!f||C.length===0,children:"Liste erstellen"})]})]})]})}const Dc={EZ:"Single (SGL)",DZ:"Double (DBL)"},Ec=s=>Dc[s==null?void 0:s.trim()]??s,Ac=s=>(s||"").replace(/\(Guide\/Team\)/g,"(guide/staff)"),Pc=s=>s==="manuell"?"manual":s,ha=s=>{const n=(s||"").trim().match(/^(\d+)/);
127return n?n[1]:null},sn=(s,n)=>{const a=(s||"").trim(),b=a.match(/^(\d+)([a-zA-Z][a-zA-Z0-9]*)$/);if(!b)return n?Pc(a):a;const[,f,i]=b,x=i.toLowerCase();let h=null;return/^(a|b\d*)$/.test(x)?h=n?"before":"vorher":/^p\d*e?$/.test(x)?h=n?"after":"nachher":/^x$/.test(x)&&(h=n?"to clarify":"zu klären"),h?`${f} (${h})`:f},Fc=(s,n)=>{const a=ha(s),b=ha(n);if(a&&!b)return-1;if(!a&&b)return 1;if(a&&b){const f=parseInt(a,10),i=parseInt(b,10);if(f!==i)return f-i}return(s??"").localeCompare(n??"")},ca=s=>[...s].sort((n,a)=>n.check_in.localeCompare(a.check_in)||Fc(n.room_label,a.room_label)),Qt=s=>[s.source,s.room_label,s.check_in,s.check_out].join("|");function Va(s,n,a){var c;const b=((a==null?void 0:a.override)??"").trim();if(b)return b;const f=(a==null?void 0:a.showArrival)!==!1,i=(s.status_note??"").trim(),x=ha(s.room_label),h=[];if(s.merged_pre_nights&&s.merged_pre_nights>0){const k=s.merged_pre_nights;return h.push(n?`Arrival ${k} night(s) before trip start, then continuous stay - one room, no room change`:`Anreise ${k} Nacht/Nächte vor Reisestart, danach durchgehend - ein Zimmer, kein Zimmerwechsel`),f&&/Flugdaten fehlen/.test(i)&&h.push(n?"some flight details still pending":"Flugdaten teilweise offen"),s.is_override&&h.push(n?"guide/staff":"Guide/Team"),h.join(" · ")}if(/nach Reiseende/.test(i))return h.push(n?"Extra night after the trip ends":"Zusatznacht nach Reiseende"),x&&x!==s.room_label&&h.push(n?`same guest(s) as room ${x}`:`gleiche Gäste wie Zimmer ${x}`),s.pairing_status==="unpaired_shared"&&h.push(n?"half double booked, currently alone - to be billed as single":"halbes Doppelzimmer gebucht, aktuell allein - als Einzelzimmer abzurechnen"),h.join(" · ");if(/^Basisnacht/.test(i))h.push(n?"Base night (trip start)":"Basisnacht (Reisestart)"),f&&/Flugdaten fehlen/.test(i)&&h.push(n?"some flight details still pending":"Flugdaten teilweise offen");else if(/^Zusatznacht/.test(i)||x)h.push(n?"Extra night before the base night":"Zusatznacht vor der Basisnacht"),x&&x!==s.room_label&&h.push(n?`same guest(s) as room ${x}`:`gleiche Gäste wie Zimmer ${x}`),s.pairing_status==="unpaired_shared"&&h.push(n?"half double booked, currently alone - to be billed as single":"halbes Doppelzimmer gebucht, aktuell allein - als Einzelzimmer abzurechnen");else if(/^Pre-Departure Stay/.test(i)){const k=((c=i.match(/(\d+)/))==null?void 0:c[1])??"";h.push(n?`Paid extra night(s) before trip start: ${k}`:`Bezahlte Zusatznächte vor Reisestart: ${k}`)}return s.is_override&&h.push(n?`arrives early (guide/staff) – ${s.nights} night(s) in total`:`frühere Anreise (Guide/Team) – insgesamt ${s.nights} Nächte`),h.length===0&&i&&h.push(i),h.join(" · ")}function tn(s){const n=(i,x)=>Math.round((new Date(`${x}T12:00:00`).getTime()-new Date(`${i}T12:00:00`).getTime())/864e5),a=new Map,b=[];for(const i of s){const x=i.pairing_status==="unpaired_shared"?`solo:${i.room_label}`:[(i.guests??"").trim(),(i.room_type??"").trim(),ha(i.room_label)??(i.room_label??"").trim(),i.source].join("|");a.has(x)||(a.set(x,[]),b.push(x)),a.get(x).push(i)}const f=[];for(const i of b){const x=[...a.get(i)].sort((c,k)=>c.check_in.localeCompare(k.check_in));let h=null;for(const c of x){if(h&&h.check_out===c.check_in){const k=(h.merged_pre_nights??0)+(c.check_in<=(c.trip_start_date??"")?n(h.check_in,c.check_in):0);h={...h,room_label:ha(h.room_label)??h.room_label,check_out:c.check_out,nights:h.nights+c.nights,room_nights:h.room_nights+c.room_nights,person_nights:h.person_nights+c.person_nights,status_note:c.status_note,arrival_info:h.arrival_info??c.arrival_info,is_override:h.is_override||c.is_override,pairing_status:null,merged_pre_nights:k||n(h.check_in,c.check_in)};continue}h&&f.push(h),h={...c}}h&&f.push(h)}return f}const an={guest_name:"",room_label:"",room_type:"EZ",check_in:"",check_out:"",pax:1,note:""};function zc({tripId:s}){const{settings:n}=hn(),[a,b]=_a("hotel-nights:person-nights",!1),[f,i]=_a("hotel-nights:merged-view",!1),[x,h]=t.useState(""),[c,k]=_a(`hotel-nights:extra-nights:${s}:${x}`,!1),[C,N]=t.useState([]),[v,G]=t.useState([]),[T,o]=t.useState("auto"),[l,V]=t.useState([]),[A,q]=t.useState([]),[y,W]=t.useState(!0),[j,d]=t.useState(!1),[u,I]=t.useState(an),[E,$]=t.useState(!1),[ge,be]=t.useState([]),[Z,H]=t.useState(null),[L,g]=t.useState({check_in:"",check_out:"",note:""}),[r,m]=t.useState(1),[X,p]=t.useState(!1),[ne,le]=t.useState([]),[K,M]=t.useState([]),[ee,he]=t.useState([]),[we,De]=t.useState(""),[_e,J]=t.useState(null),[Ae,qe]=t.useState(""),[Be,
127Ke]=t.useState(new Map),[Ce,xe]=t.useState([]),[ms,us]=_a(`hotel-nights:diet:${s}`,!0),[Q,ue]=t.useState(null),de=t.useMemo(()=>C.find(w=>w.id===x)??null,[C,x]),S=(de==null?void 0:de.partnerName)??"";t.useEffect(()=>{(async()=>{var Te,ke,os,Bs,Qs,zt;const[{data:je},{data:pe}]=await Promise.all([_.from("trip_partner_services").select("id,start_date,end_date,partner_services!inner(name,partners!inner(name,type))").eq("trip_id",s).eq("partner_services.partners.type","hotel"),_.from("trip_partners").select("id,start_date,end_date,services,partners!inner(name,type)").eq("trip_id",s).eq("partners.type","hotel")]),fe=[];for(const Ls of je??[]){const Nt=(ke=(Te=Ls.partner_services)==null?void 0:Te.partners)==null?void 0:ke.name;Nt&&fe.push({id:`svc:${Ls.id}`,partnerName:Nt,serviceName:((Bs=(os=Ls.partner_services)==null?void 0:os.name)==null?void 0:Bs.trim())||null,start:Ls.start_date,end:Ls.end_date})}for(const Ls of pe??[]){const Nt=(Qs=Ls.partners)==null?void 0:Qs.name;Nt&&fe.push({id:`prt:${Ls.id}`,partnerName:Nt,serviceName:((zt=Ls.services)==null?void 0:zt.trim())||null,start:Ls.start_date,end:Ls.end_date})}N(fe),h(Ls=>Ls||(fe.length===1?fe[0].id:""))})()},[s]),t.useEffect(()=>{(async()=>{const{data:je}=await _.from("custom_lists").select("id,name,created_at,custom_list_assignments(assignment_value)").eq("trip_id",s).eq("enable_room_assignment",!0).order("created_at",{ascending:!1}),pe=(je??[]).map(fe=>({id:fe.id,name:fe.name,assigned:(fe.custom_list_assignments??[]).filter(Te=>(Te.assignment_value??"").trim()!=="").length}));G(pe)})()},[s]);const P=t.useMemo(()=>[...v].sort((w,je)=>je.assigned-w.assigned)[0]??null,[v]),ie=t.useMemo(()=>T==="auto"?P:v.find(w=>w.id===T)??null,[T,v,P]),Se=t.useCallback(async()=>{var Bs;W(!0);const[{data:w,error:je},{data:pe},{data:fe},{data:Te},{data:ke},{data:os}]=await Promise.all([_.rpc("admin_get_hotel_room_nights",{p_trip_ids:[s],p_check_in:(de==null?void 0:de.start)??void 0,p_check_out:(de==null?void 0:de.end)??void 0,p_accommodation_key:x,p_include_extra_nights:c,p_room_list_id:T==="auto"?void 0:T}),_.from("hotel_manual_nights").select("*").eq("trip_id",s),_.rpc("admin_get_hotel_night_log",{p_trip_id:s,p_accommodation_key:x}),_.from("hotel_stay_exclusions").select("participant_id,accommodation_key,excluded").eq("trip_id",s),_.from("hotel_stay_notes").select("id,row_key,note_text,show_arrival,bed_preference").eq("trip_id",s).eq("accommodation_key",x),_.from("hotel_export_versions").select("version,reference,snapshot,created_at").eq("trip_id",s).eq("accommodation_key",x).order("version",{ascending:!1}).limit(1)]);if(W(!1),je){Y.error("Übernachtungen konnten nicht geladen werden");return}V(w??[]),q(pe??[]),be(fe??[]),M(Te??[]),he(ke??[]),De(((Bs=(ke??[]).find(Qs=>Qs.row_key===null))==null?void 0:Bs.note_text)??""),ue((os??[])[0]??null)},[s,de,x,c,T]),R=t.useMemo(()=>ee.find(w=>w.row_key===null)??null,[ee]),ce=t.useCallback(w=>{var pe,fe,Te;const je=(fe=(pe=ee.find(ke=>ke.row_key===Qt(w)))==null?void 0:pe.note_text)==null?void 0:fe.trim();return je||((Te=R==null?void 0:R.note_text)==null?void 0:Te.trim())||null},[ee,R]),oe=t.useMemo(()=>{var je;const w=((je=l[0])==null?void 0:je.trip_start_date)??null;return!(de!=null&&de.start)||!w?!0:de.start<=w},[l,de]),me=(R==null?void 0:R.show_arrival)??oe,Ee=async(w,je)=>{var Te,ke;if(!x){Y.error("Bitte zuerst eine Unterkunft wählen");return}const pe=ee.find(os=>os.row_key===w)??null,fe={note_text:je.note_text!==void 0?((Te=je.note_text)==null?void 0:Te.trim())||null:(pe==null?void 0:pe.note_text)??null,show_arrival:je.show_arrival!==void 0?je.show_arrival:(pe==null?void 0:pe.show_arrival)??null,bed_preference:je.bed_preference!==void 0?je.bed_preference:(pe==null?void 0:pe.bed_preference)??null};if(pe&&fe.note_text===null&&fe.show_arrival===null&&fe.bed_preference===null){const{error:os}=await _.from("hotel_stay_notes").delete().eq("id",pe.id);if(os){Y.error("Speichern fehlgeschlagen");return}}else if(pe){const{error:os}=await _.from("hotel_stay_notes").update(fe).eq("id",pe.id);if(os){Y.error("Speichern fehlgeschlagen");return}}else if(fe.note_text!==null||fe.show_arrival!==null||fe.bed_preference!==null){const{data:os}=await _.auth.getUser(),{error:Bs}=await _.from("hotel_stay_notes").insert({trip_id:s,accommodation_key:x,row_key:w,...fe,created_by:((ke=os.user)==null?void 0:ke.id)??null});if(Bs){Y.error("Speichern fehlgeschlagen");return}}Se()};t.useEffect(()=>{(async()=>{const{data:je}=await _.from("participants").select("id, first_name, last_name, is_guide, phone, dietary_requirements, allergies, food_dislikes, bookings(status)").eq("trip_id",s).order("last_name"),pe=(je??[]).filter(fe=>{var Te;return(((Te=fe.bookings)==null?void 0:Te.status)??"active")!=="cancelled"});le(pe.map(fe=>({id:fe.id,name:`${fe.last_name}, ${fe.first_name}`,isGuide:fe.is_guide}))),Ke(new Map(pe.map(fe=>[`${fe.last_name}, ${fe.first_name}`,{first:fe.first_name,diet:fe.dietary_requirements??"",allergies:fe.allergies??"",dislikes:fe.food_dislikes??""}]))),xe(pe.filter(fe=>fe.is_guide).map(fe=>({name:`${fe.first_name} ${fe.last_name}`,phone:fe.phone})))})()},[s]);const ze=t.useMemo(()=>ne.filter(w=>{const je=K.find(fe=>fe.participant_id===w.id&&fe.accommodation_key===null),pe=K.find(fe=>fe.participant_id===w.id&&fe.accommodation_key===x);return pe?pe.excluded:(je==null?void 0:je.excluded)??!1}),[ne,K,x]),ns=async(w,je,pe)=>{let fe=_.from("hotel_stay_exclusions").delete().eq("trip_id",s).eq("participant_id",w);fe=je===null?fe.is("accommodation_key",null):fe.eq("accommodation_key",je);const{error:Te}=await fe;if(Te){Y.error("Speichern fehlgeschlagen");return}if(pe!==null){const{error:ke}=await _.from("hotel_stay_exclusions").insert({trip_id:s,participant_id:w,accommodation_key:je,excluded:pe});if(ke){Y.error("Speichern fehlgeschlagen");return}}Se()};t.useEffect(()=>{Se()},[Se]),t.useEffect(()=>{de!=null&&de.start&&(de!=null&&de.end)&&I(w=>({...w,check_in:w.check_in||de.start,check_out:w.check_out||de.end}))},[de]);const Pe=w=>w.source==="participant"&&!w.booked_room_type,Fe=async(w,je,pe,fe)=>{var Bs;const{data:Te}=await _.auth.getUser(),ke=((Bs=Te.user)==null?void 0:Bs.id)??null,{error:os}=await _.from("hotel_night_overrides").upsert({trip_id:s,accommodation_key:x,room_label:w,check_in:je,check_out:pe,note:fe||null,created_by:ke,updated_by:ke},{onConflict:"trip_id,accommodation_key,room_label"});return os?(Y.error("Anpassung konnte nicht gespeichert werden"),!1):!0},cs=async w=>{const{error:je}=await _.from("hotel_night_overrides").delete().eq("trip_id",s).eq("accommodation_key",x).eq("room_label",w);return je?(Y.error("Zurücksetzen fehlgeschlagen"),!1):!0},vs=async()=>
127{if(!Z)return;if(!L.check_in||!L.check_out||L.check_out<=L.check_in){Y.error("Check-out muss nach Check-in liegen");return}$(!0);const w=await Fe(Z.room_label,L.check_in,L.check_out,L.note);$(!1),w&&(Y.success("Nächte angepasst"),H(null),Se())},Me=async w=>{await cs(w.room_label)&&(Y.success("Auf Automatik zurückgesetzt"),Se())},se=t.useMemo(()=>l.filter(w=>{var je;return Pe(w)&&((je=w.guests)==null?void 0:je.includes("(Guide/Team)"))}),[l]),Re=async()=>{const w=Number(r);if(!Number.isFinite(w)||w<1){Y.error("Bitte Anzahl Nächte angeben");return}if(se.length===0){Y.error("Keine Guide-/Team-Zimmer in der Liste");return}$(!0);for(const je of se){const pe=(de==null?void 0:de.start)??je.trip_start_date,fe=new Date(`${pe}T12:00:00`);fe.setDate(fe.getDate()-w);const Te=fe.toISOString().slice(0,10);await Fe(je.room_label,Te,je.check_out,`Team reist ${w} Nacht/Nächte früher an`)}$(!1),Y.success(`${se.length} Zimmer angepasst`),Se()},ts=async()=>{$(!0);for(const w of se.filter(je=>je.is_override))await cs(w.room_label);$(!1),Y.success("Anpassungen entfernt"),Se()},hs=t.useMemo(()=>ca(l.filter(w=>w.source==="participant"||w.source==="manual")),[l]),As=t.useMemo(()=>ca(l.filter(w=>w.source==="extra")),[l]),ds=t.useMemo(()=>[...hs,...As],[hs,As]),Ps=t.useMemo(()=>ca(l.filter(w=>w.source==="gap")),[l]),Fs=t.useMemo(()=>ca(tn(hs)),[hs]),Hs=t.useMemo(()=>ca(tn(As)),[As]),Ct=f?Fs:hs,F=f?Hs:As,re=w=>({roomNights:w.reduce((je,pe)=>je+pe.room_nights,0),personNights:w.reduce((je,pe)=>je+pe.person_nights,0)}),Ne=t.useMemo(()=>({...re(hs),extraRoomNights:As.reduce((w,je)=>w+je.room_nights,0),extraPersonNights:As.reduce((w,je)=>w+je.person_nights,0),open:Ps.length}),[hs,As,Ps]),as=async()=>{if(!u.guest_name||!u.check_in||!u.check_out){Y.error("Name, Check-in und Check-out sind Pflicht");return}if(u.check_out<=u.check_in){Y.error("Check-out muss nach Check-in liegen");return}$(!0);const{error:w}=await _.from("hotel_manual_nights").insert({trip_id:s,accommodation_name:S||null,accommodation_key:x||null,guest_name:u.guest_name,room_label:u.room_label||null,room_type:u.room_type,check_in:u.check_in,check_out:u.check_out,pax:Number(u.pax)||1,note:u.note||null});if($(!1),w){Y.error("Speichern fehlgeschlagen");return}Y.success("Nacht hinzugefügt"),I(an),d(!1),Se()},Ge=async w=>{const{error:je}=await _.from("hotel_manual_nights").delete().eq("id",w);if(je){Y.error("Löschen fehlgeschlagen");return}Se()},Ze=t.useCallback(w=>{const je=(w.guests||"").split(" / ").map(fe=>fe.replace(/\s*\(Guide\/Team\)/g,"").trim()).filter(Boolean),pe=[];for(const fe of je){const Te=Be.get(fe);if(!Te)continue;const ke=[Te.diet,Te.allergies,Te.dislikes].map(os=>os.trim()).filter(Boolean);ke.length>0&&pe.push(`${Te.first}: ${ke.join(", ")}`)}return pe.join(" · ")},[Be]),es=t.useMemo(()=>ds.some(w=>Ze(w)!==""),[ds,Ze]),Le=ms&&es,_s=t.useCallback(w=>{var fe;const pe=((fe=ee.find(Te=>Te.row_key===Qt(w)))==null?void 0:fe.bed_preference)??(R==null?void 0:R.bed_preference)??null;return pe==="double"||pe==="twin"?pe:null},[ee,R]),Cs=(w,je)=>w==="double"?je?"Double bed":"Doppelbett":w==="twin"?je?"Twin beds":"Zwei Einzelbetten":"",zs=t.useMemo(()=>ds.some(w=>_s(w)!==null),[ds,_s]),B=[{key:"guests",label:"Gäste",labelEn:"Guests"},{key:"type",label:"Zimmertyp",labelEn:"Room type"},...zs?[{key:"bed",label:"Bett",labelEn:"Bed"}]:[],{key:"ci",label:"Check-in",labelEn:"Check-in"},{key:"co",label:"Check-out",labelEn:"Check-out"},{key:"nights",label:"Nächte",labelEn:"Nights"},{key:"pax",label:"Pers.",labelEn:"Pax"},...a?[{key:"pn",label:"Personennächte",labelEn:"Person nights"}]:[],...me?[{key:"arrival",label:"Anreiseflug",labelEn:"Arrival flight"}]:[],...Le?[{key:"diet",label:"Ernährung / Allergien",labelEn:"Diet / allergies",translatable:!0}]:[],{key:"note",label:"Status / Hinweis",labelEn:"Status / note"}],ae=t.useMemo(()=>{const w=new Map;for(const je of ds){let pe=je.check_in;for(;pe<je.check_out;){const fe=w.get(pe)??{rooms:0,guests:0};fe.rooms+=1,fe.guests+=je.pax,w.set(pe,fe);const Te=new Date(`${pe}T12:00:00`);Te.setDate(Te.getDate()+1),pe=`${Te.getFullYear()}-${String(Te.getMonth()+1).padStart(2,"0")}-${String(Te.getDate()).padStart(2,"0")}`}}
127return[...w.entries()].sort(([je],[pe])=>je.localeCompare(pe))},[ds]),ve=t.useMemo(()=>{var pe;if(Q!=null&&Q.reference)return Q.reference;const w=(((pe=ds[0])==null?void 0:pe.trip_start_date)??"").slice(0,4)||String(new Date().getFullYear()),je=(S||"HOTEL").toUpperCase().replace(/[^A-Z0-9]/g,"").slice(0,8)||"HOTEL";return`OTP-${w}-${je}-${s.slice(0,4).toUpperCase()}`},[Q,ds,S,s]),js=t.useMemo(()=>[...Fs,...c?Hs:[]].map(w=>({room:w.room_label,guests:w.guests,ci:w.check_in,co:w.check_out,bed:_s(w)??"",note:Va(w,!1,{override:ce(w),showArrival:me})})),[Fs,Hs,c,_s,ce,me]),Ws=t.useCallback(w=>{const je=Array.isArray(Q==null?void 0:Q.snapshot)?Q==null?void 0:Q.snapshot:[];if(!Q)return[];const pe=new Map(je.map(ke=>[ke.room,ke])),fe=[],Te=ke=>w?`room ${ke}`:`Zimmer ${ke}`;for(const ke of js){const os=pe.get(ke.room);if(!os){fe.push(w?`New: ${Te(ke.room)} (${ke.guests}), ${ps(ke.ci)}–${ps(ke.co)}`:`Neu: ${Te(ke.room)} (${ke.guests}), ${ps(ke.ci)}–${ps(ke.co)}`);continue}if(pe.delete(ke.room),os.ci!==ke.ci&&fe.push(w?`Changed: ${Te(ke.room)}, check-in now ${ps(ke.ci)} (was ${ps(os.ci)})`:`Geändert: ${Te(ke.room)}, Check-in jetzt ${ps(ke.ci)} (vorher ${ps(os.ci)})`),os.co!==ke.co&&fe.push(w?`Changed: ${Te(ke.room)}, check-out now ${ps(ke.co)} (was ${ps(os.co)})`:`Geändert: ${Te(ke.room)}, Check-out jetzt ${ps(ke.co)} (vorher ${ps(os.co)})`),os.guests!==ke.guests&&fe.push(w?`Changed: ${Te(ke.room)}, guests now ${ke.guests}`:`Geändert: ${Te(ke.room)}, Gäste jetzt ${ke.guests}`),(os.bed??"")!==ke.bed){const Bs=Cs(ke.bed||null,w);fe.push(w?`Changed: ${Te(ke.room)}, bed setup now ${Bs||"not specified"}`:`Geändert: ${Te(ke.room)}, Bett jetzt ${Bs||"keine Angabe"}`)}}for(const[ke,os]of pe)fe.push(w?`Removed: ${Te(ke)} (${os.guests})`:`Entfallen: ${Te(ke)} (${os.guests})`);return fe},[Q,js]),is=t.useMemo(()=>Ws(!1),[Ws]),ls=!Q||is.length>0?((Q==null?void 0:Q.version)??0)+1:Q.version,ws=async(w,je)=>{var kr;if(ds.length===0){Y.error("Keine Daten zum Exportieren");return}const pe=je==="en",fe=ds[0]?`${ds[0].trip_title} — ${ps(ds[0].trip_start_date)}`:"",Te=pe?S?`${S} — Accommodation & room allocation`:"Accommodation & room allocation":S?`${S} — Übernachtungen & Zimmerzuteilung`:"Übernachtungen & Zimmerzuteilung",ke=de!=null&&de.start&&(de!=null&&de.end)?`${ps(de.start)}–${ps(de.end)}`:"",os=pe?[`Off The Path · ${fe}`,...ke?[`Stay: ${ke}`]:[],`Room nights: ${Ne.roomNights}`]:[`Off The Path · ${fe}`,...ke?[`Zeitraum: ${ke}`]:[],`Zimmernächte: ${Ne.roomNights}`];a&&os.push(pe?`Person nights: ${Ne.personNights}`:`Personennächte: ${Ne.personNights}`),c&&Hs.length>0&&os.push(pe?`Extra nights before/after the trip: ${Ne.extraRoomNights} room night(s)`:`Zusatznächte vor/nach der Reise: ${Ne.extraRoomNights} Zimmernächte`);const Bs={heading:pe?"Rooms per night (please confirm)":"Zimmer pro Nacht (bitte bestätigen)",headers:pe?["Night of","Rooms","Guests"]:["Nacht vom","Zimmer","Gäste"],rows:ae.map(([ks,St])=>[ps(ks),String(St.rooms),String(St.guests)])},Qs=(n==null?void 0:n.companyEmail)??(n==null?void 0:n.emailSenderAddress)??"",zt=pe?["How to read this list","· One line = one room for the period shown (check-in to check-out).","· Rows are sorted by check-in date (earliest first).","· The main block shows the nights booked with you for the period stated above.",...c&&Hs.length>0?["· The second block lists extra nights our guests booked through us before or after the trip. Please confirm them separately."]:[],'· "to be billed as single" = the guest booked half of a double room but currently has no roommate for that night. If this changes, we will let you know in advance.',...zs?['· "Bed" = requested bed setup (double bed or twin beds).']:[],...Le?['· "Diet / allergies" = information our guests gave us. Please pass it on to your kitchen.']:[],Qs?`Questions or anything unclear? Please contact Off The Path before making changes: ${Qs}`:"Questions or anything unclear? Please contact Off The Path before making changes."]:["So ist diese Liste zu lesen","· Eine Zeile = ein Zimmer für den angegebenen Zeitraum (Check-in bis Check-out).","· Die Zeilen sind nach Check-in-Datum sortiert (frühestes zuerst).","· Der Hauptblock zeigt die bei Ihnen gebuchten Nächte für den oben genannten Zeitraum.",...c&&Hs.length>0?["· Der zweite Block listet Zusatznächte, die unsere Gäste über uns vor oder nach der Reise gebucht haben. Bitte separat bestätigen."]:[],'· „als Einzelzimmer abzurechnen" = der Gast hat ein halbes Doppelzimmer gebucht, hat für diese Nacht aber noch keinen Mitbewohner. Sollte sich das ändern, melden wir es vorab.',...zs?['· „Bett" = gewünschte Bettvariante (Doppelbett oder zwei Einzelbetten).']:[],...Le?['· „Ernährung / Allergien" = Angaben unserer Gäste. Bitte an die Küche weitergeben.']:[],Qs?`Fragen oder Unklarheiten? Bitte vor Änderungen bei Off The Path melden: ${Qs}`:"Fragen oder Unklarheiten? Bitte vor Änderungen bei Off The Path melden."],Ls=ks=>({guests:pe?Ac(ks.guests):ks.guests,type:pe?Ec(ks.room_type):ks.room_type,...zs?{bed:Cs(_s(ks),pe)}:{},ci:ps(ks.check_in),co:ps(ks.check_out),nights:ks.nights,pax:ks.pax,...a?{pn:ks.person_nights}:{},...me?{arrival:ks.arrival_info??"—"}:{},...Le?{diet:Ze(ks)}:{},note:Va(ks,pe,{override:ce(ks),showArrival:me})}),Nt=new Date().toLocaleDateString(pe?"en-GB":"de-DE"),D=[pe?`Reference: ${ve} · Version ${ls} · ${Nt}${ls>1?` (replaces version ${ls-1})`:""}`:`Referenz: ${ve} · Version ${ls} · ${Nt}${ls>1?` (ersetzt Version ${ls-1})`:""}`];if(Ce.length>0){const ks=Ce.map(St=>St.phone?`${St.name} (${St.phone})`:St.name).join(", ");D.push(pe?`Guide on site: ${ks}`:`Guide vor Ort: ${ks}`)}const ye=[(n==null?void 0:n.companyName)||"Off The Path",Qs,n==null?void 0:n.companyPhone].filter(
127Boolean).join(" · ");D.push(pe?`Contact: ${ye}`:`Kontakt: ${ye}`);const xs=Ws(pe),Ys=Q?xs.length>0?[pe?"What changed since the last version":"Was sich seit der letzten Version geändert hat",...xs.map(ks=>`· ${ks}`)]:[pe?`No changes since version ${Q.version}.`:`Keine Änderungen seit Version ${Q.version}.`]:[pe?"First issue of this list.":"Erstversand dieser Liste."],ia=Fs.map(Ls),yr=c?Hs.map(Ls):[],wr=ke?pe?`Nights at your property (${ke}) — ${Ne.roomNights} room night(s)`:`Nächte in Ihrem Haus (${ke}) — ${Ne.roomNights} Zimmernächte`:pe?`Nights at your property — ${Ne.roomNights} room night(s)`:`Nächte in Ihrem Haus — ${Ne.roomNights} Zimmernächte`;if(await Wi({title:Te,subtitle:os.join(" · "),columns:B,preTable:Bs,infoLines:D,changeNotes:Ys,footerNotes:zt,rows:ia,...yr.length>0?{rowGroups:[{labelDe:wr,labelEn:wr,rows:ia},{labelDe:`Zusatznächte vor/nach der Reise — ${Ne.extraRoomNights} Zimmernächte`,labelEn:`Extra nights before/after the trip — ${Ne.extraRoomNights} room night(s)`,rows:yr}]}:{},language:je,format:w,fileBaseName:`Uebernachtungen_${S||"Unterkunft"}_v${ls}`}),ls!==(Q==null?void 0:Q.version)){const{data:ks}=await _.auth.getUser(),{error:St}=await _.from("hotel_export_versions").insert({trip_id:s,accommodation_key:x,reference:ve,version:ls,snapshot:js,exported_by:((kr=ks.user)==null?void 0:kr.id)??null});if(St){Y.error("Export erstellt, Versionsstand konnte nicht gespeichert werden");return}Se()}},Ht=(w,je)=>e.jsxs(ct,{children:[e.jsx(ss,{className:"font-medium",children:sn(w.room_label,!1)}),e.jsx(ss,{children:w.guests}),e.jsx(ss,{children:w.room_type}),e.jsx(ss,{children:w.pax>1?e.jsxs(Ie,{value:_s(w)??"none",onValueChange:pe=>Ee(Qt(w),{bed_preference:pe==="none"?null:pe}),children:[e.jsx(Oe,{className:"h-8 w-[150px] text-xs",children:e.jsx(Ve,{})}),e.jsxs(Ue,{children:[e.jsx(O,{value:"none",children:"keine Angabe"}),e.jsx(O,{value:"double",children:"Doppelbett"}),e.jsx(O,{value:"twin",children:"Zwei Einzelbetten"})]})]}):e.jsx("span",{className:"text-xs text-muted-foreground",children:"—"})}),e.jsx(ss,{children:ps(w.check_in)}),e.jsx(ss,{children:ps(w.check_out)}),e.jsx(ss,{className:"text-right",children:w.nights}),e.jsx(ss,{className:"text-right",children:w.pax}),a&&e.jsx(ss,{className:"text-right",children:w.person_nights}),me&&e.jsx(ss,{className:"text-xs",children:w.arrival_info??"—"}),Le&&e.jsx(ss,{className:"text-xs",children:Ze(w)||"—"}),e.jsxs(ss,{className:"text-xs",children:[ce(w)??(w.merged_pre_nights?Va(w,!1,{showArrival:me}):w.status_note),e.jsx(z,{variant:"ghost",size:"icon",className:"ml-1 h-6 w-6 align-middle",title:"Eigenen Hinweis für diese Zeile schreiben",onClick:()=>{var pe;J(w),qe(((pe=ee.find(fe=>fe.row_key===Qt(w)))==null?void 0:pe.note_text)??"")},children:e.jsx(vt,{className:"h-3 w-3"})}),w.source==="manual"&&e.jsx(Xe,{variant:"outline",className:"ml-2",children:"manuell"}),w.source==="extra"&&e.jsx(Xe,{variant:"outline",className:"ml-2",children:"Zusatznacht"}),w.pairing_status==="unpaired_shared"&&e.jsx(Xe,{variant:"secondary",className:"ml-2 bg-amber-100 text-amber-900",children:"halbes DZ – aktuell allein"}),w.is_override&&e.jsx(Xe,{variant:"outline",className:"ml-2",title:`Angepasst von ${w.override_by??"Unbekannt"}${w.override_at?` am ${new Date(w.override_at).toLocaleDateString("de-DE")}`:""}`,children:"angepasst"})]}),e.jsx(ss,{className:"text-right",children:Pe(w)&&!w.merged_pre_nights&&e.jsxs("div",{className:"flex justify-end gap-1",children:[e.jsx(z,{variant:"ghost",size:"icon",className:"h-7 w-7",onClick:()=>{H(w),g({check_in:w.check_in,check_out:w.check_out,note:w.override_note??""})},children:e.jsx(vt,{className:"h-3.5 w-3.5"})}),w.is_override&&e.jsx(z,{variant:"ghost",size:"icon",className:"h-7 w-7",onClick:()=>Me(w),children:e.jsx(ma,{className:"h-3.5 w-3.5"})})]})})]},je);return e.jsxs("div",{className:"space-y-6",children:[e.jsxs("div",{className:"flex flex-wrap items-end justify-between gap-3",children:[e.jsxs("div",{className:"grid gap-2 sm:min-w-[380px]",children:[e.jsxs(U,{htmlFor:"acc",className:"flex items-center gap-1.5",children:[e.jsx(Qi,{className:"h-4 w-4"})," Unterkunft (Partner dieser Reise)"]}),C.length===0?e.jsx("p",{className:"text-sm text-muted-foreground",children:'Für diese Reise ist noch keine Unterkunft als Partner hinterlegt — bitte im Reiter „Partner" ergänzen.'}):e.jsxs(Ie,{value:x,onValueChange:h,children:[e.jsx(Oe,{id:"acc",children:e.jsx(Ve,{placeholder:"Unterkunft wählen"})}),e.jsx(Ue,{children:C.map(w=>e.jsxs(O,{value:w.id,children:[w.partnerName,w.serviceName?` · ${w.serviceName}`:"",w.start&&w.end?` · ${ps(w.start)}–${ps(w.end)}`:""]},w.id))})]}),v.length>0&&e.jsxs("div",{className:"grid gap-1",children:[e.jsxs(U,{htmlFor:"room-list",className:"text-xs text-muted-foreground",children:["Zimmer laut Liste",v.length>1?" (mehrere Listen sind als Zimmerzuteilung markiert)":""]}),e.jsxs(Ie,{value:T,onValueChange:o,children:[e.jsx(Oe,{id:"room-list",className:"h-8 text-sm",children:e.jsx(Ve,{})}),e.jsxs(Ue,{children:[e.jsxs(O,{value:"auto",children:["Automatisch",ie?` · ${ie.name}`:""]}),v.map(w=>e.jsxs(O,{value:w.id,children:[w.name," · ",w.assigned," Zuweisungen"]},w.id))]})]})]})]}),e.jsxs("div",{className:"flex flex-wrap gap-2",children:[e.jsxs(We,{open:X,onOpenChange:p,children:[e.jsx(ua,{asChild:!0,children:e.jsxs(z,{variant:"outline",size:"sm",children:[e.jsx(Yi,{className:"mr-1.5 h-4 w-4"})," Gäste-Auswahl"]})}),e.jsxs(Qe,{className:"max-h-[85vh] overflow-y-auto",children:[e.jsx(Ye,{children:e.jsx(Je,{children:"Gäste-Auswahl — wer übernachtet wo?"})}),e.jsx("p",{className:"text-xs text-muted-foreground",children:"Legt fest, wer auf der Reise generell nicht mit uns übernachtet — und für welche Unterkunft einzelne Personen eine Ausnahme bekommen. Eine unterkunftsbezogene Ausnahme gewinnt immer vor der Reise-Einstellung."}),e.jsx("div",{className:"space-y-3",children:ne.map(w=>{const je=K.find(ke=>ke.participant_id===w.id&&ke.accommodation_key===null),pe=K.find(ke=>ke.participant_id===w.id&&ke.accommodation_key===x),fe=(je==null?void 0:je.excluded)??!1,Te=pe?!pe.excluded:!fe;return e.jsxs("div",{className:"rounded-lg border p-3",children:[e.jsxs("p",{className:"text-sm font-medium",children:[w.name,w.isGuide&&e.jsx("span",{className:"ml-2 text-xs text-muted-foreground",children:"(Guide)"})]}),e.jsxs("div",{className:"mt-2 space-y-2",children:[e.jsxs("div",{className:"flex items-center justify-between gap-3",children:[e.jsx(U,{htmlFor:`trip-excl-${w.id}`,className:"text-xs font-normal",children:"Übernachtet auf dieser Reise nicht bei uns"}),e.jsx(ys,{id:`trip-excl-${w.id}`,checked:fe,onCheckedChange:ke=>ns(w.id,null,ke?!0:null)})]}),x&&e.jsxs("div",{className:"flex items-center justify-between gap-3",children:[e.jsxs(U,{htmlFor:`local-excl-${w.id}`,className:"text-xs font-normal",children:["Übernachtet bei ",S||"dieser Unterkunft"]}),e.jsx(ys,{id:`local-excl-${w.id}`,checked:Te,onCheckedChange:ke=>ns(w.id,x,ke===!fe?null:!ke)})]})]})]},w.id)})}),e.jsx(gs,{children:e.jsx(z,{onClick:()=>p(!1),children:"Fertig"})})]})]}),e.jsxs(z,{variant:"outline",size:"sm",onClick:()=>ws("csv","de"),children:[e.jsx(da,{className:"mr-1.5 h-4 w-4"})," CSV"]}),e.jsxs(z,{variant:"outline",size:"sm",onClick:()=>ws("pdf","de"),children:[e.jsx(da,{className:"mr-1.5 h-4 w-4"})," PDF (DE)"]}),e.jsxs(z,{variant:"outline",size:"sm",onClick:()=>ws("pdf","en"),children:[e.jsx(da,{className:"mr-1.5 h-4 w-4"})," PDF (EN)"]})]})]}),ze.length>0&&e.jsxs("p",{className:"text-xs text-muted-foreground",children:[ze.length===1?"Eine Person übernachtet":`${ze.length} Personen übernachten`," ","nicht in dieser Unterkunft und ",ze.length===1?"ist":"sind"," ausgeblendet:"," ",ze.map(w=>
127w.name).join(", ")]}),y?e.jsxs("div",{className:"flex items-center gap-2 text-sm text-muted-foreground",children:[e.jsx($e,{className:"h-4 w-4 animate-spin"})," Übernachtungen werden berechnet …"]}):l.length===0?e.jsx(Ss,{children:e.jsx(Rs,{className:"p-6 text-sm text-muted-foreground",children:"Für diese Reise sind noch keine Übernachtungen berechenbar — sobald Buchungen und Zimmerzuteilungen vorliegen, erscheinen sie hier."})}):e.jsxs(e.Fragment,{children:[e.jsxs("div",{className:"grid gap-3 sm:grid-cols-2 lg:grid-cols-4",children:[e.jsx(Ss,{children:e.jsxs(Rs,{className:"p-4",children:[e.jsxs("p",{className:"text-xs text-muted-foreground",children:["Zimmernächte",de!=null&&de.start&&(de!=null&&de.end)?` · ${ps(de.start)}–${ps(de.end)}`:""]}),e.jsx("p",{className:"text-2xl font-bold",children:Ne.roomNights})]})}),a&&e.jsx(Ss,{children:e.jsxs(Rs,{className:"p-4",children:[e.jsx("p",{className:"text-xs text-muted-foreground",children:"Personennächte"}),e.jsx("p",{className:"text-2xl font-bold",children:Ne.personNights})]})}),c&&e.jsx(Ss,{children:e.jsxs(Rs,{className:"p-4",children:[e.jsx("p",{className:"text-xs text-muted-foreground",children:"Zusatznächte vor/nach der Reise"}),e.jsx("p",{className:"text-2xl font-bold",children:Ne.extraRoomNights}),a&&e.jsxs("p",{className:"text-xs text-muted-foreground",children:[Ne.extraPersonNights," Personennächte"]})]})}),e.jsx(Ss,{children:e.jsxs(Rs,{className:"p-4",children:[e.jsx("p",{className:"text-xs text-muted-foreground",children:"Offene Klärfälle"}),e.jsx("p",{className:"text-2xl font-bold",children:Ne.open})]})})]}),e.jsxs("div",{className:"flex flex-wrap items-center gap-x-6 gap-y-2",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(ys,{id:"show-person-nights",checked:a,onCheckedChange:b}),e.jsx(U,{htmlFor:"show-person-nights",className:"text-xs text-muted-foreground",children:"Personennächte anzeigen (Personen × Nächte — für Frühstück, Kurtaxe & Verpflegung pro Kopf)"})]}),e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(ys,{id:"show-merged",checked:f,onCheckedChange:i}),e.jsx(U,{htmlFor:"show-merged",className:"text-xs text-muted-foreground",children:"Zusammengefasst wie im Export anzeigen (aneinander anschließende Nächte derselben Gäste als ein Zimmer)"})]}),e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(ys,{id:"extra-nights",checked:c,onCheckedChange:k}),e.jsx(U,{htmlFor:"extra-nights",className:"text-xs text-muted-foreground",children:"Zusätzlich vor/nach der Reise gebuchte Nächte anzeigen (getrennt ausgewiesen, auch im Export)"})]}),e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(ys,{id:"show-arrival",checked:me,onCheckedChange:w=>Ee(null,{show_arrival:w===oe?null:w})}),e.jsxs(U,{htmlFor:"show-arrival",className:"text-xs text-muted-foreground",children:["Anreiseflug anzeigen (",oe?"automatisch an — Aufenthalt beginnt zum Reisestart":"automatisch aus — Aufenthalt liegt mitten in der Reise",")"]})]}),e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(ys,{id:"show-diet",checked:ms,onCheckedChange:us,disabled:!es}),e.jsxs(U,{htmlFor:"show-diet",className:"text-xs text-muted-foreground",children:["Ernährung & Allergien mitsenden"," ",es?"(aus den Teilnehmerdaten)":"(keine Angaben bei dieser Reise hinterlegt)"]})]})]}),e.jsx(Ss,{children:e.jsxs(Rs,{className:"flex flex-wrap items-center justify-between gap-3 p-4",children:[e.jsxs("div",{children:[e.jsx("p",{className:"text-xs text-muted-foreground",children:"Referenz für die Unterkunft"}),e.jsx("p",{className:"font-mono text-sm",children:ve})]}),e.jsx("div",{className:"text-xs text-muted-foreground",children:Q?e.jsxs(e.Fragment,{children:["Zuletzt exportiert: Version ",Q.version," am"," ",new Date(Q.created_at).toLocaleDateString("de-DE"),is.length>0?e.jsxs("span",{className:"ml-1 font-medium text-amber-700",children:["· ",is.length," Änderung",is.length===1?"":"en"," seit Version"," ",Q.version," — nächster Export wird Version ",ls]}):e.jsx("span",{className:"ml-1",children:"· keine Änderungen seit dem letzten Export"})]}):e.jsx(e.Fragment,{children:"Noch nicht exportiert — der nächste Export ist Version 1 (Erstversand)."})})]})}),e.jsx(Ss,{children:e.jsxs(Rs,{className:"space-y-2 p-4",children:[e.jsxs(U,{htmlFor:"acc-note",className:"text-sm",children:["Eigener Hinweis für ",S||"diese Unterkunft"]}),e.jsx(qs,{id:"acc-note",rows:2,value:we,onChange:w=>De(w.target.value),placeholder:"z. B. Gäste kommen mit dem Bus aus Sossusvlei, Ankunft nachmittags"}),e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(z,{size:"sm",onClick:()=>Ee(null,{note_text:we}),children:"Hinweis speichern"}),(R==null?void 0:R.note_text)&&e.jsxs(z,{size:"sm",variant:"ghost",onClick:()=>{De(""),Ee(null,{note_text:null})},children:[e.jsx(ma,{className:"mr-1.5 h-3.5 w-3.5"})," Zurück auf automatisch"]})]}),e.jsx("p",{className:"text-xs text-muted-foreground",children:"Dieser Text ersetzt in Liste und Export den automatischen Hinweis für alle Zeilen dieser Unterkunft. Ein Hinweis, den Du direkt an einer Zeile hinterlegst, gewinnt dagegen."})]})}),e.jsxs(Ss,{children:[e.jsxs(Mt,{className:"flex flex-row flex-wrap items-center justify-between gap-3 pb-3",children:[e.jsx(Gt,{className:"text-base",children:"Zimmer & Nächte"}),e.jsxs("div",{className:"flex flex-wrap items-center gap-2",children:[e.jsx(U,{htmlFor:"guide-nights",className:"text-xs text-muted-foreground",children:"Guides/Team früher anreisen"}
127),e.jsx(te,{id:"guide-nights",type:"number",min:1,className:"h-8 w-16",value:r,onChange:w=>m(Number(w.target.value))}),e.jsx("span",{className:"text-xs text-muted-foreground",children:"Nächte"}),e.jsx(z,{size:"sm",variant:"outline",onClick:Re,disabled:E,children:"Anwenden"}),se.some(w=>w.is_override)&&e.jsxs(z,{size:"sm",variant:"ghost",onClick:ts,disabled:E,children:[e.jsx(ma,{className:"mr-1.5 h-3.5 w-3.5"})," Entfernen"]})]})]}),e.jsx(Rs,{className:"overflow-x-auto p-4 pt-0",children:e.jsxs(ga,{children:[e.jsx(fa,{children:e.jsxs(ct,{children:[e.jsx(rs,{children:"Zimmer"}),e.jsx(rs,{children:"Gäste"}),e.jsx(rs,{children:"Typ"}),e.jsx(rs,{children:"Bett"}),e.jsx(rs,{children:"Check-in"}),e.jsx(rs,{children:"Check-out"}),e.jsx(rs,{className:"text-right",children:"Nächte"}),e.jsx(rs,{className:"text-right",children:"Pers."}),a&&e.jsx(rs,{className:"text-right",children:"Personennächte"}),me&&e.jsx(rs,{children:"Anreiseflug"}),Le&&e.jsx(rs,{children:"Ernährung / Allergien"}),e.jsx(rs,{children:"Status / Hinweis"}),e.jsx(rs,{className:"w-[80px]"})]})}),e.jsxs(ja,{children:[Ct.map((w,je)=>Ht(w,`p-${je}`)),c&&F.length>0&&e.jsx(ct,{className:"bg-muted/60 hover:bg-muted/60",children:e.jsxs(ss,{colSpan:10+(a?1:0)+(me?1:0)+(Le?1:0),className:"text-xs font-medium",children:["Zusätzlich vor/nach der Reise gebuchte Nächte · ",Ne.extraRoomNights," Zimmernächte"]})}),c&&F.map((w,je)=>Ht(w,`e-${je}`))]})]})})]}),Ps.length>0&&e.jsxs(Ss,{className:"border-amber-200 bg-amber-50/60",children:[e.jsx(Mt,{className:"pb-2",children:e.jsxs(Gt,{className:"flex items-center gap-2 text-base text-amber-800",children:[e.jsx(Lt,{className:"h-4 w-4"})," Zu klären — landet früher, keine Zusatznacht gebucht"]})}),e.jsxs(Rs,{className:"pt-0",children:[e.jsx("ul",{className:"space-y-1.5 text-sm text-amber-900",children:Ps.map((w,je)=>e.jsxs("li",{children:[e.jsx("span",{className:"font-medium",children:w.guests||w.room_label}),w.arrival_info?` · Anreiseflug: ${w.arrival_info}`:"",w.check_in?` · ${ps(w.check_in)}`:"",w.status_note?` · ${w.status_note}`:""]},`gap-${je}`))}),e.jsx("p",{className:"mt-3 text-xs text-amber-700",children:"Diese Hinweise sind bewusst nicht Teil der Liste und der Exporte (CSV/PDF) — es wurde nichts zusätzlich gebucht."})]})]}),e.jsx(at,{children:e.jsxs(Ss,{children:[e.jsx(rt,{asChild:!0,children:e.jsx(Mt,{className:"cursor-pointer pb-3",children:e.jsxs(Gt,{className:"flex items-center gap-2 text-base",children:[e.jsx(Ji,{className:"h-4 w-4"})," Änderungsverlauf (",ge.length,")"]})})}),e.jsx(nt,{children:e.jsx(Rs,{className:"pt-0",children:ge.length===0?e.jsx("p",{className:"text-sm text-muted-foreground",children:"Noch keine manuellen Anpassungen."}):e.jsx("div",{className:"space-y-2",children:ge.map(w=>e.jsxs("div",{className:"rounded-lg border p-3 text-sm",children:[e.jsxs("div",{className:"font-medium",children:[w.room_label," ·"," ",w.action==="created"?"angelegt":w.action==="updated"?"geändert":"entfernt"]}),e.jsxs("div",{className:"text-xs text-muted-foreground",children:[w.old_check_in&&`vorher ${ps(w.old_check_in)}–${ps(w.old_check_out)} · `,w.new_check_in&&`neu ${ps(w.new_check_in)}–${ps(w.new_check_out)} · `,w.changed_by_name??"Unbekannt"," ·"," ",new Date(w.changed_at).toLocaleString("de-DE",{dateStyle:"short",timeStyle:"short"})]}),w.note&&e.jsxs("div",{className:"mt-1 text-xs italic",children:["„",w.note,'"']})]},w.id))})})})]})})]}),e.jsx(We,{open:!!_e,onOpenChange:w=>!w&&J(null),children:e.jsxs(Qe,{children:[e.jsx(Ye,{children:e.jsxs(Je,{children:["Hinweis für ",_e?sn(_e.room_label,!1):""]})}),e.jsx("p",{className:"text-xs text-muted-foreground",children:"Gilt nur für diese Zeile und ersetzt dort den automatischen Hinweis — in Liste und Export, deutsch wie englisch."}),e.jsx(qs,{rows:3,value:Ae,onChange:w=>qe(w.target.value),placeholder:"z. B. übernachtet nur eine Nacht, Rest privat"}),e.jsxs(gs,{children:[e.jsx(z,{variant:"ghost",onClick:async()=>{_e&&await Ee(Qt(_e),{note_text:null}),J(null)},children:"Zurück auf automatisch"}),e.jsx(z,{onClick:async()=>{_e&&await Ee(Qt(_e),{note_text:Ae}),J(null)},children:"Speichern"})]})]})}),e.jsx(We,{open:!!Z,onOpenChange:w=>!w&&H(null),children:e.jsxs(Qe,{children:[e.jsx(Ye,{children:e.jsxs(Je,{children:["Nächte anpassen — ",Z==null?void 0:Z.room_label]})}),e.jsxs("div",{className:"grid gap-3",children:[e.jsxs("div",{className:"grid grid-cols-2 gap-3",children:[e.jsxs("div",{className:"grid gap-1.5",children:[e.jsx(U,{children:"Check-in"}),e.jsx(te,{type:"date",value:L.check_in,onChange:w=>g({...L,check_in:w.target.value})})]}),e.jsxs("div",{className:"grid gap-1.5",children:[e.jsx(U,{children:"Check-out"}),e.jsx(te,{type:"date",value:L.check_out,onChange:w=>g({...L,check_out:w.target.value})})]})]}),e.jsxs("div",{className:"grid gap-1.5",children:[e.jsx(U,{children:"Notiz (warum?)"}),e.jsx(qs,{rows:2,value:L.note,onChange:w=>g({...L,note:w.target.value}
127),placeholder:"z. B. Team reist zwei Nächte früher an"})]})]}),e.jsxs(gs,{children:[e.jsx(z,{variant:"outline",onClick:()=>H(null),children:"Abbrechen"}),e.jsxs(z,{onClick:vs,disabled:E,children:[E&&e.jsx($e,{className:"mr-1.5 h-4 w-4 animate-spin"}),"Speichern"]})]})]})}),e.jsxs(Ss,{children:[e.jsxs(Mt,{className:"flex flex-row items-center justify-between pb-3",children:[e.jsx(Gt,{className:"text-base",children:"Eigene Nächte (Team, Guides, Sonderfälle)"}),e.jsxs(We,{open:j,onOpenChange:d,children:[e.jsx(ua,{asChild:!0,children:e.jsxs(z,{size:"sm",children:[e.jsx(Es,{className:"mr-1.5 h-4 w-4"})," Nacht hinzufügen"]})}),e.jsxs(Qe,{children:[e.jsx(Ye,{children:e.jsx(Je,{children:"Übernachtung manuell erfassen"})}),S&&e.jsxs("p",{className:"text-sm text-muted-foreground",children:["Diese Nacht wird der Unterkunft ",e.jsx("span",{className:"font-medium",children:S})," zugeordnet und erscheint nur dort."]}),e.jsxs("div",{className:"grid gap-3",children:[e.jsxs("div",{className:"grid gap-1.5",children:[e.jsx(U,{children:"Name"}),e.jsx(te,{value:u.guest_name,onChange:w=>I({...u,guest_name:w.target.value}),placeholder:"z. B. Canaves, Sebastian (Team)"})]}),e.jsxs("div",{className:"grid grid-cols-2 gap-3",children:[e.jsxs("div",{className:"grid gap-1.5",children:[e.jsx(U,{children:"Zimmer-Nr."}),e.jsx(te,{value:u.room_label,onChange:w=>I({...u,room_label:w.target.value})})]}),e.jsxs("div",{className:"grid gap-1.5",children:[e.jsx(U,{children:"Zimmertyp"}),e.jsxs(Ie,{value:u.room_type,onValueChange:w=>I({...u,room_type:w}),children:[e.jsx(Oe,{children:e.jsx(Ve,{})}),e.jsxs(Ue,{children:[e.jsx(O,{value:"EZ",children:"EZ"}),e.jsx(O,{value:"DZ",children:"DZ"}),e.jsx(O,{value:"Suite",children:"Suite"})]})]})]})]}),e.jsxs("div",{className:"grid grid-cols-2 gap-3",children:[e.jsxs("div",{className:"grid gap-1.5",children:[e.jsx(U,{children:"Check-in"}),e.jsx(te,{type:"date",value:u.check_in,onChange:w=>I({...u,check_in:w.target.value})})]}),e.jsxs("div",{className:"grid gap-1.5",children:[e.jsx(U,{children:"Check-out"}),e.jsx(te,{type:"date",value:u.check_out,onChange:w=>I({...u,check_out:w.target.value})})]})]}),e.jsxs("div",{className:"grid gap-1.5",children:[e.jsx(U,{children:"Personen"}),e.jsx(te,{type:"number",min:1,value:u.pax,onChange:w=>I({...u,pax:Number(w.target.value)})})]}),e.jsxs("div",{className:"grid gap-1.5",children:[e.jsx(U,{children:"Notiz"}),e.jsx(qs,{value:u.note,onChange:w=>I({...u,note:w.target.value}),rows:2})]})]}),e.jsxs(gs,{children:[e.jsx(z,{variant:"outline",onClick:()=>d(!1),children:"Abbrechen"}),e.jsxs(z,{onClick:as,disabled:E,children:[E&&e.jsx($e,{className:"mr-1.5 h-4 w-4 animate-spin"}),"Speichern"]})]})]})]})]}),e.jsx(Rs,{children:A.filter(w=>!w.accommodation_key||w.accommodation_key===x).length===0?e.jsx("p",{className:"text-sm text-muted-foreground",children:"Noch keine eigenen Nächte für diese Unterkunft erfasst. Diese fließen automatisch in Liste und Summen ein."}):e.jsx("div",{className:"space-y-2",children:A.filter(w=>!w.accommodation_key||w.accommodation_key===x).map(w=>e.jsxs("div",{className:"flex items-center justify-between rounded-lg border p-3 text-sm",children:[e.jsxs("span",{children:[e.jsx("span",{className:"font-medium",children:w.guest_name}),e.jsxs("span",{className:"text-muted-foreground",children:[" ","· ",w.room_type??""," ",w.room_label?`Zi. ${w.room_label}`:""," · ",ps(w.check_in)," –"," ",ps(w.check_out)," · ",w.pax," Pers."]})]}),e.jsx(z,{variant:"ghost",size:"icon",onClick:()=>Ge(w.id),children:e.jsx(bs,{className:"h-4 w-4 text-destructive"})})]},w.id))})})]})]})}function Rc({tripId:s}){const[n,a]=t.useState([]),[b,f]=t.useState(!0);t.useEffect(()=>{let h=!1;return(async()=>{f(!0);const[{data:k},{data:C}]=await Promise.all([_.from("trips").select("start_date").eq("id",s).maybeSingle(),_.from("participants").select("id,first_name,last_name,is_guide,questionnaire_responses,booking_id,bookings(status)").eq("trip_id",s)]),N=(k==null?void 0:k.start_date)??null,v=(C??[]).filter(o=>{var l;return!o.is_guide&&((l=o.bookings)==null?void 0:l.status)!=="cancelled"}),G=[];for(const o of v){const l=(o.questionnaire_responses??{})._travel_form??{},V=l.arrival_date||null;!N||!V||V>=N||G.push({participant_id:o.id,name:`${o.first_name} ${o.last_name}`,arrival_date:V,arrival_flight:l.arrival_flight_number||null,arrival_time:l.arrival_time||null,pre_trip_type:l.pre_trip_type||null,pre_trip_name:l.pre_trip_name||null,pre_trip_address:l.pre_trip_address||null,pre_trip_time:l.pre_trip_time||null,pre_trip_phone:l.pre_trip_phone||null,pre_trip_pickup:l.pre_trip_pickup||null,pre_trip_notes:l.pre_trip_notes||null})}let T=new Set;if(G.length>0){const{data:o}=await _.from("participant_addon_purchases").select("participant_id,booked_by_participant_id,payment_status,trip_add
127ons!inner(addon_type,stay_timing)").eq("trip_id",s);T=new Set((o??[]).filter(l=>{var V,A;return((V=l.trip_addons)==null?void 0:V.addon_type)==="accommodation"&&((A=l.trip_addons)==null?void 0:A.stay_timing)==="pre"&&!["cancelled","refunded"].includes(l.payment_status??"")}).flatMap(l=>[l.participant_id,l.booked_by_participant_id].filter(Boolean)))}h||(a(G.filter(o=>!T.has(o.participant_id)).sort((o,l)=>(o.arrival_date??"").localeCompare(l.arrival_date??""))),f(!1))})(),()=>{h=!0}},[s]);const i=t.useMemo(()=>n.filter(h=>!Ma(h)),[n]),x=()=>{const h=["Gast","Ankunft","Flug","Uhrzeit","Art","Unterkunft / Beschreibung","Adresse","Treffzeit","Telefon","Abholung","Notiz"],c=n.map(v=>[v.name,v.arrival_date?ps(v.arrival_date):"",v.arrival_flight??"",v.arrival_time??"",$r(v.pre_trip_type),v.pre_trip_name??"",v.pre_trip_address??"",v.pre_trip_time??"",v.pre_trip_phone??"",Br(v.pre_trip_pickup),v.pre_trip_notes??""].map(G=>`"${String(G).replace(/"/g,'""')}"`).join(";")),k=new Blob([`\uFEFF${[h.join(";"),...c].join(`
128`)}`],{type:"text/csv;charset=utf-8;"}),C=URL.createObjectURL(k),N=document.createElement("a");N.href=C,N.download=`standorte-vor-der-reise-${s.slice(0,8)}.csv`,N.click(),URL.revokeObjectURL(C)};return b||n.length===0?null:e.jsxs(Ss,{children:[e.jsxs(Mt,{className:"flex flex-row items-center justify-between gap-3",children:[e.jsxs("div",{children:[e.jsxs(Gt,{className:"flex items-center gap-2 text-base",children:[e.jsx(Dn,{className:"h-4 w-4"})," Eigene Arrangements vor der Reise"]}),e.jsx("p",{className:"text-xs text-muted-foreground mt-1",children:"Gäste, die früher anreisen und selbst übernachten — nicht Teil der Hotelliste."})]}),e.jsxs(z,{variant:"outline",size:"sm",onClick:x,children:[e.jsx(da,{className:"h-4 w-4 mr-1"})," Standorte-CSV"]})]}),e.jsxs(Rs,{className:"space-y-3",children:[e.jsxs(ga,{children:[e.jsx(fa,{children:e.jsxs(ct,{children:[e.jsx(rs,{children:"Gast"}),e.jsx(rs,{children:"Ankunft"}),e.jsx(rs,{children:"Art"}),e.jsx(rs,{children:"Wo"}),e.jsx(rs,{children:"Kontakt"}),e.jsx(rs,{children:"Abholung"})]})}),e.jsx(ja,{children:n.map(h=>e.jsxs(ct,{children:[e.jsx(ss,{className:"font-medium",children:h.name}),e.jsxs(ss,{className:"text-xs",children:[h.arrival_date?ps(h.arrival_date):"—",h.arrival_flight&&e.jsx("div",{className:"text-muted-foreground",children:h.arrival_flight})]}),e.jsx(ss,{className:"text-xs",children:Ma(h)?$r(h.pre_trip_type):e.jsx(Xe,{variant:"outline",children:"offen"})}),e.jsxs(ss,{className:"text-xs",children:[h.pre_trip_name&&e.jsx("div",{children:h.pre_trip_name}),h.pre_trip_address&&e.jsx("div",{className:"text-muted-foreground",children:h.pre_trip_address}),h.pre_trip_time&&e.jsxs("div",{className:"text-muted-foreground",children:["ab ",h.pre_trip_time]}),!Ma(h)&&e.jsx("span",{className:"text-muted-foreground",children:"noch nicht angegeben"})]}),e.jsx(ss,{className:"text-xs",children:h.pre_trip_phone??"—"}),e.jsx(ss,{className:"text-xs",children:Br(h.pre_trip_pickup)})]},h.participant_id))})]}),i.length>0&&e.jsxs("p",{className:"text-xs text-muted-foreground",children:[i.length," Gäste haben ihren Aufenthalt noch nicht angegeben — sie erhalten die automatische Erinnerung zur früheren Anreise."]}),n.some(h=>h.pre_trip_notes)&&e.jsx("div",{className:"space-y-1 text-xs text-muted-foreground",children:n.filter(h=>h.pre_trip_notes).map(h=>e.jsxs("div",{children:[e.jsxs("span",{className:"font-medium text-foreground",children:[h.name,":"]})," ",h.pre_trip_notes]},`note-${h.participant_id}`))})]})]})}const Tc=["EUR","USD","CAD","GBP","CHF","ISK","NOK","SEK","ZAR","NAD","BWP","UGX","CRC"],Xa=[{value:"bank_transfer",label:"Überweisung"},{value:"paypal",label:"PayPal"},{value:"credit_card",label:"Kreditkarte"},{value:"amex",label:"AMEX"},{value:"cash",label:"Bar"},{value:"wise",label:"Wise"},{value:"other",label:"Sonstige"}],Ka=[{value:"0",label:"0%"},{value:"7",label:"7%"},{value:"10",label:"10%"},{value:"19",label:"19%"},{value:"24",label:"24%"},{value:"custom",label:"Manuell"}],$c=s=>{var n;return s?((n=Xa.find(a=>a.value===s))==null?void 0:n.label)||s:null},ba=s=>{if(typeof s=="number"&&Number.isFinite(s))return s;if(typeof s=="string"){const n=s.replace(",",".").trim();if(!n)return null;const a=Number(n);return Number.isFinite(a)?a:null}return null};function Bc({tripId:s}){const[n,a]=t.useState(""),{partners:b}=un(),{expenses:f,isLoading:i}=ai(s),{convertToEUR:x}=vr(),h=ri(),c=ni(),k=ii(),C=li(),[N,v]=t.useState(!1),[G,T]=t.useState(null),[o,l]=t.useState(null),[V,A]=t.useState("0"),[q,y]=t.useState(!1),[W,j]=t.useState(!1),d=t.useRef(null),[u,I]=t.useState(!1),[E,$]=t.useState(null),[ge,be]=t.useState(null),[Z,H]=t.useState(null),[L,g]=t.useState(!1),[r,m]=t.useState({trip_id:s,description:"",amount:0,currency:"EUR",expense_date:Ks(),due_date:null,partner_id:null,notes:null,payment_method:null,vat_rate:0,vat_amount:0,net_amount:0,invoice_file_path:null}),X=t.useMemo(()=>f.filter(S=>{var P;return S.description.toLowerCase().includes(n.toLowerCase())||((P=b.find(ie=>ie.id===S.partner_id))==null?void 0:P.name.toLowerCase().includes(n.toLowerCase()))}),[f,n,b]),p=f.some(S=>S.currency!=="EUR"),ne=f.reduce((S,P)=>S+x(Number(P.amount),P.currency),0),le=f.filter(S=>S.is_paid).reduce((S,P)=>S+x(Number(P.amount),P.currency),0),K=ne-le,M=(S,P="EUR")=>new Intl.NumberFormat("de-DE",{style:"currency",currency:P}).format(S),ee=S=>S?new Date(S).toLocaleDateString("de-DE"):"–",he=(S,P)=>{const ie=P>0?S/(1+P/100):S,Se=S-ie;return{net_amount:Math.round(ie*100)/100,vat_amount:Math.round(Se*100)/100}},we=S=>{const{net_amount:P,vat_amount:ie}=he(S,r.vat_rate||0);m({...r,amount:S,net_amount:P,vat_amount:ie})},De=S=>{const{net_amount:P,vat_amount:ie}=he(r.amount,S);m({...r,vat_rate:S,net_amount:P,vat_amount:ie})},_e=()=>{m({trip_id:s,description:"",amount:0,currency:"EUR",expense_date:Ks(),due_date:null,partner_id:null,notes:null,payment_method:null,vat_rate:0,vat_amount:0,net_amount:0,invoice_file_path:null}),A("0")},J=()=>{_e(),v(!0)},Ae=S=>{const P=S.vat_rate||0,ie=Ka.find(Se=>Se.value===String(P));A(ie?String(P):"custom"),m({trip_id:s,description:S.description,amount:S.amount,currency:S.currency,expense_date:S.expense_date,due_date:S.due_date,partner_id:S.partner_id,notes:S.notes,payment_method:S.payment_method,vat_rate:S.vat_rate,vat_amount:S.vat_amount,net_amount:S.net_amount,invoice_file_path:S.invoice_file_path}),T(S)},qe=async()=>{G?(await c.mutateAsync({id:G.id,description:r.description,amount:r.amount,currency:r.currency,expense_date:r.expense_date,due_date:r.due_date,partner_id:r.partner_id,notes:r.notes,payment_method:r.payment_method,vat_rate:r.vat_rate,vat_amount:r.vat_amount,net_amount:r.net_amount,invoice_file_path:r.invoice_file_path}),T(null)):(await h.mutateAsync(r),v(!1)),_e()},Be=async()=>{o&&(await k.mutateAsync(o),l(null))},Ke=async S=>{await C.mutateAsync({id:S.id,isPaid:!S.is_paid})},Ce=async S=>{var ie;const P=(ie=S.target.files)==null?void 0:ie[0];if(P){if(P.size>10*1024*1024){Y.error("Datei zu groß (max. 10MB)");return}y(!0);try{const Se=P.name.split(".").pop(),R=`${s}/${crypto.randomUUID()}.${Se}`,{error:ce}=await _.storage.from("partner-documents").upload(R,P);if(ce)throw ce;m({...r,invoice_file_path:R}),Y.success("Rechnung hochgeladen")}catch(Se){Y.error("Upload fehlgeschlagen: "+Se.message)}finally{y(!1),d.current&&(d.current.value="")}}},xe=async()=>
128{if(!r.invoice_file_path){Y.error("Bitte zuerst eine Rechnung hochladen");return}j(!0);try{const{data:S,error:P}=await _.functions.invoke("extract-invoice-data",{body:{bucket:"partner-documents",filePath:r.invoice_file_path}});if(P)throw P;const ie=S==null?void 0:S.extracted;if(!ie){Y.error("Keine Daten erkannt – bitte manuell eintragen");return}if(ie.items&&Array.isArray(ie.items)&&ie.items.length>0){const Se=ie.items.map(R=>({description:(R.description||"").toString().trim(),net_amount:ba(R.net_amount),vat_rate:ba(R.vat_rate),vat_amount:ba(R.vat_amount),gross_amount:ba(R.gross_amount),selected:!0}));$({invoice_date:ie.invoice_date||null,vendor_name:ie.vendor_name||null,currency:ie.currency||null,items:Se}),be(r.partner_id),H(r.payment_method),I(!0),v(!1),T(null)}else{const Se={};if(ie.gross_amount!=null&&(Se.amount=ie.gross_amount),ie.vat_rate!=null){Se.vat_rate=ie.vat_rate;const R=Ka.find(ce=>ce.value===String(ie.vat_rate));A(R?String(ie.vat_rate):"custom")}ie.vat_amount!=null&&(Se.vat_amount=ie.vat_amount),ie.net_amount!=null&&(Se.net_amount=ie.net_amount),ie.invoice_date&&(Se.expense_date=ie.invoice_date),ie.description&&!r.description&&(Se.description=ie.description),m(R=>({...R,...Se})),Y.success("AI-Vorschlag übernommen – bitte prüfen & bestätigen")}}catch(S){Y.error("AI-Extraktion fehlgeschlagen: "+S.message)}finally{j(!1)}},ms=S=>{if(!E)return;const P=[...E.items];P[S]={...P[S],selected:!P[S].selected},$({...E,items:P})},us=()=>{if(!E)return;const S=E.items.every(P=>P.selected);$({...E,items:E.items.map(P=>({...P,selected:!S}))})},Q=async()=>{if(!E)return;const S=E.items.filter(P=>P.selected);if(S.length===0){Y.error("Bitte mindestens eine Position auswählen");return}g(!0);try{for(const P of S){const ie=P.gross_amount||0,Se=P.net_amount||ie,R=P.vat_amount||0,ce=P.vat_rate||0;await h.mutateAsync({trip_id:s,description:P.description||"Position",amount:ie,currency:E.currency||r.currency||"EUR",expense_date:E.invoice_date||Ks(),partner_id:ge,payment_method:Z,vat_rate:ce,vat_amount:R,net_amount:Se,invoice_file_path:r.invoice_file_path,notes:null,due_date:null})}Y.success(`${S.length} Position${S.length>1?"en":""} übernommen`),I(!1),$(null),_e()}catch(P){Y.error("Fehler beim Anlegen: "+P.message)}finally{g(!1)}},ue=r.description.trim()!==""&&r.amount>0,de=h.isPending||c.isPending;return i?e.jsx("div",{className:"flex min-h-[200px] items-center justify-center",children:e.jsx($e,{className:"h-8 w-8 animate-spin text-primary"})}):e.jsxs("div",{className:"space-y-6",children:[e.jsxs("div",{className:"grid gap-4 sm:grid-cols-3",children:[e.jsxs("div",{className:"glass-card p-4",children:[e.jsx("p",{className:"text-sm text-muted-foreground",children:"Gesamt Ausgaben"}),e.jsx("p",{className:"mt-1 text-2xl font-bold text-foreground",children:M(ne)}),p&&e.jsx("p",{className:"text-xs text-muted-foreground",children:"(umgerechnet)"})]}),e.jsxs("div",{className:"glass-card p-4",children:[e.jsx("p",{className:"text-sm text-muted-foreground",children:"Bezahlt"}),e.jsx("p",{className:"mt-1 text-2xl font-bold text-emerald-500",children:M(le)}),p&&e.jsx("p",{className:"text-xs text-muted-foreground",children:"(umgerechnet)"})]}),e.jsxs("div",{className:"glass-card p-4",children:[e.jsx("p",{className:"text-sm text-muted-foreground",children:"Offen"}),e.jsx("p",{className:"mt-1 text-2xl font-bold text-amber-500",children:M(K)}),p&&e.jsx("p",{className:"text-xs text-muted-foreground",children:"(umgerechnet)"})]})]}),e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsxs("div",{className:"relative max-w-md flex-1",children:[e.jsx(wt,{className:"absolute left-3 top-1/2 h-4 w-4 -translate-y-1/2 text-muted-foreground"}),e.jsx(te,{type:"text",placeholder:"Ausgaben suchen...",value:n,onChange:S=>a(S.target.value),className:"pl-10 rounded-xl bg-muted/50 border-0"})]}),e.jsxs(z,{className:"gap-2 rounded-xl",onClick:J,children:[e.jsx(Es,{className:"h-4 w-4"}),"Ausgabe hinzufügen"]})]}),e.jsx("div",{className:"glass-card overflow-hidden",children:e.jsx("div",{className:"overflow-x-auto",children:e.jsxs("table",{className:"w-full",children:[e.jsx("thead",{children:e.jsxs("tr",{className:"border-b border-border bg-muted/30",children:[e.jsx("th",{className:"px-5 py-4 text-left text-sm font-medium text-muted-foreground",children:"Beschreibung"}),e.jsx("th",{className:"px-5 py-4 text-left text-sm font-medium text-muted-foreground",children:"Partner"}),e.jsx("th",{className:"px-5 py-4 text-left text-sm font-medium text-muted-foreground",children:"Datum"}),e.jsx("th",{className:"px-5 py-4 text-right text-sm font-medium text-muted-foreground",children:"Brutto"}),e.jsx("th",{className:"px-5 py-4 text-right text-sm font-medium text-muted-foreground",children:"MwSt"}),e.jsx("th",{className:"px-5 py-4 text-center text-sm font-medium text-muted-foreground",children:"Status"}),e.jsx("th",{className:"px-5 py-4 text-center text-sm font-medium text-muted-foreground",children:"Zahlungsart"}),e.jsx("th",{className:"px-5 py-4 text-right text-sm font-medium text-muted-foreground",children:"Aktionen"})]})}),e.jsx("tbody",{children:X.map(S=>{const P=b.find(R=>R.id===S.partner_id),ie=S.currency!=="EUR",Se=ie?x(Number(S.amount),S.currency):null;return e.jsxs("tr",{className:"border-b border-border/50 transition-colors hover:bg-muted/20",children:[e.jsx("td",{className:"px-5 py-4",children:e.jsxs("div",{className:"flex items-center gap-3",children:[e.jsx("div",{className:"flex h-10 w-10 items-center justify-center rounded-xl bg-red-500/10",children:e.jsx(Jt,{className:"h-5 w-5 text-red-400"})}),e.jsxs("div",{children:[e.jsx("p",{className:"font-medium text-foreground",children:S.description}),S.notes&&e.jsx("p",{className:"text-sm text-muted-foreground line-clamp-1",children:S.notes}),S.invoice_file_path&&e.jsxs("span",{className:"inline-flex items-center gap-1 text-xs text-primary",children:[e.jsx($s,{className:"h-3 w-3"})," Rechnung"]})]})]})}),e.jsx("td",{className:"px-5 py-4",children:P?e.jsxs("div",{className:"flex items-center gap-2 text-sm text-foreground",children:[e.jsx(bt,{className:"h-4 w-4 text-muted-foreground"}),P.name]}):e.jsx("span",{className:"text-sm text-muted-foreground",children:"–"})}),e.jsx("td",{className:"px-5 py-4",children:e.jsxs("div",{className:"space-y-1",children:[e.jsxs("div",{className:"flex items-center gap-2 text-sm text-foreground",children:[e.jsx(kt,{className:"h-4 w-4 text-muted-foreground"}),ee(S.expense_date)]}),S.due_date&&e.jsxs("p",{className:"text-xs text-muted-foreground",children:["Fällig: ",ee(S.due_date)]})]})}),e.jsxs("td",{className:"px-5 py-4 text-right",children:[e.jsx("span",{className:"font-semibold text-foreground",children:M(S.amount,S.currency)}),ie&&Se!=null&&e.jsxs("p",{className:"text-xs text-muted-foreground",children:["~",M(Se)]})]}),e.jsx("td",{className:"px-5 py-4 text-right",children:S.vat_rate>0?e.jsxs("div",{children:[e.jsxs("span",{className:"text-sm text-foreground",children:[S.vat_rate,"%"]}),e.jsx("p",{className:"text-xs text-muted-foreground",children:M(S.vat_amount,S.currency)})]}):e.jsx("span",{className:"text-sm text-muted-foreground",children:"–"})}),e.jsx("td",{className:"px-5 py-4",children:e.jsx("div",{className:"flex justify-center",children:e.jsx("button",{onClick:()=>Ke(S),className:`inline-flex items-center gap-1.5 rounded-full px-3 py-1 text-sm font-medium transition-colors ${S.is_paid?"bg-emerald-500/10 text-emerald-500 hover:bg-emerald-500/20":"bg-
128amber-500/10 text-amber-500 hover:bg-amber-500/20"}`,children:S.is_paid?e.jsxs(e.Fragment,{children:[e.jsx(tt,{className:"h-3.5 w-3.5"}),"Bezahlt"]}):e.jsxs(e.Fragment,{children:[e.jsx(er,{className:"h-3.5 w-3.5"}),"Offen"]})})})}),e.jsx("td",{className:"px-5 py-4",children:e.jsx("div",{className:"flex justify-center",children:S.payment_method?e.jsxs(Xe,{variant:"secondary",className:"gap-1",children:[e.jsx(Kt,{className:"h-3 w-3"}),$c(S.payment_method)]}):e.jsx("span",{className:"text-sm text-muted-foreground",children:"–"})})}),e.jsx("td",{className:"px-5 py-4",children:e.jsxs("div",{className:"flex justify-end gap-2",children:[e.jsx(z,{variant:"ghost",size:"icon",className:"h-8 w-8 rounded-lg",onClick:()=>Ae(S),children:e.jsx(Ta,{className:"h-4 w-4"})}),e.jsx(z,{variant:"ghost",size:"icon",className:"h-8 w-8 rounded-lg text-destructive hover:text-destructive",onClick:()=>l(S.id),children:e.jsx(bs,{className:"h-4 w-4"})})]})})]},S.id)})})]})})}),X.length===0&&e.jsxs("div",{className:"glass-card p-12 text-center",children:[e.jsx(Jt,{className:"mx-auto h-12 w-12 text-muted-foreground"}),e.jsx("h3",{className:"mt-4 text-lg font-medium text-foreground",children:"Keine Ausgaben erfasst"}),e.jsx("p",{className:"mt-1 text-muted-foreground",children:"Erfassen Sie Ausgaben für Hotels, Guides, Transport und andere Kosten."})]}),e.jsx(We,{open:N||!!G,onOpenChange:S=>{S||(v(!1),T(null),_e())},children:e.jsxs(Qe,{className:"glass-modal sm:max-w-lg max-h-[90vh] overflow-y-auto",children:[e.jsx(Ye,{children:e.jsxs(Je,{className:"flex items-center gap-2",children:[e.jsx(Jt,{className:"h-5 w-5 text-primary"}),G?"Ausgabe bearbeiten":"Neue Ausgabe"]})}),e.jsxs("div",{className:"space-y-4 py-4",children:[e.jsxs("div",{className:"space-y-2",children:[e.jsx(U,{htmlFor:"description",children:"Beschreibung *"}),e.jsx(te,{id:"description",value:r.description,onChange:S=>m({...r,description:S.target.value}),placeholder:"z.B. Hotelübernachtung, Busmiete, etc.",className:"rounded-xl"})]}),e.jsxs("div",{className:"grid grid-cols-2 gap-4",children:[e.jsxs("div",{className:"space-y-2",children:[e.jsx(U,{htmlFor:"amount",children:"Bruttobetrag *"}),e.jsx(te,{id:"amount",type:"number",min:"0",step:"0.01",value:r.amount,onChange:S=>we(parseFloat(S.target.value)||0),className:"rounded-xl"})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(U,{htmlFor:"currency",children:"Währung"}),e.jsxs(Ie,{value:r.currency,onValueChange:S=>m({...r,currency:S}),children:[e.jsx(Oe,{className:"rounded-xl",children:e.jsx(Ve,{})}),e.jsx(Ue,{children:Tc.map(S=>e.jsx(O,{value:S,children:S},S))})]})]})]}),e.jsxs("div",{className:"rounded-lg border border-border/50 p-3 space-y-3 bg-muted/20",children:[e.jsx("p",{className:"text-sm font-medium text-foreground",children:"MwSt-Angaben"}),e.jsxs("div",{className:"grid grid-cols-3 gap-3",children:[e.jsxs("div",{className:"space-y-1",children:[e.jsx(U,{className:"text-xs",children:"MwSt-Satz"}),e.jsxs(Ie,{value:V,onValueChange:S=>{A(S),S!=="custom"&&De(parseFloat(S))},children:[e.jsx(Oe,{className:"rounded-xl h-9",children:e.jsx(Ve,{})}),e.jsx(Ue,{children:Ka.map(S=>e.jsx(O,{value:S.value,children:S.label},S.value))})]}),V==="custom"&&e.jsx(te,{type:"number",min:"0",step:"0.1",value:r.vat_rate,onChange:S=>De(parseFloat(S.target.value)||0),className:"rounded-xl h-9 mt-1",placeholder:"%"})]}),e.jsxs("div",{className:"space-y-1",children:[e.jsx(U,{className:"text-xs",children:"Netto"}),e.jsx(te,{type:"number",step:"0.01",value:r.net_amount,onChange:S=>{const P=parseFloat(S.target.value)||0,ie=r.amount-P;m({...r,net_amount:P,vat_amount:Math.max(0,Math.round(ie*100)/100)})},className:"rounded-xl h-9"})]}),e.jsxs("div",{className:"space-y-1",children:[e.jsx(U,{className:"text-xs",children:"MwSt €"}),e.jsx(te,{type:"number",step:"0.01",value:r.vat_amount,readOnly:!0,className:"rounded-xl h-9 bg-muted/50"})]})]})]}),e.jsxs("div",{className:"rounded-lg border border-border/50 p-3 space-y-2 bg-muted/20",children:[e.jsx("p",{className:"text-sm font-medium text-foreground",children:"Rechnung"}),e.jsxs("div",{className:"flex gap-2",children:[e.jsx("input",{ref:d,type:"file",accept:".pdf,.jpg,.jpeg,.png,.webp",onChange:Ce,className:"hidden"}),e.jsxs(z,{type:"button",variant:"outline",size:"sm",className:"rounded-xl gap-1",onClick:()=>{var S;return(S=d.current)==null?void 0:S.click()},disabled:q,children:[q?e.jsx($e,{className:"h-3 w-3 animate-spin"}):e.jsx(_t,{className:"h-3 w-3"}),r.invoice_file_path?"Ersetzen":"Hochladen"]}),r.invoice_file_path&&e.jsxs(z,{type:"button",variant:"outline",size:"sm",className:"rounded-xl gap-1",onClick:xe,disabled:W,children:[W?e.jsx($e,{className:"h-3 w-3 animate-spin"}):e.jsx(Rt,{className:"h-3 w-3"}),"AI auslesen"]}),r.invoice_file_path&&e.jsxs(Xe,{variant:"secondary",className:"gap-1 text-xs",children:[e.jsx($s,{className:"h-3 w-3"}),"Hochgeladen"]})]})]}),e.jsxs("div",{className:"grid grid-cols-2 gap-4",children:[e.jsxs("div",{className:"space-y-2",children:[e.jsx(U,{htmlFor:"partner",children:"Partner (optional)"}),e.jsxs(Ie,{value:r.partner_id||"none",onValueChange:S=>m({...r,partner_id:S==="none"?null:S}),children:[e.jsx(Oe,{className:"rounded-xl",children:e.jsx(Ve,{placeholder:"Partner auswählen..."})}),e.jsxs(Ue,{children:[e.jsx(O,{value:"none",children:"Kein Partner"}),b.map(S=>e.jsx(O,{value:S.id,children:S.name},S.id))]})]})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(U,{htmlFor:"payment_method",children:"Zahlungsart"}),e.jsxs(Ie,{value:r.payment_method||"none",onValueChange:S=>m({...r,payment_method:S==="none"?null:S}),children:[e.jsx(Oe,{className:"rounded-xl",children:e.jsx(Ve,{placeholder:"Zahlungsart..."})}),e.jsxs(Ue,{children:[e.jsx(O,{value:"none",children:"Keine Angabe"}),Xa.map(S=>e.jsx(O,{value:S.value,children:S.label},S.value))]})]})]})]}),e.jsxs("div",{className:"grid grid-cols-2 gap-4",children:[e.jsxs("div",{className:"space-y-2",children:[e.jsx(U,{htmlFor:"expense_date",children:"Ausgabedatum"}),e.jsx(te,{id:"expense_date",type:"date",value:r.expense_date,onChange:S=>m({...r,expense_date:S.target.value}),className:"rounded-xl"})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(U,{htmlFor:"due_date",children:"Zahlungsziel (optional)"}),e.jsx(te,{id:"due_date",type:"date",value:r.due_date||"",onChange:S=>m({...r,due_date:S.target.value||null}),className:"rounded-xl"})]})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(U,{htmlFor:"notes",children:"Notizen"}),e.jsx(qs,{id:"notes",value:r.notes||"",onChange:S=>m({...r,notes:S.target.value||null}),placeholder:"Zusätzliche Informationen...",className:"rounded-xl",rows:3})]})]}),e.jsxs(gs,{children:[e.jsx(z,{variant:"outline",className:"rounded-xl",onClick:()=>{v(!1),T(null),_e()},children:"Abbrechen"}),e.jsx(z,{className:"rounded-xl",onClick:qe,disabled:!ue||de,children:de?e.jsxs(e.Fragment,{children:[e.jsx($e,{className:"mr-2 h-4 w-4 animate-spin"}),"Speichern..."]}):G?"Speichern":"Hinzufügen"})]})]})}),e.jsx(mt,{open:!!o,onOpenChange:S=>!S&&l(null),children:e.jsxs(ut,{className:"glass-modal",children:[e.jsxs(ht,{children:[e.jsx(xt,{children:"Ausgabe löschen?"}),e.jsx(pt,{children:"Diese Aktion kann nicht rückgängig gemacht werden. Die Ausgabe wird dauerhaft gelöscht."})]}),e.jsxs(gt,{children:[e.jsx(ft,{className:"rounded-xl",children:"Abbrechen"}),e.jsx(jt,{className:"rounded-xl bg-destructive text-destructive-foreground hover:bg-destructive/90",onClick:Be,children:"Löschen"})]})]})}),e.jsx(We,{open:u,onOpenChange:S=>{S||(I(!1),$(null))},children:e.jsxs(Qe,{className:"glass-modal sm:max-w-2xl max-h-[90vh] overflow-y-auto",children:[e.jsx(Ye,{children:e.jsxs(Je,{className:"flex items-center gap-2",children:[e.jsx(Rt,{className:"h-5 w-5 text-primary"}
128),"AI-Rechnungsanalyse"]})}),E&&e.jsxs("div",{className:"space-y-4 py-2",children:[e.jsxs("div",{className:"flex flex-wrap gap-3 text-sm text-muted-foreground",children:[E.vendor_name&&e.jsxs("span",{className:"flex items-center gap-1",children:[e.jsx(bt,{className:"h-3.5 w-3.5"}),E.vendor_name]}),E.invoice_date&&e.jsxs("span",{className:"flex items-center gap-1",children:[e.jsx(kt,{className:"h-3.5 w-3.5"}),He(E.invoice_date).toLocaleDateString("de-DE")]}),E.currency&&e.jsx(Xe,{variant:"secondary",children:E.currency})]}),e.jsxs("div",{className:"grid grid-cols-2 gap-4",children:[e.jsxs("div",{className:"space-y-1",children:[e.jsx(U,{className:"text-xs",children:"Partner"}),e.jsxs(Ie,{value:ge||"none",onValueChange:S=>be(S==="none"?null:S),children:[e.jsx(Oe,{className:"rounded-xl h-9",children:e.jsx(Ve,{placeholder:"Partner..."})}),e.jsxs(Ue,{children:[e.jsx(O,{value:"none",children:"Kein Partner"}),b.map(S=>e.jsx(O,{value:S.id,children:S.name},S.id))]})]})]}),e.jsxs("div",{className:"space-y-1",children:[e.jsx(U,{className:"text-xs",children:"Zahlungsart"}),e.jsxs(Ie,{value:Z||"none",onValueChange:S=>H(S==="none"?null:S),children:[e.jsx(Oe,{className:"rounded-xl h-9",children:e.jsx(Ve,{placeholder:"Zahlungsart..."})}),e.jsxs(Ue,{children:[e.jsx(O,{value:"none",children:"Keine Angabe"}),Xa.map(S=>e.jsx(O,{value:S.value,children:S.label},S.value))]})]})]})]}),e.jsx("div",{className:"rounded-lg border border-border overflow-hidden",children:e.jsxs("table",{className:"w-full text-sm",children:[e.jsx("thead",{children:e.jsxs("tr",{className:"border-b border-border bg-muted/30",children:[e.jsx("th",{className:"px-3 py-2 text-left w-8",children:e.jsx("button",{onClick:us,className:"text-muted-foreground hover:text-foreground",children:E.items.every(S=>S.selected)?e.jsx(An,{className:"h-4 w-4"}):e.jsx(Xi,{className:"h-4 w-4"})})}),e.jsx("th",{className:"px-3 py-2 text-left font-medium text-muted-foreground",children:"Beschreibung"}),e.jsx("th",{className:"px-3 py-2 text-right font-medium text-muted-foreground",children:"Netto"}),e.jsx("th",{className:"px-3 py-2 text-right font-medium text-muted-foreground",children:"MwSt%"}),e.jsx("th",{className:"px-3 py-2 text-right font-medium text-muted-foreground",children:"MwSt"}),e.jsx("th",{className:"px-3 py-2 text-right font-medium text-muted-foreground",children:"Brutto"})]})}),e.jsx("tbody",{children:E.items.map((S,P)=>e.jsxs("tr",{className:`border-b border-border/50 transition-colors cursor-pointer hover:bg-muted/20 ${S.selected?"":"opacity-40"}`,onClick:()=>ms(P),children:[e.jsx("td",{className:"px-3 py-2",children:e.jsx(Zs,{checked:S.selected,onClick:ie=>ie.stopPropagation(),onCheckedChange:()=>ms(P)})}),e.jsx("td",{className:"px-3 py-2 text-foreground",children:S.description||"–"}),e.jsx("td",{className:"px-3 py-2 text-right text-foreground",children:S.net_amount!=null?M(S.net_amount,E.currency||"EUR"):"–"}),e.jsx("td",{className:"px-3 py-2 text-right text-foreground",children:S.vat_rate!=null?`${S.vat_rate}%`:"–"}),e.jsx("td",{className:"px-3 py-2 text-right text-foreground",children:S.vat_amount!=null?M(S.vat_amount,E.currency||"EUR"):"–"}),e.jsx("td",{className:"px-3 py-2 text-right font-medium text-foreground",children:S.gross_amount!=null?M(S.gross_amount,E.currency||"EUR"):"–"})]},P))}),e.jsx("tfoot",{children:e.jsxs("tr",{className:"bg-muted/20",children:[e.jsxs("td",{colSpan:5,className:"px-3 py-2 text-right font-medium text-foreground",children:["Summe (",E.items.filter(S=>S.selected).length," ausgewählt):"]}),e.jsx("td",{className:"px-3 py-2 text-right font-bold text-foreground",children:M(E.items.filter(S=>S.selected).reduce((S,P)=>S+(P.gross_amount||0),0),E.currency||"EUR")})]})})]})}),e.jsx("p",{className:"text-xs text-muted-foreground",children:"Jede ausgewählte Position wird als separate Ausgabe angelegt – alle verknüpft mit derselben Rechnung."})]}),e.jsxs(gs,{children:[e.jsx(z,{variant:"outline",className:"rounded-xl",onClick:()=>{I(!1),$(null)},children:"Abbrechen"}),e.jsx(z,{className:"rounded-xl gap-2",onClick:Q,disabled:L||!(E!=null&&E.items.some(S=>S.selected)),children:L?e.jsxs(e.Fragment,{children:[e.jsx($e,{className:"h-4 w-4 animate-spin"}),"Übernehme..."]}):e.jsxs(e.Fragment,{children:[e.jsx(tt,{className:"h-4 w-4"}),(E==null?void 0:E.items.filter(S=>S.selected).length)||0," Position",((E==null?void 0:E.items.filter(S=>S.selected).length)||0)!==1?"en":""," übernehmen"]})})]})]})})]})}function Bn(s){const[n,a]=t.useState([]),[b,f]=t.useState([]),[i,x]=t.useState(!0),{toast:h}=aa(),c=t.useCallback(async()=>{try{const{data:j,error:d}
128=await _.from("trip_addons").select("*").eq("trip_id",s).order("position",{ascending:!0}).order("created_at",{ascending:!0});if(d)throw d;a(j||[])}catch(j){console.error("Error fetching addons:",j)}},[s]),k=t.useCallback(async()=>{try{const{data:j,error:d}=await _.from("participant_addon_purchases").select(`
129          *,
130          trip_addons!inner(name)
131        `).eq("trip_id",s).order("created_at",{ascending:!1});if(d)throw d;const u=[...new Set((j||[]).map($=>$.profile_id).filter(Boolean))];let I={};if(u.length>0){const{data:$}=await _.from("participant_profiles").select("id, first_name, last_name, email").in("id",u);$&&(I=$.reduce((ge,be)=>(ge[be.id]=be,ge),{}))}const E=(j||[]).map($=>{var ge;return{id:$.id,addon_id:$.addon_id,trip_id:$.trip_id,profile_id:$.profile_id,participant_id:$.participant_id,booked_by_profile_id:$.booked_by_profile_id??null,booked_by_participant_id:$.booked_by_participant_id??null,quantity:$.quantity,unit_price:$.unit_price,total_price:$.total_price,currency:$.currency,payment_status:$.payment_status,purchased_at:$.purchased_at,created_at:$.created_at,payment_due_date:$.payment_due_date??null,paid_at:$.paid_at??null,payment_reminder_sent_at:$.payment_reminder_sent_at??null,overdue_reminder_sent_at:$.overdue_reminder_sent_at??null,easybill_document_id:$.easybill_document_id,easybill_cancel_document_id:$.easybill_cancel_document_id,invoice_url:$.invoice_url,addon_name:(ge=$.trip_addons)==null?void 0:ge.name,participant_name:$.profile_id&&I[$.profile_id]?`${I[$.profile_id].first_name} ${I[$.profile_id].last_name}`:"Unbekannt",participant_email:$.profile_id&&I[$.profile_id]&&I[$.profile_id].email||void 0}});f(E)}catch(j){console.error("Error fetching purchases:",j)}},[s]),C=t.useCallback(async()=>{x(!0),await Promise.all([c(),k()]),x(!1)},[c,k]);t.useEffect(()=>{C()},[C]);const N=async j=>{try{const{error:d}=await _.from("trip_addons").insert(j);if(d)throw d;return h({title:"Add-on erstellt",description:`${j.name} wurde erfolgreich erstellt.`}),await c(),!0}catch(d){return console.error("Error creating addon:",d),h({title:"Fehler",description:"Add-on konnte nicht erstellt werden.",variant:"destructive"}),!1}},v=async(j,d)=>{try{const{error:u}=await _.from("trip_addons").update(d).eq("id",j);if(u)throw u;return h({title:"Add-on aktualisiert",description:"Die Änderungen wurden gespeichert."}),await c(),!0}catch(u){return console.error("Error updating addon:",u),h({title:"Fehler",description:"Add-on konnte nicht aktualisiert werden.",variant:"destructive"}),!1}},G=async j=>{try{const{count:d}=await _.from("participant_addon_purchases").select("id",{count:"exact",head:!0}).eq("addon_id",j);if((d??0)>0)return h({title:"Löschen nicht möglich",description:`${d} Käufe hängen an diesem Add-on — bitte zuerst stornieren. Alternativ das Add-on einfach deaktivieren.`,variant:"destructive"}),!1;const{error:u}=await _.from("trip_addons").delete().eq("id",j);if(u)throw u;return h({title:"Add-on gelöscht",description:"Das Add-on wurde entfernt."}),await c(),!0}catch(d){console.error("Error deleting addon:",d);const u=(d==null?void 0:d.code)==="23503";return h({title:u?"Löschen nicht möglich":"Fehler",description:u?"An diesem Add-on hängen noch Käufe — bitte zuerst stornieren oder das Add-on deaktivieren.":"Add-on konnte nicht gelöscht werden.",variant:"destructive"}),!1}},T=async(j,d)=>v(j,{is_active:d}),o=async j=>{try{const d=j.map((u,I)=>_.from("trip_addons").update({position:I+1}).eq("id",u.id));return await Promise.all(d),a(j.map((u,I)=>({...u,position:I+1}))),h({title:"Reihenfolge aktualisiert",description:"Die Add-on-Reihenfolge wurde gespeichert."}),!0}catch(d){return console.error("Error reordering addons:",d),h({title:"Fehler",description:"Reihenfolge konnte nicht gespeichert werden.",variant:"destructive"}),await c(),!1}},l=async j=>{try{if(j.easybill_document_id){const{data:d,error:u}=await _.functions.invoke("cancel-easybill-invoice",{body:{easybill_document_id:j.easybill_document_id,purchase_ids:[j.id],refund_reference:"Manuelle Stornierung"}});u?console.error("Error cancelling easybill invoice:",u):console.log("Easybill invoice cancelled:",d)}else{const{error:d}=await _.from("participant_addon_purchases").update({payment_status:"refunded"}).eq("id",j.id);if(d)throw d}try{await _.rpc("log_activity",{p_action:"addon_purchase_cancelled",p_details:JSON.stringify({purchase_id:j.id,addon_name:j.addon_name,participant_name:j.participant_name,total_price:j.total_price,currency:j.currency,easybill_document_id:j.easybill_document_id})})}catch{console.log("Activity logging skipped")}return h({title:"Add-on storniert",description:`Der Kauf von ${j.addon_name} wurde storniert.`}),await k(),!0}catch(d){return console.error("Error cancelling purchase:",d),h({title:"Fehler",description:"Kauf konnte nicht storniert werden.",variant:"destructive"}),!1}},V=async j=>{try{const{error:d}=await _.from("participant_addon_purchases").update({payment_status:"paid",paid_at:new Date().toISOString()}).eq("id",j);if(d)throw d;return h({title:"Als bezahlt markiert",description:'Der Zahlungsstatus wurde auf "bezahlt" gesetzt.'}),await k(),!0}catch(d){return console.error("Error marking purchase as paid:",d),h({title:"Fehler",description:"Status konnte nicht aktualisiert werden.",variant:"destructive"}),!1}},A=async(j,d)=>{try{const{error:u}=await _.from("participant_addon_purchases").update({payment_due_date:d}).eq("id",j);if(u)throw u;return h({title:"Zahlungsziel aktualisiert",description:"Das Fälligkeitsdatum wurde gespeichert."}),await k(),!0}catch(u){return console.error("Error updating due date:",u),h({title:"Fehler",description:"Zahlungsziel konnte nicht gespeichert werden.",variant:"destructive"}),!1}},q=async j=>{try{const{error:d}=await _.from("participant_addon_purchases").delete().eq("id",j);if(d)throw d;return h({title:"Buchung gelöscht",description:"Die Buchung wurde entfernt."}),await k(),!0}catch(d){return console.error("Error deleting purchase:",d),h({title:"Fehler",description:"Buchung konnte nicht gelöscht werden.",variant:"destructive"}),!1}},y=async(j,d)=>{try{const u=`invoices/addon-replacement-${j}.pdf`,{error:I}=await _.storage.from("booking-documents").upload(u,d,{upsert:!0,contentType:"application/pdf"});
131if(I)throw I;const{error:E}=await _.from("participant_addon_purchases").update({invoice_url:u}).eq("id",j);if(E)throw E;const{data:$}=await _.from("participant_addon_purchases").select("participant_id, addon_id, trip_id").eq("id",j).single();if($!=null&&$.participant_id){const{data:ge}=await _.from("participants").select("booking_id").eq("id",$.participant_id).single();if(ge!=null&&ge.booking_id){const{data:be}=await _.from("booking_documents").select("id, url, name").eq("booking_id",ge.booking_id).eq("type","invoice");if(be){const Z=be.find(H=>H.name.toLowerCase().includes("add-on")||H.url.includes(`addon-replacement-${j}`)||H.url.includes(`addon-${j}`));Z&&await _.from("booking_documents").update({url:u}).eq("id",Z.id)}}}return h({title:"Rechnung ersetzt",description:"Die neue Rechnung wurde hochgeladen."}),await k(),!0}catch(u){return console.error("Error replacing invoice:",u),h({title:"Fehler",description:"Rechnung konnte nicht ersetzt werden.",variant:"destructive"}),!1}},W={totalRevenue:b.filter(j=>j.payment_status==="paid").reduce((j,d)=>j+d.total_price,0),pendingRevenue:b.filter(j=>j.payment_status==="pending"||j.payment_status==="invoice").reduce((j,d)=>j+d.total_price,0),paidCount:b.filter(j=>j.payment_status==="paid").length,pendingCount:b.filter(j=>j.payment_status==="pending"||j.payment_status==="invoice").length,refundedCount:b.filter(j=>j.payment_status==="refunded").length};return{addons:n,purchases:b,isLoading:i,purchaseStats:W,fetchAll:C,createAddon:N,updateAddon:v,deleteAddon:G,toggleAddonActive:T,reorderAddons:o,cancelPurchase:l,deletePurchase:q,markPurchaseAsPaid:V,updatePurchaseDueDate:A,replaceInvoice:y}}function Lc(s){const[n,a]=t.useState([]),[b,f]=t.useState(!0),i=t.useCallback(async()=>{f(!0);try{const{data:x,error:h}=await _.rpc("admin_get_lost_addon_purchases");if(h)throw h;const c=(x||[]).map(k=>({...k,price:k.price===null?null:Number(k.price)}));a(s?c.filter(k=>k.trip_id===s):c)}catch(x){console.error("Error fetching lost addon purchases:",x),a([])}finally{f(!1)}},[s]);return t.useEffect(()=>{i()},[i]),{lostPurchases:n,isLoading:b,refetch:i}}function qc({open:s,onOpenChange:n,addon:a,tripId:b,onSave:f}){const[i,x]=t.useState({name:"",description:"",price:0,cost:0,price_type:"per_person",room_type:"none",stay_timing:"pre",limited_spots:null,deadline_days_before:null,minimum_participants:null,is_active:!0,external_url:"",is_highlighted:!1,image_url:null,addon_type:"standard",transfer_partner_id:"",transfer_max_pax_per_vehicle:4,pickup_buffer_minutes:30,default_pre_flight_hours:3,estimated_transfer_minutes:45,default_arrival_hotel:"",default_departure_hotel:""}),[h,c]=t.useState(!1),[k,C]=t.useState([]);t.useEffect(()=>{s&&_.from("partners").select("id, name").order("name").then(({data:l})=>C(l||[]))},[s]),t.useEffect(()=>{x(a?{name:a.name,description:a.description||"",price:a.price,cost:a.cost||0,price_type:a.price_type,room_type:a.room_type||"none",stay_timing:a.stay_timing||"pre",limited_spots:a.limited_spots,deadline_days_before:a.deadline_days_before,minimum_participants:a.minimum_participants??null,is_active:a.is_active,external_url:a.external_url||"",is_highlighted:a.is_highlighted??!1,image_url:a.image_url??null,addon_type:a.addon_type||"standard",transfer_partner_id:a.transfer_partner_id||"",transfer_max_pax_per_vehicle:a.transfer_max_pax_per_vehicle??4,pickup_buffer_minutes:a.pickup_buffer_minutes??30,default_pre_flight_hours:a.default_pre_flight_hours??3,estimated_transfer_minutes:a.estimated_transfer_minutes??45,default_arrival_hotel:a.default_arrival_hotel||"",default_departure_hotel:a.default_departure_hotel||""}:{name:"",description:"",price:0,cost:0,price_type:"per_person",room_type:"none",stay_timing:"pre",limited_spots:null,deadline_days_before:null,minimum_participants:null,is_active:!0,external_url:"",is_highlighted:!1,image_url:null,addon_type:"standard",transfer_partner_id:"",transfer_max_pax_per_vehicle:4,pickup_buffer_minutes:30,default_pre_flight_hours:3,estimated_transfer_minutes:45,default_arrival_hotel:"",default_departure_hotel:""})},[a,s]);const N=i.addon_type.startsWith("airport_transfer"),v=i.addon_type==="airport_transfer_arrival"||i.addon_type==="airport_transfer_roundtrip",G=i.addon_type==="airport_transfer_departure"||i.addon_type==="airport_transfer_roundtrip",T=async()=>{c(!0);const l=await f({trip_id:b,name:i.name,description:i.description||null,price:i.price,cost:i.cost,price_type:i.price_type,room_type:i.addon_type==="accommodation"?i.room_type==="none"?"single":i.room_type:"none",stay_timing:i.addon_type==="accommodation"?i.stay_timing:"pre",limited_spots:i.limited_spots,deadline_days_before:i.deadline_days_before,minimum_participants:i.minimum_participants,is_active:i.is_active,external_url:N?null:i.external_url||null,is_highlighted:i.is_highlighted,image_url:i.image_url,addon_type:i.addon_type,transfer_partner_id:N&&i.transfer_partner_id||null,transfer_max_pax_per_vehicle:N?i.transfer_max_pax_per_vehicle||4:null,pickup_buffer_minutes:N?i.pickup_buffer_minutes||30:null,default_pre_flight_hours:N?i.default_pre_flight_hours||3:null,estimated_transfer_minutes:N?i.estimated_transfer_minutes||45:null,default_arrival_hotel:N&&v&&i.default_arrival_hotel.trim()||null,default_departure_hotel:N&&G&&i.default_departure_hotel.trim()||null});c(!1),l&&n(!1)},o=i.name.trim()!==""&&i.price>=0;return e.jsx(We,{open:s,onOpenChange:n,children:e.jsxs(Qe,{className:"glass-modal sm:max-w-lg max-h-[90vh] overflow-y-auto",children:[e.jsx(Ye,{children:e.jsxs(Je,{className:"flex items-center gap-2",children:[e.jsx(yt,{className:"h-5 w-5 text-primary"}),a?"Add-on bearbeiten":"Neues Add-on erstellen"]})}),e.jsxs("div",{className:"space-y-4 py-4",children:[e.jsxs("div",{className:"space-y-2",children:[e.jsx(U,{children:"Typ"}),e.jsxs(Ie,{value:i.addon_type,onValueChange:l=>x(V=>{const A=l,q=A!=="airport_transfer_arrival"&&A!=="airport_transfer_departure"&&A!=="airport_transfer_roundtrip"&&V.price_type==="per_vehicle"?"per_person":V.price_type;return{...V,addon_type:A,price_type:q,room_type:A==="accommodation"?V.room_type==="none"?"single":V.room_type:"none"}}),children:[e.jsx(Oe,{className:"rounded-xl",children:e.jsx(Ve,{})}),e.jsxs(Ue,{children:[e.jsx(O,{value:"standard",children:"Standard"}
131),e.jsx(O,{value:"accommodation",children:"Unterkunft (Zusatznacht)"}),e.jsx(O,{value:"airport_transfer_arrival",children:"Flughafentransfer — Ankunft"}),e.jsx(O,{value:"airport_transfer_departure",children:"Flughafentransfer — Abflug"}),e.jsx(O,{value:"airport_transfer_roundtrip",children:"Flughafentransfer — Hin & Zurück"})]})]}),N&&e.jsxs("p",{className:"text-xs text-sky-700 dark:text-sky-300 flex items-center gap-1.5",children:[e.jsx($t,{className:"h-3 w-3"}),"Abhol-/Bringzeiten werden automatisch aus den Flugdaten der Teilnehmer berechnet."]})]}),i.addon_type==="accommodation"&&e.jsxs("div",{className:"space-y-2 rounded-xl border border-amber-200 bg-amber-50/50 p-3 dark:border-amber-900/50 dark:bg-amber-950/20",children:[e.jsx(U,{htmlFor:"room_type",children:"Zimmerart"}),e.jsxs(Ie,{value:i.room_type==="none"?"single":i.room_type,onValueChange:l=>x({...i,room_type:l}),children:[e.jsx(Oe,{className:"rounded-xl bg-background",children:e.jsx(Ve,{})}),e.jsxs(Ue,{children:[e.jsx(O,{value:"single",children:"Einzelzimmer"}),e.jsx(O,{value:"shared_half",children:"Halbes Doppelzimmer (Sharing)"})]})]}),e.jsx(U,{htmlFor:"stay_timing",children:"Zeitpunkt"}),e.jsxs(Ie,{value:i.stay_timing,onValueChange:l=>x({...i,stay_timing:l}),children:[e.jsx(Oe,{className:"rounded-xl bg-background",children:e.jsx(Ve,{})}),e.jsxs(Ue,{children:[e.jsx(O,{value:"pre",children:"Vor Reisebeginn (Zusatznacht)"}),e.jsx(O,{value:"post",children:"Nach Reiseende"})]})]}),e.jsx("p",{className:"text-xs text-muted-foreground",children:"Steuert die Hotel-Zimmerliste: Sharing-Bucher werden gepaart, Alleinbleiber als EZ mit Hinweis geführt."})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(U,{htmlFor:"name",children:"Name *"}),e.jsx(te,{id:"name",value:i.name,onChange:l=>x({...i,name:l.target.value}),placeholder:"z.B. Tauchkurs, Flughafentransfer, etc.",className:"rounded-xl"})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(U,{htmlFor:"description",children:"Beschreibung"}),e.jsx(qs,{id:"description",value:i.description,onChange:l=>x({...i,description:l.target.value}),placeholder:"Details zum Add-on...",className:"rounded-xl",rows:3})]}),e.jsxs("div",{className:"grid grid-cols-3 gap-4",children:[e.jsxs("div",{className:"space-y-2",children:[e.jsx(U,{htmlFor:"price",children:i.external_url?"ab (EUR)":"Preis (EUR) *"}),e.jsx(te,{id:"price",type:"number",min:"0",step:"0.01",value:i.price,onChange:l=>x({...i,price:parseFloat(l.target.value)||0}),className:"rounded-xl"})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(U,{htmlFor:"cost",children:"Kosten (EUR)"}),e.jsx(te,{id:"cost",type:"number",min:"0",step:"0.01",value:i.cost,onChange:l=>x({...i,cost:parseFloat(l.target.value)||0}),className:"rounded-xl",placeholder:"Einkaufspreis"})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(U,{htmlFor:"price_type",children:"Preistyp"}),e.jsxs(Ie,{value:i.price_type,onValueChange:l=>x({...i,price_type:l}),children:[e.jsx(Oe,{className:"rounded-xl",children:e.jsx(Ve,{})}),e.jsxs(Ue,{children:[e.jsx(O,{value:"per_person",children:"Pro Person"}),e.jsx(O,{value:"flat",children:"Pauschal"}),N&&e.jsx(O,{value:"per_vehicle",children:"Pro Fahrzeug"})]})]})]})]}),N&&e.jsx("p",{className:"text-xs text-sky-700 dark:text-sky-300 -mt-2",children:'Preis pro Richtung (One-Way). Beim Typ „Hin & Zurück" wählt der Gast Ankunft, Abflug oder beides – bei beiden Fahrten wird automatisch der doppelte Preis berechnet.'}),N&&e.jsxs("div",{className:"space-y-4 rounded-xl border border-sky-200 dark:border-sky-900/50 bg-sky-50/50 dark:bg-sky-950/20 p-4",children:[e.jsxs("p",{className:"text-sm font-medium flex items-center gap-1.5 text-sky-900 dark:text-sky-100",children:[e.jsx($t,{className:"h-4 w-4"}),"Transfer-Einstellungen"]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(U,{children:"Partner (Transportdienstleister)"}),e.jsxs(Ie,{value:i.transfer_partner_id||"none",onValueChange:l=>x({...i,transfer_partner_id:l==="none"?"":l}),children:[e.jsx(Oe,{className:"rounded-xl",children:e.jsx(Ve,{placeholder:"Kein Partner zugewiesen"})}),e.jsxs(Ue,{children:[e.jsx(O,{value:"none",children:"— Kein Partner —"}),k.map(l=>e.jsx(O,{value:l.id,children:l.name},l.id))]})]}),e.jsx("p",{className:"text-xs text-muted-foreground",children:"An diesen Partner wird das Transfer-Manifest gesendet."})]}),i.price_type==="per_vehicle"&&e.jsxs("div",{className:"space-y-2",children:[e.jsx(U,{children:"Max. Personen pro Fahrzeug"}),e.jsx(te,{type:"number",min:"1",value:i.transfer_max_pax_per_vehicle,onChange:l=>x({...i,transfer_max_pax_per_vehicle:parseInt(l.target.value)||4}),className:"rounded-xl"})]}),e.jsxs("div",{className:"grid grid-cols-2 gap-4",children:[e.jsxs("div",{className:"space-y-2",children:[e.jsx(U,{children:"Pickup-Puffer bei Ankunft (Min.)"}),e.jsx(te,{type:"number",min:"0",value:i.pickup_buffer_minutes,onChange:l=>x({...i,pickup_buffer_minutes:parseInt(l.target.value)||0}),className:"rounded-xl"}),e.jsx("p",{className:"text-xs text-muted-foreground",children:"Wartezeit nach Landung (Gepäck/Immigration)"})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(U,{children:"Geschätzte Fahrtzeit (Min.)"}),e.jsx(te,{type:"number",min:"0",value:i.estimated_transfer_minutes,onChange:l=>x({...i,estimated_transfer_minutes:parseInt(l.target.value)||0}),className:"rounded-xl"}),e.jsx("p",{className:"text-xs text-muted-foreground",children:"Hotel ↔ Flughafen"})]})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(U,{children:"Default-Vorlauf vor Abflug (Std.)"}),e.jsxs(Ie,{value:String(i.default_pre_flight_hours),onValueChange:l=>x({...i,default_pre_flight_hours:parseFloat(l)}),children:[e.jsx(Oe,{className:"rounded-xl",children:e.jsx(Ve,{})}),e.jsxs(Ue,{children:[e.jsx(O,{value:"2",children:"2 Stunden"}),e.jsx(O,{value:"2.5",children:"2,5 Stunden"}),e.jsx(O,{value:"3",children:"3 Stunden"})]})]}),e.jsx("p",{className:"text-xs text-muted-foreground",children:"Teilnehmer kann beim Buchen ändern."})]}),v&&e.jsxs("div",{className:"space-y-2",children:[e.jsx(U,{children:"Default-Hotel bei Ankunft"}),e.jsx(te,{value:i.default_arrival_hotel,onChange:l=>x({...i,default_arrival_hotel:l.target.value}),placeholder:"z.B. Lake Naivasha Sopa Lodge",className:"rounded-xl"})]}),G&&e.jsxs("div",{className:"space-y-2",children:[e.jsx(U,{children:"Default-Hotel bei Abflug"}),e.jsx(te,{value:i.default_departure_hotel,onChange:l=>x({...i,default_departure_hotel:l.target.value}),placeholder:"z.B. Eka Hotel Nairobi",className:"rounded-xl"})]})]}),e.jsxs("div",{className:"grid grid-cols-2 gap-4",children:[e.jsxs("div",{className:"space-y-2",children:[e.jsx(U,{htmlFor:"limited_spots",children:"Max. Plätze"}),e.jsx(te,{id:"limited_spots",type:"number",min:"0",value:i.limited_spots??"",onChange:l=>x({...i,limited_spots:l.target.value?parseInt(l.target.value):null}),placeholder:"Unbegrenzt",className:"rounded-xl"})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(U,{htmlFor:"minimum_participants",children:"Min. Teilnehmer"}),e.jsx(te,{id:"minimum_participants",type:"number",min:"1",value:i.minimum_participants??"",onChange:l=>x({...i,minimum_participants:l.target.value?parseInt(l.target.value):null}),placeholder:"Kein Minimum",className:"rounded-xl"})]})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(U,{htmlFor:"deadline",children:"Buchungsschluss (Tage vor Start)"}),e.jsx(te,{id:"deadline",type:"number",min:"0",value:i.deadline_days_before??"",onChange:l=>x({...i,deadline_days_before:l.target.value?parseInt(l.target.value):null}),placeholder:"Kein Limit",className:"rounded-xl"})]}),!N&&e.jsxs("div",{className:"space-y-2",children:[e.jsxs(U,{htmlFor:"external_url",className:"flex items-center gap-1.5",children:[e.jsx(Zt,{className:"h-3.5 w-3.5"}),"Externer Link (URL)"]}),e.jsx(te,{id:"external_url",type:"url",value:i.external_url,onChange:l=>x({...i,external_url:l.target.value}),placeholder:"https://...",className:"rounded-xl"}),i.external_url&&e.jsx("p",{className:"text-xs text-muted-foreground",children:"Teilnehmer werden direkt zu diesem Link weitergeleitet (neuer Tab)."})]}),e.jsx(el,{value:i.image_url,onChange:l=>x({...i,image_url:l})}),e.jsxs("div",{className:"flex items-center justify-between rounded-xl bg-muted/30 p-4",children:[e.jsxs("div",{children:[e.jsxs(U,{htmlFor:"is_highlighted",className:"font-medium flex items-center gap-1.5",children:[e.jsx(xn,{className:"h-3.5 w-3.5 text-amber-500"}),"Empfohlen"]}),e.jsx("p",{className:"text-sm text-muted-foreground",children:"Add-on wird im Portal hervorgehoben"})]}),e.jsx(ys,{id:"is_highlighted",checked:i.is_highlighted,onCheckedChange:l=>x({...i,is_highlighted:l})})]}),e.jsxs("div",{className:"flex items-center justify-between rounded-xl bg-muted/30 p-4",children:[e.jsxs("div",{children:[e.jsx(U,{htmlFor:"is_active",className:"font-medium",children:"Aktiv"}),e.jsx("p",{className:"text-sm text-muted-foreground",children:"Nur aktive Add-ons können gebucht werden"})]}),e.jsx(ys,{id:"is_active",checked:i.is_active,onCheckedChange:l=>x({...i,is_active:l})})]})]}),e.jsxs(gs,{children:[e.jsx(z,{variant:"outline",className:"rounded-xl",onClick:()=>n(!1),children:"Abbrechen"}),e.jsx(z,{className:"rounded-xl",onClick:T,disabled:!o||h,children:h?"Speichern...":a?"Speichern":"Erstellen"})]})]})})}
131function Mc({open:s,onOpenChange:n,tripId:a,addons:b,onSuccess:f}){const{toast:i}=aa(),[x,h]=t.useState([]),[c,k]=t.useState(!1),[C,N]=t.useState(!1),[v,G]=t.useState(""),[T,o]=t.useState(""),[l,V]=t.useState(1),[A,q]=t.useState(!1),[y,W]=t.useState("");t.useEffect(()=>{s&&a&&(k(!0),_.from("participants").select("id, first_name, last_name, profile_id").eq("trip_id",a).order("first_name",{ascending:!0}).then(({data:$,error:ge})=>{ge?console.error("Error loading participants:",ge):h($||[]),k(!1)}))},[s,a]),t.useEffect(()=>{s||(G(""),o(""),V(1),q(!1),W(""))},[s]);const j=b.find($=>$.id===T),d=x.find($=>$.id===v),u=$=>new Intl.NumberFormat("de-DE",{style:"currency",currency:"EUR"}).format($),I=async()=>{if(!v||!T){i({title:"Fehler",description:"Bitte wählen Sie Teilnehmer und Add-on aus.",variant:"destructive"});return}N(!0);try{const{error:$}=await _.functions.invoke("create-addon-invoice",{body:{trip_id:a,participant_id:v,profile_id:(d==null?void 0:d.profile_id)||void 0,items:[{addon_id:T,quantity:l}],is_complimentary:A,complimentary_reason:y||void 0}});if($)throw $;i({title:A?"Geschenk vergeben":"Add-on zugewiesen",description:A?`${j==null?void 0:j.name} wurde kostenlos an ${d==null?void 0:d.first_name} ${d==null?void 0:d.last_name} vergeben.`:`${j==null?void 0:j.name} wurde ${d==null?void 0:d.first_name} ${d==null?void 0:d.last_name} auf Rechnung zugewiesen.`}),f(),n(!1)}catch($){console.error("Error assigning addon:",$),i({title:"Fehler",description:"Add-on konnte nicht zugewiesen werden.",variant:"destructive"})}finally{N(!1)}},E=A?0:((j==null?void 0:j.price)||0)*l;return e.jsx(We,{open:s,onOpenChange:n,children:e.jsxs(Qe,{className:"glass-modal sm:max-w-md",children:[e.jsxs(Ye,{children:[e.jsxs(Je,{className:"flex items-center gap-2",children:[e.jsx(Ot,{className:"h-5 w-5 text-primary"}),"Add-on zuweisen"]}),e.jsx(Ds,{children:"Weisen Sie einem Teilnehmer manuell ein Add-on zu."})]}),e.jsxs("div",{className:"space-y-4 py-4",children:[e.jsxs("div",{className:"space-y-2",children:[e.jsx(U,{children:"Teilnehmer"}),e.jsxs(Ie,{value:v,onValueChange:G,children:[e.jsx(Oe,{className:"rounded-xl",children:e.jsx(Ve,{placeholder:c?"Laden...":"Teilnehmer auswählen"})}),e.jsx(Ue,{children:x.map($=>e.jsxs(O,{value:$.id,children:[$.first_name," ",$.last_name]},$.id))})]})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(U,{children:"Add-on"}),e.jsxs(Ie,{value:T,onValueChange:o,children:[e.jsx(Oe,{className:"rounded-xl",children:e.jsx(Ve,{placeholder:"Add-on auswählen"})}),e.jsx(Ue,{children:b.filter($=>$.is_active).map($=>e.jsxs(O,{value:$.id,children:[$.name," – ",u($.price)]},$.id))})]})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(U,{children:"Menge"}),e.jsx(te,{type:"number",min:1,max:10,value:l,onChange:$=>V(Math.max(1,parseInt($.target.value)||1)),className:"rounded-xl"})]}),e.jsxs("div",{className:"flex items-center space-x-3 rounded-xl bg-muted/50 p-4",children:[e.jsx(Zs,{id:"complimentary",checked:A,onCheckedChange:$=>q($===!0)}),e.jsxs("div",{className:"flex-1",children:[e.jsxs("label",{htmlFor:"complimentary",className:"text-sm font-medium leading-none cursor-pointer flex items-center gap-2",children:[e.jsx(Ot,{className:"h-4 w-4 text-success"}),"Kostenlos vergeben (Geschenk)"]}),e.jsx("p",{className:"text-xs text-muted-foreground mt-1",children:'Keine Zahlung erforderlich. Status wird auf "Bezahlt" gesetzt.'})]})]}),A&&e.jsxs("div",{className:"space-y-2",children:[e.jsx(U,{children:"Grund (optional)"}),e.jsx(te,{placeholder:"z.B. Treuebonus, Geburtstagsgeschenk...",value:y,onChange:$=>W($.target.value),className:"rounded-xl"})]}),j&&e.jsxs("div",{className:"rounded-xl bg-muted/30 p-4 space-y-2",children:[e.jsxs("div",{className:"flex justify-between text-sm",children:[e.jsx("span",{className:"text-muted-foreground",children:"Add-on"}),e.jsx("span",{className:"font-medium",children:j.name})]}),e.jsxs("div",{className:"flex justify-between text-sm",children:[e.jsx("span",{className:"text-muted-foreground",children:"Menge"}),e.jsxs("span",{className:"font-medium",children:[l,"x"]})]}),e.jsxs("div",{className:"flex justify-between text-sm border-t border-border pt-2",children:[e.jsx("span",{className:"text-muted-foreground",children:"Gesamt"}),e.jsx("span",{className:`font-bold ${A?"text-success":"text-foreground"}`,children:A?"🎁 Kostenlos":u(E)})]})]})]}),e.jsxs(gs,{children:[e.jsx(z,{variant:"outline",className:"rounded-xl",onClick:()=>n(!1),children:"Abbrechen"}),e.jsx(z,{className:"rounded-xl gap-2",onClick:I,disabled:C||!v||!T,children:C?e.jsxs(e.Fragment,{children:[e.jsx($e,{className:"h-4 w-4 animate-spin"}),"Wird zugewiesen..."]}):e.jsxs(e.Fragment,{children:[A?e.jsx(Ot,{className:"h-4 w-4"}):null,A?"Geschenk vergeben":"Auf Rechnung zuweisen"]})})]})]})})}function Gc({addon:s,spotsDisplay:n,isFull:a,formatCurrency:b,onEdit:f,onDelete:i,onToggleActive:x}){const{attributes:h,listeners:c,setNodeRef:k,transform:C,transition:N,isDragging:v}=xr({id:s.id}),G={transform:pr.Transform.toString(C),transition:N,opacity:v?.5:1},T=!!s.addon_type&&s.addon_type.startsWith("airport_transfer"),o=s.addon_type==="airport_transfer_arrival"?"Transfer (Ankunft)":s.addon_type==="airport_transfer_departure"?"Transfer (Abflug)":s.addon_type==="airport_transfer_roundtrip"?"Transfer (Hin & Zurück)":"";return e.jsxs("tr",{ref:k,style:G,className:"border-b border-border/50 transition-colors hover:bg-muted/20",children:[e.jsx("td",{className:"px-2 py-4",children:e.jsx("button",{...h,...c,className:"cursor-grab active:cursor-grabbing p-1 rounded hover:bg-muted",children:e.jsx(Ra,{className:"h-4 w-4 text-muted-foreground"})})}),e.jsx("td",{className:"px-5 py-4",children:e.jsxs("div",{className:"flex items-center gap-3",children:[e.jsx("div",{className:`flex h-10 w-10 items-center justify-center rounded-xl ${T?"bg-sky-100 dark:bg-sky-900/30":"bg-primary/10"}`,children:T?e.jsx($t,{className:"h-5 w-5 text-sky-600 dark:text-sky-400"}):e.jsx(yt,{className:"h-5 w-5 text-primary"})}),e.jsxs("div",{children:[e.jsx("p",{className:"font-medium text-foreground",children:s.name}),T&&e.jsx("p",{className:"text-xs text-sky-700 dark:text-sky-300",children:o}),s.description&&e.jsx("p",{className:"text-sm text-muted-foreground line-clamp-1",children:s.description})]})]})}),e.jsx("td",{className:"px-5 py-4 text-right",children:e.jsxs("div",{children:[e.jsx("span",{className:"font-semibold text-foreground",children:b(s.price)}),e.jsx("p",{className:"text-xs text-muted-foreground",children:s.price_type==="per_person"?"pro Person":s.price_type==="per_vehicle"?"pro Fahrzeug":"pauschal"})]})}),e.jsx("td",{className:"px-5 py-4 text-center",children:e.jsxs("div",{className:"flex items-center justify-center gap-1 text-sm",children:[e.jsx(Ns,{className:"h-4 w-4 text-muted-foreground"}),e.jsx("span",{className:a?"text-destructive":"text-foreground",children:n})]})}),e.jsx("td",{className:"px-5 py-4 text-center",children:s.deadline_days_before?e.jsxs("span",{className:"text-sm text-foreground",children:[s.deadline_days_before," Tage"]}):e.jsx("span",{className:"text-sm text-muted-foreground",children:"–"})}),e.jsx("td",{className:"px-5 py-4",children:e.jsx("div",{className:"flex justify-center",children:e.jsx(ys,{checked:s.is_active,onCheckedChange:x})})}),e.jsx("td",{className:"px-5 py-4",children:e.jsxs("div",{className:"flex justify-end gap-2",children:[e.jsx(z,{variant:"ghost",size:"icon",className:"h-8 w-8 rounded-lg",onClick:f,children:e.jsx(Ta,{className:"h-4 w-4"})}),e.jsx(z,{variant:"ghost",size:"icon",className:"h-8 w-8 rounded-lg text-destructive hover:text-destructive",onClick:i,children:e.jsx(bs,{className:"h-4 w-4"})})]})})]})}function Ic({tripId:s}){const{addons:n,purchases:a,isLoading:b,purchaseStats:f,createAddon:i,updateAddon:x,deleteAddon:h,toggleAddonActive:c,reorderAddons:k,cancelPurchase:C,deletePurchase:N,markPurchaseAsPaid:v,updatePurchaseDueDate:G,replaceInvoice:T,fetchAll:o}=Bn(s),{lostPurchases:l}=Lc(s),[V,A]=t.useState(""),[q,y]=t.useState("all"),[W,j]=t.useState(!1),[d,u]=t.useState(!1),[I,E]=t.useState(null),[$,ge]=t.useState(null),[be,Z]=t.useState(null),[H,L]=t.useState(null),[g,r]=t.useState(!1),[m,X]=t.useState(null),[p,ne]=t.useState(null),[le,K]=t.useState(""),M=t.useRef(null),[ee,he]=t.useState(null),we=async P=>{he(P.id);try{const ie=P.booked_by_profile_id??P.profile_id,Se=a.filter(oe=>oe.payment_status==="paid"&&!oe.easybill_document_id&&(oe.booked_by_profile_id??oe.profile_id)===ie).map(oe=>oe.id),{data:R,error:ce}=await _.functions.invoke("create-easybill-invoice",{body:{purchase_ids:Se.length>0?Se:[P.id],trip_id:P.trip_id,participant_id:P.booked_by_participant_id??P.participant_id,profile_id:P.booked_by_profile_id??P.profile_id,payment_type:"stripe"}});if(ce)throw ce;R!=null&&R.skipped?Y.info("Rechnung existiert bereits — es wurde keine zweite erzeugt."):Y.success("Rechnung erstellt und in de
131n Unterlagen hinterlegt."),await o()}catch(ie){Y.error(`Rechnung konnte nicht erstellt werden: ${ie instanceof Error?ie.message:"Unbekannter Fehler"}`)}finally{he(null)}},De=P=>{var ie;X(P),(ie=M.current)==null||ie.click()},_e=async P=>{var Se;const ie=(Se=P.target.files)==null?void 0:Se[0];ie&&m&&await T(m,ie),X(null),M.current&&(M.current.value="")},J=(P,ie="EUR")=>new Intl.NumberFormat("de-DE",{style:"currency",currency:ie}).format(P),Ae=P=>P?new Date(P).toLocaleDateString("de-DE",{day:"2-digit",month:"2-digit",year:"numeric",hour:"2-digit",minute:"2-digit"}):"–",qe=t.useMemo(()=>{let P=a;if(q!=="all"&&(P=P.filter(ie=>ie.payment_status===q)),V){const ie=V.toLowerCase();P=P.filter(Se=>{var R,ce,oe;return((R=Se.participant_name)==null?void 0:R.toLowerCase().includes(ie))||((ce=Se.addon_name)==null?void 0:ce.toLowerCase().includes(ie))||((oe=Se.participant_email)==null?void 0:oe.toLowerCase().includes(ie))})}return P},[a,q,V]),Be=P=>{switch(P){case"paid":return"Bezahlt";case"invoice":return"Rechnung";case"pending":return"Ausstehend";case"refunded":return"Storniert";default:return P}},Ke=P=>{switch(P){case"paid":return"bg-success/10 text-success";case"invoice":return"bg-blue-500/10 text-blue-600";case"pending":return"bg-warning/10 text-warning";case"refunded":return"bg-destructive/10 text-destructive";default:return"bg-muted text-muted-foreground"}},Ce=async P=>I?x(I.id,P):i(P),xe=async()=>{$&&(await h($),ge(null))},ms=async()=>{be&&!g&&(r(!0),await C(be),r(!1),Z(null))},us=async()=>{H&&(await N(H.id),L(null))},Q=()=>{const P=["Teilnehmer","E-Mail","Add-on","Menge","Einzelpreis","Gesamt","Status","Kaufdatum"],ie=qe.map(me=>[me.participant_name||"",me.participant_email||"",me.addon_name||"",me.quantity.toString(),J(me.unit_price,me.currency),J(me.total_price,me.currency),Be(me.payment_status),me.purchased_at?Ae(me.purchased_at):Ae(me.created_at)]),Se=[P.join(";"),...ie.map(me=>me.join(";"))].join(`
132`),R=new Blob(["\uFEFF"+Se],{type:"text/csv;charset=utf-8;"}),ce=URL.createObjectURL(R),oe=document.createElement("a");oe.href=ce,oe.download=`addon-purchases-${Ks()}.csv`,oe.click(),URL.revokeObjectURL(ce)},ue=t.useMemo(()=>{const P={};return a.filter(ie=>ie.payment_status==="paid").forEach(ie=>{P[ie.addon_id]=(P[ie.addon_id]||0)+ie.quantity}),P},[a]),de=ir(sa(or),sa(cr,{coordinateGetter:lr})),S=P=>{const{active:ie,over:Se}=P;if(Se&&ie.id!==Se.id){const R=n.findIndex(me=>me.id===ie.id),ce=n.findIndex(me=>me.id===Se.id),oe=gr(n,R,ce);k(oe)}};return b?e.jsx("div",{className:"flex min-h-[200px] items-center justify-center",children:e.jsx($e,{className:"h-8 w-8 animate-spin text-primary"})}):e.jsxs("div",{className:"space-y-8",children:[l.length>0&&e.jsxs("div",{className:"rounded-xl border border-destructive/30 bg-destructive/5 p-4",children:[e.jsxs("p",{className:"text-sm font-semibold text-destructive",children:[l.length," protokollierte",l.length===1?"r":""," Add-on-Kauf ohne Datensatz"]}),e.jsx("ul",{className:"mt-2 space-y-1 text-sm text-muted-foreground",children:l.map(P=>e.jsxs("li",{children:[new Date(P.logged_at).toLocaleDateString("de-DE")," · ",P.participant_name," · ",P.addon_name,P.price!==null?` · ${J(P.price)}`:""]},`${P.log_id}-${P.addon_name}`))})]}),e.jsx("input",{ref:M,type:"file",accept:".pdf",className:"hidden",onChange:_e}),e.jsxs("div",{className:"grid gap-4 sm:grid-cols-4",children:[e.jsx("div",{className:"glass-card p-4",children:e.jsxs("div",{className:"flex items-center gap-3",children:[e.jsx("div",{className:"flex h-10 w-10 items-center justify-center rounded-xl bg-primary/10",children:e.jsx(yt,{className:"h-5 w-5 text-primary"})}),e.jsxs("div",{children:[e.jsx("p",{className:"text-sm text-muted-foreground",children:"Aktive Add-ons"}),e.jsx("p",{className:"text-xl font-bold text-foreground",children:n.filter(P=>P.is_active).length})]})]})}),e.jsx("div",{className:"glass-card p-4",children:e.jsxs("div",{className:"flex items-center gap-3",children:[e.jsx("div",{className:"flex h-10 w-10 items-center justify-center rounded-xl bg-success/10",children:e.jsx(Lr,{className:"h-5 w-5 text-success"})}),e.jsxs("div",{children:[e.jsx("p",{className:"text-sm text-muted-foreground",children:"Bezahlte Buchungen"}),e.jsx("p",{className:"text-xl font-bold text-foreground",children:f.paidCount})]})]})}),e.jsx("div",{className:"glass-card p-4",children:e.jsxs("div",{className:"flex items-center gap-3",children:[e.jsx("div",{className:"flex h-10 w-10 items-center justify-center rounded-xl bg-success/10",children:e.jsx(tt,{className:"h-5 w-5 text-success"})}),e.jsxs("div",{children:[e.jsx("p",{className:"text-sm text-muted-foreground",children:"Umsatz (bezahlt)"}),e.jsx("p",{className:"text-xl font-bold text-success",children:J(f.totalRevenue)})]})]})}),e.jsx("div",{className:"glass-card p-4",children:e.jsxs("div",{className:"flex items-center gap-3",children:[e.jsx("div",{className:"flex h-10 w-10 items-center justify-center rounded-xl bg-warning/10",children:e.jsx(Vs,{className:"h-5 w-5 text-warning"})}),e.jsxs("div",{children:[e.jsx("p",{className:"text-sm text-muted-foreground",children:"Ausstehend"}),e.jsx("p",{className:"text-xl font-bold text-warning",children:J(f.pen
132dingRevenue)})]})]})})]}),e.jsxs("div",{className:"space-y-4",children:[e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsx("h3",{className:"text-lg font-semibold text-foreground",children:"Verfügbare Add-ons"}),e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsxs(z,{variant:"outline",className:"gap-2 rounded-xl",onClick:()=>u(!0),disabled:n.filter(P=>P.is_active).length===0,children:[e.jsx(Ot,{className:"h-4 w-4"}),"Add-on zuweisen"]}),e.jsxs(z,{className:"gap-2 rounded-xl",onClick:()=>j(!0),children:[e.jsx(Es,{className:"h-4 w-4"}),"Add-on erstellen"]})]})]}),n.length===0?e.jsxs("div",{className:"glass-card p-12 text-center",children:[e.jsx(yt,{className:"mx-auto h-12 w-12 text-muted-foreground"}),e.jsx("h3",{className:"mt-4 text-lg font-medium text-foreground",children:"Keine Add-ons erstellt"}),e.jsx("p",{className:"mt-1 text-muted-foreground",children:"Erstellen Sie optionale Zusatzleistungen für Teilnehmer."}),e.jsxs(z,{className:"mt-4 gap-2 rounded-xl",onClick:()=>j(!0),children:[e.jsx(Es,{className:"h-4 w-4"}),"Erstes Add-on erstellen"]})]}):e.jsx(dr,{sensors:de,collisionDetection:mr,onDragEnd:S,children:e.jsx("div",{className:"glass-card overflow-hidden",children:e.jsx("div",{className:"overflow-x-auto",children:e.jsxs("table",{className:"w-full",children:[e.jsx("thead",{children:e.jsxs("tr",{className:"border-b border-border bg-muted/30",children:[e.jsx("th",{className:"px-2 py-4 text-left text-sm font-medium text-muted-foreground w-10"}),e.jsx("th",{className:"px-5 py-4 text-left text-sm font-medium text-muted-foreground",children:"Name"}),e.jsx("th",{className:"px-5 py-4 text-right text-sm font-medium text-muted-foreground",children:"Preis"}),e.jsx("th",{className:"px-5 py-4 text-center text-sm font-medium text-muted-foreground",children:"Plätze"}),e.jsx("th",{className:"px-5 py-4 text-center text-sm font-medium text-muted-foreground",children:"Deadline"}),e.jsx("th",{className:"px-5 py-4 text-center text-sm font-medium text-muted-foreground",children:"Aktiv"}),e.jsx("th",{className:"px-5 py-4 text-right text-sm font-medium text-muted-foreground",children:"Aktionen"})]})}),e.jsx(ur,{items:n.map(P=>P.id),strategy:hr,children:e.jsx("tbody",{children:n.map(P=>{const ie=ue[P.id]||0,Se=P.limited_spots?`${ie}/${P.limited_spots}`:"∞";return e.jsx(Gc,{addon:P,spotsDisplay:Se,isFull:P.limited_spots?ie>=P.limited_spots:!1,formatCurrency:J,onEdit:()=>E(P),onDelete:()=>ge(P.id),onToggleActive:R=>c(P.id,R)},P.id)})})})]})})})})]}),e.jsxs("div",{className:"space-y-4",children:[e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsxs("h3",{className:"text-lg font-semibold text-foreground",children:["Gebuchte Add-ons (",qe.length,")"]}),e.jsxs("div",{className:"flex items-center gap-3",children:[e.jsxs(Ie,{value:q,onValueChange:P=>y(P),children:[e.jsx(Oe,{className:"w-[140px] rounded-xl",children:e.jsx(Ve,{})}),e.jsxs(Ue,{children:[e.jsx(O,{value:"all",children:"Alle"}),e.jsx(O,{value:"paid",children:"Bezahlt"}),e.jsx(O,{value:"invoice",children:"Rechnung"}),e.jsx(O,{value:"pending",children:"Ausstehend"}),e.jsx(O,{value:"refunded",children:"Storniert"})]})]}),e.jsxs("div",{className:"relative max-w-xs",children:[e.jsx(wt,{className:"absolute left-3 top-1/2 h-4 w-4 -translate-y-1/2 text-muted-foreground"}),e.jsx(te,{type:"text",placeholder:"Suchen...",value:V,onChange:P=>A(P.target.value),className:"pl-10 rounded-xl bg-muted/50 border-0 w-48"})]}),e.jsxs(z,{variant:"outline",className:"gap-2 rounded-xl",onClick:Q,disabled:qe.length===0,children:[e.jsx(lt,{className:"h-4 w-4"}),"Export"]})]})]}),a.length===0?e.jsxs("div",{className:"glass-card p-12 text-center",children:[e.jsx(Lr,{className:"mx-auto h-12 w-12 text-muted-foreground"}),e.jsx("h3",{className:"mt-4 text-lg font-medium text-foreground",children:"Keine Buchungen"}),e.jsx("p",{className:"mt-1 text-muted-foreground",children:"Sobald Teilnehmer Add-ons buchen, erscheinen diese hier."})]}):e.jsx("div",{className:"glass-card overflow-hidden",children:e.jsx("div",{className:"overflow-x-auto",children:e.jsxs("table",{className:"w-full",children:[e.jsx("thead",{children:e.jsxs("tr",{className:"border-b border-border bg-muted/30",children:[e.jsx("th",{className:"px-5 py-4 text-left text-sm font-medium text-muted-foreground",children:"Teilnehmer"}),e.jsx("th",{className:"px-5 py-4 text-left text-sm font-medium text-muted-foreground",children:"Add-on"}),e.jsx("th",{className:"px-5 py-4 text-center text-sm font-medium text-muted-foreground",children:"Menge"}),e.jsx("th",{className:"px-5 py-4 text-right text-sm font-medium text-muted-foreground",children:"Betrag"}),e.jsx("th",{className:"px-5 py-4 text-center text-sm font-medium text-muted-foreground",children:"Status"}),e.jsx("th",{className:"px-5 py-4 text-center text-sm font-medium text-muted-foreground",children:"Rechnung"}),e.jsx("th",{className:"px-5 py-4 text-right text-sm font-medium text-muted-foreground",children:"Zahlung"}),e.jsx("th",{className:"px-5 py-4 text-right text-sm font-medium text-muted-foreground",children:"Datum"}),e.jsx("th",{className:"px-5 py-4 text-right text-sm font-medium text-muted-foreground",children:"Aktionen"})]})}),e.jsx("tbody",{children:qe.map(P=>e.jsxs("tr",{className:`border-b border-border/50 transition-colors hover:bg-muted/20 ${P.payment_status==="refunded"?"opacity-60":""}`,children:[e.jsx("td",{className:"px-5 py-4",children:e.jsxs("div",{children:[e.jsx("p",{className:"font-medium text-foreground",children:P.participant_name}),P.participant_email&&e.jsx("p",{className:"text-sm text-muted-foreground",children:P.participant_email})]})}),e.jsx("td",{className:"px-5 py-4",children:e.jsx("span",{className:"font-medium text-foreground",children:P.addon_name})}),e.jsx("td",{className:"px-5 py-4 text-center",children:e.jsx("span",{className:"text-foreground",children:P.quantity})}),e.jsx("td",{className:"px-5 py-4 text-right",children:e.jsx("span",{className:`font-semibold ${P.payment_status==="refunded"?"line-through text-muted-foreground":"text-foreground"}`,children:J(P.total_price,P.currency)})}),e.jsx("td",{className:"px-5 py-4",children:e.jsx("div",{className:"flex justify-center",children:e.jsxs("span",{className:`inline-flex items-center gap-1.5 rounded-full px-3 py-1 text-sm font-medium ${Ke(P.payment_status)}`,children:[P.payment_status==="paid"&&e.jsx(tt,{className:"h-3.5 w-3.5"}),P.payment_status==="invoice"&&e.jsx($s,{className:"h-3.5 w-3.5"}),P.payment_status==="pending"&&e.jsx(Vs,{className:"h-3.5 w-3.5"}),P.payment_status==="refunded"&&e.jsx(ma,{className:"h-3.5 w-3.5"}),Be(P.payment_status)]})})}),e.jsx("td",{className:"px-5 py-4",children:e.jsx("div",{className:"flex justify-center gap-2",children:P.invoice_url?e.jsxs("a",{href:P.invoice_url,target:"_blank",rel:"noopener noreferrer",className:"inline-flex items-center gap-1.5 text-sm text-primary hover:underline",children:[e.jsx(lt,{className:"h-3.5 w-3.5"}),"PDF"]}):P.easybill_document_id?e.jsxs("span",{className:"text-xs text-muted-foreground",children:["#",P.easybill_document_id]}):P.payment_status==="paid"?e.jsxs(z,{size:"sm",variant:"outline",className:"h-7 gap-1.5 border-amber-300 text-xs text-amber-800 hover:bg-amber-50",disabled:ee===P.id,onClick:()=>we(P),children:[ee===P.id?e.jsx($e,{className:"h-3.5 w-3.5 animate-spin"}):e.jsx(Lt,{className:"h-3.5 w-3.5"}),"Rechnung fehlt"]}):e.jsx("span",{className:"text-xs text-muted-foreground",children:"–"})})}),e.jsx("td",{className:"px-5 py-4 text-right text-sm text-muted-foreground",children:P.paid_at?e.jsxs("div",{children:[e.jsxs("span",{className:"text-foreground",children:["Bezahlt ",Ae(P.paid_at)]}),e.jsxs("span",{className:"block text-xs text-muted-foreground",children:["nach ",Math.max(0,ui(ka(P.paid_at),ka(P.created_at)))," Tagen"]})]}):P.payment_status==="invoice"&&P.payment_due_date?e.jsxs("div",{children:[e.jsxs("span",{className:hi(ka(P.payment_due_date))?"text-destructive":"text-foreground",children:["Fällig ",Ae(P.payment_due_date)]}),(P.payment_reminder_sent_at||P.overdue_reminder_sent_at)&&e.jsxs("span",{className:"block text-xs text-muted-foreground",children:["Erinnert ",Ae(P.overdue_reminder_sent_at||P.payment_reminder_sent_at)]})]}):e.jsx("span",{children:"–"})}),e.jsx("td",{className:"px-5 py-4 text-right text-sm text-muted-foreground",children:Ae(P.purchased_at||P.created_at)}),e.jsx("td",{className:"px-5 py-4",children:e.jsx("div",{className:"flex justify-end",children:e.jsxs(pn,{children:[e.jsx(gn,{asChild:!0,children:e.jsx(z,{variant:"ghost",size:"icon",className:"h-8 w-8 rounded-lg",children:e.jsx(Pn,{className:"h-4 w-4"})})}),e.jsxs(fn,{align:"end",className:"w-48",children:[(P.payment_status==="invoice"||P.payment_status==="paid")&&e.jsxs(ot,{onClick:()=>De(P.id),children:[e.jsx(_t,{className:"mr-2 h-4 w-4"}),"Rechnung ersetzen"]}),P.payment_status==="invoice"&&e.jsxs(e.Fragment,{children:[e.jsxs(ot,{onClick:()=>v(P.id),children:[e.jsx(Aa,{className:"mr-2 h-4 w-4"}),"Als bezahlt markieren"]}),e.jsxs(ot,{onClick:()=>{ne(P),K(P.payment_due_date||"")},children:[e.jsx(Vs,{className:"mr-2 h-4 w-4"}),"Zahlungsziel ändern"]}),e.jsx(Sa,{})]}),P.payment_status!=="refunded"&&e.jsxs(ot,{onClick:()=>Z(P),className:"text-destructive focus:text-destructive",children:[e.jsx(ma,{className:"mr-2 h-4 w-4"}),"Stornieren"]}),P.payment_status==="pending"&&e.jsxs(e.Fragment,{children:[e.jsx(Sa,{}),e.jsxs(ot,{onClick:()=>L(P),className:"text-destructive focus:text-destructive",children:[e.jsx(bs,{className:"mr-2 h-4 w-4"}),"Löschen"]})]}),P.payment_status==="refunded"&&e.jsxs(ot,{onClick:()=>L(P),className:"text-destructive focus:text-destructive",children:[e.jsx(bs,{className:"mr-2 h-4 w-4"}),"Löschen"]})]})]})})})]},P.id))})]})})})]}),e.jsx(qc,{open:W||!!I,onOpenChange:P=>{P||(j(!1),E(null))},addon:I,tripId:s,onSave:Ce}),e.jsx(Mc,{open:d,onOpenChange:u,tripId:s,addons:n,onSuccess:o}),e.jsx(mt,{open:!!$,onOpenChange:()=>ge(null),children:e.jsxs(ut,{className:"glass-modal",children:[e.jsxs(ht,{children:[e.jsx(xt,{children:"Add-on löschen?"}),e.jsx(pt,{children:"Dieses Add-on wird unwiderruflich gelöscht. Bestehende Buchungen bleiben erhalten."})]}),e.jsxs(gt,{children:[e.jsx(ft,{className:"rounded-xl",children:"Abbrechen"}),e.jsx(jt,{className:"rounded-xl bg-destructive text-destructive-foreground hover:bg-destructive/90",onClick:xe,children:"Löschen"})]})]})}),e.jsx(mt,{open:!!p,onOpenChange:P=>{P||ne(null)},children:e.jsxs(ut,{className:"glass-modal",children:[e.jsxs(ht,{children:[e.jsx(xt,{children:"Zahlungsziel ändern"}),e.jsxs(pt,{children:["Fälligkeitsdatum der Rechnung für ",e.jsx("strong",{children:p==null?void 0:p.addon_name})," (",p==null?void 0:p.participant_name,"). Die Zahlungserinnerung geht 3 Tage vor diesem Datum raus."]})]}),e.jsx(te,{type:"date",value:le,onChange:P=>K(P.target.value),className:"rounded-xl"}),e.jsxs(gt,{children:[e.jsx(ft,{className:"rounded-xl",children:"Abbrechen"}),e.jsx(jt,{className:"rounded-xl",disabled:!le,onClick:async()=>{p&&le&&await G(p.id,le),ne(null)},children:"Speichern"})]})]})}),e.jsx(mt,{open:!!be,onOpenChange:()=>Z(null),children:e.jsxs(ut,{className:"glass-modal",children:[e.jsxs(ht,{children:[e.jsx(xt,{children:"Add-on-Kauf stornieren?"}),e.jsxs(pt,{className:"space-y-2",children:[e.jsxs("p",{children:["Der Kauf von ",e.jsx("strong",{children:be==null?void 0:be.addon_name})," für"," ",e.jsx("strong",{children:be==null?void 0:be.participant_name})," wird storniert."]}),(be==null?void 0:be.easybill_document_id)&&e.jsxs("p",{className:"text-sm",children:["Die zugehörige easybill-Rechnung #",be.easybill_document_id," wird automatisch storniert und eine Stornorechnung erstellt."]}),e.jsx("p",{className:"text-sm text-warning",children:"Hinweis: Die Rückerstattung bei Stripe muss manuell über das Stripe Dashboard erfolgen."})]})]}),e.jsxs(gt,{children:[e.jsx(ft,{className:"rounded-xl",disabled:g,children:"Abbrechen"}),e.jsx(jt,{className:"rounded-xl bg-destructive text-destructive-foreground hover:bg-destructive/90",onClick:ms,disabled:g,children:g?e.jsxs(e.Fragment,{children:[e.jsx($e,{className:"mr-2 h-4 w-4 animate-spin"}),"Storniere..."]}):"Stornieren"})]})]})}),e.jsx(mt,{open:!!H,onOpenChange:()=>L(null),children:e.jsxs(ut,{className:"glass-modal",children:[e.jsxs(ht,{children:[e.jsx(xt,{children:"Buchung löschen?"}),e.jsxs(pt,{children:["Die Buchung von ",e.jsx("strong",{children:H==null?void 0:H.addon_name})," für"," ",e.jsx("strong",{children:H==null?void 0:H.participant_name})," wird unwiderruflich gelöscht."]})]}),e.jsxs(gt,{children:[e.jsx(ft,{className:"rounded-xl",children:"Abbrechen"}),e.jsx(jt,{className:"rounded-xl bg-destructive text-destructive-foreground hover:bg-destructive/90",onClick:us,children:"Löschen"})]})]})})]})}const rn=s=>{if(!s)return"";const n=new Date(s);if(Number.isNaN(n.getTime()))return"";const a=b=>String(b).padStart(2,"0");return`${n.getFullYear()}-${a(n.getMonth()+1)}-${a(n.getDate())}T${a(n.getHours())}:${a(n.getMinutes())}`},Oc=s=>s==null?void 0:s.startsWith("airport_transfer_");function Uc({tripId:s}){const{toast:n}=aa(),[a,b]=t.useState(!0),[f,i]=t.useState(null),[x,h]=t.useState(null),[c,k]=t.useState([]),[C,N]=t.useState([]),[v,G]=t.useState([]),[T,o]=t.useState({}),l=async()=>{var j;b(!0);try{const{data:d,error:u}
132=await _.from("trip_addons").select(`
133          id, name, addon_type, transfer_partner_id,
134          transfer_max_pax_per_vehicle, estimated_transfer_minutes,
135          partner:partners!trip_addons_transfer_partner_id_fkey(id, name, email)
136        `).eq("trip_id",s);if(u)throw u;const I=(d||[]).filter(g=>Oc(g.addon_type));k(I);const E=I.map(g=>g.id);if(E.length===0){N([]),G([]);return}const{data:$,error:ge}=await _.from("participant_addon_purchases").select(`
137          id, addon_id, profile_id, participant_id, quantity,
138          transfer_pax_count, transfer_direction, transfer_pre_flight_hours, transfer_pickup_time,
139          transfer_arrival_datetime, transfer_departure_pickup_time,
140          transfer_arrival_hotel, transfer_departure_hotel,
141
142          participant_profiles:participant_profiles!participant_addon_purchases_profile_id_fkey(first_name, last_name, email)
143        `).eq("trip_id",s).in("addon_id",E).not("payment_status","in",'("cancelled","refunded")');if(ge)throw ge;const be=Array.from(new Set(($||[]).map(g=>g.participant_id).filter(Boolean))),Z=new Map;if(be.length>0){const{data:g}=await _.from("participants").select("id, questionnaire_responses").in("id",be);for(const r of g||[]){const m=(j=r.questionnaire_responses)==null?void 0:j._travel_form;if(!m)continue;const X=p=>!!(p&&String(p).trim());Z.set(r.id,{arrival_flight_no:m.arrival_flight_number||null,arrival_date:m.arrival_date||null,arrival_time:X(m.arrival_time)?m.arrival_time:null,arrival_airport:m.arrival_airport||null,departure_flight_no:m.departure_flight_number||null,departure_date:m.departure_date||null,departure_time:X(m.departure_time)?m.departure_time:null,departure_airport:m.departure_airport||null})}}const H=($||[]).map(g=>({...g,participant_flights:g.participant_id?Z.get(g.participant_id)??null:null}));N(H);const{data:L}=await _.from("transfer_manifest_sends").select("id, addon_id, sent_at, trigger_source").eq("trip_id",s).order("sent_at",{ascending:!1});G(L||[])}catch(d){n({title:"Fehler beim Laden",description:d.message,variant:"destructive"})}finally{b(!1)}};t.useEffect(()=>{l()},[s]);const V=t.useMemo(()=>{const j=new Map;for(const d of C)j.has(d.addon_id)||j.set(d.addon_id,[]),j.get(d.addon_id).push(d);return j},[C]),A=t.useMemo(()=>{const j=new Map;for(const d of v)d.addon_id&&!j.has(d.addon_id)&&j.set(d.addon_id,d);return j},[v]),q=(j,d,u)=>{o(I=>({...I,[j]:{...I[j]||{},[d]:u}}))},y=async j=>{const d=T[j];if(d){h(j);try{const{error:u}=await _.from("participant_addon_purchases").update(d).eq("id",j);if(u)throw u;N(I=>I.map(E=>E.id===j?{...E,...d}:E)),o(I=>{const E={...I};return delete E[j],E}),n({title:"Gespeichert"})}catch(u){n({title:"Speichern fehlgeschlagen",description:u.message,variant:"destructive"})}finally{h(null)}}},W=async j=>{i(j);try{const{data:d,error:u}=await _.functions.invoke("send-transfer-manifest",{body:{trip_id:s,addon_id:j,trigger_source:"manual"}});if(u)throw u;n({title:"Manifest gesendet",description:(d==null?void 0:d.message)||"Partner wurde informiert."}),l()}catch(d){n({title:"Versand fehlgeschlagen",description:d.message,variant:"destructive"})}finally{i(null)}};return a?e.jsx("div",{className:"flex items-center justify-center py-20",children:e.jsx($e,{className:"h-6 w-6 animate-spin text-muted-foreground"})}):c.length===0?e.jsxs(Ss,{className:"p-12 text-center",children:[e.jsx($t,{className:"h-10 w-10 mx-auto text-muted-foreground mb-3"}),e.jsx("p",{className:"text-muted-foreground",children:"Keine Flughafentransfer-Add-ons für diese Reise konfiguriert."})]}):e.jsxs("div",{className:"space-y-6",children:[e.jsxs("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($t,{className:"h-5 w-5"})," Flughafen-Transfers"]}),e.jsx("p",{className:"text-sm text-muted-foreground mt-1",children:"Verwalte Abholzeiten, Hotels und Versand an Partner."})]}),e.jsxs(z,{variant:"outline",size:"sm",onClick:l,children:[e.jsx(Qa,{className:"h-4 w-4 mr-2"})," Aktualisieren"]})]}),c.map(j=>{var Z;const d=V.get(j.id)||[],u=A.get(j.id),I=d.reduce((H,L)=>H+(L.transfer_pax_count||L.quantity||0),0),E=j.transfer_max_pax_per_vehicle||4,$=d.reduce((H,L)=>H+Math.ceil((L.transfer_pax_count||L.quantity||0)/E),0),ge=j.addon_type==="airport_transfer_arrival"||j.addon_type==="airport_transfer_roundtrip",be=j.addon_type==="airport_transfer_departure"||j.addon_type==="airport_transfer_roundtrip";return e.jsxs(Ss,{className:"p-6 space-y-4",children:[e.jsxs("div",{className:"flex items-start justify-between gap-4 flex-wrap",children:[e.jsxs("div",{children:[e.jsxs("div",{className:"flex items-center gap-2 flex-wrap",children:[e.jsx("h3",{className:"text-lg font-semibold",children:j.name}),e.jsx(Xe,{variant:"secondary",children:j.addon_type.replace("airport_transfer_","")}),j.partner?e.jsxs(Xe,{variant:"outline",children:["Partner: ",j.partner.name,j.partner.email?` · ${j.partner.email}`:""]}):e.jsx(Xe,{variant:"destructive",children:"Kein Partner zugeordnet"})]}),e.jsxs("p",{className:"text-sm text-muted-foreground mt-2 flex gap-4 flex-wrap",children:[e.jsxs("span",{className:"inline-flex items-center gap-1",children:[e.jsx(Ns,{className:"h-3.5 w-3.5"})," ",d.length," Buchungen · ",I," Personen · ",$," Fahrzeuge"]}),u&&e.jsxs("span",{className:"inline-flex items-center gap-1",children:[e.jsx(Vs,{className:"h-3.5 w-3.5"})," Zuletzt gesendet: ",fs(new Date(u.sent_at),"d. MMM yyyy HH:mm",{locale:Ts})," (",u.trigger_source,")"]})]})]}),e.jsxs(z,{onClick:()=>W(j.id),disabled:!((Z=j.partner)!=null&&Z.email)||d.length===0||f===j.id,children:[f===j.id?e.jsx($e,{className:"h-4 w-4 mr-2 animate-spin"}):e.jsx(Bt,{className:"h-4 w-4 mr-2"}),"Manifest an Partner senden"]})]}),d.length===0?e.jsx("p",{className:"text-sm text-muted-foreground italic py-6 text-center",children:"Noch keine Buchungen für diesen Transfer."}):e.jsx("div",{className:"overflow-x-auto",children:e.jsxs("table",{className:"w-full text-sm",children:[e.jsx("thead",{className:"text-xs uppercase text-muted-foreground border-b",children:e.jsxs("tr",{children:[e.jsx("th",{className:"text-left py-2 pr-3",children:"Gast"}),e.jsx("th",{className:"text-left py-2 pr-3",children:"Personen / Autos"}),ge&&e.jsx("th",{className:"text-left py-2 pr-3",children:"Ankunft"}),ge&&e.jsx("th",{className:"text-left py-2 pr-3",children:"Hotel (Ankunft)"}),be&&e.jsx("th",{className:"text-left py-2 pr-3",children:"Abflug"}),be&&e.jsx("th",{className:"text-left py-2 pr-3",children:"Hotel (Abflug)"}),be&&e.jsx("th",{className:"text-left py-2 pr-3",children:"Abholzeit"}),e.jsx("th",{className:"text-right py-2",children:"Aktion"})]})}),e.jsx("tbody",{children:d.map(H=>{var De,_e,J;const L=T[H.id]||{},g=(L.transfer_pax_count??H.transfer_pax_count)||H.quantity||1,r=Math.ceil(g/E),m=H.participant_flights,X=(L.transfer_arrival_hotel??H.transfer_arrival_hotel)||"",p=(L.transfer_departure_hotel??H.transfer_departure_hotel)||"",ne=(L.transfer_pickup_time??H.transfer_pickup_time)||"",le=!!T[H.id],K=`${((De=H.participant_profiles)==null?void 0:De.first_name)||""} ${((_e=H.participant_profiles)==null?void 0:_e.last_name)||""}
143`.trim()||"—",M=H.transfer_direction||(ge&&be?"both":ge?"arrival":"departure"),ee=M==="arrival"||M==="both",he=M==="departure"||M==="both",we=M==="both"?"Hin & Zurück":M==="arrival"?"Nur Ankunft":"Nur Abflug";return e.jsxs("tr",{className:"border-b last:border-0 align-top",children:[e.jsxs("td",{className:"py-3 pr-3",children:[e.jsx("div",{className:"font-medium",children:K}),e.jsx("div",{className:"text-xs text-muted-foreground",children:(J=H.participant_profiles)==null?void 0:J.email}),ge&&be&&e.jsx(Xe,{variant:"outline",className:"mt-1 text-[10px]",children:we})]}),e.jsxs("td",{className:"py-3 pr-3",children:[e.jsx(te,{type:"number",min:1,className:"w-20",value:g,onChange:Ae=>q(H.id,"transfer_pax_count",parseInt(Ae.target.value)||1)}),e.jsxs("div",{className:"text-xs text-muted-foreground mt-1",children:[r," Fahrzeug",r!==1?"e":""]})]}),ge&&e.jsxs("td",{className:"py-3 pr-3 text-xs",children:[ee?m!=null&&m.arrival_date||m!=null&&m.arrival_flight_no?e.jsxs(e.Fragment,{children:[e.jsx("div",{className:"font-mono",children:(m==null?void 0:m.arrival_flight_no)||"—"}),e.jsxs("div",{children:[m!=null&&m.arrival_date?fs(He(m.arrival_date),"d.MM.",{locale:Ts}):"—"," ",m!=null&&m.arrival_time?m.arrival_time:e.jsx("span",{className:"text-muted-foreground italic",children:"Zeit fehlt"})]}),e.jsx("div",{className:"text-muted-foreground",children:m==null?void 0:m.arrival_airport})]}):e.jsx("span",{className:"text-muted-foreground italic",children:"Keine Flugdaten"}):e.jsx("span",{className:"text-muted-foreground",children:"—"}),ee&&e.jsx(te,{type:"datetime-local",className:"mt-2 min-w-[180px]",value:rn((L.transfer_arrival_datetime??H.transfer_arrival_datetime)||null),onChange:Ae=>q(H.id,"transfer_arrival_datetime",Ae.target.value?new Date(Ae.target.value).toISOString():null)})]}),ge&&e.jsx("td",{className:"py-3 pr-3",children:ee?e.jsx(te,{value:X,onChange:Ae=>q(H.id,"transfer_arrival_hotel",Ae.target.value),placeholder:"Hotel bei Ankunft",className:"min-w-[180px]"}):e.jsx("span",{className:"text-muted-foreground text-xs",children:"—"})}),be&&e.jsx("td",{className:"py-3 pr-3 text-xs",children:he?m!=null&&m.departure_date||m!=null&&m.departure_flight_no?e.jsxs(e.Fragment,{children:[e.jsx("div",{className:"font-mono",children:(m==null?void 0:m.departure_flight_no)||"—"}),e.jsxs("div",{children:[m!=null&&m.departure_date?fs(He(m.departure_date),"d.MM.",{locale:Ts}):"—"," ",m!=null&&m.departure_time?m.departure_time:e.jsx("span",{className:"text-muted-foreground italic",children:"Zeit fehlt"})]}),e.jsx("div",{className:"text-muted-foreground",children:m==null?void 0:m.departure_airport})]}):e.jsx("span",{className:"text-muted-foreground italic",children:"Keine Flugdaten"}):e.jsx("span",{className:"text-muted-foreground",children:"—"})}),be&&e.jsx("td",{className:"py-3 pr-3",children:he?e.jsx(te,{value:p,onChange:Ae=>q(H.id,"transfer_departure_hotel",Ae.target.value),placeholder:"Hotel bei Abflug",className:"min-w-[180px]"}):e.jsx("span",{className:"text-muted-foreground text-xs",children:"—"})}),be&&e.jsx("td",{className:"py-3 pr-3",children:he?e.jsx(te,{type:"datetime-local",value:rn(ne||null),onChange:Ae=>q(H.id,"transfer_pickup_time",Ae.target.value?new Date(Ae.target.value).toISOString():null),className:"min-w-[180px]"}):e.jsx("span",{className:"text-muted-foreground text-xs",children:"—"})}),e.jsx("td",{className:"py-3 text-right",children:e.jsx(z,{size:"sm",variant:le?"default":"ghost",disabled:!le||x===H.id,onClick:()=>y(H.id),children:x===H.id?e.jsx($e,{className:"h-4 w-4 animate-spin"}):e.jsx(Da,{className:"h-4 w-4"})})})]},H.id)})})]})})]},j.id)})]})}function Vc({tripId:s}){const[n,a]=t.useState([]),[b,f]=t.useState(!0),[i,x]=t.useState(!1),[h,c]=t.useState(!1),k=async()=>{f(!0);try{const{data:o,error:l}=await _.from("trip_waitlist").select("*").eq("trip_id",s).order("created_at",{ascending:!0});if(l)throw l;const V=(o==null?void 0:o.map(y=>y.profile_id))||[];let A=new Map;if(V.length>0){const{data:y}=await _.from("participant_profiles").select("id, first_name, last_name, email, phone").in("id",V);A=new Map((y==null?void 0:y.map(W=>[W.id,{first_name:W.first_name,last_name:W.last_name,email:W.email,phone:W.phone}]))||[])}const q=(o||[]).map(y=>({...y,profile:A.get(y.profile_id)}));a(q)}catch(o){console.error("Error fetching waitlist:",o),Y.error("Fehler beim Laden der Warteliste")}finally{f(!1)}};t.useEffect(()=>{k()},[s]);const C=async()=>{x(!0);try{if(n.filter(A=>A.status==="waiting").length===0){Y.info("Keine wartenden Einträge zum Benachrichtigen");return}const{data:l,error:V}=await _.functions.invoke("notify-waitlist-available",{body:{tripId:s,freedSpots:1}});if(V)throw V;Y.success(`${l.notified} Interessent(en) wurden benachrichtigt`),c(!1),k()}catch(o){console.error("Error notifying waitlist:",o),Y.error("Fehler beim Benachrichtigen",{description:"Bitte versuche es erneut."})}finally{x(!1)}},N=(o,l)=>{switch(o){case"waiting":return e.jsxs(Xe,{variant:"outline",className:"gap-1.5 bg-amber-50 text-amber-700 border-amber-200 dark:bg-amber-950/30 dark:text-amber-400 dark:border-amber-800",children:[e.jsx(Vs,{className:"h-3 w-3"}),"Wartend"]});case"notified":return e.jsxs(Xe,{variant:"outline",className:"gap-1.5 bg-blue-50 text-blue-700 border-blue-200 dark:bg-blue-950/30 dark:text-blue-400 dark:border-blue-800",children:[e.jsx(Ga,{className:"h-3 w-3"}),"Benachrichtigt"]});case"booked":return e.jsxs(Xe,{variant:"outline",className:"gap-1.5 bg-green-50 text-green-700 border-green-200 dark:bg-green-950/30 dark:text-green-400 dark:border-green-800",children:[e.jsx(ra,{className:"h-3 w-3"}),"Gebucht"]});case"cancelled":return e.jsxs(Xe,{variant:"outline",className:"gap-1.5 bg-muted text-muted-foreground",children:[e.jsx(tl,{className:"h-3 w-3"}),"Abgemeldet"]});default:return e.jsxs(Xe,{variant:"outline",className:"gap-1.5",children:[e.jsx(_r,{className:"h-3 w-3"}),o]})}},v=n.filter(o=>o.status==="waiting").length,G=n.filter(o=>o.status==="notified").length,T=n.reduce((o,l)=>o+l.participant_count,0);return b?e.jsx("div",{className:"flex items-center justify-center py-12",children:e.jsx($e,{className:"h-8 w-8 animate-spin text-primary"})}):e.jsxs("div",{className:"space-y-6",children:[e.jsxs("div",{className:"grid grid-cols-1 md:grid-cols-3 gap-4",children:[e.jsxs("div",{className:"glass-card p-4 flex items-center gap-4",children:[e.jsx("div",{className:"flex h-10 w-10 items-center justify-center rounded-xl bg-amber-100 dar
143k:bg-amber-900/30",children:e.jsx(Vs,{className:"h-5 w-5 text-amber-600 dark:text-amber-400"})}),e.jsxs("div",{children:[e.jsx("p",{className:"text-sm text-muted-foreground",children:"Wartend"}),e.jsxs("p",{className:"font-semibold text-foreground",children:[v," Einträge"]})]})]}),e.jsxs("div",{className:"glass-card p-4 flex items-center gap-4",children:[e.jsx("div",{className:"flex h-10 w-10 items-center justify-center rounded-xl bg-blue-100 dark:bg-blue-900/30",children:e.jsx(Ga,{className:"h-5 w-5 text-blue-600 dark:text-blue-400"})}),e.jsxs("div",{children:[e.jsx("p",{className:"text-sm text-muted-foreground",children:"Benachrichtigt"}),e.jsxs("p",{className:"font-semibold text-foreground",children:[G," Einträge"]})]})]}),e.jsxs("div",{className:"glass-card p-4 flex items-center gap-4",children:[e.jsx("div",{className:"flex h-10 w-10 items-center justify-center rounded-xl bg-primary/10",children:e.jsx(Ns,{className:"h-5 w-5 text-primary"})}),e.jsxs("div",{children:[e.jsx("p",{className:"text-sm text-muted-foreground",children:"Interessenten gesamt"}),e.jsxs("p",{className:"font-semibold text-foreground",children:[T," Personen"]})]})]})]}),v>0&&e.jsx("div",{className:"flex justify-end",children:e.jsxs(z,{onClick:()=>c(!0),className:"gap-2",children:[e.jsx(Bt,{className:"h-4 w-4"}),"Alle benachrichtigen (",v,")"]})}),n.length===0?e.jsxs("div",{className:"glass-card p-12 text-center",children:[e.jsx(Ns,{className:"h-12 w-12 mx-auto text-muted-foreground/40 mb-4"}),e.jsx("h3",{className:"text-lg font-medium text-foreground mb-2",children:"Keine Wartelisten-Einträge"}),e.jsx("p",{className:"text-muted-foreground",children:"Wenn die Reise ausgebucht ist, können sich Interessenten auf die Warteliste setzen."})]}):e.jsx("div",{className:"glass-card overflow-hidden",children:e.jsxs(ga,{children:[e.jsx(fa,{children:e.jsxs(ct,{children:[e.jsx(rs,{children:"Name"}),e.jsx(rs,{children:"Kontakt"}),e.jsx(rs,{className:"text-center",children:"Personen"}),e.jsx(rs,{children:"Status"}),e.jsx(rs,{children:"Eingetragen am"}),e.jsx(rs,{children:"Benachrichtigt am"}),e.jsx(rs,{children:"Notizen"})]})}),e.jsx(ja,{children:n.map(o=>{var l,V,A,q,y,W,j,d,u,I;return e.jsxs(ct,{children:[e.jsx(ss,{children:e.jsxs("div",{className:"flex items-center gap-3",children:[e.jsx("div",{className:"flex h-9 w-9 items-center justify-center rounded-full bg-muted",children:e.jsx(sl,{className:"h-5 w-5 text-muted-foreground"})}),e.jsx("div",{children:e.jsxs("p",{className:"font-medium text-foreground",children:[(o.first_name??((l=o.profile)==null?void 0:l.first_name))&&(o.last_name??((V=o.profile)==null?void 0:V.last_name))?`${o.first_name??((A=o.profile)==null?void 0:A.first_name)} ${o.last_name??((q=o.profile)==null?void 0:q.last_name)}`:"Unbekannt",o.date_of_birth&&e.jsxs("span",{className:"text-muted-foreground font-normal ml-1",children:["(",bn(new Date,He(o.date_of_birth)),")"]})]})})]})}),e.jsx(ss,{children:e.jsxs("div",{className:"space-y-1",children:[(o.email??((y=o.profile)==null?void 0:y.email))&&e.jsxs("div",{className:"flex items-center gap-1.5 text-sm text-muted-foreground",children:[e.jsx(Os,{className:"h-3 w-3"}),e.jsx("a",{href:`mailto:${o.email??((W=o.profile)==null?void 0:W.email)}`,className:"hover:text-primary",children:o.email??((j=o.profile)==null?void 0:j.email)})]}),(o.phone??((d=o.profile)==null?void 0:d.phone))&&e.jsxs("div",{className:"flex items-center gap-1.5 text-sm text-muted-foreground",children:[e.jsx(xa,{className:"h-3 w-3"}),e.jsx("a",{href:`tel:${o.phone??((u=o.profile)==null?void 0:u.phone)}`,className:"hover:text-primary",children:o.phone??((I=o.profile)==null?void 0:I.phone)})]})]})}),e.jsx(ss,{className:"text-center",children:e.jsx(Xe,{variant:"secondary",children:o.participant_count})}),e.jsx(ss,{children:N(o.status||"waiting",o.notified_at)}),e.jsx(ss,{children:e.jsxs("div",{className:"flex items-center gap-1.5 text-sm text-muted-foreground",children:[e.jsx(kt,{className:"h-3 w-3"}),fs(new Date(o.created_at),"dd.MM.yyyy HH:mm",{locale:Ts})]})}),e.jsx(ss,{children:o.notified_at?e.jsxs("div",{className:"flex items-center gap-1.5 text-sm text-blue-600 dar
143k:text-blue-400",children:[e.jsx(Ga,{className:"h-3 w-3"}),fs(new Date(o.notified_at),"dd.MM.yyyy HH:mm",{locale:Ts})]}):e.jsx("span",{className:"text-sm text-muted-foreground",children:"—"})}),e.jsx(ss,{children:e.jsx("span",{className:"text-sm text-muted-foreground",children:o.notes||"—"})})]},o.id)})})]})}),e.jsx(mt,{open:h,onOpenChange:c,children:e.jsxs(ut,{children:[e.jsxs(ht,{children:[e.jsxs(xt,{className:"flex items-center gap-2",children:[e.jsx(Bt,{className:"h-5 w-5 text-primary"}),"Warteliste benachrichtigen"]}),e.jsxs(pt,{children:["Es werden ",e.jsxs("strong",{children:[v," E-Mails"]})," an alle wartenden Interessenten versendet. Sie werden informiert, dass Plätze frei geworden sind."]})]}),e.jsxs(gt,{children:[e.jsx(ft,{disabled:i,children:"Abbrechen"}),e.jsx(jt,{onClick:o=>{o.preventDefault(),C()},disabled:i,className:"gap-2",children:i?e.jsxs(e.Fragment,{children:[e.jsx($e,{className:"h-4 w-4 animate-spin"}),"Wird gesendet..."]}):e.jsxs(e.Fragment,{children:[e.jsx(Os,{className:"h-4 w-4"}),"Jetzt senden"]})})]})]})})]})}const Kc={open:"Offen",contacted:"Angeschrieben",booked:"Gebucht",archived:"Archiviert"};function Zc({templateId:s}){const n=ta(),{data:a,isLoading:b}=al(),{data:f}=rl(),i=t.useMemo(()=>{if(!s)return[];const h=new Map((f||[]).map(c=>[c.profile_id,c]));return(a||[]).filter(c=>c.template_id===s&&c.status!=="booked"&&c.status!=="archived").map(c=>({...c,person:h.get(c.profile_id)||null}))},[a,f,s]),x=async h=>{const{error:c}=await _.from("participant_travel_intents").update({status:"contacted",contacted_at:new Date().toISOString()}).eq("id",h);if(c){Y.error("Konnte nicht gespeichert werden");return}Y.success("Als angeschrieben markiert"),n.invalidateQueries({queryKey:["loyalty-intent-pipeline"]})};return s?b?e.jsx(Pa,{className:"h-40 w-full"}):e.jsxs(Ss,{children:[e.jsxs(Mt,{children:[e.jsxs(Gt,{className:"flex items-center gap-2",children:[e.jsx(jn,{className:"h-4 w-4 text-muted-foreground"}),"Interessenten aus dem Explorer Club"]}),e.jsx(Vn,{children:"Gäste, die diese Reise im Portal als nächsten Wunsch hinterlegt haben — ideal für die Ansprache bei letzten Plätzen."})]}),e.jsx(Rs,{children:i.length?e.jsx("div",{className:"overflow-x-auto",children:e.jsxs(ga,{children:[e.jsx(fa,{children:e.jsxs(ct,{children:[e.jsx(rs,{children:"Name"}),e.jsx(rs,{children:"Zeitraum"}),e.jsx(rs,{className:"text-right",children:"Punkte"}),e.jsx(rs,{children:"Stufe (Prognose)"}),e.jsx(rs,{children:"Notiz"}),e.jsx(rs,{children:"Status"}),e.jsx(rs,{})]})}),e.jsx(ja,{children:i.map(h=>{var c,k,C,N;return e.jsxs(ct,{children:[e.jsxs(ss,{className:"font-medium",children:[[(c=h.person)==null?void 0:c.first_name,(k=h.person)==null?void 0:k.last_name].filter(Boolean).join(" ")||"Unbekannt",e.jsx("div",{className:"text-xs text-muted-foreground",children:(C=h.person)==null?void 0:C.email})]}),e.jsxs(ss,{children:[nl[h.timeframe]??"Noch offen",e.jsxs("div",{className:"text-xs text-muted-foreground",children:["seit ",fs(new Date(h.created_at),"dd.MM.yyyy",{locale:Ts})]})]}),e.jsx(ss,{className:"text-right",children:h.person?`${h.person.current_points} (+${h.person.pending_points})`:"—"}),e.jsx(ss,{children:h.person?e.jsxs(Xe,{variant:"secondary",children:[h.person.current_tier," → ",h.person.projected_tier]}):"—"}),e.jsx(ss,{className:"max-w-[220px]",children:e.jsx("span",{className:"block truncate text-sm",children:h.note||"—"})}),e.jsx(ss,{children:e.jsx(Xe,{variant:h.status==="contacted"?"outline":"default",children:Kc[h.status]??h.status})}),e.jsx(ss,{className:"text-right",children:e.jsxs("div",{className:"flex justify-end gap-2",children:[((N=h.person)==null?void 0:N.email)&&e.jsx(z,{asChild:!0,variant:"outline",size:"sm",children:e.jsx("a",{href:`mailto:${h.person.email}`,children:e.jsx(Os,{className:"h-4 w-4"})})}),h.status==="open"&&e.jsx(z,{variant:"ghost",size:"sm",onClick:()=>x(h.id),children:"Angeschrieben"})]})})]},h.id)})})]})}):e.jsx("p",{className:"py-6 text-center text-muted-foreground",children:"Noch keine Wünsche für diese Reise"})})]}):null}const Hc=20*1024*1024;function Wc({tripId:s}){const{user:n}=tr(),a=ta(),b=t.useRef(null),[f,i]=t.useState([]),[x,h]=t.useState(!1),[c,k]=t.useState("all"),[C,N]=t.useState(!1),[v,G]=t.useState(!1),{data:T}=dt({queryKey:["admin-trip-photo-meta",s],queryFn:async()=>{const{data:L}=await _.from("trips").select("id, name, photo_reminder_sent_at").eq("id",s).single();return L}}),{data:o=[],isLoading:l}=dt({queryKey:["admin-trip-photos",s],queryFn:async()=>{const{data:L,error:g}=await _.from("trip_photos").select("id, storage_path, file_size_kb, profile_id, uploaded_by_admin_id, created_at, participant_profiles(first_name, last_name, profile_image)").eq("trip_id",s).order("created_at",{ascending:!1});if(g)throw g;return L||[]}}),{data:V={}}=dt({queryKey:["admin-trip-photo-downloads",s],queryFn:async()=>{const{data:L,error:g}=await _.from("trip_photo_downloads").select("photo_id").eq("trip_id",s);if(g)throw g;const r={};
143return(L||[]).forEach(m=>{r[m.photo_id]=(r[m.photo_id]||0)+1}),r}}),A=t.useMemo(()=>Object.values(V).reduce((L,g)=>L+g,0),[V]),q=t.useMemo(()=>Array.from(new Set(o.map(L=>L.uploaded_by_admin_id).filter(Boolean))),[o]),{data:y=[]}=dt({queryKey:["admin-profiles",q.join(",")],queryFn:async()=>{if(q.length===0)return[];const{data:L}=await _.from("profiles").select("user_id, full_name, email").in("user_id",q);return L||[]},enabled:q.length>0}),W=t.useMemo(()=>{const L=new Map;return y.forEach(g=>L.set(g.user_id,g.full_name||g.email||"Admin")),L},[y]),[j,d]=t.useState({});t.useMemo(()=>{(async()=>{const L=o.filter(r=>!j[r.storage_path]);if(L.length===0)return;const g={};for(const r of L){const{data:m}=await _.storage.from("trip-photos").createSignedUrl(r.storage_path,3600);m!=null&&m.signedUrl&&(g[r.storage_path]=m.signedUrl)}Object.keys(g).length&&d(r=>({...r,...g}))})()},[o]);const u=async L=>{if(!n)return;const g=L.name;i(r=>[...r,{fileName:g,progress:10,status:"uploading"}]);try{let r=L,m=L.name;if(ll(L)){const ee=await cl(L,{maxWidth:1920,maxHeight:1080,quality:.85,outputFormat:"webp"});r=ee.blob,m=ee.filename}const{sha256Hex:X}=await Ca(async()=>{const{sha256Hex:ee}=await import("./contentHash-CBeKi1jz.js");return{sha256Hex:ee}},[]),p=await X(r),{data:ne}=await _.from("trip_photos").select("id").eq("trip_id",s).eq("content_hash",p).maybeSingle();if(ne){i(ee=>ee.map(he=>he.fileName===g?{...he,progress:100,status:"done"}:he)),Y.info(`"${g}" wurde bereits hochgeladen`);return}i(ee=>ee.map(he=>he.fileName===g?{...he,progress:50}:he));const le=`admin/${s}/${Date.now()}-${m}`,{error:K}=await _.storage.from("trip-photos").upload(le,r);if(K)throw K;const{error:M}=await _.from("trip_photos").insert({trip_id:s,profile_id:null,uploaded_by_admin_id:n.id,storage_path:le,file_size_kb:Math.round(r.size/1024),content_hash:p});if(M)throw M;i(ee=>ee.map(he=>he.fileName===g?{...he,progress:100,status:"done"}:he))}catch(r){console.error(r),i(m=>m.map(X=>X.fileName===g?{...X,status:"error"}:X)),Y.error(`Upload fehlgeschlagen: ${g}`)}},I=t.useCallback(async L=>{const g=Array.from(L).filter(r=>r.type.startsWith("image/")?r.size>Hc?(Y.error(`${r.name} zu groß (max 20MB)`),!1):!0:(Y.error(`${r.name} ist kein Bild`),!1));for(const r of g)await u(r);a.invalidateQueries({queryKey:["admin-trip-photos",s]}),setTimeout(()=>i([]),2e3)},[s,n]),E=async(L,g)=>{if(confirm("Foto wirklich löschen?"))try{await _.storage.from("trip-photos").remove([g]),await _.from("trip_photos").delete().eq("id",L),a.invalidateQueries({queryKey:["admin-trip-photos",s]}),Y.success("Gelöscht")}catch{Y.error("Fehler beim Löschen")}},$=async L=>{var g;if(n)try{const r=j[L.storage_path]||((g=(await _.storage.from("trip-photos").createSignedUrl(L.storage_path,3600)).data)==null?void 0:g.signedUrl);if(!r){Y.error("Download fehlgeschlagen");return}
143const m=document.createElement("a");m.href=r,m.download=L.storage_path.split("/").pop()||"photo.webp",m.target="_blank",document.body.appendChild(m),m.click(),document.body.removeChild(m),await _.from("trip_photo_downloads").insert({photo_id:L.id,trip_id:s,downloaded_by_admin_id:n.id,download_type:"single"}),a.invalidateQueries({queryKey:["admin-trip-photo-downloads",s]})}catch(r){console.warn("Download failed",r)}},ge=async()=>{G(!0);try{const{data:L,error:g}=await _.functions.invoke("send-photo-upload-reminder",{body:{tripId:s}});if(g)throw g;Y.success(`Erinnerung an ${(L==null?void 0:L.sent)??0} Teilnehmer gesendet`),a.invalidateQueries({queryKey:["admin-trip-photo-meta",s]}),N(!1)}catch(L){Y.error(L.message||"Fehler beim Versand")}finally{G(!1)}},be=t.useMemo(()=>{const L=new Map;return o.forEach(g=>{var p,ne;const r=g.uploaded_by_admin_id?`admin:${g.uploaded_by_admin_id}`:`user:${g.profile_id}`,m=g.uploaded_by_admin_id?W.get(g.uploaded_by_admin_id)||"Admin":`${((p=g.participant_profiles)==null?void 0:p.first_name)||""} ${((ne=g.participant_profiles)==null?void 0:ne.last_name)||""}`.trim()||"Unbekannt",X=L.get(r);X?X.count++:L.set(r,{label:m,count:1})}),Array.from(L.entries())},[o,W]),Z=c==="all"?o:o.filter(L=>(L.uploaded_by_admin_id?`admin:${L.uploaded_by_admin_id}`:`user:${L.profile_id}`)===c),H=T!=null&&T.photo_reminder_sent_at?fs(new Date(T.photo_reminder_sent_at),"dd.MM.yyyy 'um' HH:mm",{locale:Ts}):null;return e.jsxs("div",{className:"space-y-6",children:[e.jsxs("div",{className:"flex flex-col sm:flex-row sm:items-center justify-between gap-3",children:[e.jsxs("div",{children:[e.jsxs("h2",{className:"text-lg font-semibold flex items-center gap-2",children:[e.jsx(Ya,{className:"h-5 w-5"}),"Gruppen-Fotoalbum"]}),e.jsxs("p",{className:"text-sm text-muted-foreground",children:[o.length," Foto",o.length!==1?"s":""," insgesamt",A>0&&e.jsxs("span",{className:"ml-2 inline-flex items-center gap-1",children:["· ",e.jsx(lt,{className:"h-3 w-3 inline"})," ",A," Download",A!==1?"s":""]})]})]}),e.jsxs(z,{variant:"outline",onClick:()=>N(!0),className:"gap-2",children:[e.jsx(Bt,{className:"h-4 w-4"}),"Foto-Erinnerung senden"]})]}),H&&e.jsxs("p",{className:"text-xs text-muted-foreground",children:["Letzte Erinnerung: ",H]}),e.jsxs("div",{onDragOver:L=>{L.preventDefault(),h(!0)},onDragLeave:()=>h(!1),onDrop:L=>{L.preventDefault(),h(!1),L.dataTransfer.files.length&&I(L.dataTransfer.files)},onClick:()=>{var L;return(L=b.current)==null?void 0:L.click()},className:`border-2 border-dashed rounded-xl p-8 text-center cursor-pointer transition-colors ${x?"border-primary bg-primary/5":"border-muted-foreground/20 hover:border-primary/50"}`,children:[e.jsx(_t,{className:"h-10 w-10 mx-auto mb-2 text-muted-foreground"}),e.jsx("p",{className:"font-medium",children:"Fotos hierhin ziehen oder klicken"}),e.jsx("p",{className:"text-xs text-muted-foreground mt-1",children:"Werden mit deinem Admin-Namen gespeichert"}),e.jsx("input",{ref:b,type:"file",accept:"image/*",multiple:!0,className:"hidden",onChange:L=>{L.target.files&&I(L.target.files),L.target.value=""}})]}),f.length>0&&e.jsx("div",{className:"space-y-2",children:f.map((L,g)=>e.jsxs("div",{className:"flex items-center gap-3",children:[L.status==="uploading"&&e.jsx($e,{className:"h-4 w-4 animate-spin text-primary"}),e.jsxs("div",{className:"flex-1 min-w-0",children:[e.jsx("p",{className:"text-sm truncate",children:L.fileName}),e.jsx(il,{value:L.progress,className:"h-1.5 mt-1"})]})]},g))}),be.length>1&&e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(ol,{className:"h-4 w-4 text-muted-foreground"}),e.jsxs(Ie,{value:c,onValueChange:k,children:[e.jsx(Oe,{className:"w-[260px]",children:e.jsx(Ve,{})}),e.jsxs(Ue,{children:[e.jsxs(O,{value:"all",children:["Alle (",o.length,")"]}),be.map(([L,g])=>e.jsxs(O,{value:L,children:[g.label," (",g.count,")"]},L))]})]})]}),l?e.jsx("div",{className:"flex justify-center py-8",children:e.jsx($e,{className:"h-6 w-6 animate-spin text-primary"})}):Z.length===0?e.jsx(Ss,{className:"border-dashed",children:e.jsxs(Rs,{className:"pt-6 text-center text-muted-foreground",children:[e.jsx(Ya,{className:"h-10 w-10 mx-auto mb-2 opacity-50"}),"Noch keine Fotos"]})}):e.jsx("div",{className:"grid grid-cols-2 sm:grid-cols-3 md:grid-cols-4 gap-3",children:Z.map(L=>{var X,p;const g=j[L.storage_path],r=V[L.id]||0,m=L.uploaded_by_admin_id?`${W.get(L.uploaded_by_admin_id)||"Admin"} (Team)`:`${((X=L.participant_profiles)==null?void 0:X.first_name)||""} ${((p=L.participant_profiles)==null?void 0:p.last_name)||""}`.trim()||"Unbekannt";return e.jsxs("div",{className:"relative group aspect-square rounded-lg overflow-hidden bg-muted",children:[g?e.jsx("img",{src:g,alt:"",className:"w-full h-full object-cover",loading:"lazy"}):e.jsx("div",{className:"flex items-center justify-center h-full",children:e.jsx($e,{className:"h-5 w-5 animate-spin text-muted-foreground"})}),r>0&&e.jsxs("div",{className:"absolute top-2 left-2 bg-black/70 text-white rounded-full px-2 py-0.5 text-[10px] font-medium flex items-center gap-1",children:[e.jsx(lt,{className:"h-3 w-3"})," ",r]}),e.jsx("div",{className:"absolute inset-x-0 bottom-0 bg-gradient-to-t from-black/70 to-transparent p-2",children:e.jsx("p",{className:"text-[11px] text-white truncate",children:m})}),e.jsxs("div",{className:"absolute top-2 right-2 flex gap-1 opacity-0 group-hover:opacity-100 transition-opacity",children:[e.jsx("button",{onClick:()=>$(L),className:"bg-black/70 hover:bg-black rounded-full p-1.5",title:"Herunterladen",children:e.jsx(lt,{className:"h-3.5 w-3.5 text-white"})}),e.jsx("button",{onClick:()=>E(L.id,L.storage_path),className:"bg-destructive/90 hover:bg-destructive rounded-full p-1.5",title:"Löschen",children:e.jsx(bs,{className:"h-3.5 w-3.5 text-white"})})]})]},L.id)})}),e.jsx(mt,{open:C,onOpenChange:N,children:e.jsxs(ut,{children:[e.jsxs(ht,{children:[e.jsx(xt,{children:"Foto-Erinnerung versenden?"}),e.jsxs(pt,{children:["Es wird eine E-Mail an alle Teilnehmer dieser Reise gesendet, die noch keine Fotos hochgeladen haben.",H&&e.jsxs("span",{className:"block mt-2 text-orange-600",children:["⚠️ Letzte Erinnerung wurde am ",H," gesendet."]})]})]}),e.jsxs(gt,{children:[e.jsx(ft,{disabled:v,children:"Abbrechen"}),e.jsxs(jt,{onClick:ge,disabled:v,children:[v?e.jsx($e,{className:"h-4 w-4 animate-spin mr-2"}):null,"Senden"]})]})]})})]})}function Qc(s){const n=ta(),a=["trip-inquiries",s],{data:b=[],isLoading:f,error:i}=dt({queryKey:a,queryFn:async()=>
143{if(!s)return[];const{data:N,error:v}=await _.from("trip_inquiries").select(`
144          *,
145          companions:inquiry_companions(*),
146          rejection_template:inquiry_rejection_templates(name)
147        `).eq("trip_id",s).order("created_at",{ascending:!1});if(v)throw v;return N},enabled:!!s}),x=oa({mutationFn:async({id:N,...v})=>{const{data:G,error:T}=await _.from("trip_inquiries").update(v).eq("id",N).select().single();if(T)throw T;return G},onSuccess:()=>{n.invalidateQueries({queryKey:a})},onError:N=>{console.error("Error updating inquiry:",N),Y.error("Fehler beim Aktualisieren der Anfrage")}}),h=oa({mutationFn:async N=>{const{data:v,error:G}=await _.from("trip_inquiries").select("*").eq("id",N).single();if(G)throw G;const{error:T}=await _.from("trip_inquiries").update({status:"approved",processed_at:new Date().toISOString()}).eq("id",N);if(T)throw T;const{error:o}=await _.functions.invoke("send-inquiry-approved",{body:{inquiryId:N}});return o&&console.error("Email error:",o),v},onSuccess:()=>{n.invalidateQueries({queryKey:a}),Y.success("Anfrage freigegeben – E-Mail wurde versendet")},onError:N=>{console.error("Error approving inquiry:",N),Y.error("Fehler beim Freigeben der Anfrage")}}),c=oa({mutationFn:async({inquiryId:N,reason:v,customMessage:G,templateId:T})=>{const o={inquiryId:N};T?o.templateId=T:G&&(o.customSubject="Deine Anfrage bei Off The Path",o.customBody=G),v&&(o.reason=v);const{error:l}=await _.functions.invoke("send-inquiry-rejected",{body:o});if(l)throw new Error("E-Mail konnte nicht gesendet werden")},onSuccess:()=>{n.invalidateQueries({queryKey:a}),Y.success("Anfrage abgelehnt – E-Mail wurde versendet")},onError:N=>{console.error("Error rejecting inquiry:",N),Y.error("Fehler beim Ablehnen der Anfrage")}}),k=oa({mutationFn:async N=>{const{error:v}=await _.from("leads").update({inquiry_id:null}).eq("inquiry_id",N);if(v)throw v;const{error:G}=await _.from("inquiry_companions").delete().eq("inquiry_id",N);if(G)throw G;const{error:T}=await _.from("trip_inquiries").delete().eq("id",N);if(T)throw T},onSuccess:()=>{n.invalidateQueries({queryKey:a}),n.invalidateQueries({queryKey:["all-inquiries"]}),Y.success("Anfrage gelöscht")},onError:N=>{console.error("Error deleting inquiry:",N),Y.error("Fehler beim Löschen der Anfrage")}}),C={total:b.length,pending:b.filter(N=>N.status==="pending").length,approved:b.filter(N=>N.status==="approved").length,rejected:b.filter(N=>N.status==="rejected").length,converted:b.filter(N=>N.status==="converted").length};return{inquiries:b,isLoading:f,error:i,stats:C,updateInquiry:x,approveInquiry:h,rejectInquiry:c,deleteInquiry:k}}const Yc={pending:{label:"Offen",variant:"default",icon:Vs},approved:{label:"Freigegeben",variant:"secondary",icon:Ut},rejected:{label:"Abgelehnt",variant:"destructive",icon:Fa},converted:{label:"Gebucht",variant:"outline",icon:Fn}};function Za(s){return s?bn(new Date,He(s)):null}function Jc({tripId:s}){const{inquiries:n,isLoading:a,stats:b,approveInquiry:f,rejectInquiry:i,updateInquiry:x,deleteInquiry:h}=Qc(s),[c,k]=t.useState(null),[C,N]=t.useState(!1),[v,G]=t.useState(!1),[T,o]=t.useState(!1),[l,V]=t.useState(null),[A,q]=t.useState(""),[y,W]=t.useState(""),[j,d]=t.useState(null),[u,I]=t.useState(null),{data:E=[]}=dt({queryKey:["rejection-templates"],queryFn:async()=>{const{data:p,error:ne}=await _.from("inquiry_rejection_templates").select("*").eq("is_active",!0).order("sort_order",{ascending:!0});if(ne)throw ne;return p}}),{data:$}=dt({queryKey:["trip-info-reject",s],queryFn:async()=>{const{data:p,error:ne}=await _.from("trips").select("name, start_date, end_date").eq("id",s).single();if(ne)throw ne;return p},enabled:!!s});t.useEffect(()=>{v&&(W(""),q(""))},[v]);const ge=t.useMemo(()=>{if(!y||!c||!$)return"";const p=E.find(K=>K.id===y);if(!p)return"";const ne=He($.start_date).toLocaleDateString("de-DE",{day:"2-digit",month:"long",year:"numeric"}),le=He($.end_date).toLocaleDateString("de-DE",{day:"2-digit",month:"long",year:"numeric"});return p.body_template.replace(/{first_name}/g,c.first_name).replace(/{last_name}/g,c.last_name).replace(/{trip_name}/g,$.name).replace(/{trip_date}/g,`${ne} - ${le}`)},[y,c,$,E]),be=n.filter(p=>!p.inquiry_type||p.inquiry_type==="group"),Z=j?be.filter(p=>p.status===j):be,H=p=>{I(ne=>ne===p?null:p)},L=async p=>{await f.mutateAsync(p.id),N(!1)},g=async()=>{c&&(await i.mutateAsync({inquiryId:c.id,...y?{templateId:y}:{customMessage:A}}),G(!1),N(!1),q(""),W(""))},r=async()=>{c&&(await x.mutateAsync({id:c.id,status:"rejected",processed_at:new Date().toISOString(),...y?{rejection_template_id:y,rejection_reason:null}:{rejection_reason:A||null,rejection_template_id:null}}),G(!1),N(!1),q(""),W(""),Y.success("Anfrage abgelehnt – ohne E-Mail"))},m=p=>{const ne=`${window.location.origin}/booking?token=${p}`;navigator.clipboard.writeText(ne),Y.success("Buchungslink kopiert")},X=p=>{k(p),N(!0)};return a?e.jsxs("div",{className:"space-y-4",children:[e.jsx("div",{className:"grid grid-cols-4 gap-4",children:[1,2,3,4].map(p=>e.jsx(Pa,{className:"h-24"},p))}),e.jsx(Pa,{className:"h-64"})]}):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(Ss,{className:`curs
147or-pointer transition-all ${j==="pending"?"ring-2 ring-primary":"hover:bg-muted/50"}`,onClick:()=>d(j==="pending"?null:"pending"),children:e.jsx(Rs,{className:"pt-4",children:e.jsxs("div",{className:"flex items-center gap-3",children:[e.jsx("div",{className:"p-2 rounded-lg bg-amber-100 dark:bg-amber-900/30",children:e.jsx(Vs,{className:"h-5 w-5 text-amber-600 dark:text-amber-400"})}),e.jsxs("div",{children:[e.jsx("p",{className:"text-2xl font-bold",children:b.pending}),e.jsx("p",{className:"text-sm text-muted-foreground",children:"Offen"})]})]})})}),e.jsx(Ss,{className:`cursor-pointer transition-all ${j==="approved"?"ring-2 ring-primary":"hover:bg-muted/50"}`,onClick:()=>d(j==="approved"?null:"approved"),children:e.jsx(Rs,{className:"pt-4",children:e.jsxs("div",{className:"flex items-center gap-3",children:[e.jsx("div",{className:"p-2 rounded-lg bg-green-100 dark:bg-green-900/30",children:e.jsx(Ut,{className:"h-5 w-5 text-green-600 dark:text-green-400"})}),e.jsxs("div",{children:[e.jsx("p",{className:"text-2xl font-bold",children:b.approved}),e.jsx("p",{className:"text-sm text-muted-foreground",children:"Freigegeben"})]})]})})}),e.jsx(Ss,{className:`cursor-pointer transition-all ${j==="rejected"?"ring-2 ring-primary":"hover:bg-muted/50"}`,onClick:()=>d(j==="rejected"?null:"rejected"),children:e.jsx(Rs,{className:"pt-4",children:e.jsxs("div",{className:"flex items-center gap-3",children:[e.jsx("div",{className:"p-2 rounded-lg bg-red-100 dark:bg-red-900/30",children:e.jsx(Fa,{className:"h-5 w-5 text-red-600 dark:text-red-400"})}),e.jsxs("div",{children:[e.jsx("p",{className:"text-2xl font-bold",children:b.rejected}),e.jsx("p",{className:"text-sm text-muted-foreground",children:"Abgelehnt"})]})]})})}),e.jsx(Ss,{className:`cursor-pointer transition-all ${j==="converted"?"ring-2 ring-primary":"hover:bg-muted/50"}`,onClick:()=>d(j==="converted"?null:"converted"),children:e.jsx(Rs,{className:"pt-4",children:e.jsxs("div",{className:"flex items-center gap-3",children:[e.jsx("div",{className:"p-2 rounded-lg bg-blue-100 dark:bg-blue-900/30",children:e.jsx(Fn,{className:"h-5 w-5 text-blue-600 dark:text-blue-400"})}),e.jsxs("div",{children:[e.jsx("p",{className:"text-2xl font-bold",children:b.converted}),e.jsx("p",{className:"text-sm text-muted-foreground",children:"Gebucht"})]})]})})})]}),e.jsxs(Ss,{children:[e.jsxs(Mt,{className:"flex flex-row items-center justify-between",children:[e.jsx(Gt,{children:"Anfragen"}),j&&e.jsx(z,{variant:"ghost",size:"sm",onClick:()=>d(null),children:"Filter zurücksetzen"})]}),e.jsx(Rs,{children:Z.length===0?e.jsxs("div",{className:"text-center py-12 text-muted-foreground",children:[e.jsx(_n,{className:"h-12 w-12 mx-auto mb-4 opacity-50"}),e.jsx("p",{children:"Keine Anfragen vorhanden"})]}):e.jsxs(ga,{children:[e.jsx(fa,{children:e.jsxs(ct,{children:[e.jsx(rs,{children:"Name"}),e.jsx(rs,{children:"Kontakt"}),e.jsx(rs,{children:"Alter"}),e.jsx(rs,{children:"Teilnehmer"}),e.jsx(rs,{children:"Status"}),e.jsx(rs,{children:"Eingang"}),e.jsx(rs,{className:"w-[80px]"})]})}),e.jsx(ja,{children:Z.map(p=>{var ee,he;const ne=Za(p.date_of_birth),le=Yc[p.status||"pending"],K=le.icon,M=u===p.id;return e.jsxs(e.Fragment,{children:[e.jsxs(ct,{className:"cursor-pointer hover:bg-muted/50",onClick:()=>H(p.id),children:[e.jsx(ss,{className:"font-medium",children:e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(Us,{className:`h-4 w-4 shrink-0 text-muted-foreground transition-transform duration-200 ${M?"rotate-180":""}`}),p.first_name," ",p.last_name,p.inquiry_type==="private"&&e.jsx(Xe,{variant:"outline",className:"text-xs bg-purple-50 text-purple-700 border-purple-200 dark:bg-purple-900/30 dark:text-purple-300 dark:border-purple-700",children:"Private Tour"}),p.needs_gender_review&&e.jsx("span",{title:"Geschlechter-Review erforderlich",children:e.jsx(Lt,{className:"h-4 w-4 text-amber-500"})})]})}),e.jsx(ss,{children:e.jsxs("div",{className:"flex flex-col gap-1",children:[e.jsxs("span",{className:"flex items-center gap-1 text-sm",children:[e.jsx(Os,{className:"h-3 w-3"}),p.email]}),p.phone&&e.jsxs("span",{className:"flex items-center gap-1 text-sm text-muted-foreground",children:[e.jsx(xa,{
147className:"h-3 w-3"}),p.phone]})]})}),e.jsx(ss,{children:ne!==null?`${ne} Jahre`:"-"}),e.jsx(ss,{children:e.jsxs("div",{className:"flex items-center gap-1",children:[e.jsx(Ns,{className:"h-4 w-4 text-muted-foreground"}),p.participant_count||1]})}),e.jsx(ss,{children:e.jsxs(Xe,{variant:le.variant,className:"gap-1",title:p.status==="rejected"?`Grund: ${p.rejection_reason||((ee=p.rejection_template)==null?void 0:ee.name)||"Kein Grund hinterlegt"}`:void 0,children:[e.jsx(K,{className:"h-3 w-3"}),le.label]})}),e.jsx(ss,{className:"text-muted-foreground",children:fs(new Date(p.created_at),"dd.MM.yyyy HH:mm",{locale:Ts})}),e.jsx(ss,{onClick:we=>we.stopPropagation(),children:e.jsxs(pn,{children:[e.jsx(gn,{asChild:!0,children:e.jsx(z,{variant:"ghost",size:"icon",children:e.jsx(Pn,{className:"h-4 w-4"})})}),e.jsxs(fn,{align:"end",children:[e.jsxs(ot,{onClick:()=>X(p),children:[e.jsx(st,{className:"h-4 w-4 mr-2"}),"Details anzeigen"]}),p.status==="pending"&&e.jsxs(e.Fragment,{children:[e.jsx(Sa,{}),e.jsxs(ot,{onClick:()=>L(p),children:[e.jsx(Aa,{className:"h-4 w-4 mr-2 text-green-600"}),"Freigeben"]}),e.jsxs(ot,{onClick:()=>{k(p),G(!0)},children:[e.jsx(Vt,{className:"h-4 w-4 mr-2 text-red-600"}),"Ablehnen"]})]}),p.booking_token&&e.jsxs(ot,{onClick:()=>m(p.booking_token),children:[e.jsx(Ba,{className:"h-4 w-4 mr-2"}),"Link kopieren"]}),e.jsx(Sa,{}),e.jsxs(ot,{onClick:()=>{V(p),o(!0)},className:"text-destructive focus:text-destructive",children:[e.jsx(bs,{className:"h-4 w-4 mr-2"}),"Löschen"]})]})]})})]},p.id),M&&e.jsx(ct,{className:"bg-muted/30 hover:bg-muted/30",children:e.jsx(ss,{colSpan:7,className:"p-0",children:e.jsxs("div",{className:"px-6 py-4 space-y-4 animate-fade-in",children:[e.jsxs("div",{className:"grid grid-cols-2 md:grid-cols-4 gap-4",children:[e.jsxs("div",{children:[e.jsx("p",{className:"text-xs text-muted-foreground",children:"Geburtsdatum"}),e.jsx("p",{className:"text-sm font-medium",children:p.date_of_birth?fs(He(p.date_of_birth),"dd.MM.yyyy"):"-"})]}),e.jsxs("div",{children:[e.jsx("p",{className:"text-xs text-muted-foreground",children:"Teilnehmeranzahl"}),e.jsx("p",{className:"text-sm font-medium",children:p.participant_count||1})]}),e.jsxs("div",{children:[e.jsx("p",{className:"text-xs text-muted-foreground",children:"Aufmerksam durch"}),e.jsx("p",{className:"text-sm font-medium",children:p.discovery_source?e.jsx(Xe,{variant:"secondary",className:"font-medium",children:dl(p.discovery_source.startsWith("other:")?"other":p.discovery_source)}):"-"})]}),e.jsxs("div",{children:[e.jsx("p",{className:"text-xs text-muted-foreground",children:"Bearbeitet am"}),e.jsx("p",{className:"text-sm font-medium",children:p.processed_at?fs(new Date(p.processed_at),"dd.MM.yyyy HH:mm",{locale:Ts}):"-"})]})]}),p.message&&e.jsxs("div",{children:[e.jsx("p",{className:"text-xs text-muted-foreground mb-1",children:"Nachricht"}),e.jsx("div",{className:"p-3 bg-background rounded-lg border text-sm whitespace-pre-wrap",children:p.message})]}),p.admin_notes&&e.jsxs("div",{children:[e.jsx("p",{className:"text-xs text-muted-foreground mb-1",children:"Admin-Notizen"}),e.jsx("div",{className:"p-3 bg-background rounded-lg border text-sm whitespace-pre-wrap",children:p.admin_notes})]}),p.status==="rejected"&&e.jsxs("div",{className:"p-3 bg-red-50 dark:bg-red-900/20 border border-red-200 dark:border-red-900/50 rounded-lg space-y-2",children:[e.jsxs("p",{className:"text-xs font-medium text-red-800 dark:text-red-200 flex items-center gap-1",children:[e.jsx(Fa,{className:"h-3 w-3"}),"Ablehnungsgrund"]}),((he=p.rejection_template)==null?void 0:he.name)&&e.jsxs("p",{className:"text-sm",children:[e.jsx("span",{className:"text-muted-foreground",children:"Vorlage:"})," ",e.jsx("span",{className:"font-medium",children:p.rejection_template.name})]}),e.jsx("p",{className:"text-sm whitespace-pre-wrap",children:p.rejection_reason||e.jsx("span",{className:"text-muted-foreground italic",children:"Kein Grund hinterlegt"})}),p.processed_at&&e.jsxs("p",{className:"text-xs text-muted-foreground",children:["Abgelehnt am ",fs(new Date(p.processed_at),"dd.MM.yyyy HH:mm",{locale:Ts})]})]}),e.jsxs("div",{className:"flex gap-4 text-xs text-muted-foreground",children:[e.jsxs("span",{children:["Datenschutz: ",p.privacy_accepted?"✓ Akzeptiert":"✗ Nicht akzeptiert"]}),e.jsxs("span",{children:["AGB: ",p.terms_accepted?"✓ Akzeptiert":"✗ Nicht akzeptiert"]})]}),p.companions&&p.companions.length>0?e.jsx(ml,{type:"single",collapsible:!0,className:"w-full",children:e.jsxs(ul,{value:"companions",className:"border rounded-lg overflow-hidden",children:[e.jsx(hl,{className:"px-4 py-3 hover:no-underline bg-background",children:e.jsxs("div",{className:"flex items-center gap-2 text-sm font-medium",children:[e.jsx(Ns,{className:"h-4 w-4 text-muted-foreground"}),"Begleitpersonen (",p.companions.length,")"]})}),e.jsx(xl,{className:"px-4 pb-3",children:e.jsx("div",{className:"space-y-3 pt-2",children:p.companions.map(we=>e.jsx("div",{className:"p-3 bg-muted/50 rounded-lg",children:e.jsxs("div",{className:"grid grid-cols-1 md:grid-cols-3 gap-3",children:[e.jsxs("div",{children:[e.jsx("p",{className:"text-xs text-muted-foreground",children:"Name"}),e.jsxs("p",{className:"text-sm font-medium",children:[we.first_name," ",we.last_name]})]}),e.jsxs("div",{children:[e.jsx("p",{className:"text-xs text-muted-foreground",children:"E-Mail"}),e.jsx("a",{href:`mailto:${we.email}`,className:"text-sm text-primary hover:underline",onClick:De=>De.stopPropagation(),children:we.email})]}),e.jsxs("div",{children:[e.jsx("p",{className:"text-xs text-muted-foreground",children:"Erstellt am"}),e.jsx("p",{className:"text-sm font-medium",children:fs(new Date(we.created_at),"dd.MM.yyyy",{locale:Ts})})]})]})},we.id))})})]})}):(p.participant_count||1)>1?e.jsxs("div",{className:"flex items-center gap-2 text-sm text-muted-foreground italic",children:[e.jsx(Ns,{className:"h-4 w-4"}),(p.participant_count||1)-1," weitere",(p.participant_count||1)-1===1?"r":""," Teilnehmer angegeben – keine Details hinterlegt"]}):null,p.booking_token&&p.status==="approved"&&e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx("p",{className:"text-xs text-muted-foreground shrink-0",children:"Buchungslink:"}),e.jsx(te,{value:`${window.location.origin}/booking?token=${p.booking_token}`,readOnly:!0,className:"flex-1 h-8 text-xs",onClick:we=>we.stopPropagation()}),e.jsx(z,{variant:"outline",size:"icon",className:"h-8 w-8 shrink-0",onClick:we=>{we.stopPropagation(),m(p.booking_token)},children:e.jsx(Ba,{className:"h-3 w-3"})})]})]})})},`${p.id}-detail`)]})})})]})})]}),e.jsx(We,{open:C,onOpenChange:N,children:e.jsxs(Qe,{className:"max-w-2xl",children:[e.jsx(Ye,{children:e.jsx(Je,{children:"Anfrage-Details"})}),c&&e.jsxs("div",{className:"space-y-6",children:[e.jsxs("div",{className:"grid grid-cols-2 gap-4",children:[e.jsxs("div",{children:[e.jsx("p",{className:"text-sm text-muted-foreground",children:"Name"}),e.jsxs("p",{className:"font-medium",children:[c.first_name," ",c.last_name]})]}),e.jsxs("div",{children:[e.jsx("p",{className:"text-sm text-muted-foreground",children:"Alter"}),e.jsxs("p",{className:"font-medium",children:[Za(c.date_of_birth)!==null?`${Za(c.date_of_birth)} Jahre`:"-",c.date_of_birth&&e.jsxs("span",{className:"text-muted-foreground ml-2",children:["(",fs(He(c.date_of_birth),"dd.MM.yyyy"),")"]})]})]}),e.jsxs("div",{children:[e.jsx("p",{className:"text-sm text-muted-foreground",children:"E-Mail"}),e.jsx("a",{href:`mailto:${c.email}`,className:"font-medium text-primary hover:underline",children:c.email})]}),e.jsxs("div",{children:[e.jsx("p",{className:"text-sm text-muted-foreground",children:"Telefon"}
147),c.phone?e.jsx("a",{href:`tel:${c.phone}`,className:"font-medium text-primary hover:underline",children:c.phone}):e.jsx("p",{className:"text-muted-foreground",children:"-"})]})]}),c.companions&&c.companions.length>0&&e.jsxs("div",{children:[e.jsxs("p",{className:"text-sm text-muted-foreground mb-2",children:["Begleitpersonen (",c.companions.length,")"]}),e.jsx("div",{className:"space-y-2",children:c.companions.map(p=>e.jsxs("div",{className:"flex items-center justify-between p-3 bg-muted/50 rounded-lg",children:[e.jsxs("span",{className:"font-medium",children:[p.first_name," ",p.last_name]}),e.jsx("a",{href:`mailto:${p.email}`,className:"text-sm text-primary hover:underline",children:p.email})]},p.id))})]}),c.message&&e.jsxs("div",{children:[e.jsx("p",{className:"text-sm text-muted-foreground mb-2",children:"Nachricht"}),e.jsx("div",{className:"p-4 bg-muted/50 rounded-lg",children:e.jsx("p",{className:"whitespace-pre-wrap",children:c.message})})]}),e.jsxs("div",{children:[e.jsx("p",{className:"text-sm text-muted-foreground mb-2",children:"Admin-Notizen"}),e.jsx(qs,{value:c.admin_notes||"",onChange:p=>{k({...c,admin_notes:p.target.value})},onBlur:()=>{c.admin_notes!==void 0&&x.mutate({id:c.id,admin_notes:c.admin_notes})},placeholder:"Interne Notizen...",rows:3})]}),c.booking_token&&c.status==="approved"&&e.jsxs("div",{className:"p-4 bg-green-50 dark:bg-green-900/20 rounded-lg",children:[e.jsx("p",{className:"text-sm font-medium text-green-800 dark:text-green-200 mb-2",children:"Buchungslink"}),e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(te,{value:`${window.location.origin}/booking?token=${c.booking_token}`,readOnly:!0,className:"flex-1 bg-white dark:bg-background"}),e.jsx(z,{variant:"outline",size:"icon",onClick:()=>m(c.booking_token),children:e.jsx(Ba,{className:"h-4 w-4"})})]})]})]}),e.jsx(gs,{children:(c==null?void 0:c.status)==="pending"&&e.jsxs(e.Fragment,{children:[e.jsxs(z,{variant:"destructive",onClick:()=>G(!0),children:[e.jsx(Vt,{className:"h-4 w-4 mr-2"}),"Ablehnen"]}),e.jsxs(z,{onClick:()=>L(c),disabled:f.isPending,children:[e.jsx(Aa,{className:"h-4 w-4 mr-2"}),"Freigeben & E-Mail senden"]})]})})]})}),e.jsx(We,{open:v,onOpenChange:G,children:e.jsxs(Qe,{className:"max-w-2xl",children:[e.jsxs(Ye,{children:[e.jsx(Je,{children:"Anfrage ablehnen"}),e.jsxs(Ds,{children:["Wähle einen Grund aus. Eine Absage-E-Mail an ",c==null?void 0:c.first_name," wird nur beim Versand-Button gesendet."]})]}),e.jsxs("div",{className:"space-y-4 py-2",children:[E.length>0&&e.jsxs("div",{children:[e.jsx("p",{className:"text-sm font-medium mb-2",children:"Vorlage wählen"}),e.jsxs("div",{className:"space-y-2",children:[E.map(p=>e.jsxs("label",{className:`flex items-center gap-3 p-3 rounded-lg border cursor-pointer transition-colors ${y===p.id?"border-primary bg-primary/5":"border-border hover:bg-muted/50"}`,children:[e.jsx("input",{type:"radio",name:"rejection-template",checked:y===p.id,onChange:()=>{W(p.id),q("")},className:"accent-[hsl(var(--primary))]"}),e.jsx("span",{className:"text-sm font-medium",children:p.name})]},p.id)),e.jsxs("label",{className:`flex items-center gap-3 p-3 rounded-lg border cursor-pointer transition-colors ${y===""?"border-primary bg-primary/5":"border-border hover:bg-muted/50"}`,children:[e.jsx("input",{type:"radio",name:"rejection-template",checked:y==="",onChange:()=>W(""),className:"accent-[hsl(var(--primary))]"}),e.jsx("span",{className:"text-sm font-medium",children:"Eigene Nachricht schreiben"})]})]})]}),y&&ge&&e.jsxs("div",{children:[e.jsx("p",{className:"text-sm font-medium mb-2",children:"Vorschau"}),e.jsx("div",{className:"p-3 bg-muted/50 rounded-lg border text-sm whitespace-pre-wrap max-h-48 overflow-y-auto",children:ge})]}),!y&&e.jsxs("div",{children:[e.jsx("p",{className:"text-sm text-muted-foreground mb-2",children:"Begründung (optional)"}),e.jsx(qs,{value:A,onChange:p=>q(p.target.value),placeholder:"z.B. Leider ist die Reise bereits ausgebucht...",rows:4})]})]}),e.jsxs(gs,{className:"flex-col sm:flex-row gap-2",children:[e.jsx(z,{variant:"outline",onClick:()=>G(!1),children:"Abbrechen"}),e.jsx(z,{variant:"secondary",onClick:r,disabled:x.isPending,children:"Nur ablehnen (ohne E-Mail)"}),e.jsx(z,{variant:"destructive",onClick:g,disabled:i.isPending,children:"Ablehnen & E-Mail senden"})]})]})}),e.jsx(mt,{open:T,onOpenChange:o,children:e.jsxs(ut,{children:[e.jsxs(ht,{children:[e.jsx(xt,{children:"Anfrage löschen?"}),e.jsxs(pt,{children:["Bist du sicher, dass du die Anfrage von ",e.jsxs("strong",{children:[l==null?void 0:l.first_name," ",l==null?void 0:l.last_name]})," endgültig löschen möchtest?",e.jsx("br",{}),e.jsx("br",{}),"Diese Aktion kann nicht rückgängig gemacht werden."]})]}),e.jsxs(gt,{children:[e.jsx(ft,{children:"Abbrechen"}),e.jsx(jt,{onClick:async()=>{l&&(await h.mutateAsync(l.id),o(!1),V(null))},className:"bg-destructive text-destructive-foreground hover:bg-destructive/90",children:"Löschen"})]})]})})]})}const nn={visa:{label:"Visum",color:"bg-red-100 text-red-800 dark:bg-red-900/30 dark:text-red-400"},documents:{label:"Dokumente",color:"bg-blue-100 text-blue-800 dark:bg-blue-900/30 dark:text-blue-400"},preparation:{label:"Vorbereitung",color:"bg-green-100 text-green-800 dark:bg-green-900/30 dark:text-green-400"}},Xc=[{title:"Visum beantragen",description:"Beantrage rechtzeitig dein Visum für die Einreise.",details:"",externalLink:"",externalLinkLabel:"Visum beantragen",dueDaysBefore:null,category:"visa",isRequired:!0,isActive:!0,attachmentUrl:""},{title:"Reiseversicherung abschließen",description:"Stelle sicher, dass du eine gültige Auslandskrankenversicherung hast.",details:"",externalLink:"",externalLinkLabel:"",dueDaysBefore:null,category:"documents",isRequired:!0,isActive:!0,attachmentUrl:""},{title:"Impfungen prüfen",description:"Informiere dich über empfohlene Impfungen für das Reiseland.",details:"",externalLink:"",externalLinkLabel:"",dueDaysBefore:null,category:"preparation",isRequired:!1,isActive:!0,attachmentUrl:""},{title:"Reisepass gültig?",description:"Dein Reisepass muss noch mindestens 6 Monate über das Reiseende hinaus gültig sein.",details:"",externalLink:"",externalLinkLabel:"",dueDaysBefore:null,category:"documents",isRequired:!0,isActive:!0,attachmentUrl:""}];function eo({item:s,onUpdate:n,onRemove:a}
147){const{attributes:b,listeners:f,setNodeRef:i,transform:x,transition:h,isDragging:c}=xr({id:s.id}),k={transform:pr.Transform.toString(x),transition:h};return e.jsxs("div",{ref:i,style:k,className:`rounded-xl border border-border bg-card p-4 space-y-4 ${c?"opacity-50 shadow-lg":""}`,children:[e.jsxs("div",{className:"flex items-center gap-3",children:[e.jsx("button",{...b,...f,className:"cursor-grab hover:text-primary touch-none",children:e.jsx(Ra,{className:"h-5 w-5 text-muted-foreground"})}),e.jsx(Xe,{className:nn[s.category].color,children:nn[s.category].label}),e.jsx("div",{className:"flex-1"}),e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(U,{className:"text-xs text-muted-foreground",children:"Pflicht"}),e.jsx(ys,{checked:s.isRequired,onCheckedChange:C=>n(s.id,"isRequired",C)})]}),e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(U,{className:"text-xs text-muted-foreground",children:"Aktiv"}),e.jsx(ys,{checked:s.isActive,onCheckedChange:C=>n(s.id,"isActive",C)})]}),e.jsx(z,{variant:"ghost",size:"icon",className:"h-8 w-8 text-destructive hover:text-destructive",onClick:()=>a(s.id),children:e.jsx(bs,{className:"h-4 w-4"})})]}),e.jsxs("div",{className:"grid gap-4 sm:grid-cols-2",children:[e.jsxs("div",{className:"space-y-2",children:[e.jsx(U,{className:"text-xs",children:"Titel"}),e.jsx(te,{value:s.title,onChange:C=>n(s.id,"title",C.target.value),placeholder:"z.B. Visum beantragen",className:"rounded-lg"})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(U,{className:"text-xs",children:"Kategorie"}),e.jsxs(Ie,{value:s.category,onValueChange:C=>n(s.id,"category",C),children:[e.jsx(Oe,{className:"rounded-lg",children:e.jsx(Ve,{})}),e.jsxs(Ue,{children:[e.jsx(O,{value:"visa",children:"Visum"}),e.jsx(O,{value:"documents",children:"Dokumente"}),e.jsx(O,{value:"preparation",children:"Vorbereitung"})]})]})]})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(U,{className:"text-xs",children:"Kurzbeschreibung"}),e.jsx(te,{value:s.description,onChange:C=>n(s.id,"description",C.target.value),placeholder:"1-2 Sätze, immer sichtbar im Portal",className:"rounded-lg"})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(U,{className:"text-xs",children:"Detailinformationen (optional)"}),e.jsx(qs,{value:s.details,onChange:C=>n(s.id,"details",C.target.value),placeholder:"z.B. Adressen der Unterkünfte für den Visum-Antrag, mehrzeilig...",className:"rounded-lg resize-none",rows:3})]}),e.jsxs("div",{className:"grid gap-4 sm:grid-cols-2",children:[e.jsxs("div",{className:"space-y-2",children:[e.jsxs(U,{className:"text-xs flex items-center gap-2",children:[e.jsx(gl,{className:"h-3 w-3"}),"Externer Link (optional)"]}),e.jsx(te,{value:s.externalLink,onChange:C=>n(s.id,"externalLink",C.target.value),placeholder:"https://evisa.gov.vn",className:"rounded-lg"})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(U,{className:"text-xs",children:"Button-Text für Link"}),e.jsx(te,{value:s.externalLinkLabel,onChange:C=>n(s.id,"externalLinkLabel",C.target.value),placeholder:"z.B. Visum beantragen",className:"rounded-lg"})]})]}),e.jsxs("div",{className:"grid gap-4 sm:grid-cols-2",children:[e.jsxs("div",{className:"space-y-2",children:[e.jsxs(U,{className:"text-xs flex items-center gap-2",children:[e.jsx(Vs,{className:"h-3 w-3"}),"Deadline (Tage vor Reisestart)"]}),e.jsx(te,{type:"number",min:1,value:s.dueDaysBefore??"",onChange:C=>n(s.id,"dueDaysBefore",C.target.value?parseInt(C.target.value):null),placeholder:"z.B. 30 = 30 Tage vorher",className:"rounded-lg"}),e.jsx("p",{className:"text-xs text-muted-foreground",children:"Leer lassen = keine Deadline-Warnung"})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsxs(U,{className:"text-xs flex items-center gap-2",children:[e.jsx($s,{className:"h-3 w-3"}),"Anhang / PDF (optional)"]}),e.jsxs("div",{className:"flex gap-2",children:[e.jsx(te,{value:s.attachmentUrl,onChange:C=>n(s.id,"attachmentUrl",C.target.value),placeholder:"https://... oder PDF-Link",className:"rounded-lg"}),s.attachmentUrl&&e.jsx("a",{href:s.attachmentUrl,target:"_blank",rel:"noopener noreferrer",className:"shrink-0",children:e.jsx(z,{variant:"outline",size:"icon",className:"rounded-lg",children:e.jsx(Zt,{className:"h-4 w-4"})})})]})]})]})]})}
147function so({open:s,onOpenChange:n,tripId:a}){const{checklists:b,loading:f,fetchChecklists:i,createChecklistItem:x,updateChecklistItem:h,deleteChecklistItem:c,reorderChecklists:k}=zn(),[C,N]=t.useState([]),[v,G]=t.useState(!1),[T,o]=t.useState([]),l=ir(sa(or),sa(cr,{coordinateGetter:lr}));t.useEffect(()=>{s&&a&&i(a)},[s,a,i]),t.useEffect(()=>{N(b.map(d=>({id:d.id,title:d.title,description:d.description||"",details:d.details||"",externalLink:d.externalLink||"",externalLinkLabel:d.externalLinkLabel||"",dueDaysBefore:d.dueDaysBefore,category:d.category,isRequired:d.isRequired,isActive:d.isActive,attachmentUrl:d.attachmentUrl||""}))),o([])},[b]);const V=d=>{const{active:u,over:I}=d;I&&u.id!==I.id&&N(E=>{const $=E.findIndex(be=>be.id===u.id),ge=E.findIndex(be=>be.id===I.id);return gr(E,$,ge)})},A=()=>{N(d=>[...d,{id:`new_${Date.now()}`,title:"",description:"",details:"",externalLink:"",externalLinkLabel:"",dueDaysBefore:null,category:"preparation",isRequired:!1,isActive:!0,attachmentUrl:"",isNew:!0}])},q=d=>{N(u=>[...u,{...d,id:`new_${Date.now()}`,isNew:!0}])},y=(d,u,I)=>{N(E=>E.map($=>$.id===d?{...$,[u]:I}:$))},W=d=>{const u=C.find(I=>I.id===d);u&&!u.isNew&&o(I=>[...I,d]),N(I=>I.filter(E=>E.id!==d))},j=async()=>{G(!0);try{for(const d of T)await c(d);for(let d=0;d<C.length;d++){const u=C[d],I={title:u.title,description:u.description||null,details:u.details||null,externalLink:u.externalLink||null,externalLinkLabel:u.externalLinkLabel||null,dueDaysBefore:u.dueDaysBefore,category:u.category,sortOrder:d,isRequired:u.isRequired,isActive:u.isActive,attachmentUrl:u.attachmentUrl||null};u.isNew?await x(a,I):await h(u.id,I)}n(!1)}catch(d){console.error("Error saving checklists:",d)}finally{G(!1)}};return e.jsx(We,{open:s,onOpenChange:n,children:e.jsxs(Qe,{className:"glass-modal sm:max-w-3xl max-h-[90vh] overflow-y-auto",children:[e.jsx(Ye,{children:e.jsx(Je,{className:"text-xl",children:"Checkliste verwalten"})}),f?e.jsx("div",{className:"py-12 flex items-center justify-center",children:e.jsx($e,{className:"h-8 w-8 animate-spin text-muted-foreground"})}):e.jsxs("div",{className:"space-y-4 py-4",children:[C.length===0&&e.jsxs("div",{className:"rounded-xl border border-dashed border-border p-4 space-y-3",children:[e.jsx("p",{className:"text-sm text-muted-foreground",children:"Schnellstart mit Vorlagen:"}),e.jsx("div",{className:"flex flex-wrap gap-2",children:Xc.map((d,u)=>e.jsxs(z,{variant:"outline",size:"sm",className:"rounded-lg gap-2",onClick:()=>q(d),children:[e.jsx(Es,{className:"h-3 w-3"}),d.title]},u))})]}),e.jsx(dr,{sensors:l,collisionDetection:mr,onDragEnd:V,children:e.jsx(ur,{items:C.map(d=>d.id),strategy:hr,children:e.jsx("div",{className:"space-y-4",children:C.map(d=>e.jsx(eo,{item:d,onUpdate:y,onRemove:W},d.id))})})}),e.jsxs(z,{variant:"outline",className:"w-full gap-2 rounded-xl border-dashed",onClick:A,children:[e.jsx(Es,{className:"h-4 w-4"}),"Neuen Eintrag hinzufügen"]})]}),e.jsxs(gs,{className:"gap-2",children:[e.jsx(z,{variant:"outline",className:"rounded-xl",onClick:()=>n(!1),disabled:v,children:"Abbrechen"}),e.jsx(z,{className:"rounded-xl gap-2",onClick:j,disabled:v,children:v?e.jsxs(e.Fragment,{children:[e.jsx($e,{className:"h-4 w-4 animate-spin"}),"Speichern..."]}):"Änderungen speichern"})]})]})})}function to({open:s,onOpenChange:n,trip:a,onSave:b}){var Pe,Fe,cs,vs,Me;const[f,i]=t.useState(a.name),[x,h]=t.useState(a.destination),[c,k]=t.useState(a.countryId),[C,N]=t.useState(a.countryName),[v,G]=t.useState(a.isRecurring),[T,o]=t.useState(He(a.startDate)),[l,V]=t.useState(He(a.endDate)),[A,q]=t.useState(a.image||""),[y,W]=t.useState(a.imageFocalPoint??null),[j,d]=t.useState(((Pe=a.minGroupSize)==null?void 0:Pe.toString())||""),[u,I]=t.useState(((Fe=a.maxGroupSize)==null?void 0:Fe.toString())||""),[E,$]=t.useState(((cs=a.price)==null?void 0:cs.toString())||""),[ge,be]=t.useState("0"),[Z,H]=t.useState(((vs=a.vatRate)==null?void 0:vs.toString())||"0"),[L,g]=t.useState(a.whatsappGroupLink||""),[r,m]=t.useState(a.bookletLink||""),[X,p]=t.useState(a.status),[ne,le]=t.useState(!1),[K,M]=t.useState((((Me=a.addOns)==null?void 0:Me.length)||0)>0),[ee,he]=t.useState(()=>(a.addOns||[]).map(se=>{var Re,ts;return{id:se.id,name:se.name,description:se.description,price:se.price.toString(),priceType:se.priceType,limitedSpots:((Re=se.limitedSpots)==null?void 0:Re.toString())||"",deadlineDaysBefore:((ts=se.deadlineDaysBefore)==null?void 0:ts.toString())||"",isActive:se.isActive,externalUrl:se.externalUrl||"",isHighlighted:se.isHighlighted??!1,templateAddonId:se.templateAddonId??null}})),[we,De]=t.useState(!1),[_e,J]=t.useState(""),[Ae,qe]=t.useState(!1),{checklists:Be,fetchChecklists:Ke}=zn(),[Ce,xe]=t.useState(a.insuranceCertificateId),{certificates:ms,loading:us}=fl();t.useEffect(()=>{var se,Re,ts,hs,As;s&&(i(a.name),h(a.destination),k(a.countryId),N(a.countryName),G(a.isRecurring),o(He(a.startDate)),V(He(a.endDate)),q(a.image||""),d(((se=a.minGroupSize)==null?void 0:se.toString())||""),I(((Re=a.maxGroupSize)==null?void 0:Re.toString())||""),$(((ts=a.price)==null?void 0:ts.toString())||""),H(((hs=a.vatRate)==null?void 0:hs.toString())||"0"),ue(),g(a.whatsappGroupLink||""),m(a.bookletLink||""),p(a.status),xe(a.insuranceCertificateId),M((((As=a.addOns)==null?void 0:As.length)||0)>0),he((a.addOns||[]).map(ds=>{var Ps,Fs;return{id:ds.id,name:ds.name,description:ds.description,price:ds.price.toString(),priceType:ds.priceType,limitedSpots:((Ps=ds.limitedSpots)==null?void 0:Ps.toString())||"",deadlineDaysBefore:((Fs=ds.deadlineDaysBefore)==null?void 0:Fs.toString())||"",isActive:ds.isActive,externalUrl:ds.externalUrl||"",isHighlighted:ds.isHighlighted??!1,templateAddonId:ds.templateAddonId??null}})),Q(),Ke(a.id))},[a,s,Ke]);const Q=async()=>{const{data:se}=await _.from("trips").select("visa_required, visa_info_link").eq("id",a.id).single();se&&(De(se.visa_required||!1),J(se.visa_info_link||""))},ue=async()=>{const{data:se}=await _.from("trips").select("permit_amount").eq("id",a.id).single();se&&be(String(se.permit_amount||0))},de=t.useRef(null),S=async se=>{var ts;const Re=(ts=se.target.files)==null?void 0:ts[0];if(Re){le(!0);try{const hs=Re.name.split(".").pop(),ds=`${`${a.id}-${Date.now()}.${hs}`}`,{error:Ps}=await _.storage.from("trip-images").upload(ds,Re,{upsert:!0});if(Ps)throw Ps;const{data:{publicUrl:Fs}}=_.storage.from("trip-images").getPublicUrl(ds);q(Fs)}catch(hs){console.error("Error uploading image:",hs)}finally{le(!1)}}},P=()=>{he([...ee,{id:`addon_${Date.now()}`,name:"",description:"",price:"",priceType:"per_person",limitedSpots:"",deadlineDaysBefore:"",isActive:!0,externalUrl:"",isHighlighted:!1}])},ie=(se,Re,ts)=>{he(ee.map(hs=>hs.id===se?{...hs,[Re]:ts}:hs))},Se=se=>{he(ee.filter(Re=>Re.id!==se))},[R,ce]=t.useState(!1),[oe,me]=t.useState("none"),{templates:Ee}=jl();t.useEffect(()=>{if(!s||a.templateId)return;let se=!1;return(async()=>{const{data:Re}=await _.from("trips").select("review_template_id").eq("id",a.id).maybeSingle();se||me((Re==null?void 0:Re.review_template_id)||"none")})(),()=>{se=!0}},[s,a.id,a.templateId]);const ze=async()=>
147{if(!(!f||!x||!T||!l)){ce(!0);try{const se=K?ee.filter(Re=>Re.name).map(Re=>({id:Re.id,name:Re.name,description:Re.description,price:parseFloat(Re.price)||0,priceType:Re.priceType,limitedSpots:Re.limitedSpots?parseInt(Re.limitedSpots):void 0,deadlineDaysBefore:Re.deadlineDaysBefore?parseInt(Re.deadlineDaysBefore):void 0,isActive:Re.isActive,externalUrl:Re.externalUrl||void 0,isHighlighted:Re.isHighlighted??!1,templateAddonId:Re.templateAddonId??null})):void 0;await _.from("trips").update({visa_required:we,visa_info_link:_e||null,insurance_certificate_id:Ce||null,permit_amount:parseFloat(ge)||0,...a.templateId?{}:{review_template_id:oe==="none"?null:oe}}).eq("id",a.id),await b({...a,name:f,destination:x,countryId:c,countryName:C,startDate:Pr(T),endDate:Pr(l),status:X,image:A||void 0,imageFocalPoint:A?y:null,isRecurring:v,minGroupSize:j?parseInt(j):void 0,maxGroupSize:u?parseInt(u):void 0,price:E?parseFloat(E):void 0,vatRate:Z?parseFloat(Z):0,whatsappGroupLink:L||void 0,bookletLink:r||void 0,addOns:se})}catch(se){console.error("Error saving trip:",se)}finally{ce(!1)}}},ns=f&&x&&T&&l;return e.jsxs(e.Fragment,{children:[e.jsx(We,{open:s,onOpenChange:n,children:e.jsxs(Qe,{className:"glass-modal sm:max-w-2xl max-h-[90vh] overflow-y-auto",children:[e.jsx(Ye,{children:e.jsx(Je,{className:"text-xl",children:"Reise bearbeiten"})}),e.jsxs("div",{className:"space-y-6 py-4",children:[a.templateId&&e.jsxs(Yt,{to:`/admin/templates/${a.templateId}`,className:"flex items-center gap-2 px-4 py-3 rounded-xl bg-primary/10 text-primary hover:bg-primary/20 transition-colors",onClick:()=>n(!1),children:[e.jsx($s,{className:"h-4 w-4"}),e.jsx("span",{className:"text-sm font-medium",children:"Verknüpfte Vorlage bearbeiten"}),e.jsx(Zt,{className:"h-3.5 w-3.5 ml-auto"})]}),!a.templateId&&e.jsxs("div",{className:"space-y-2",children:[e.jsx(U,{children:"Bewertung zählt zu Vorlage (optional)"}),e.jsxs(Ie,{value:oe,onValueChange:me,children:[e.jsx(Oe,{className:"rounded-xl",children:e.jsx(Ve,{placeholder:"Keine Zuordnung"})}),e.jsxs(Ue,{children:[e.jsx(O,{value:"none",children:"Keine Zuordnung"}),(Ee||[]).map(se=>e.jsx(O,{value:se.id,children:se.name},se.id))]})]}),e.jsx("p",{className:"text-xs text-muted-foreground",children:"Nur für Bewertungen: Die Bewertung dieser individuellen Reise erscheint dann auch auf der gewählten Reiseseite. Sichtbarkeit und Buchbarkeit der Reise bleiben unverändert."})]}),e.jsxs("div",{className:"grid gap-4 sm:grid-cols-2",children:[e.jsxs("div",{className:"space-y-2",children:[e.jsx(U,{htmlFor:"edit-name",children:"Reisename *"}),e.jsx(te,{id:"edit-name",value:f,onChange:se=>i(se.target.value),placeholder:"z.B. Wanderreise Alpen",className:"rounded-xl"})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(U,{htmlFor:"edit-destination",children:"Destination *"}),e.jsx(te,{id:"edit-destination",value:x,onChange:se=>h(se.target.value),placeholder:"z.B. Österreich, Tirol",className:"rounded-xl"})]})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(U,{children:"Land"}),e.jsx(pl,{value:c,onChange:(se,Re)=>{k(se),N(Re)},placeholder:"Land wählen oder hinzufügen..."})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(U,{children:"Status"}),e.jsxs(Ie,{value:X,onValueChange:se=>p(se),children:[e.jsx(Oe,{className:"rounded-xl",children:e.jsx(Ve,{})}),e.jsxs(Ue,{children:[e.jsx(O,{value:"draft",children:"Entwurf"}),e.jsx(O,{value:"planning",children:"Veröffentlicht"}),e.jsx(O,{value:"confirmed",children:"Bestätigt"}),e.jsx(O,{value:"completed",children:"Abgeschlossen"})]})]}),e.jsxs("p",{className:"text-xs text-muted-foreground",children:[X==="draft"&&"Nur für Admins sichtbar, nicht buchbar",X==="planning"&&"Öffentlich sichtbar und buchbar",X==="confirmed"&&"Mindestteilnehmerzahl erreicht, Reise findet statt",X==="completed"&&"Reise wurde abgeschlossen"]})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(U,{children:"Reisezeitraum *"}),e.jsx(Hn,{startDate:T,endDate:l,onStartDateChange:o,onEndDateChange:V,startLabel:"Startdatum",endLabel:"Enddatum"})]}),e.jsxs("div",{className:"grid gap-4 sm:grid-cols-2",children:[e.jsxs("div",{className:"space-y-2",children:[e.jsx(U,{htmlFor:"edit-price",children:"Preis pro Person (€)"}),e.jsx(te,{id:"edit-price",type:"number",min:"0",step:"0.01",value:E,onChange:se=>$(se.target.value),placeholder:"z.B. 1299.00",className:"rounded-xl"})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(U,{htmlFor:"edit-vatRate",children:"MwSt-Satz (%)"}),e.jsxs(Ie,{value:Z,onValueChange:H,children:[e.jsx(Oe,{className:"rounded-xl",children:e.jsx(Ve,{})}),e.jsxs(Ue,{children:[e.jsx(O,{value:"0",children:"0% (Drittland)"}),e.jsx(O,{value:"7",children:"7% (ermäßigt)"}),e.jsx(O,{value:"19",children:"19% (EU-Margenbesteuerung)"})]})]}),e.jsx("p",{className:"text-xs text-muted-foreground",children:Z==="0"?"Keine MwSt für Reisen außerhalb der EU":Z==="19"?"Margenbesteuerung für EU-Reisen":"Ermäßigter Steuersatz"})]})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(U,{htmlFor:"edit-permitAmount",children:"Permit-Betrag (€)"}),e.jsx(te,{id:"edit-permitAmount",type:"number",min:"0",step:"1",value:ge,onChange:se=>be(se.target.value),placeholder:"0",className:"rounded-xl"}),e.jsx("p",{className:"text-xs text-muted-foreground",children:"Betrag für Permits, der zusätzlich zu 25% des Restbetrags als Anzahlung berechnet wird. 0 = normale 25%-Anzahlung."})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(U,{htmlFor:"edit-heroImage",children:"Hero Foto"}),e.jsxs("div",{className:"flex gap-2",children:[e.jsx(te,{id:"edit-heroImage",value:A,onChange:se=>q(se.target.value),placeholder:"https://example.com/image.jpg",className:"rounded-xl"}),e.jsx("input",{ref:de,type:"file",accept:"image/*",className:"hidden",onChange:S}),e.jsx(z,{variant:"outline",className:"rounded-xl shrink-0",onClick:()=>{var se;return(se=de.current)==null?void 0:se.click()},disabled:ne,children:ne?e.jsx($e,{className:"h-4 w-4 animate-spin"}):e.jsx(Nl,{className:"h-4 w-4"})})]}),A&&e.jsx(_l,{className:"mt-2",imageUrl:A,value:y,onChange:W,heightClass:"h-40",alt:"Hero Foto der Reise",hint:"Klicke ins Bild, um den Bildmittelpunkt zu setzen — dieser Punkt bleibt in allen Portalen (Teilnehmer, Partner, Guide) sichtbar."})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsxs(U,{htmlFor:"edit-whatsappGroupLink",className:"flex items-center gap-2",children:[e.jsx(vl,{className:"h-4 w-4 text-green-500"}),"WhatsApp Gruppenlink"]}),e.jsx(te,{id:"edit-whatsappGroupLink",value:L,onChange:se=>g(se.target.value),placeholder:"https://chat.whatsapp.com/...",className:"rounded-xl"}),e.jsx("p",{className:"text-xs text-muted-foreground",children:"Link zur WhatsApp-Gruppe für Teilnehmer dieser Reise"})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsxs(U,{htmlFor:"edit-bookletLink",className:"flex items-center gap-2",children:[e.jsx($s,{className:"h-4 w-4 text-primary"}),"Booklet Link"]}),e.jsx(te,{id:"edit-bookletLink",value:r,onChange:se=>m(se.target.value),placeholder:"https://...",className:"rounded-xl"}),e.jsx("p",{className:"text-xs text-muted-foreground",children:"Link zum Re
147ise-Booklet für Teilnehmer zum Download"})]}),e.jsxs("div",{className:"grid gap-4 sm:grid-cols-2",children:[e.jsxs("div",{className:"space-y-2",children:[e.jsx(U,{htmlFor:"edit-minGroupSize",children:"Minimum Gruppengröße"}),e.jsx(te,{id:"edit-minGroupSize",type:"number",min:"1",value:j,onChange:se=>d(se.target.value),placeholder:"z.B. 10",className:"rounded-xl"})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(U,{htmlFor:"edit-maxGroupSize",children:"Maximum Gruppengröße"}),e.jsx(te,{id:"edit-maxGroupSize",type:"number",min:"1",value:u,onChange:se=>I(se.target.value),placeholder:"z.B. 25",className:"rounded-xl"})]})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsxs(U,{className:"flex items-center gap-2",children:[e.jsx(sr,{className:"h-4 w-4 text-muted-foreground"}),"Sicherungsschein"]}),e.jsxs(Ie,{value:Ce||"none",onValueChange:se=>xe(se==="none"?void 0:se),disabled:us,children:[e.jsx(Oe,{className:"rounded-xl",children:e.jsx(Ve,{placeholder:"Sicherungsschein auswählen..."})}),e.jsxs(Ue,{children:[e.jsx(O,{value:"none",children:"Keiner"}),ms.map(se=>e.jsxs(O,{value:se.id,children:[se.name," (bis ",He(se.validUntil).toLocaleDateString("de-DE"),")"]},se.id))]})]}),e.jsx("p",{className:"text-xs text-muted-foreground",children:"Der Sicherungsschein wird bei neuen Reisen automatisch zugewiesen"})]}),e.jsxs("div",{className:"space-y-4",children:[e.jsxs("div",{className:"flex items-center justify-between rounded-xl bg-muted/30 p-4",children:[e.jsxs("div",{className:"flex items-center gap-3",children:[e.jsx(qr,{className:"h-5 w-5 text-primary"}),e.jsxs("div",{children:[e.jsx("p",{className:"font-medium text-foreground",children:"Visum & Checkliste"}),e.jsxs("p",{className:"text-sm text-muted-foreground",children:[we?"Visum erforderlich":"Kein Visum erforderlich",Be.length>0&&` • ${Be.length} Checklisten-Einträge`]})]})]}),e.jsx(ys,{checked:we,onCheckedChange:De})]}),we&&e.jsx("div",{className:"space-y-4 pl-4 border-l-2 border-primary/20",children:e.jsxs("div",{className:"space-y-2",children:[e.jsxs(U,{htmlFor:"edit-visaInfoLink",className:"flex items-center gap-2",children:[e.jsx(Zt,{className:"h-4 w-4 text-muted-foreground"}),"Visum-Infoseite (optional)"]}),e.jsx(te,{id:"edit-visaInfoLink",value:_e,onChange:se=>J(se.target.value),placeholder:"https://... (Link zu offiziellen Visum-Informationen)",className:"rounded-xl"})]})}),e.jsxs(z,{variant:"outline",className:"w-full gap-2 rounded-xl",onClick:()=>qe(!0),children:[e.jsx(qr,{className:"h-4 w-4"}),"Checkliste verwalten (",Be.length," Einträge)"]})]}),e.jsxs("div",{className:"space-y-4",children:[e.jsxs("div",{className:"flex items-center justify-between rounded-xl bg-muted/30 p-4",children:[e.jsxs("div",{children:[e.jsx("p",{className:"font-medium text-foreground",children:"Add-Ons"}),e.jsx("p",{className:"text-sm text-muted-foreground",children:"Optionale Zusatzleistungen für Teilnehmer"})]}),e.jsx(ys,{checked:K,onCheckedChange:M})]}),K&&e.jsxs("div",{className:"space-y-4",children:[ee.map((se,Re)=>e.jsxs("div",{className:"rounded-xl border border-border bg-muted/20 p-4 space-y-4",children:[e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsxs("h4",{className:"font-medium text-foreground",children:["Add-On ",Re+1]}),e.jsx(z,{variant:"ghost",size:"icon",className:"h-8 w-8 text-destructive",onClick:()=>Se(se.id),children:e.jsx(bs,{className:"h-4 w-4"})})]}),e.jsxs("div",{className:"grid gap-4 sm:grid-cols-2",children:[e.jsxs("div",{className:"space-y-2",children:[e.jsx(U,{children:"Name"}),e.jsx(te,{value:se.name,onChange:ts=>ie(se.id,"name",ts.target.value),placeholder:"z.B. Flughafentransfer",className:"rounded-xl"})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(U,{children:"Preis (€)"}),e.jsx(te,{type:"number",min:"0",step:"0.01",value:se.price,onChange:ts=>ie(se.id,"price",ts.target.value),placeholder:"0.00",className:"rounded-xl"})]})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(U,{children:"Beschreibung"}),e.jsx(qs,{value:se.description,onChange:ts=>ie(se.id,"description",ts.target.value),placeholder:"Kurze Beschreibung des Add-Ons",className:"rounded-xl resize-none",rows:2})]}),e.jsxs("div",{className:"grid gap-4 sm:grid-cols-3",children:[e.jsxs("div",{className:"space-y-2",children:[e.jsx(U,{children:"Preistyp"}),e.jsxs(Ie,{value:se.priceType,onValueChange:ts=>ie(se.id,"priceType",ts),children:[e.jsx(Oe,{className:"rounded-xl",children:e.jsx(Ve,{})}),e.jsxs(Ue,{children:[e.jsx(O,{value:"per_person",children:"Pro Person"}),e.jsx(O,{value:"flat",children:"Pauschal"})]})]})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(U,{children:"Limitierte Plätze"}),e.jsx(te,{type:"number",min:"0",value:se.limitedSpots,onChange:ts=>ie(se.id,"limitedSpots",ts.target.value),placeholder:"Unbegrenzt",className:"rounded-xl"})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(U,{children:"Deadline (Tage vor Reise)"}),e.jsx(te,{type:"number",min:"0",value:se.deadlineDaysBefore,onChange:ts=>ie(se.id,"deadlineDaysBefore",ts.target.value),placeholder:"z.B. 14",className:"rounded-xl"})]})]}),e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(ys,{checked:se.isActive,onCheckedChange:ts=>ie(se.id,"isActive",ts)}),e.jsx(U,{className:"text-sm",children:"Add-On aktiv"})]})]},se.id)),e.jsxs(z,{variant:"outline",className:"w-full gap-2 rounded-xl border-dashed",onClick:P,children:[e.jsx(Es,{className:"h-4 w-4"}),"Add-On hinzufügen"]})]})]})]}),e.jsxs(gs,{className:"gap-2",children:[e.jsx(z,{variant:"outline",className:"rounded-xl",onClick:()=>n(!1),disabled:R,children:"Abbrechen"}),e.jsx(z,{className:"rounded-xl gap-2",onClick:ze,disabled:!ns||R,children:R?e.jsxs(e.Fragment,{children:[e.jsx($e,{className:"h-4 w-4 animate-spin"}),"Speichern..."]}):"Änderungen speichern"})]})]})}),e.jsx(so,{open:Ae,onOpenChange:qe,tripId:a.id})]})}function ao({open:s,onOpenChange:n,trip:a,onSuccess:b}){const[f,i]=t.useState(""),[x,h]=t.useState(!1),[c,k]=t.useState({addOnsCount:0,checklistsCount:0,partner
147ServicesCount:0,guidesCount:0,hasQuestionnaire:!1}),[C,N]=t.useState(!0),[v,G]=t.useState([]);t.useEffect(()=>{s&&a&&(i(a.name),T())},[s,a]);const T=async()=>{N(!0);try{const{count:V}=await _.from("trip_addons").select("*",{count:"exact",head:!0}).eq("trip_id",a.id),{count:A}=await _.from("trip_checklists").select("*",{count:"exact",head:!0}).eq("trip_id",a.id),{count:q}=await _.from("trip_partner_services").select("*",{count:"exact",head:!0}).eq("trip_id",a.id),{data:y}=await _.from("participants").select("profile_id").eq("trip_id",a.id).eq("is_guide",!0).not("profile_id","is",null),W=(y||[]).map(d=>d.profile_id).filter(Boolean);G(W);const{data:j}=await _.from("questionnaires").select("id").eq("trip_id",a.id).eq("is_template",!1).maybeSingle();k({addOnsCount:V||0,checklistsCount:A||0,partnerServicesCount:q||0,guidesCount:W.length,hasQuestionnaire:!!j})}catch(V){console.error("Error loading stats:",V)}finally{N(!1)}},o=async()=>{if(!f.trim()){Y.error("Bitte geben Sie einen Namen für die Vorlage ein.");return}h(!0);try{const{data:V}=await _.from("trip_templates").select("id").eq("name",f).maybeSingle();let A;const q={name:f,destination:a.destination,country_id:a.countryId||null,country_name:a.countryName||null,image:a.image||null,min_group_size:a.minGroupSize||null,max_group_size:a.maxGroupSize||null,price:a.price||null,vat_rate:a.vatRate??0,whatsapp_group_link:a.whatsappGroupLink||null,booklet_link:a.bookletLink||null};if(V)await _.from("trip_templates").update(q).eq("id",V.id),A=V.id;else{const{data:d,error:u}=await _.from("trip_templates").insert(q).select("id").single();if(u)throw u;A=d.id}await _.from("trip_template_addons").delete().eq("template_id",A);const{data:y}=await _.from("trip_addons").select("*").eq("trip_id",a.id);y&&y.length>0&&await _.from("trip_template_addons").insert(y.map(d=>({template_id:A,name:d.name,description:d.description,price:d.price,price_type:d.price_type,limited_spots:d.limited_spots,deadline_days_before:d.deadline_days_before,is_active:d.is_active,external_url:d.external_url||null,is_highlighted:d.is_highlighted??!1}))),await _.from("trip_template_checklists").delete().eq("template_id",A);const{data:W}=await _.from("trip_checklists").select("*").eq("trip_id",a.id);W&&W.length>0&&await _.from("trip_template_checklists").insert(W.map((d,u)=>({template_id:A,title:d.title,description:d.description,details:d.details,external_link:d.external_link,external_link_label:d.external_link_label,attachment_url:d.attachment_url,due_days_before:d.due_days_before,category:d.category,sort_order:d.sort_order??u,is_required:d.is_required,is_active:d.is_active}))),await _.from("trip_template_partner_services").delete().eq("template_id",A);const{data:j}=await _.from("trip_partner_services").select("*").eq("trip_id",a.id);if(j&&j.length>0&&await _.from("trip_template_partner_services").insert(j.map((d,u)=>({template_id:A,partner_service_id:d.partner_service_id,price:d.price,price_type:d.price_type,currency:"EUR",notes:d.notes,sort_order:u}))),await _.from("trip_template_guides").delete().eq("template_id",A),v.length>0&&await _.from("trip_template_guides").insert(v.map((d,u)=>({template_id:A,profile_id:d,sort_order:u}))),c.hasQuestionnaire){const{data:d}=await _.from("questionnaires").select("*").eq("trip_id",a.id).eq("is_template",!1).maybeSingle();d&&(await _.from("questionnaires").delete().eq("template_id",A),await _.from("questionnaires").insert({name:d.name,description:d.description,fields:d.fields,is_template:!0,template_id:A,trip_id:null}))}Y.success(V?"Vorlage aktualisiert":"Vorlage erstellt"),b==null||b(),n(!1)}catch(V){console.error("Error saving template:",V),Y.error("Fehler beim Speichern der Vorlage")}finally{h(!1)}},l=c.addOnsCount+c.checklistsCount+c.partnerServicesCount+c.guidesCount+(c.hasQuestionnaire?1:0);return e.jsx(We,{open:s,onOpenChange:n,children:e.jsxs(Qe,{className:"glass-modal sm:max-w-md",children:[e.jsxs(Ye,{children:[e.jsxs(Je,{className:"flex items-center gap-2",children:[e.jsx($s,{className:"h-5 w-5 text-primary"}),"Reise als Vorlage speichern"]}),e.jsx(Ds,{children:"Speichern Sie diese Reise als Vorlage, um sie für zukünftige Reisen wiederzuverwenden."})]}),e.jsxs("div",{className:"space-y-4 py-4",children:[e.jsxs("div",{className:"space-y-2",children:[e.jsx(U,{htmlFor:"templateName",children:"Vorlagen-Name"}),e.jsx(te,{id:"templateName",value:f,onChange:V=>
147i(V.target.value),placeholder:"z.B. Costa Rica Deluxe",className:"rounded-xl"})]}),e.jsxs("div",{className:"rounded-xl bg-muted/30 p-4 space-y-3",children:[e.jsx("p",{className:"text-sm font-medium text-foreground",children:"Diese Vorlage enthält:"}),C?e.jsx("div",{className:"flex items-center justify-center py-4",children:e.jsx($e,{className:"h-5 w-5 animate-spin text-muted-foreground"})}):e.jsxs("div",{className:"space-y-2",children:[e.jsxs("div",{className:"flex items-center justify-between text-sm",children:[e.jsxs("span",{className:"flex items-center gap-2 text-muted-foreground",children:[e.jsx(yt,{className:"h-4 w-4"}),"Add-Ons"]}),e.jsx("span",{className:"font-medium text-foreground",children:c.addOnsCount})]}),e.jsxs("div",{className:"flex items-center justify-between text-sm",children:[e.jsxs("span",{className:"flex items-center gap-2 text-muted-foreground",children:[e.jsx(An,{className:"h-4 w-4"}),"Checklisten-Einträge"]}),e.jsx("span",{className:"font-medium text-foreground",children:c.checklistsCount})]}),e.jsxs("div",{className:"flex items-center justify-between text-sm",children:[e.jsxs("span",{className:"flex items-center gap-2 text-muted-foreground",children:[e.jsx(bt,{className:"h-4 w-4"}),"Partner-Dienstleistungen"]}),e.jsx("span",{className:"font-medium text-foreground",children:c.partnerServicesCount})]}),e.jsxs("div",{className:"flex items-center justify-between text-sm",children:[e.jsxs("span",{className:"flex items-center gap-2 text-muted-foreground",children:[e.jsx(Ns,{className:"h-4 w-4"}),"Guides"]}),e.jsx("span",{className:"font-medium text-foreground",children:c.guidesCount})]}),e.jsxs("div",{className:"flex items-center justify-between text-sm",children:[e.jsxs("span",{className:"flex items-center gap-2 text-muted-foreground",children:[e.jsx(jr,{className:"h-4 w-4"}),"Fragebogen"]}),e.jsx("span",{className:"font-medium text-foreground",children:c.hasQuestionnaire?"Ja":"Nein"})]})]})]}),l===0&&!C&&e.jsx("p",{className:"text-sm text-muted-foreground",children:"Die Vorlage enthält die Basisdaten der Reise (Name, Preis, etc.). Sie können später Add-Ons, Checklisten und Partner hinzufügen."})]}),e.jsxs(gs,{className:"gap-2",children:[e.jsx(z,{variant:"outline",className:"rounded-xl",onClick:()=>n(!1),disabled:x,children:"Abbrechen"}),e.jsx(z,{className:"gap-2 rounded-xl",onClick:o,disabled:x||!f.trim(),children:x?e.jsxs(e.Fragment,{children:[e.jsx($e,{className:"h-4 w-4 animate-spin"}),"Speichern..."]}):e.jsxs(e.Fragment,{children:[e.jsx($s,{className:"h-4 w-4"}),"Als Vorlage speichern"]})})]})]})})}function ln(s,n,a){if(!s)return!1;const b=He(s),f=He(n),i=He(a),x=new Date(f.getFullYear(),b.getMonth(),b.getDate()),h=new Date(f.getFullYear()+1,b.getMonth(),b.getDate());return x>=f&&x<=i||h>=f&&h<=i}function cn(s,n){if(!s)return!1;const a=He(s),b=He(n),f=new Date(b);return f.setMonth(f.getMonth()+6),a<=f}function ro(s){const{participants:n,guides:a,bookings:b,payments:f,addonPurchases:i,groups:x,tripStartDate:h,tripEndDate:c}=s,k=t.useMemo(()=>{const v=new Date;return v.setHours(0,0,0,0),b.filter(G=>G.status==="active").map(G=>{const o=f.filter(A=>A.booking_id===G.id).reduce((A,q)=>A+q.amount,0),l=G.total_amount-o;let V=!1;return l>0&&(G.first_installment_due&&He(G.first_installment_due)<v&&o<G.deposit&&(V=!0),G.last_installment_due&&He(G.last_installment_due)<v&&l>0&&(V=!0)),{bookingId:G.id,customerEmail:G.customer_email,totalPaid:o,remaining:l,isOverdue:V,isPending:l>0&&!V}})},[b,f]);return{filterCategories:t.useMemo(()=>{const v=b.filter(l=>l.status==="active"),G=n.filter(l=>l.email),T=[...new Map(i.map(l=>[l.addon_id,{id:l.addon_id,name:l.addon_name||"Unbekannt"}])).values()],o=x.map(l=>({id:l.id,label:l.name,count:l.participantIds.length}));return[{id:"all",label:"Alle Teilnehmer",count:G.length},{id:"booker",label:"Nur Hauptbucher",count:v.filter(l=>l.customer_email).length},{id:"payment_overdue",label:"Überfällige Zahlungen",count:k.filter(l=>l.isOverdue).length},{id:"payment_pending",label:"Offene Zahlungen",count:k.filter(l=>l.isPending).length},{id:"forms_incomplete",label:"Unvollständige Formulare",count:G.filter(l=>l.questionnaire_status==="incomplete"||l.questionnaire_progress!==null&&l.questionnaire_progress>0&&l.questionnaire_progress<100).length},{id:"forms_not_started",label:"Formulare nicht begonnen",count:G.filter(l=>l.questionnaire_status==="pending"||l.questionnaire_progress===0||l.questionnaire_progress===null).length},...T.length>0?[{id:"addon",label:"Mit Add-on",count:new Set(i.filter(l=>l.payment_status==="paid").map(l=>l.profile_id)).size,subOptions:T.map(l=>({id:`addon_${l.id}`,label:l.name,count:i.filter(V=>V.addon_id===l.id&&V.payment_status==="paid").length}))}]:[],...o.length>0?[{id:"group",label:"Nach Gruppe",count:G.filter(l=>l.group_id).length,subOptions:o}]:[],{id:"birthday",label:"Geburtstag während Reise",count:G.filter(l=>ln(l.date_of_birth,h,c)).length},{id:"first_trip",label:"Erste Reise mit uns",count:G.filter(l=>(l.total_nights_stayed||0)===0).length},{id:"returning",label:"Wiederkehrende Gäste",count:G.filter(l=>(l.total_nights_stayed||0)>0).length},{id:"passport_expiring",label:"Ablaufender Reisepass",count:G.filter(l=>cn(l.document_expiry_date,c)).length},{id:"no_emergency_contact",label:"Ohne Notfallkontakt",count:G.filter(l=>!l.emergency_contact).length},{id:"no_portal_account",label:"Ohne Portal-Zugang",count:G.filter(l=>!l.profile_id).length},{id:"guides",label:"Guides dieser Reise",count:a.filter(l=>l.email).length}]},[n,a,b,i,x,k,h,c]),getRecipients:v=>{const G=[],T=new Set,o=(q,y)=>{q.email&&!T.has(q.email.toLowerCase())&&(T.add(q.email.toLowerCase()),G.push({id:q.id,email:q.email,firstName:q.first_name,lastName:q.last_name,type:y,bookingId:q.booking_id||void 0,profileId:q.profile_id||void 0}))},l=q=>{if(q.customer_email&&!T.has(q.customer_email.toLowerCase())){T.add(q.customer_email.toLowerCase());const y=q.customer_name.split(" ");G.push({id:q.id,email:q.customer_email,firstName:y[0]||"",lastName:y.slice(1).join(" ")||"",type:"booker",bookingId:q.id})}},V=b.filter(q=>q.status==="active"),A=n.filter(q=>q.email);for(const q of v)if(q==="all")A.forEach(y=>o(y,"participant"));else if(q==="booker")V.forEach(l);else if(q==="payment_overdue"){const y=new Set(k.filter(W=>W.isOverdue).map(W=>W.customerEmail.toLowerCase()));V.filter(W=>
147y.has(W.customer_email.toLowerCase())).forEach(l)}else if(q==="payment_pending"){const y=new Set(k.filter(W=>W.isPending).map(W=>W.customerEmail.toLowerCase()));V.filter(W=>y.has(W.customer_email.toLowerCase())).forEach(l)}else if(q==="forms_incomplete")A.filter(y=>y.questionnaire_status==="incomplete"||y.questionnaire_progress!==null&&y.questionnaire_progress>0&&y.questionnaire_progress<100).forEach(y=>o(y,"participant"));else if(q==="forms_not_started")A.filter(y=>y.questionnaire_status==="pending"||y.questionnaire_progress===0||y.questionnaire_progress===null).forEach(y=>o(y,"participant"));else if(q.startsWith("addon_")){const y=q.replace("addon_",""),W=new Set(i.filter(j=>j.addon_id===y&&j.payment_status==="paid").map(j=>j.profile_id));A.filter(j=>W.has(j.profile_id)).forEach(j=>o(j,"participant"))}else if(q.startsWith("group_")||x.some(y=>y.id===q)){const y=q.startsWith("group_")?q.replace("group_",""):q,W=x.find(j=>j.id===y);W&&A.filter(j=>W.participantIds.includes(j.id)).forEach(j=>o(j,"participant"))}else q==="birthday"?A.filter(y=>ln(y.date_of_birth,h,c)).forEach(y=>o(y,"participant")):q==="first_trip"?A.filter(y=>(y.total_nights_stayed||0)===0).forEach(y=>o(y,"participant")):q==="returning"?A.filter(y=>(y.total_nights_stayed||0)>
1470).forEach(y=>o(y,"participant")):q==="passport_expiring"?A.filter(y=>cn(y.document_expiry_date,c)).forEach(y=>o(y,"participant")):q==="no_emergency_contact"?A.filter(y=>!y.emergency_contact).forEach(y=>o(y,"participant")):q==="no_portal_account"?A.filter(y=>!y.profile_id).forEach(y=>o(y,"participant")):q==="guides"&&a.filter(y=>y.email).forEach(y=>o(y,"guide"));return G},bookingPaymentStatus:k}}const no={all:Ns,booker:Kt,payment_overdue:_r,payment_pending:Vs,forms_incomplete:jr,forms_not_started:bl,addon:yt,group:Sn,birthday:Nr,first_trip:Rt,returning:xn,passport_expiring:Lt,no_emergency_contact:xa,no_portal_account:Fa,guides:jn,specific:Ut},io=[{key:"{{vorname}}",label:"Vorname"},{key:"{{nachname}}",label:"Nachname"},{key:"{{reisename}}",label:"Reisename"},{key:"{{reiseziel}}",label:"Reiseziel"},{key:"{{startdatum}}",label:"Startdatum"},{key:"{{enddatum}}",label:"Enddatum"},{key:"{{buchungsnummer}}",label:"Buchungsnummer"},{key:"{{tage_bis_reise}}",label:"Tage bis Reise"},{key:"{{portal_link}}",label:"Portal-Link"}];function lo({open:s,onOpenChange:n,trip:a}){const{toast:b}=aa(),{user:f}=tr(),{participants:i,guides:x,bookings:h,payments:c}=na(a.id),{purchases:k}=Bn(a.id),C=t.useMemo(()=>{const r={};return i.forEach(m=>{m.group_id&&(r[m.group_id]||(r[m.group_id]=[]),r[m.group_id].push(m.id))}),Object.entries(r).map(([m,X],p)=>({id:m,tripId:a.id,name:m,color:["#8B5CF6","#EC4899","#F59E0B","#10B981"][p%4],participantIds:X}))},[i,a.id]),{filterCategories:N,getRecipients:v}=ro({participants:i,guides:x,bookings:h,payments:c,addonPurchases:k,groups:C,tripStartDate:a.startDate,tripEndDate:a.endDate}),[G,T]=t.useState("filters"),[o,l]=t.useState([]),[V,A]=t.useState([]),[q,y]=t.useState(""),[W,j]=t.useState(""),[d,u]=t.useState(!1),[I,E]=t.useState([]);t.useEffect(()=>{s&&(T("filters"),l([]),y(""),j(""),E([]))},[s]);const $=t.useMemo(()=>{const r=v(o);if(I.length>0){const m=new Set(r.map(p=>p.email.toLowerCase()));i.filter(p=>p.email&&I.includes(p.id)&&!m.has(p.email.toLowerCase())).forEach(p=>{p.email&&r.push({id:p.id,email:p.email,firstName:p.first_name,lastName:p.last_name,type:"participant",bookingId:p.booking_id||void 0,profileId:p.profile_id||void 0})})}return r},[o,v,I,i]),ge=r=>{l(m=>m.includes(r)?m.filter(X=>X!==r):[...m,r])},be=r=>{A(m=>m.includes(r)?m.filter(X=>X!==r):[...m,r])},Z=r=>{j(m=>m+r)},H=Math.ceil((He(a.startDate).getTime()-Date.now())/(1e3*60*60*24)),L=async(r=!1)=>{if($.length===0){b({title:"Keine Empfänger",description:"Bitte wähle mindestens einen Empfänger aus.",variant:"destructive"});return}if(!q.trim()||!W.trim()){b({title:"Fehlende Daten",description:"Bitte gib Betreff und Nachricht ein.",variant:"destructive"});return}u(!0);try{let m=$;r&&(f!=null&&f.email)&&(m=[{...$[0],email:f.email}]);const{data:X,error:p}=await _.functions.invoke("send-trip-email",{body:{tripId:a.id,tripName:a.name,destination:a.destination,startDate:a.startDate,endDate:a.endDate,daysUntilTrip:H,subject:q,body:W,recipients:m,testMode:r}});if(p)throw p;b({title:r?"Test-E-Mail gesendet":"E-Mails gesendet",description:r?`Test-E-Mail wurde an ${f==null?void 0:f.email} gesendet.`:`${X.sent} E-Mails wurden erfolgreich versendet.`}),r||n(!1)}catch(m){console.error("Error sending emails:",m),b({title:"Fehler beim Senden",description:m.message||"E-Mails konnten nicht gesendet werden.",variant:"destructive"})}finally{u(!1)}},g=(r,m=!1)=>{const X=no[r.id.split("_")[0]]||Ns,p=r.subOptions&&r.subOptions.length>0,ne=V.includes(r.id),le=o.includes(r.id);return e.jsxs("div",{children:[e.jsxs("div",{className:`flex items-center gap-3 p-3 rounded-xl cursor-pointer transition-colors ${le?"bg-primary/10 border border-primary/30":"hover:bg-muted/50"} ${m?"ml-6":""}`,onClick:()=>p?be(r.id):ge(r.id),children:[!p&&e.jsx(Zs,{checked:le,onCheckedChange:()=>ge(r.id),onClick:K=>K.stopPropagation()}),p&&e.jsx("div",{className:"w-5 h-5 flex items-center justify-center",children:ne?e.jsx(Us,{className:"h-4 w-4 text-muted-foreground"}):e.jsx(Ar,{className:"h-4 w-4 text-muted-foreground"})}),e.jsx(X,{className:"h-4 w-4 text-muted-foreground"}),e.jsx("span",{className:"flex-1 text-sm",children:r.label}),e.jsx(Xe,{variant:"secondary",className:"text-xs",children:r.count})]}),p&&ne&&e.jsx("div",{className:"mt-1 space-y-1",children:r.subOptions.map(K=>e.jsxs("div",{className:`flex items-center gap-3 p-2.5 rounded-lg cursor-pointer ml-8 transition-colors ${o.includes(K.id)?"bg-primary/10 border border-primary/30":"hover:bg-muted/50"}`,onClick:()=>ge(K.id),children:[e.jsx(Zs,{checked:o.includes(K.id),onCheckedChange:()=>ge(K.id),onClick:M=>M.stopPropagation()}),e.jsx("span",{className:"flex-1 text-sm",children:K.label}),e.jsx(Xe,{variant:"secondary",className:"text-xs",children:K.count})]},K.id))})]},r.id)};return e.jsx(We,{open:s,onOpenChange:n,children:e.jsxs(Qe,{className:"glass-modal sm:max-w-2xl max-h-[90vh] flex flex-col",children:[e.jsxs(Ye,{children:[e.jsxs(Je,{className:"flex items-center gap-2",children:[e.jsx(Os,{className:"h-5 w-5 text-primary"}),"E-Mail an Teilnehmer senden"]}),e.jsxs(Ds,{children:[a.name," · ",a.destination]})]}),e.jsxs("div",{className:"flex items-center gap-2 py-2",children:[["filters","compose","preview"].map((r,m)=>e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx("div",{className:`w-8 h-8 rounded-full flex items-center justify-center text-sm font-medium transition-colors ${G===r?"bg-primary text-primary-foreground":r==="filters"||r==="compose"&&G!=="filters"||G==="preview"?"bg-primary/20 text-primary":"bg-muted text-muted-foreground"}`,children:m+1}),m<2&&e.jsx("div",{className:"w-8 h-0.5 bg-muted"})]},r)),e.jsx("div",{className:"flex-1"}),e.jsxs(Xe,{variant:"outline",className:"gap-1",children:[e.jsx(Ns,{className:"h-3 w-3"}),$.length," Empfänger"]})]}),e.jsx(Ia,{}),e.jsx(za,{className:"flex-1 min-h-0 max-h-[50vh]",children:e.jsxs("div",{className:"pr-4",children:[G==="filters"&&e.jsxs("div",{className:"space-y-4 py-4",children:[e.jsxs("div",{className:"grid grid-cols-2 gap-4",children:[e.jsxs("div",{className:"space-y-3",children:[e.jsxs(at,{defaultOpen:!0,children:[e.jsxs(rt,{className:"flex items-center justify-between w-full p-2 rounded-lg hover:bg-muted/50 transition-colors",children:[e.jsx("span",{className:"text-sm font-medium",children:"Basis"}),e.jsx(Us,{className:"h-4 w-4 text-muted-foreground"})]}),e.jsx(nt,{className:"space-y-1 mt-1",children:N.slice(0,2).map(r=>g(r))})]}),e.jsxs(at,{children:[e.jsxs(rt,{className:"flex items-center justify-between w-full p-2 rounded-lg hover:bg-muted/50 transition-colors",children:[e.jsx("span",{className:"text-sm font-medium",children:"Zahlungsstatus"}),e.jsx(Us,{className:"h-4 w-4 text-muted-foreground"})]}),e.jsx(nt,{className:"space-y-1 mt-1",children:N.filter(r=>r.id.startsWith("payment")).map(r=>g(r))})]}),e.jsxs(at,{children:[e.jsxs(rt,{className:"flex items-center justify-between w-full p-2 rounded-lg hover:bg-muted/50 transition-colors",children:[e.jsx("span",{className:"text-sm font-medium",children:"Formular-Status"}),e.jsx(Us,{className:"h-4 w-4 text-muted-foreground"})]}),e.jsx(nt,{className:"space-y-1 mt-1",children:N.filter(r=>r.id.startsWith("forms")).map(r=>g(r))})]}),N.find(r=>r.id==="addon")&&e.jsxs(at,{children:[e.jsxs(rt,{className:"flex items-center justify-between w-full p-2 rounded-lg hover:bg-muted/50 transition-colors",children:[e.jsx("span",{className:"text-sm font-medium",children:"Add-ons & Pakete"}),e.jsx(Us,{className:"h-4 w-4 text-muted-foreground"})]}),e.jsx(nt,{className:"space-y-1 mt-1",children:N.filter(r=>r.id==="addon").map(r=>g(r))})]})]}),e.jsxs("div",{className:"space-y-3",children:[N.find(r=>r.id==="group")&&e.jsxs(at,{children:[e.jsxs(rt,{className:"flex items-center justify-between w-full p-2 rounded-lg hover:bg-muted/50 transition-colors",children:[e.jsx("span",{className:"text-sm font-medium",children:"Gruppen"}),e.jsx(Us,{className:"h-4 w-4 text-muted-foreground"})]}),e.jsx(nt,{className:"space-y-1 mt-1",children:N.filter(r=>r.id==="group").map(r=>g(r))})]}),e.jsxs(at,{children:[e.jsxs(rt,{className:"flex items-center justify-between w-full p-2 rounded-lg hover:bg-muted/50 transition-colors",children:[e.jsx("span",{className:"text-sm font-medium",children:"Spezielle Gruppen"}),e.jsx(Us,{className:"h-4 w-4 text-muted-foreground"})]}),e.jsx(nt,{className:"space-y-1 mt-1",children:N.filter(r=>["birthday","first_trip","returning"].includes(r.id)).map(r=>g(r))})]}),e.jsxs(at,{children:[e.jsxs(rt,{className:"flex items-center justify-between w-full p-2 rounded-lg hover:bg-muted/50 transition-colors",children:[e.jsx("span",{className:"text-sm font-medium",children:"Dokumente & Daten"}),e.jsx(Us,{className:"h-4 w-4 text-muted-foreground"})]}),e.jsx(nt,{className:"space-y-1 mt-1",children:N.filter(r=>["passport_expiring","no_emergency_contact","no_portal_account"].includes(r.id)).map(r=>g(r))})]}),e.jsxs(at,{children:[e.jsxs(rt,{className:"flex items-center justify-between w-full p-2 rounded-lg hover:bg-muted/50 transition-colors",children:[e.jsx("span",{className:"text-sm font-medium",children:"Team"}),e.jsx(Us,{className:"h-4 w-4 text-muted-foreground"})]}),e.jsx(nt,{className:"space-y-1 mt-1",children:N.filter(r=>r.id==="guides").map(r=>g(r))})]})]})]}),e.jsx(Ia,{}),e.jsxs(at,{children:[e.jsxs(rt,{className:"flex items-center justify-between w-full p-2 rounded-lg hover:bg-muted/50 transition-colors",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(Ut,{className:"h-4 w-4 text-muted-foreground"}),e.jsx("span",{className:"text-sm font-medium",children:"Einzelne Teilnehmer auswählen"})]}),e.jsxs("div",{className:"flex items-center gap-2",children:[I.length>0&&e.jsxs(Xe,{variant:"secondary",className:"text-xs",children:[I.length," ausgewählt"]}),e.jsx(Us,{className:"h-4 w-4 text-muted-foreground"})]})]}),e.jsx(nt,{className:"mt-2",children:e.jsxs("div",{className:"rounded-xl border divide-y max-h-[250px] overflow-auto",children:[e.jsxs("div",{className:"flex items-center justify-between p-3 bg-muted/30 sticky top-0",children:[e.jsxs("span",{className:"text-sm font-medium text-muted-foreground",children:[i.filter(r=>r.email).length," Teilnehmer mit E-Mail"]}),e.jsxs("div",{className:"flex gap-2",children:[e.jsx(z,{variant:"ghost",size:"sm",className:"h-7 text-xs",onClick:()=>{const r=i.filter(m=>m.email).map(m=>m.id);E(r)}
147,children:"Alle auswählen"}),e.jsx(z,{variant:"ghost",size:"sm",className:"h-7 text-xs",onClick:()=>E([]),children:"Auswahl aufheben"})]})]}),i.filter(r=>r.email).sort((r,m)=>(r.last_name||"").localeCompare(m.last_name||"")).map(r=>{const m=I.includes(r.id),X=o.length>0&&v(o).some(p=>{var ne,le;return((ne=p.email)==null?void 0:ne.toLowerCase())===((le=r.email)==null?void 0:le.toLowerCase())});return e.jsxs("div",{className:`flex items-center gap-3 p-3 cursor-pointer transition-colors ${m||X?"bg-primary/10":"hover:bg-muted/50"}`,onClick:()=>{X||E(p=>p.includes(r.id)?p.filter(ne=>ne!==r.id):[...p,r.id])},children:[e.jsx(Zs,{checked:m||X,disabled:X,onCheckedChange:()=>{X||E(p=>p.includes(r.id)?p.filter(ne=>ne!==r.id):[...p,r.id])},onClick:p=>p.stopPropagation()}),e.jsxs("div",{className:"flex-1 min-w-0",children:[e.jsxs("p",{className:"font-medium text-sm truncate",children:[r.first_name," ",r.last_name]}),e.jsx("p",{className:"text-xs text-muted-foreground truncate",children:r.email})]}),X&&e.jsx(Xe,{variant:"outline",className:"text-xs",children:"via Filter"})]},r.id)})]})})]})]}),G==="compose"&&e.jsxs("div",{className:"space-y-4 py-4",children:[e.jsxs("div",{className:"space-y-2",children:[e.jsx("label",{className:"text-sm font-medium",children:"Betreff"}),e.jsx(te,{placeholder:"z.B. Wichtige Info zu deiner Reise nach Tansania",value:q,onChange:r=>y(r.target.value)})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx("label",{className:"text-sm font-medium",children:"Nachricht"}),e.jsx(qs,{placeholder:`Hallo {{vorname}},
148
149nur noch ${H} Tage bis zu unserer gemeinsamen Reise nach ${a.destination}!
150
151...`,value:W,onChange:r=>j(r.target.value),className:"min-h-[200px] font-mono text-sm"})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx("label",{className:"text-sm font-medium text-muted-foreground",children:"Verfügbare Variablen"}),e.jsx("div",{className:"flex flex-wrap gap-2",children:io.map(r=>e.jsx(z,{variant:"outline",size:"sm",className:"h-7 text-xs font-mono",onClick:()=>Z(r.key),children:r.key},r.key))})]})]}),G==="preview"&&e.jsxs("div",{className:"space-y-4 py-4",children:[e.jsxs("div",{className:"rounded-xl border p-4 space-y-3",children:[e.jsxs("div",{children:[e.jsx("span",{className:"text-xs text-muted-foreground",children:"Betreff:"}),e.jsx("p",{className:"font-medium",children:q})]}),e.jsx(Ia,{}),e.jsxs("div",{children:[e.jsx("span",{className:"text-xs text-muted-foreground",children:"Nachricht:"}),e.jsx("div",{className:"mt-2 text-sm bg-muted/30 rounded-lg p-4 max-h-[200px] overflow-auto",dangerouslySetInnerHTML:{__html:W.replace(/&/g,"&amp;").replace(/</g,"&lt;").replace(/>/g,"&gt;").replace(/\*\*(.*?)\*\*/g,"<strong>$1</strong>").replace(/\*(.*?)\*/g,"<em>$1</em>").replace(/\n/g,"<br>")}})]})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsxs("h3",{className:"text-sm font-medium",children:["Empfänger (",$.length,")"]}),e.jsx("div",{className:"rounded-xl border divide-y max-h-[200px] overflow-auto",children:$.map(r=>e.jsxs("div",{className:"flex items-center gap-3 p-3",children:[e.jsxs("div",{className:"flex-1 min-w-0",children:[e.jsxs("p",{className:"font-medium text-sm truncate",children:[r.firstName," ",r.lastName]}),e.jsx("p",{className:"text-xs text-muted-foreground truncate",children:r.email})]}),e.jsx(Xe,{variant:"secondary",className:"text-xs",children:r.type==="guide"?"Guide":r.type==="booker"?"Bucher":"Teilnehmer"})]},r.id))})]})]})]})}),e.jsxs(gs,{className:"gap-2 flex-wrap",children:[G!=="filters"&&e.jsx(z,{variant:"outline",onClick:()=>T(G==="preview"?"compose":"filters"),disabled:d,children:"Zurück"}),e.jsx("div",{className:"flex-1"}),G==="filters"&&e.jsxs(z,{onClick:()=>T("compose"),disabled:$.length===0,children:["Weiter",e.jsx(Ar,{className:"h-4 w-4 ml-1"})]}),G==="compose"&&e.jsxs(z,{onClick:()=>T("preview"),disabled:!q.trim()||!W.trim(),children:["Vorschau",e.jsx(st,{className:"h-4 w-4 ml-1"})]}),G==="preview"&&e.jsxs(e.Fragment,{children:[e.jsxs(z,{variant:"outline",onClick:()=>L(!0),disabled:d,children:[d?e.jsx($e,{className:"h-4 w-4 animate-spin mr-2"}):e.jsx(Os,{className:"h-4 w-4 mr-2"}),"Test-Mail senden"]}),e.jsx(z,{onClick:()=>L(!1),disabled:d,children:d?e.jsxs(e.Fragment,{children:[e.jsx($e,{className:"h-4 w-4 animate-spin mr-2"}),"Sende..."]}):e.jsxs(e.Fragment,{children:[e.jsx(Bt,{className:"h-4 w-4 mr-2"}),$.length," E-Mails senden"]})})]})]})]})})}function co({tripId:s,tripPrice:n,currentParticipants:a,maxParticipants:b}){const[f,i]=t.useState(!1),{data:x,isLoading:h}=mo(s),{convertToEUR:c}=vr(),k=b??16,C=t.useMemo(()=>
151{if(!x)return null;const o=[...wl(x.addons),...kl(x.partnerServices,c)],l=n?[{label:"Basispreis",amount:Number(n),scale:"per_person"}]:[];return{costs:o,revenues:l,minGroupSize:2,maxGroupSize:k}},[x,n,k,c]),N=t.useMemo(()=>C?Cl(C):null,[C]),v=t.useMemo(()=>C&&a>0?Rn(C,a):null,[C,a]);if(h)return e.jsx(Pa,{className:"h-24 w-full"});if(!C||C.costs.length===0)return null;const G=(v==null?void 0:v.marginPerPerson)??0,T=G>=0;return e.jsxs(e.Fragment,{children:[e.jsxs("div",{className:"glass-card p-4 flex items-center gap-4",children:[e.jsx("div",{className:"flex h-10 w-10 items-center justify-center rounded-xl bg-primary/10",children:e.jsx(Sl,{className:"h-5 w-5 text-primary"})}),e.jsxs("div",{className:"flex-1 min-w-0",children:[e.jsx("p",{className:"text-sm text-muted-foreground",children:"Preis-Skalierung"}),e.jsxs("p",{className:"font-medium text-foreground",children:[N!=null&&N.breakEvenN?`Break-Even ab ${N.breakEvenN} TN`:"Break-Even nicht erreicht",v&&e.jsxs(e.Fragment,{children:[" · ",e.jsxs("span",{className:T?"text-emerald-600":"text-destructive",children:[ea(G)," / Kopf"]})]})]})]}),e.jsxs(z,{variant:"ghost",size:"sm",onClick:()=>i(!0),className:"gap-1",children:["Details ",e.jsx(Dl,{className:"h-4 w-4"})]})]}),e.jsx(We,{open:f,onOpenChange:i,children:e.jsxs(Qe,{className:"max-w-4xl max-h-[90vh] overflow-y-auto",children:[e.jsx(Ye,{children:e.jsx(Je,{children:"Preis-Skalierung dieser Reise"})}),e.jsx(oo,{inputs:C,result:N,currentParticipants:a,max:k,tripPrice:n??null})]})})]})}function oo({inputs:s,result:n,currentParticipants:a,max:b,tripPrice:f}){const[i,x]=t.useState(a>0?a:Math.min(8,b)),h=t.useMemo(()=>Rn(s,i),[s,i]),c=n.points.map(N=>({n:N.n,Kosten:Math.round(N.costPerPerson),Preis:Math.round(N.pricePerPerson)})),k=s.costs.filter(N=>N.scale==="flat"),C=s.costs.filter(N=>N.scale==="per_person");return e.jsxs("div",{className:"space-y-6",children:[e.jsxs("div",{className:"grid grid-cols-2 md:grid-cols-4 gap-3",children:[e.jsx(ya,{label:"Aktuell gebucht",value:`${a} TN`}),e.jsx(ya,{label:"Break-Even",value:n.breakEvenN?`${n.breakEvenN} TN`:"—"}),e.jsx(ya,{label:"Fixkosten",value:ea(n.flatCost)}),e.jsx(ya,{label:"Preis / Kopf",value:f?ea(f):"—"})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsxs("div",{className:"flex items-center justify-between text-sm",children:[e.jsx("span",{className:"text-muted-foreground",children:"Simulation"}),e.jsxs("span",{className:"font-semibold",children:[i," TN · Marge"," ",e.jsx("span",{className:h.marginPerPerson>=0?"text-emerald-600":"text-destructive",children:ea(h.marginPerPerson)})," ","/ Kopf (",h.marginPct.toFixed(0)," %)"]})]}),e.jsx(yl,{min:2,max:b,step:1,value:[i],onValueChange:N=>x(N[0])})]}),e.jsx("div",{className:"h-64",children:e.jsx(El,{width:"100%",height:"100%",children:e.jsxs(Tl,{data:c,margin:{top:10,right:24,left:0,bottom:0},children:[e.jsx(Al,{strokeDasharray:"3 3",opacity:.3}),e.jsx(Pl,{dataKey:"n"}),e.jsx(Fl,{tickFormatter:N=>`${N} €`,width:80}),e.jsx(zl,{formatter:N=>`${N.toLocaleString("de-DE")} €`,labelFormatter:N=>`${N} TN`}),e.jsx(Rl,{}),e.jsx(Mr,{type:"monotone",dataKey:"Preis",stroke:"hsl(var(--primary))",strokeWidth:2,dot:{r:3}}),e.jsx(Mr,{type:"monotone",dataKey:"Kosten",stroke:"hsl(var(--destructive))",strokeWidth:2,dot:{r:3}}),n.breakEvenN&&e.jsx(Gr,{x:n.breakEvenN,stroke:"hsl(var(--muted-foreground))",strokeDasharray:"4 4",label:{value:"Break-Even",position:"top",fontSize:11}}),a>0&&e.jsx(Gr,{x:a,stroke:"hsl(var(--primary))",strokeDasharray:"2 2",label:{value:"aktuell",position:"top",fontSize:11}})]})})}),e.jsxs("div",{className:"grid grid-cols-2 gap-4 text-sm",children:[e.jsx(on,{title:"Fixkosten (pauschal)",icon:e.jsx($l,{className:"h-4 w-4"}),items:k,total:n.flatCost}),e.jsx(on,{title:"Variable Kosten (pro Person)",icon:e.jsx(Kn,{className:"h-4 w-4"}),items:C,total:n.perPersonCost})]})]})}function ya({label:s,value:n}){return e.jsxs("div",{className:"rounded-lg border p-3",children:[e.jsx("div",{className:"text-xs uppercase tracking-wide text-muted-foreground",children:s}),e.jsx("div",{className:"text-lg font-bold mt-1",children:n})]})}function on({title:s,icon:n,items:a,total:b}){return a.length===0?null:e.jsxs("div",{className:"rounded-lg border p-3",children:[e.jsxs("div",{className:"flex items-center justify-between mb-2",children:[e.jsxs("div",{className:"flex items-center gap-2 font-medium",children:[n,s]}),e.jsx("span",{className:"font-semibold",children:ea(b)})]}),e.jsxs("ul",{className:"space-y-1",children:[a.slice(0,6).map((f,i)=>e.jsxs("li",{className:"flex items-center justify-between text-xs",children:[e.jsx("span",{className:"text-muted-foreground truncate max-w-[70%]",title:f.label,children:f.label}),e.jsx("span",{className:"font-medium",children:ea(f.amount)})]},i)),a.length>6&&e.jsxs("li",{className:"text-xs text-muted-foreground",children:["+ ",a.length-6," weitere"]})]})]})}function mo(s){return dt({queryKey:["trip-pricing-scale",s],queryFn:async()=>
151{const[n,a]=await Promise.all([_.from("trip_addons").select("name, cost, price, price_type, is_active").eq("trip_id",s),_.from("trip_partner_services").select(`
152            price,
153            price_type,
154            partner_services (
155              name,
156              currency,
157              partners ( name )
158            )
159          `).eq("trip_id",s)]);if(n.error)throw n.error;if(a.error)throw a.error;const b=(n.data||[]).map(i=>({name:i.name,cost:i.cost,price:i.price,price_type:i.price_type,is_active:i.is_active})),f=(a.data||[]).map(i=>{var x,h,c,k;return{label:`${((h=(x=i.partner_services)==null?void 0:x.partners)==null?void 0:h.name)??"Partner"} – ${((c=i.partner_services)==null?void 0:c.name)??"Service"}`,price:i.price,price_type:i.price_type,currency:((k=i.partner_services)==null?void 0:k.currency)??"EUR"}});return{addons:b,partnerServices:f}},staleTime:3e4,refetchOnMount:"always"})}const dn=["#8B5CF6","#EC4899","#F59E0B","#10B981","#3B82F6","#EF4444","#14B8A6","#F97316"],uo=s=>s||null,ho=(s,n,a)=>{if(!s)return{hasBirthday:!1,birthdayDate:null,formattedDate:""};const b=He(s),f=He(n),i=He(a),x=new Date(f.getFullYear(),b.getMonth(),b.getDate()),h=new Date(f.getFullYear()+1,b.getMonth(),b.getDate()),c=k=>k>=f&&k<=i;return c(x)?{hasBirthday:!0,birthdayDate:x,formattedDate:x.toLocaleDateString("de-DE",{day:"2-digit",month:"2-digit"})}:c(h)?{hasBirthday:!0,birthdayDate:h,formattedDate:h.toLocaleDateString("de-DE",{day:"2-digit",month:"2-digit"})}:{hasBirthday:!1,birthdayDate:null,formattedDate:""}};function tu(){const{id:s}=qn(),[n,a]=Mn(),{trips:b,loading:f,updateTrip:i,confirmTrip:x}=nr(),{bookings:h,participants:c,isLoading:k,fetchBookings:C,updateParticipant:N}=na(s||""),v=b.find(K=>K.id===s),G=f,{toast:T}=aa(),{genderBalance:o}=Gn(s||null),l=n.get("tab")||"bookings",V=K=>{a(M=>{const ee=new URLSearchParams(M);return ee.set("tab",K),ee})},A=t.useMemo(()=>{const K={};return c.forEach(M=>{M.group_id&&(K[M.group_id]||(K[M.group_id]=[]),K[M.group_id].push(M.id))}),Object.entries(K).map(([M,ee],he)=>({id:M,tripId:s||"",name:M,color:dn[he%dn.length],participantIds:ee}))},[c,s]),q=t.useMemo(()=>v?c.map(K=>{const M=uo(K.date_of_birth||void 0),ee=ho(M,v.startDate,v.endDate);return ee.hasBirthday?{id:K.id,firstName:K.first_name,lastName:K.last_name,birthdayDate:ee.birthdayDate,formattedDate:ee.formattedDate}:null}).filter(K=>K!==null).sort((K,M)=>{var ee,he;return(((ee=K.birthdayDate)==null?void 0:ee.getTime())||0)-(((he=M.birthdayDate)==null?void 0:he.getTime())||0)}):[],[c,v]),y=async K=>{try{const M=c.map(ee=>ee.id);M.length>0&&await _.from("participants").update({group_id:null}).in("id",M);for(const ee of K)ee.participantIds.length>0&&await _.from("participants").update({group_id:ee.name}).in("id",ee.participantIds);C()}catch(M){console.error("Error updating groups:",M),T({title:"Fehler",description:"Gruppen konnten nicht gespeichert werden.",variant:"destructive"})}},[W,j]=t.useState(!1),[d,u]=t.useState(!1),[I,E]=t.useState(!1),[$,ge]=t.useState(!1),[be,Z]=t.useState(!1);if(G)return e.jsx("div",{className:"flex min-h-[50vh] items-center justify-center",children:e.jsx($e,{className:"h-8 w-8 animate-spin text-primary"})});if(!v)return e.jsx("div",{className:"flex min-h-[50vh] items-center justify-center",children:e.jsxs("div",{className:"text-center",children:[e.jsx("h2",{className:"text-xl font-semibold text-foreground",children:"Reise nicht gefunden"}),e.jsx(Yt,{to:"/admin/trips",className:"mt-4 text-primary hover:underline",children:"Zurück zur Übersicht"})]})});const H=v.minGroupSize||0,L=v.status==="draft",g=v.status==="planning"&&v.totalParticipants>=H,r=Math.max(0,H-v.totalParticipants),m=async()=>{try{await i(v.id,{...v,status:"planning"}),T({title:"Reise veröffentlicht!",description:"Die Reise ist jetzt öffentlich sichtbar und buchbar."})}catch{T({title:"Fehler",description:"Reise konnte nicht veröffentlicht werden.",variant:"destructive"})}},X=async()=>{const K=c.filter(ee=>ee.email).map(ee=>{const he=h.find(we=>we.id===ee.booking_id);return{email:ee.email||"",firstName:ee.first_name,lastName:ee.last_name,type:"participant",bookingId:(he==null?void 0:he.id)||""}}),M=[];try{const{data:ee}=await _.from("trip_partners").select("partner_id, partner_booking_number").eq("trip_id",s||""),{data:he}=await _.from("trip_partner_services").select("partner_service_id").eq("trip_id",s||"");if(he&&he.length>0){const we=he.map(_e=>_e.partner_service_id),{data:De}=await _.from("partner_services").select("id, partner_id").in("id",we);
159if(De){const _e=[...new Set(De.map(Ae=>Ae.partner_id))],{data:J}=await _.from("partners").select("id, contact_person, email, receives_emails").in("id",_e);if(J){const Ae={};if(ee)for(const Be of ee)Be.partner_booking_number&&(Ae[Be.partner_id]=Be.partner_booking_number);const qe=new Set;for(const Be of J)if(Be.receives_emails!==!1&&Be.email&&!qe.has(Be.email)){qe.add(Be.email);const Ke=Be.contact_person.split(" "),Ce=Ke[0]||"",xe=Ke.slice(1).join(" ")||"";M.push({email:Be.email,firstName:Ce,lastName:xe,type:"partner",bookingId:Ae[Be.id]||""})}}}}}catch(ee){console.error("Error fetching partner recipients:",ee)}return[...K,...M]},p=async()=>{Z(!0);try{if(!await x(v.id))throw new Error("Reise konnte nicht bestätigt werden");let M=0,ee=null;try{const he=await X(),{data:we}=await _.from("company_settings").select("company_name, email_sender_address, email_sender_name, company_logo_url").single(),De=we!=null&&we.email_sender_address?`${we.email_sender_name||we.company_name} <${we.email_sender_address}>`:void 0;console.log("Sending confirmation emails to:",he.length,"recipients");const{data:_e,error:J}=await _.functions.invoke("send-trip-confirmation",{body:{tripName:v.name,destination:v.destination,startDate:v.startDate,endDate:v.endDate,recipients:he,participantCount:v.totalParticipants,companyName:(we==null?void 0:we.company_name)||"Off The Path",senderEmail:De,companyLogoUrl:we==null?void 0:we.company_logo_url,portalUrl:`${window.location.origin}/portal`,whatsappLink:v.whatsappGroupLink,tripImageUrl:v.image,maxGroupSize:v.maxGroupSize}});J?ee=J.message:M=(_e==null?void 0:_e.sent)||0}catch(he){ee=he.message,console.error("Error sending emails:",he)}T(ee?{title:"Reise bestätigt",description:"Status wurde aktualisiert. E-Mail-Versand fehlgeschlagen.",variant:"default"}:{title:"Reise bestätigt!",description:`${M} E-Mails wurden erfolgreich versendet.`}),j(!1)}catch(K){console.error("Error confirming trip:",K),T({title:"Fehler beim Bestätigen",description:"Status konnte nicht aktualisiert werden.",variant:"destructive"})}finally{Z(!1)}},ne=async K=>{await i(v.id,K)&&u(!1)},le=Math.ceil((He(v.endDate).getTime()-He(v.startDate).getTime())/(1e3*60*60*24));return e.jsxs("div",{className:"space-y-8 animate-fade-in",children:[e.jsxs("div",{className:"flex items-start justify-between",children:[e.jsxs("div",{className:"flex items-start gap-4",children:[e.jsx(Yt,{to:v.status==="completed"?"/admin/trips?status=completed":"/admin/trips",className:"mt-1 flex h-10 w-10 items-center justify-center rounded-xl bg-muted transition-colors hover:bg-muted/80",children:e.jsx(Bl,{className:"h-5 w-5 text-muted-foreground"})}),e.jsxs("div",{children:[e.jsxs("div",{className:"flex items-center gap-3",children:[e.jsx("h1",{className:"text-3xl font-bold text-foreground",children:v.name}),e.jsx(Nn,{status:v.status}),o&&(o.male_count>0||o.female_count>0)&&e.jsxs("div",{className:"flex items-center gap-2 px-3 py-1.5 rounded-lg bg-muted/60 text-sm font-medium border border-border/50",children:[e.jsxs("div",{className:"flex items-center gap-1",children:[e.jsx("span",{className:"text-blue-600",children:"♂"}),e.jsx("span",{className:"text-foreground",children:o.male_count})]}),e.jsx("div",{className:"w-px h-4 bg-border"}),e.jsxs("div",{className:"flex items-center gap-1",children:[e.jsx("span",{className:"text-pink-600",children:"♀"}),e.jsx("span",{className:"text-foreground",children:o.female_count})]}),o.unknown_count>0&&e.jsxs(e.Fragment,{children:[e.jsx("div",{className:"w-px h-4 bg-border"}),e.jsxs("div",{className:"flex items-center gap-1",children:[e.jsx("span",{className:"text-muted-foreground",children:"?"}),e.jsx("span",{className:"text-foreground",children:o.unknown_count})]})]}),o.spots_left===1&&o.needed_gender&&e.jsx("span",{className:"ml-1 text-amber-600",title:`Letzter Platz für ${o.needed_gender==="male"?"Männer":"Frauen"} reserviert`,children:"⚠️"})]})]}),e.jsx("p",{className:"mt-1 text-muted-foreground",children:v.destination}),v.insuranceCertificate?e.jsxs("div",{className:"mt-2 flex items-center gap-2 text-sm text-muted-foreground",children:[e.jsx(sr,{className:"h-3.5 w-3.5"}),e.jsx("span",{children:v.insuranceCertificate.name}
159),e.jsx("span",{className:"text-muted-foreground/60",children:"·"}),e.jsxs("span",{children:["bis ",He(v.insuranceCertificate.validUntil).toLocaleDateString("de-DE")]}),e.jsx("a",{href:v.insuranceCertificate.fileUrl,target:"_blank",rel:"noopener noreferrer",className:"ml-1 text-primary hover:text-primary/80 transition-colors",title:"PDF herunterladen",children:e.jsx(da,{className:"h-3.5 w-3.5"})})]}):e.jsxs("div",{className:"mt-2 flex items-center gap-2 text-sm text-warning",children:[e.jsx(Lt,{className:"h-3.5 w-3.5"}),e.jsx("span",{children:"Kein Sicherungsschein zugewiesen"})]})]})]}),e.jsxs("div",{className:"flex gap-3",children:[e.jsxs(z,{variant:"outline",className:"gap-2 rounded-xl",onClick:()=>ge(!0),children:[e.jsx(Os,{className:"h-4 w-4"}),"E-Mail senden"]}),e.jsxs(z,{variant:"outline",className:"gap-2 rounded-xl",children:[e.jsx(lt,{className:"h-4 w-4"}),"CSV Export"]}),L&&e.jsxs(z,{className:"gap-2 rounded-xl bg-blue-600 hover:bg-blue-700 text-white",onClick:m,children:[e.jsx(Bt,{className:"h-4 w-4"}),"Veröffentlichen"]}),g&&e.jsxs(z,{className:"gap-2 rounded-xl bg-success hover:bg-success/90",onClick:()=>j(!0),children:[e.jsx(Aa,{className:"h-4 w-4"}),"Reise bestätigen"]}),v.status==="planning"&&H>0&&!g&&e.jsxs("div",{className:"flex items-center gap-2 px-4 py-2 rounded-xl bg-warning/10 text-warning text-sm font-medium",children:[e.jsx(Ns,{className:"h-4 w-4"}),"Noch ",r," Teilnehmer bis zur Mindestgröße"]}),e.jsxs(z,{variant:"outline",className:"gap-2 rounded-xl",onClick:()=>E(!0),children:[e.jsx($s,{className:"h-4 w-4"}),"Als Vorlage speichern"]}),v.templateId&&e.jsx(Yt,{to:`/admin/templates/${v.templateId}`,children:e.jsxs(z,{variant:"outline",className:"gap-2 rounded-xl",children:[e.jsx($s,{className:"h-4 w-4"}),"Vorlage bearbeiten"]})}),e.jsxs(z,{className:"gap-2 rounded-xl",onClick:()=>u(!0),children:[e.jsx(Ta,{className:"h-4 w-4"}),"Bearbeiten"]})]})]}),e.jsx(ao,{open:I,onOpenChange:E,trip:v}),e.jsx(to,{open:d,onOpenChange:u,trip:v,onSave:ne}),e.jsx(lo,{open:$,onOpenChange:ge,trip:v}),e.jsx(We,{open:W,onOpenChange:j,children:e.jsxs(Qe,{className:"glass-modal sm:max-w-md",children:[e.jsxs(Ye,{children:[e.jsxs(Je,{className:"flex items-center gap-2",children:[e.jsx(Os,{className:"h-5 w-5 text-primary"}),"Reise bestätigen & E-Mails senden"]}),e.jsx(Ds,{children:"Mit der Bestätigung werden automatisch E-Mails an alle Teilnehmer und Partner gesendet."})]}),e.jsxs("div",{className:"py-4 space-y-4",children:[e.jsxs("div",{className:"rounded-xl bg-muted/30 p-4 space-y-2",children:[e.jsxs("div",{className:"flex justify-between text-sm",children:[e.jsx("span",{className:"text-muted-foreground",children:"Teilnehmer:"}),e.jsx("span",{className:"font-medium text-foreground",children:v.totalParticipants})]}),e.jsxs("div",{className:"flex justify-between text-sm",children:[e.jsx("span",{className:"text-muted-foreground",children:"E-Mails an Teilnehmer:"}),e.jsx("span",{className:"font-medium text-foreground",children:c.filter(K=>K.email).length})]})]}),e.jsx("p",{className:"text-sm text-muted-foreground",children:"Alle Empfänger erhalten eine E-Mail mit den Reisedetails und der Bestätigung."})]}),e.jsxs(gs,{className:"gap-2",children:[e.jsx(z,{variant:"outline",className:"rounded-xl",onClick:()=>j(!1),disabled:be,children:"Abbrechen"}),e.jsx(z,{className:"gap-2 rounded-xl bg-success hover:bg-success/90",onClick:p,disabled:be,children:be?e.jsxs(e.Fragment,{children:[e.jsx($e,{className:"h-4 w-4 animate-spin"}),"E-Mails werden gesendet..."]}):e.jsxs(e.Fragment,{children:[e.jsx(Os,{className:"h-4 w-4"}),"Bestätigen & E-Mails senden"]})})]})]})}),e.jsxs("div",{className:"grid gap-4 sm:grid-cols-4",children:[e.jsxs("div",{className:"glass-card p-4 flex items-center gap-4",children:[e.jsx("div",{className:"flex h-10 w-10 items-center justify-center rounded-xl bg-primary/10",children:e.jsx(kt,{className:"h-5 w-5 text-primary"})}),e.jsxs("div",{children:[e.jsx("p",{className:"text-sm text-muted-foreground",children:"Zeitraum"}),e.jsxs("p",{className:"font-medium text-foreground",children:[He(v.startDate).toLocaleDateString("de-DE")," – ",He(v.endDate).toLocaleDateString("de-DE")]})]})]}),e.jsxs("div",{className:"glass-card p-4 flex items-center gap-4",children:[e.jsx("div",{className:"flex h-10 w-10 items-center justify-center rounded-xl bg-primary/10",children:e.jsx(Zn,{className:"h-5 w-5 text-primary"})}),e.jsxs("div",{children:[e.jsx("p",{className:"text-sm text-muted-foreground",children:"Dauer"}),e.jsxs("p",{className:"font-medium text-foreground",children:[le," Tage"]})]})]}),e.jsxs("div",{className:"glass-card p-4 flex items-center gap-4",children:[e.jsx("div",{className:"flex h-10 w-10 items-center justify-center rounded-xl bg-primary/10",children:e.jsx(Ns,{className:"h-5 w-5 text-primary"})}),e.jsxs("div",{children:[e.jsx("p",{className:"text-sm text-muted-foreground",children:"Teilnehmer"}),e.jsxs("p",{className:"font-medium text-foreground",children:[v.totalParticipants," Personen"]})]})]}),e.jsxs("div",{className:"glass-card p-4 flex items-center gap-4",children:[e.jsx("div",{className:"flex h-10 w-10 items-center justify-center rounded-xl bg-primary/10",children:e.jsx(Kt,{className:"h-5 w-5 text-primary"})}),e.jsxs("div",{children:[e.jsx("p",{className:"text-sm text-muted-foreground",children:"Umsatz"}),e.jsx("p",{className:"font-medium text-foreground",children:new Intl.NumberFormat("de-DE",{style:"currency",currency:"EUR"}).format(v.totalRevenue)})]})]}),q.length>0&&e.jsxs("div",{className:"glass-card p-4 flex items-center gap-4 bg-gradient-to-br from-amber-50 to-orange-50 dark:from-amber-950/30 dark:to-orange-950/30 border-amber-200/50 dark:border-amber-800/50",children:[e.jsx("div",{className:"flex h-10 w-10 items-center justify-center rounded-xl bg-amber-100 dar
159k:bg-amber-900/50",children:e.jsx(Nr,{className:"h-5 w-5 text-amber-600 dark:text-amber-400"})}),e.jsxs("div",{className:"flex-1 min-w-0",children:[e.jsx("p",{className:"text-sm text-amber-700 dark:text-amber-300",children:q.length===1?"Geburtstag":"Geburtstage"}),e.jsx("p",{className:"font-medium text-amber-800 dark:text-amber-200 truncate",children:q.map(K=>`${K.firstName} ${K.lastName.charAt(0)}. (${K.formattedDate})`).join(", ")})]})]})]}),e.jsx(co,{tripId:v.id,tripPrice:v.price??null,currentParticipants:v.totalParticipants,maxParticipants:v.maxGroupSize??null}),e.jsxs(ar,{value:l,onValueChange:V,className:"space-y-6",children:[e.jsxs(rr,{className:"glass-card p-1.5 h-auto w-auto inline-flex",children:[e.jsxs(Gs,{value:"bookings",className:"gap-2 rounded-xl px-4 py-2.5 data-[state=active]:bg-primary data-[state=active]:text-primary-foreground",children:[e.jsx(Kt,{className:"h-4 w-4"}),"Buchungen"]}),e.jsxs(Gs,{value:"participants",className:"gap-2 rounded-xl px-4 py-2.5 data-[state=active]:bg-primary data-[state=active]:text-primary-foreground",children:[e.jsx(Ns,{className:"h-4 w-4"}),"Teilnehmer"]}),e.jsxs(Gs,{value:"lists",className:"gap-2 rounded-xl px-4 py-2.5 data-[state=active]:bg-primary data-[state=active]:text-primary-foreground",children:[e.jsx(En,{className:"h-4 w-4"}),"Listen"]}),e.jsxs(Gs,{value:"hotel",className:"gap-2 rounded-xl px-4 py-2.5 data-[state=active]:bg-primary data-[state=active]:text-primary-foreground",children:[e.jsx(pa,{className:"h-4 w-4"}),"Hotel"]}),e.jsxs(Gs,{value:"partners",className:"gap-2 rounded-xl px-4 py-2.5 data-[state=active]:bg-primary data-[state=active]:text-primary-foreground",children:[e.jsx(bt,{className:"h-4 w-4"}),"Partner"]}),e.jsxs(Gs,{value:"expenses",className:"gap-2 rounded-xl px-4 py-2.5 data-[state=active]:bg-primary data-[state=active]:text-primary-foreground",children:[e.jsx(Jt,{className:"h-4 w-4"}),"Ausgaben"]}),e.jsxs(Gs,{value:"addons",className:"gap-2 rounded-xl px-4 py-2.5 data-[state=active]:bg-primary data-[state=active]:text-primary-foreground",children:[e.jsx(yt,{className:"h-4 w-4"}),"Add-ons"]}),e.jsxs(Gs,{value:"transfers",className:"gap-2 rounded-xl px-4 py-2.5 data-[state=active]:bg-primary data-[state=active]:text-primary-foreground",children:[e.jsx($t,{className:"h-4 w-4"}),"Transfers"]}),e.jsxs(Gs,{value:"inquiries",className:"gap-2 rounded-xl px-4 py-2.5 data-[state=active]:bg-primary data-[state=active]:text-primary-foreground",children:[e.jsx(_n,{className:"h-4 w-4"}),"Anfragen"]}),e.jsxs(Gs,{value:"waitlist",className:"gap-2 rounded-xl px-4 py-2.5 data-[state=active]:bg-primary data-[state=active]:text-primary-foreground",children:[e.jsx(Vs,{className:"h-4 w-4"}),"Warteliste"]}),e.jsxs(Gs,{value:"photos",className:"gap-2 rounded-xl px-4 py-2.5 data-[state=active]:bg-primary data-[state=active]:text-primary-foreground",children:[e.jsx(Ya,{className:"h-4 w-4"}),"Fotoalbum"]})]}),e.jsx(Is,{value:"bookings",className:"mt-6",children:e.jsx(Il,{tripId:v.id})}),e.jsx(Is,{value:"participants",className:"mt-6",children:e.jsx(lc,{tripId:v.id,groups:A,onGroupsChange:y})}),e.jsx(Is,{value:"lists",className:"mt-6",children:e.jsx(kc,{tripId:v.id,trip:v,groups:A,onGroupsChange:y,onUpdateParticipant:N})}),e.jsxs(Is,{value:"hotel",className:"mt-6 space-y-6",children:[e.jsx(zc,{tripId:v.id}),e.jsx(Rc,{tripId:v.id})]}),e.jsx(Is,{value:"partners",className:"mt-6",children:e.jsx(gc,{tripId:v.id,tripCountry:v.countryName,onOpenEmailDialog:()=>ge(!0)})}),e.jsx(Is,{value:"expenses",className:"mt-6",children:e.jsx(Bc,{tripId:v.id})}),e.jsx(Is,{value:"addons",className:"mt-6",children:e.jsx(Ic,{tripId:v.id})}),e.jsx(Is,{value:"transfers",className:"mt-6",children:e.jsx(Uc,{tripId:v.id})}),e.jsx(Is,{value:"inquiries",className:"mt-6",children:e.jsx(Jc,{tripId:v.id})}),e.jsxs(Is,{value:"waitlist",className:"mt-6 space-y-6",children:[e.jsx(Vc,{tripId:v.id}),e.jsx(Zc,{templateId:v.templateId})]}),e.jsx(Is,{value:"photos",className:"mt-6",children:e.jsx(Wc,{tripId:v.id})})]})]})}export{tu as TripDetailPage};

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.