1import{j as e}from"./vendor-radix-0e72cabc.js";import{r as t}from"./vendor-react-9016e4a2.js";import{B as s,s as a,U as n,L as r,I as i,w as l}from"./index-31192add.js";import{f as c,P as o,r as d,T as m,a as u,p as x,b as p,d as h,c as g,t as f,e as b,h as j,s as y,j as v,g as N,A as _,I as w,W as z,k,v as S,l as C,m as T,N as P,n as E,C as R,o as A}from"./generateSignedContractPdf-6fc3e588.js";import{g as D,a as M,L as $}from"./legalVersions-960ff602.js";import{F as L,p as B,D as I,P as F,V,T as q,b as H,I as U}from"./react-pdf.browser-7b6938ec.js";import{P as O}from"./pdfTheme-b0f67e9b.js";import{bj as K,bU as G,y as Y,L as W,aY as X,a8 as Q,O as J,c as Z,ar as ee,k as te,a9 as se,j as ae,a3 as ne,a2 as re,b7 as ie,s as le,au as ce,aG as oe,aF as de,bt as me,a7 as ue,R as xe,bo as pe,o as he,bl as ge,l as fe,X as be}from"./vendor-icons-e8b10069.js";import"./vendor-supabase-36eb0853.js";import"./vendor-capacitor-43d743f6.js";import"./vendor-motion-a26fe6c4.js";import"./_commonjs-dynamic-modules-3e972b61.js";const je={tr:{restaurant_name:"Restoran adı (resmî)",restaurant_business_id:"Y-tunnus (Fin vergi no)",restaurant_address:"Adres",restaurant_email:"E-posta (sözleÅme kopyası buraya gider)",restaurant_phone:"Telefon",signer_title:"İmzalayanın sıfatı",commission_own_site:"Komisyon â kendi web sitesi (⬠/ sipariÅ, ALV hariç)",commission_marketplace:"Komisyon â pitza.fi pazaryeri (⬠/ sipariÅ, ALV hariç)",setup_fee:"Kurulum ücreti (â¬, ALV hariç; faturalandıysa 0)",payment_terms_days:"Ãdeme vadesi (gün, net)",notice_period_days:"Fesih ihbar süresi (gün)",start_date:"Hizmet baÅlangıç tarihi",place_of_signing:"İmza yeri (gerçek Åehir)",dpa_version:"DPA sürümü (pitza.fi/dpa)",dpa_sha256:"DPA Fince metninin SHA-256 özeti (kanıt)",merchant_terms_version:"Kauppiasehdot sürümü (pitza.fi/merchant-terms)",merchant_terms_sha256:"Kauppiasehdot Fince metninin SHA-256 özeti (kanıt)",availability_terms:"Kesinti telafisi maddesi (metin â yalnız sabit ücret)",billing_model:"Faturalama modeli",subscription_fee:"Sabit ücret (â¬, ALV hariç)",free_period_months:"Ãcretsiz ay sayısı",equipment_mode:"Cihaz düzeni",equipment_monthly_fee:"Cihaz kirası / ay (â¬, ALV hariç)",fee_terms:"Ãcret maddesi (metin â restoran ayarından üretilir)",free_period_terms:"Ãcretsiz dönem maddesi (metin)",equipment_terms:"Cihaz maddesi (metin)",termination_terms:"Fesih özel Åartı (metin)"},en:{restaurant_name:"Restaurant name (official)",restaurant_business_id:"Business ID (Y-tunnus)",restaurant_address:"Address",restaurant_email:"Email (signed copy is sent here)",restaurant_phone:"Phone",signer_title:"Signatory role",commission_own_site:"Commission â own website (⬠/ order, excl. VAT)",commission_marketplace:"Commission â pitza.fi marketplace (⬠/ order, excl. VAT)",setup_fee:"Setup fee (â¬, excl. VAT; 0 if already invoiced)",payment_terms_days:"Payment terms (days net)",notice_period_days:"Notice period (days)",start_date:"Service start date",place_of_signing:"Place of signing (actual city)",dpa_version:"DPA version (pitza.fi/dpa)",dpa_sha256:"SHA-256 of the Finnish DPA text (evidence)",merchant_terms_version:"Merchant terms version (pitza.fi/merchant-terms)",merchant_terms_sha256:"SHA-256 of the Finnish merchant terms text (evidence)",availability_terms:"Outage credit clause (text â flat fee only)",billing_model:"Billing model",subscription_fee:"Flat fee (â¬, excl. VAT)",free_period_months:"Free months",equipment_mode:"Equipment arrangement",equipment_monthly_fee:"Equipment rent / month (â¬, excl. VAT)",fee_terms:"Fee clause (text â derived from restaurant settings)",free_period_terms:"Free period clause (text)",equipment_terms:"Equipment clause (text)",termination_terms:"Termination special clause (text)"}},ye={billing_model:{tr:{per_order:"SipariÅ baÅı komisyon",flat_monthly:"Aylık sabit ücret",flat_yearly:"Yıllık sabit ücret",lifetime:"Ãmür boyu tek seferlik lisans"},en:{per_order:"Per-order commission",flat_monthly:"Monthly flat fee",flat_yearly:"Yearly flat fee",lifetime:"Lifetime one-time licence"},fi:{per_order:"Tilauskohtainen palkkio",flat_monthly:"Kuukausimaksu",flat_yearly:"Vuosimaksu",lifetime:"Kertaluonteinen lisenssimaksu"}},equipment_mode:{tr:{none:"Kendi cihazı",purchased:"Satın alma",rented:"Kiralama"},en:{none:"Own device",purchased:"Purchase",rented:"Rental"},fi:{none:"Oma laite",purchased:"Osto",rented:"Vuokra"}}},ve={tr:{yhteistyosopimus:"İŠBirliÄi SözleÅmesi (pitza.fi)"},en:{yhteistyosopimus:"Partnership Agreement (pitza.fi)"}};function Ne(e,t){const s=e?.key??"";return je[t]?.[s]||e?.label||s}
1function _e(e,t,s){const a=String(t??""),n=ye[e];return n&&""!==a&&(n[s]?.[a]||n.fi?.[a])||null}function we(e,t){const s=e?.slug??"";return ve[t]?.[s]||e?.title||s}async function ze({geolocation:e,geocoder:t,timeoutMs:s=1e4}={}){if(!e||"function"!=typeof e.getCurrentPosition)return{city:null,source:"manual",error:"contracts.inpPlaceErrUnsupported"};let a;try{a=await new Promise((t,a)=>{e.getCurrentPosition(t,()=>e.getCurrentPosition(t,a,{enableHighAccuracy:!1,timeout:s}),{enableHighAccuracy:!0,timeout:s})})}catch(l){return{city:null,source:"manual",error:(n=l,n&&"number"==typeof n.code?1===n.code?"contracts.inpPlaceErrDenied":2===n.code?"contracts.inpPlaceErrUnavailable":3===n.code?"contracts.inpPlaceErrTimeout":"contracts.inpPlaceErrGeneric":"contracts.inpPlaceErrGeneric")}}var n;const r=a?.coords?.latitude,i=a?.coords?.longitude;if("number"!=typeof r||"number"!=typeof i)return{city:null,source:"manual",error:"contracts.inpPlaceErrGeneric"};if(!t||"function"!=typeof t.geocode)return{city:null,source:"manual",error:"contracts.inpPlaceErrGeocoder"};try{const e=function(e){if(!Array.isArray(e))return null;const t=t=>{const s=e.find(e=>e&&Array.isArray(e.types)&&e.types.includes(t)&&"string"==typeof e.long_name&&""!==e.long_name.trim());return s?s.long_name.trim():null};return t("locality")||t("postal_town")||t("administrative_area_level_3")||t("administrative_area_level_2")||null}(await new Promise((e,s)=>{t.geocode({location:{lat:r,lng:i}},(t,a)=>{"OK"===a&&t&&t[0]?e(t[0].address_components):s(new Error(String(a)))})}));return e?{city:e,source:"device",error:null}:{city:null,source:"manual",error:"contracts.inpPlaceErrNoCity"}}catch{return{city:null,source:"manual",error:"contracts.inpPlaceErrGeocoder"}}}const ke=[{key:"title",pattern:/YHTEISTYÃSOPIMUS/,label:"sözleÅme baÅlıÄı"},{key:"fees",pattern:/##\s*5\.\s*Palkkiot ja laskutus/,label:"§5 ücret maddesi"},{key:"lastSection",pattern:/##\s*18\.\s*Muut ehdot/,label:"§18 (son madde â gövde kırpılmamıÅ)"},{key:"euro",pattern:/euroa/,label:"ücret tutarı (euroa)"},{key:"prevailingLang",pattern:/suomenkielinen sopimusteksti on ratkaiseva/,label:"öncelikli dil maddesi"},{key:"platformAccount",pattern:/pitza\.fi-alustan käyttäjätilin/,label:"platform hesabı beyanı"}];function Se(e,{restaurantName:t}={}){const s=[],a=String(e??"");if(""===a.trim())return{ok:!1,issues:[{code:"empty_body",detail:"sözleÅme metni boÅ"}]};const n=c(a);n.length>0&&s.push({code:"unresolved_placeholders",detail:n.join(", ")});for(const l of ke)l.pattern.test(a)||s.push({code:"missing_marker",detail:l.label});const r=(a.match(/^##\s+\d+\./gm)||[]).length;18!==r&&s.push({code:"section_count",detail:`${r} madde bulundu, 18 bekleniyordu`}),/[äöÃÃ]/.test(a)||s.push({code:"missing_diacritics",detail:"metinde hiç ä/ö yok â kodlama/font sorunu"}),/�/.test(a)&&s.push({code:"replacement_char",detail:"metinde � (bozuk karakter) var"});const i=String(t??"").trim();return""===i||a.includes(i)||s.push({code:"restaurant_name_missing",detail:`"${i}" metinde geçmiyor`}),{ok:0===s.length,issues:s}}function Ce(e){return(e||[]).map(e=>`${e.code}: ${e.detail}`).join(" · ")}function Te(e){const t=String(e??"").trim().replace(",",".");return""!==t&&/^-?\d+(\.\d+)?$/.test(t)?Number(t):null}function Pe(e,t,s){const a=[];if(!t)return{ok:!1,issues:[{code:"no_restaurant",detail:"restoran seçilmedi"}]};if(null==s?.payment_terms_days)return{ok:!1,issues:[{code:"settings_unavailable",detail:"faturalama ayarları okunamadı"}]};const n=d(t,s),r=n.billing_model,i=(t,s)=>{const r=Te(e?.[t]),i=Te(n[t]);null!=i&&(null!=r?Math.round(100*r)!==Math.round(100*i)&&a.push({code:"engine_mismatch",detail:`${s}: sözleÅme ${r} â uygulanan ${i}`}):a.push({code:"missing_value",detail:`${s}: sözleÅmede deÄer yok`}))};return"flat_monthly"!==r&&"flat_yearly"!==r&&"lifetime"!==r||Te(n.subscription_fee)>0||a.push({code:"zero_subscription_fee",detail:"lifetime"===r?'tek seferlik lisans ücreti girilmemiÅ â sözleÅme "0,00 euroa" olarak düzenlenir':'sabit ücret girilmemiÅ â sözleÅme "0,00 euroa" olarak düzenlenir'}),"rented"!==n.equipment_mode||Te(n.equipment_monthly_fee)>0||a.push({code:"zero_equipment_fee",detail:'cihaz kirası girilmemiÅ â sözleÅme "Vuokra on 0,00 euroa" olarak düzenlenir'}),i("payment_terms_days","ödeme vadesi"),"lifetime"!==r&&i("commission_marketplace","pazaryeri komisyonu"),"per_order"===r&&i("commission_own_site","kendi site komisyonu"),{ok:0===a.length,issues:a}}const Ee=[{slug:M,versionKey:"dpa_version",shaKey:"dpa_sha256",label:"DPA"},{slug:$,versionKey:"merchant_terms_version",shaKey:"merchant_terms_sha256",label:"kauppiasehdot"}];function Re(e,t){if(Number(t)<m)return{ok:!0,issues:[]};const s=[];for(const a of Ee){const n=String(e?.[a.versionKey]??"").trim(),r
1=n?D(a.slug,n):null;r&&"published"===r.status?Number(r.contractRevision)<Number(t)?s.push({code:"legal_doc_revision",detail:`${a.label} ${n}: v6 ile eÅleÅmeyen eski sürüm`}):r.sha256&&r.sha256===String(e?.[a.shaKey]??"")||s.push({code:"legal_doc_hash_mismatch",detail:`${a.label} ${n}: SHA-256 kayıtla uyuÅmuyor`}):s.push({code:"legal_doc_unpublished",detail:`${a.label}: yayımlanmıŠv6 sürümü yok (${n||"â"})`})}return{ok:0===s.length,issues:s}}L.registerHyphenationCallback(e=>[e]);const{ACCENT:Ae,INK:De,MUTED:Me}=O,$e=H.create({page:{paddingTop:48,paddingHorizontal:56,paddingBottom:64,fontFamily:"Helvetica",fontSize:9,color:De,lineHeight:1.5},h1:{fontSize:16,fontWeight:700,letterSpacing:1.1,lineHeight:1.2},headerRule:{height:2,backgroundColor:De,marginTop:8},accentRule:{height:2,width:64,backgroundColor:Ae,marginTop:-2,marginBottom:6},h2:{fontSize:10.5,fontWeight:700,marginTop:12,marginBottom:2},p:{marginTop:3,textAlign:"justify"},liRow:{flexDirection:"row",marginTop:2,paddingLeft:10},liBullet:{width:10,fontSize:9},liText:{flex:1,textAlign:"justify"},bold:{fontWeight:700},sigSection:{marginTop:26},sigHeading:{fontSize:10.5,fontWeight:700,letterSpacing:.8},sigRule:{height:1.5,backgroundColor:De,marginTop:4},sigAccent:{height:1.5,width:48,backgroundColor:Ae,marginTop:-1.5},sigPlace:{marginTop:8,color:Me},sigRow:{flexDirection:"row",marginTop:16},sigCol:{flex:1,paddingRight:24},sigColLast:{flex:1,paddingRight:0},sigImageBox:{height:64,justifyContent:"flex-end"},sigImage:{maxHeight:60,height:60,objectFit:"contain",objectPositionX:0},sigLine:{height:1,backgroundColor:De,marginTop:4},sigName:{fontSize:9.5,fontWeight:700,marginTop:4},sigMeta:{fontSize:8,color:Me},docsSection:{marginTop:18,paddingTop:6,borderTopWidth:.75,borderTopColor:Me},docsLead:{fontSize:8,color:Me},docsRow:{marginTop:3},docsLabel:{fontSize:8,fontWeight:700},docsHash:{fontSize:7.5,color:Me}});function Le(e){const t=e||{};return[["Tietojenkäsittelysopimus (DPA)",t.dpa_version,t.dpa_sha256,"pitza.fi/dpa"],["Kauppiasehdot",t.merchant_terms_version,t.merchant_terms_sha256,"pitza.fi/merchant-terms"]].filter(([,e,t])=>e&&t).map(([e,t,s,a])=>({label:e,version:t,sha:s,url:`${a}?versio=${t}`}))}function Be({runs:t,style:s}){return e.jsx(q,{style:s,children:t.map((t,s)=>e.jsx(q,{style:t.bold?$e.bold:void 0,children:t.text},s))})}function Ie({style:t,src:s,name:a,lines:n}){return e.jsxs(V,{style:t,children:[e.jsx(V,{style:$e.sigImageBox,children:s?e.jsx(U,{src:s,style:$e.sigImage}):null}),e.jsx(V,{style:$e.sigLine}),e.jsx(q,{style:$e.sigName,children:a||" "}),n.filter(Boolean).map((t,s)=>e.jsx(q,{style:$e.sigMeta,children:t},s))]})}function Fe({title:t,blocks:s=[],signature:a={},documents:n=[]}){const{place:r,signedAtDate:i,customerName:l,customerTitle:c,restaurantName:o,businessId:d,providerName:m,customerSigSrc:u,providerSigSrc:x}=a,p=`Paikka ja aika: ${r||"________________"}, ${i?new Date(i).toLocaleDateString("fi-FI"):"__.__.____"}`;return e.jsx(I,{title:t||"Sopimus",children:e.jsxs(F,{size:"A4",style:$e.page,children:[s.map((t,s)=>{const a=s;return"h1"===t.type?e.jsxs(V,{children:[e.jsx(Be,{runs:t.runs,style:$e.h1}),e.jsx(V,{style:$e.headerRule}),e.jsx(V,{style:$e.accentRule})]},a):"h2"===t.type?e.jsx(Be,{runs:t.runs,style:$e.h2},a):"li"===t.type?e.jsxs(V,{style:$e.liRow,children:[e.jsx(q,{style:$e.liBullet,children:"â¢"}),e.jsx(Be,{runs:t.runs,style:$e.liText})]},a):e.jsx(Be,{runs:t.runs,style:$e.p},a)}),n.length>0?e.jsxs(V,{style:$e.docsSection,wrap:!1,children:[e.jsx(q,{style:$e.docsLead,children:"Kohdassa 2 mainittujen asiakirjojen allekirjoitushetken suomenkieliset tekstit yksilöidään seuraavilla SHA-256-tiivisteillä:"}),n.map(t=>e.jsxs(V,{style:$e.docsRow,children:[e.jsx(q,{style:$e.docsLabel,children:`${t.label}, versio ${t.version} (${t.url})`}),e.jsx(q,{style:$e.docsHash,children:t.sha})]},t.label))]}):null,e.jsxs(V,{style:$e.sigSection,wrap:!1,children:[e.jsx(q,{style:$e.sigHeading,children:"ALLEKIRJOITUKSET"}),e.jsx(V,{style:$e.sigRule}),e.jsx(V,{style:$e.sigAccent}),e.jsx(q,{style:$e.sigPlace,children:p}),e.jsxs(V,{style:$e.sigRow,children:[e.jsx(Ie,{style:$e.sigCol,src:u,name:l,lines:[c,[o,d?`Y-tunnus ${d}
1`:""].filter(Boolean).join(" â ")]}),e.jsx(Ie,{style:$e.sigColLast,src:x,name:m,lines:["Dorylus Oy / pitza.fi"]})]})]})]})})}async function Ve({template:t,values:s,restaurant:a=null,customerName:n="",providerName:r="",customerSigPngBytes:i=null,providerSigPngBytes:l=null,signedAtDate:c=null}){const o=u(t.body_md,t.variables,s),d=x(o),m=e.jsx(Fe,{title:t.title,blocks:d,documents:Le(s),signature:{place:s?.place_of_signing||"",signedAtDate:c,customerName:n,customerTitle:s?.signer_title||"",restaurantName:s?.restaurant_name||a?.name||"",businessId:s?.restaurant_business_id||a?.business_id||"",providerName:r,customerSigSrc:i?p(i):null,providerSigSrc:l?p(l):null}}),h=await B(m).toBlob();return new Uint8Array(await h.arrayBuffer())}const qe="#18181b",He=2.5;function Ue(e){return"number"!=typeof e.p||e.p<=0?He:He*(.55+(1.65-.55)*e.p)}function Oe(e,t){if(0===t.length)return;if(e.strokeStyle=qe,e.fillStyle=qe,e.lineJoin="round",e.lineCap="round",1===t.length)return e.beginPath(),e.arc(t[0].x,t[0].y,Ue(t[0])/2,0,2*Math.PI),void e.fill();if(!t.some(e=>"number"==typeof e.p&&e.p>0)){e.lineWidth=He,e.beginPath(),e.moveTo(t[0].x,t[0].y);for(let a=1;a<t.length-1;a+=1){const s=(t[a].x+t[a+1].x)/2,n=(t[a].y+t[a+1].y)/2;e.quadraticCurveTo(t[a].x,t[a].y,s,n)}const s=t[t.length-1];return e.lineTo(s.x,s.y),void e.stroke()}for(let s=1;s<t.length;s+=1){const a=t[s-1],n=t[s];e.lineWidth=(Ue(a)+Ue(n))/2,e.beginPath(),e.moveTo(a.x,a.y),e.lineTo(n.x,n.y),e.stroke()}}const Ke=t.forwardRef(function({height:a=180,clearLabel:n,hint:r,onChange:i},l){const c=t.useRef(null),o=t.useRef([]),d=t.useRef(null),m=t.useRef(!0),u=t.useRef(!1),x=t.useRef(null),p=t.useRef(0),[h,g]=t.useState(!0),f=t.useCallback(()=>o.current.some(e=>e.length>=2),[]),b=t.useCallback(()=>{const e=!f();e!==m.current&&(m.current=e,g(e),i?.(e))},[f,i]),j=t.useCallback(()=>{const e=c.current;if(!e)return;const t=e.getContext("2d"),s=window.devicePixelRatio||1;t.setTransform(s,0,0,s,0,0),t.clearRect(0,0,e.width/s,e.height/s);for(const a of o.current)Oe(t,a)},[]),y=t.useCallback(()=>{const e=c.current;if(!e)return;const t=e.getBoundingClientRect();if(0===t.width||0===t.height)return;const s=window.devicePixelRatio||1,a=Math.round(t.width*s),n=Math.round(t.height*s);e.width===a&&e.height===n||(e.width=a,e.height=n),j()},[j]);t.useEffect(()=>{y();const e=c.current;if(!e||"undefined"==typeof ResizeObserver)return;const t=new ResizeObserver(()=>y());return t.observe(e),()=>t.disconnect()},[y]);const v=t.useCallback((e,t)=>{const s=c.current.getBoundingClientRect(),a={x:Math.min(Math.max(e.clientX-s.left,0),s.width),y:Math.min(Math.max(e.clientY-s.top,0),s.height),t:Math.round(performance.now()-p.current)};return t&&"number"==typeof e.pressure&&e.pressure>0&&(a.p=Math.min(Math.max(e.pressure,0),1),"number"==typeof e.tiltX&&(a.tx=Math.round(e.tiltX)),"number"==typeof e.tiltY&&(a.ty=Math.round(e.tiltY))),a},[]),N=t.useCallback(e=>{const t=c.current;if(!t)return;const s="pen"===e.pointerType;if(!s&&u.current&&"touch"===e.pointerType)return;s&&(u.current=!0),e.preventDefault(),t.setPointerCapture(e.pointerId),0===o.current.length&&(p.current=performance.now()),x.current=e.pointerType;const a=[v(e,s)];d.current=a,o.current.push(a),j()},[j,v]),_=t.useCallback(e=>{const t=d.current;if(!t)return;if(x.current&&e.pointerType!==x.current)return;e.preventDefault();const s="pen"===e.pointerType,a=e.nativeEvent,n="function"==typeof a.getCoalescedEvents&&a.getCoalescedEvents().length>0?a.getCoalescedEvents():[a];for(const r of n)t.push(v(r,s));j(),b()},[b,j,v]),w=t.useCallback(e=>{d.current&&(d.current=null,x.current=null,b());const t=c.current;t?.hasPointerCapture?.(e.pointerId)&&t.releasePointerCapture(e.pointerId)},[b]),z=t.useCallback(()=>{o.current=[],d.current=null,x.current=null,u.current=!1,p.current=0,j(),b()},[b,j]);return t.useImperativeHandle(l,()=>({isEmpty:()=>!f(),clear:z,getBiometrics:()=>{if(!f())return null;const e=o.current.filter(e=>e.length>0),t=e.flat(),s=t.filter(e=>"number"==typeof e.p).map(e=>e.p),a=t.length?t[t.length-1].t:0;let n=0;for(const r of e)for(let e=1;e<r.length;e+=1)n+=Math.hypot(r[e].x-r[e-1].x,r[e].y-r[e-1].y);
1return{version:1,captured_with:u.current?"pen":x.current||"unknown",stroke_count:e.length,point_count:t.length,duration_ms:a,path_length_px:Math.round(n),avg_speed_px_per_s:a>0?Math.round(n/a*1e3):null,pressure:s.length?{samples:s.length,min:Number(Math.min(...s).toFixed(3)),max:Number(Math.max(...s).toFixed(3)),avg:Number((s.reduce((e,t)=>e+t,0)/s.length).toFixed(3))}:null,strokes:e.map(e=>e.map(e=>[Math.round(10*e.x)/10,Math.round(10*e.y)/10,e.t,"number"==typeof e.p?Math.round(1e3*e.p)/1e3:null]))}},toPngBlob:()=>{if(!f())return Promise.resolve(null);let e=1/0,t=1/0,s=-1/0,a=-1/0;for(const d of o.current)for(const n of d)n.x<e&&(e=n.x),n.y<t&&(t=n.y),n.x>s&&(s=n.x),n.y>a&&(a=n.y);const n=10.5,r=Math.max(1,Math.ceil(s-e+21)),i=Math.max(1,Math.ceil(a-t+21)),l=document.createElement("canvas");l.width=2*r,l.height=2*i;const c=l.getContext("2d");c.setTransform(2,0,0,2,0,0),c.translate(n-e,n-t);for(const d of o.current)Oe(c,d);return new Promise(e=>l.toBlob(e,"image/png"))}}),[z,f]),e.jsxs("div",{className:"relative rounded-xl border border-zinc-700 bg-white",children:[e.jsx("canvas",{ref:c,className:"block w-full rounded-xl",style:{height:a,touchAction:"none"},onPointerDown:N,onPointerMove:_,onPointerUp:w,onPointerCancel:w}),r&&h?e.jsx("span",{className:"pointer-events-none absolute inset-x-0 bottom-2 text-center text-xs text-zinc-400 select-none",children:r}):null,e.jsxs(s,{type:"button",size:"sm",variant:"ghost",className:"absolute top-1 right-1 text-zinc-500 hover:text-zinc-700",onClick:z,children:[e.jsx(K,{className:"w-3.5 h-3.5 mr-1"})," ",n]})]})}),Ge="h-11 rounded-md border border-zinc-700 bg-zinc-900 px-2 text-sm text-zinc-200 focus:outline-none focus:ring-1 focus:ring-orange-500",Ye=/^[^\s@]+@[^\s@]+\.[^\s@]+$/;function We(e,t){const s={...t};for(const a of e?.variables||[])"date"===a?.type&&s[a.key]&&(s[a.key]=new Date(s[a.key]).toLocaleDateString("fi-FI"));return s}function Xe(e){return"409"===e?.statusCode||409===e?.status||/already exists|duplicate/i.test(e?.message||"")}const Qe={text:"text",number:"number",date:"date",email:"email"},Je=new Set(["fee_terms","free_period_terms","equipment_terms","termination_terms","availability_terms"]),Ze=new Set(["billing_model","equipment_mode","commission_own_site","commission_marketplace","subscription_fee","free_period_months","equipment_monthly_fee","payment_terms_days","dpa_version","dpa_sha256","merchant_terms_version","merchant_terms_sha256"]);function et(e,t){const s=new Set((t||[]).map(e=>e.code));return s.has("settings_unavailable")?e("contracts.inpErrNoBillingDefaults"):s.has("zero_subscription_fee")||s.has("zero_equipment_fee")?e("contracts.inpErrZeroFee"):e("contracts.inpErrBillability",{issues:Ce(t)})}function tt({t:l,language:m,restaurants:x,onClose:p,onCompleted:R}){const[A,D]=t.useState("setup"),[M,$]=t.useState([]),[L,B]=t.useState(!0),[I,F]=t.useState({}),[V,q]=t.useState(!1),[H,U]=t.useState(""),[O,K]=t.useState(""),[ae,ne]=t.useState(""),[re,ie]=t.useState({}),[le,ce]=t.useState(null),[oe,de]=t.useState({}),me=t.useMemo(()=>M.find(e=>e.id===H)||null,[M,H]),ue=t.useMemo(()=>x.find(e=>String(e.id)===String(O))||null,[x,O]);t.useEffect(()=>{let e=!0;return(async()=>{try{const t=await h.listActiveTemplates();e&&$(t)}catch(t){e&&ce(t.message)}finally{e&&B(!1)}})(),g.getBillingDefaults().then(t=>{e&&F(t||{})}).catch(()=>{e&&F({})}),()=>{e=!1}},[]),t.useEffect(()=>{me&&ue&&ie(e=>({...e,...d(ue,I,{revision:f(me)})}))},[I,me,ue]);const xe=t.useCallback((e,t,s)=>{if(!e)return;const a={};for(const i of e.variables||[])i?.key&&null!=i.default&&""!==i.default&&(a[i.key]=String(i.default));const n=b(e.variables,t),r=d(t,s,{revision:f(e)});ie({...a,...n,...r}),ne(t?.name?`${e.title} â ${t.name}`:e.title)},[]),pe=(e,t)=>{ie(s=>({...s,[e]:t})),de(t=>t[e]?{...t,[e]:null}:t)},[he,ge]=t.useState(null),[fe,be]=t.useState(null);t.useEffect(()=>{if("preview"!==A||!me)return;let e=!0,t=null;return ge(null),be(null),(async()=>{try{const s=await Ve({template:me,values:We(me,re),restaurant:ue});if(!e)return;t=URL.createObjectURL(new Blob([s],{type:"application/pdf"})),ge(t)}catch(s){e&&be(s.message)}})(),()=>{e=!1,t&&URL.revokeObjectURL(t)}},[A,me,re,ue]);const[je,ye]=t.useState(!1),[ve,ke]=t.useState(!1),[Te,Ee]=t.useState(!1),[Ae,De]=t.useState(""),[Me,$e]=t.useState({consent_confirmed_at:null,authority_confirmed_at:null,witness_confirmed_at:null,id_verification_selected_at:null,terms_summary_shown_at:null,terms_summary_language:null}),Le=(e,t)=>{$e(s=>({...s,[e]:t?(new Date).toISOString():null}))},[Be,Ie]=t.useState(""),[Fe,qe]=t.useState(""),[He,Ue]=t.useState(""),[Oe,tt]=t.useState({customer:!0,provider:!0}),st=t.useRef(null),at=t.useRef(null);t.useEffect(()=>{let e=!0;return(async()=>{const{data:t,error:s}=await a.auth.getUser();if(s||!e)return;const n=t?.user,r=n?.user_metadata?.full_name||n?.user_metadata?.name||n?.email||"";r&&Ue(e=>e||r)})(),()=>{e=!1}},[]);const[nt,rt]=t.useState("manual"),[it,lt]=t.useState(!1),[ct,ot]=t.useState(null),dt=t.useCallback(async()=>{lt(!0),ot(null);try{const e=window.google?.maps?.Geocoder?new window.google.maps.Geocoder:null,t=await ze({geolocation:navigator.geolocation,geocoder:e});t.city?(ie(e=>({...e,place_of_signing:t.city})),rt("device"),$e(e=>({...e,place_source:"device",place_resolved_at:(new Date).toISOString()}))):(rt("manual"),ot(t.error),$e(e=>({...e,place_source:"manual",place_resolved_at:null})))}finally{lt(!1)}},[]),mt=t.useMemo(()=>ue?j({billingModel:ue.billing_model||"per_order",commissionOwnSite:ue.commission_own_site??I.default_unit_fee??.5,commissionMarketplace:ue.commission_marketplace??I.marketplace_unit_fee??1,subscriptionFee:ue.flat_fee_net??0,freePeriodMonths:ue.free_period_months,billingStartDate:ue.billing_start_date,equipmentMode:ue.equipment_mode||"none",equipmentMonthlyFee:ue.equipment_monthly_fee??0,paymentTermsDays:re.payment_terms_days??I.payment_terms_days??14,setupFee:re.setup_fee,revision:f(me)}):[],[ue,me,I,re.payment_terms_days,re.setup_fee]),[ut,xt]=t.useState(!1),[pt,ht]=t.useState(null),[gt,ft]=t.useState(null),[bt,jt]=t.useState(null),yt=t.useRef({sig:null,contract:null,sigsUploaded:!1,signedRow:null,sealed:null}),vt=je&&ve&&Te&&""!==Ae&&""!==Be.trim()&&""!==He.trim()&&Ye.test(Fe.trim())&&!Oe.customer&&!Oe.provider,Nt=t.useCallback(async()=>
1{if(ut)return;xt(!0),ft(null);const e=yt.current;try{if(!e.sig){const[t,s]=await Promise.all([st.current?.toPngBlob(),at.current?.toPngBlob()]);if(!t||!s)throw new Error(l("contracts.inpNeedSigs"));const a=new Uint8Array(await t.arrayBuffer()),n=new Uint8Array(await s.arrayBuffer());e.sig={customerBytes:a,providerBytes:n,customerSha:await y(a),providerSha:await y(n)}}if(!e.contract){ht("creating");const t=u(me.body_md,me.variables,We(me,re)),s=c(t);if(s.length>0)throw new Error(l("contracts.inpErrUnresolvedVars",{vars:s.join(", ")}));const a=Pe(re,ue,I);if(!a.ok)throw new Error(et(l,a.issues));const n=Re(re,f(me));if(!n.ok)throw new Error(l("contracts.inpErrLegalDocs",{issues:Ce(n.issues)}));const r=Se(t,{restaurantName:ue?.name});if(!r.ok)throw new Error(l("contracts.inpErrQualityGate",{issues:Ce(r.issues)}));const i=await Ve({template:me,values:We(me,re),restaurant:ue,customerName:Be.trim(),providerName:He.trim(),customerSigPngBytes:e.sig.customerBytes,providerSigPngBytes:e.sig.providerBytes,signedAtDate:new Date}),d=await async function(e,{minPages:t=2,minBytes:s=8e3}={}){const a=[];if(!e||"number"!=typeof e.byteLength||0===e.byteLength)return{ok:!1,issues:[{code:"empty_pdf",detail:"PDF üretilemedi (0 bayt)"}],pages:null};e.byteLength<s&&a.push({code:"suspiciously_small",detail:`${e.byteLength} bayt â en az ${s} bekleniyordu`});const n=new TextDecoder("latin1").decode(e.slice(0,5));if("%PDF-"!==n)return{ok:!1,issues:[...a,{code:"not_pdf",detail:`dosya %PDF- ile baÅlamıyor (${n})`}],pages:null};let r=null;try{r=(await o.load(e,{updateMetadata:!1})).getPageCount()}catch(i){return{ok:!1,issues:[...a,{code:"corrupt_pdf",detail:i?.message||"PDF açılamadı"}],pages:null}}return r<t&&a.push({code:"too_few_pages",detail:`${r} sayfa â en az ${t} bekleniyordu`}),{ok:0===a.length,issues:a,pages:r}}(i);if(!d.ok)throw new Error(l("contracts.inpErrQualityGate",{issues:Ce(d.issues)}));e.contract=await g.createInPersonContract({restaurantId:Number(O),title:ae.trim()||me.title,description:null,templateId:me.id,templateVariables:re,pdfBytes:i})}const s=v(e.contract.restaurant_id,e.contract.id);if(!e.sigsUploaded){ht("uploading");for(const[a,n]of[[s.customer,e.sig.customerBytes],[s.provider,e.sig.providerBytes]])try{await g.uploadSignatureImage(a,new Blob([n],{type:"image/png"}))}catch(t){if(!Xe(t))throw t}e.sigsUploaded=!0}e.signedRow||(ht("signing"),e.signedRow=await g.signInPerson({contractId:e.contract.id,customerName:Be.trim(),customerEmail:Fe.trim(),providerName:He.trim(),customerSigPath:s.customer,customerSigSha256:e.sig.customerSha,providerSigPath:s.provider,providerSigSha256:e.sig.providerSha,authorityConfirmed:ve,witnessConfirmed:Te,idVerification:Ae,ceremony:Me})),e.sealed||(ht("sealing"),e.sealed=await N(e.signedRow));const a=await g.downloadUrl(e.sealed.signedPath);jt(a),ht(null),D("done"),R?.()}catch(t){ft(t.message),n({category:"business_logic",code:"CONTRACT_INPERSON_SIGN_FAILED",summary:"in-person contract signing ceremony step failed",action:"sign_contract_in_person",error:t,context:{restaurantId:O,contractId:e.contract?.id||null,stage:pt}})}finally{xt(!1)}},[ut,me,re,ue,O,ae,Be,Fe,He,ve,Te,Ae,Me,pt,l,R,I]),_t={setup:1,preview:2,terms:3,ceremony:4,done:5}[A];return e.jsxs("div",{className:"rounded-xl border border-zinc-800 bg-zinc-900 p-6",children:[e.jsxs("div",{className:"flex items-center justify-between mb-4",children:[e.jsxs("div",{children:[e.jsxs("h2",{className:"text-lg font-bold flex items-center gap-2",children:[e.jsx(G,{className:"w-5 h-5 text-orange-500"})," ",l("contracts.inpTitle")]}),e.jsx("p",{className:"text-xs text-zinc-500 mt-1",children:l("contracts.inpSubtitle")})]}),e.jsxs(s,{variant:"ghost",size:"sm",onClick:()=>{const e=yt.current;(!e.contract||e.sealed||"done"===A||window.confirm(l("contracts.inpCancelConfirm")))&&p()},children:[e.jsx(Y,{className:"w-4 h-4 mr-1"})," ",l("contracts.back")]})]}),e.jsx("div",{className:"flex items-center gap-2 mb-6 text-xs",children:["inpStepSetup","inpStepPreview","inpStepTerms","inpStepCeremony","inpStepDone"].map((t,s)=>e.jsxs("span",{className:"px-2 py-1 rounded-full border "+(s+1===_t?"border-orange-500 text-orange-400 bg-orange-500/10":s+1<_t?"border-emerald-500/40 text-emerald-400":"border-zinc-700 text-zinc-500"),children:[s+1,". ",l(`contracts.${t}`)]},t))}),"setup"===A&&e.jsxs("div",{className:"space-y-4",children:[e.jsxs("div",{className:"flex flex-wrap gap-3",children:[e.jsxs("div",{className:"flex flex-col",children:[e.jsx(r,{className:"text-xs text-zinc-500 mb-1",children:l("contracts.inpTemplate")}),e.jsxs("select",{className:`${Ge} w-72`,value:H,onChange:e=>(e=>{U(e);const t=M.find(t=>
1t.id===e)||null;xe(t,ue,I)})(e.target.value),children:[e.jsx("option",{value:"",children:L?"â¦":0===M.length?l("contracts.inpNoTemplates"):l("contracts.inpSelectTemplate")}),M.map(t=>e.jsxs("option",{value:t.id,children:[we(t,m)," (v",t.version,")"]},t.id))]})]}),e.jsxs("div",{className:"flex flex-col",children:[e.jsx(r,{className:"text-xs text-zinc-500 mb-1",children:l("contracts.fRestaurant")}),e.jsxs("select",{className:`${Ge} w-64`,value:O,onChange:e=>(e=>{K(e);const t=x.find(t=>String(t.id)===String(e))||null;if(!me)return;const s=b(me.variables,t),a=d(t,I,{revision:f(me)});ie(e=>{const t={...e};for(const[a,n]of Object.entries(s))t[a]&&""!==String(t[a]).trim()||(t[a]=n);return{...t,...a}}),t?.name&&ne(`${me.title} â ${t.name}`)})(e.target.value),children:[e.jsx("option",{value:"",children:l("contracts.selectRestaurant")}),x.map(t=>e.jsx("option",{value:t.id,children:t.name},t.id))]})]}),e.jsxs("div",{className:"flex flex-col flex-1 min-w-[260px]",children:[e.jsx(r,{className:"text-xs text-zinc-500 mb-1",children:l("contracts.fTitle")}),e.jsx(i,{className:"h-11",value:ae,onChange:e=>ne(e.target.value)})]})]}),me&&e.jsxs("div",{children:[e.jsx("p",{className:"text-xs text-zinc-500 font-semibold uppercase tracking-wider mb-2",children:l("contracts.inpVariables")}),e.jsxs("p",{className:"text-xs text-zinc-500 mb-3 flex items-start gap-1.5",children:[e.jsx(W,{className:"w-3.5 h-3.5 mt-0.5 shrink-0"}),e.jsx("span",{children:l("contracts.inpAmountsLocked")})]}),e.jsx("div",{className:"grid gap-3 sm:grid-cols-2 lg:grid-cols-3",children:(me.variables||[]).filter(e=>!Je.has(e.key)).map(t=>{const s=Ze.has(t.key);return e.jsxs("div",{className:"flex flex-col",children:[e.jsxs(r,{className:"text-xs text-zinc-500 mb-1",children:[Ne(t,m),t.required?" *":""]}),s?e.jsx("p",{title:re[t.key]||"",className:"h-11 flex items-center px-3 rounded-md border border-zinc-800 bg-zinc-900/60 text-sm text-zinc-400",children:_e(t.key,re[t.key],m)||re[t.key]||"â"}):e.jsx(i,{className:"h-11"+(oe[t.key]?" border-red-500/60":""),type:Qe[t.type]||"text",value:re[t.key]||"",onChange:e=>pe(t.key,e.target.value)}),oe[t.key]?e.jsx("p",{className:"text-xs text-red-400 mt-1",children:oe[t.key]}):null]},t.key)})})]}),le&&e.jsx("div",{className:"rounded-lg bg-red-500/10 border border-red-500/20 text-red-400 px-4 py-2 text-sm",children:le}),e.jsxs(s,{size:"lg",onClick:()=>{if(ce(null),!me)return void ce(l("contracts.inpNeedTemplate"));if(!ue)return void ce(l("contracts.inpNeedRestaurant"));const e=Pe(re,ue,I);if(!e.ok)return void ce(et(l,e.issues));const t=Re(re,f(me));if(!t.ok)return void ce(l("contracts.inpErrLegalDocs",{issues:Ce(t.issues)}));const s=(me.variables||[]).filter(e=>e?.required&&""===String(re[e.key]??"").trim()).map(e=>e.label||e.key),a=(()=>{const e={};for(const t of me?.variables||[]){const s=t?.key;if(!s)continue;const a=String(re[s]??"").trim();""!==a&&("restaurant_business_id"!==s||S(a)?C(t)&&!T(a)?e[s]=l("contracts.inpErrMoneyFormat"):P[s]&&!E(s,a)&&(e[s]=l("contracts.inpErrRange",P[s])):e[s]=l("contracts.inpErrBusinessId"))}return e})();if(de(a),s.length>0)ce(l("contracts.inpMissingRequired",{fields:s.join(", ")}));else if(Object.values(a).some(Boolean))ce(l("contracts.inpFixFields"));else{try{const e=u(me.body_md,me.variables,We(me,re)),t=c(e);if(t.length>0)return void ce(l("contracts.inpErrUnresolvedVars",{vars:t.join(", ")}));const s=Se(e,{restaurantName:ue?.name});if(!s.ok)return void ce(l("contracts.inpErrQualityGate",{issues:Ce(s.issues)}))}catch(n){return void ce(n.message)}D("preview")}},disabled:!me||!ue,children:[l("contracts.inpNext")," ",e.jsx(X,{className:"w-4 h-4 ml-1"})]})]}),"preview"===A&&e.jsxs("div",{className:"space-y-4",children:[e.jsx("p",{className:"text-sm text-zinc-400",children:l("contracts.inpPreviewHelp")}),fe?e.jsx("div",{className:"rounded-lg bg-red-500/10 border border-red-500/20 text-red-400 px-4 py-2 text-sm",children:fe}):he?e.jsx("iframe",{title:ae,src:he,className:"w-full h-[62vh] rounded-xl border border-zinc-700 bg-white"}):e.jsx("div",{className:"flex items-center justify-center h-40 text-zinc-500",children:e.jsx(Q,{className:"w-6 h-6 animate-spin"})}),e.jsxs("div",{className:"flex gap-3",children:[e.jsxs(s,{variant:"outline",onClick:()=>D("setup"),children:[e.jsx(Y,{className:"w-4 h-4 mr-1"})," ",l("contracts.back")]}),e.jsxs(s,{size:"lg",onClick:()=>{qe(e=>e||re.restaurant_email||""),D("terms")},disabled:!he,children:[l("contracts.inpToCeremony")," ",e.jsx(X,{className:"w-4 h-4 ml-1"})]})]})]}),"terms"===A&&e.jsxs("div",{className:"space-y-4",children:[e.jsxs("div",{children:[e.jsx("h3",{className:"text-base font-semibold text-zinc-100",children:l("contracts.inpTermsTitle")}),e.jsx("p",{className:"text-sm text-zinc-400 mt-1",children:l("contracts.inpTermsIntro")})]}),e.jsx("div",{className:"rounded-xl border border-zinc-700 divide-y divide-zinc-800 overflow-hidden",children:mt.map(t=>e.jsxs("div",{className:"px-4 py-3",children:[e.jsxs("div",{className:"flex flex-wrap items-baseline justify-between gap-2",children:[e.jsx("span",{className:"text-sm text-zinc-400",children:t.k}),e.jsx("span",{className:"text-base font-semibold text-zinc-100",children:t.v})]}),t.note&&e.jsx("p",{className:"text-xs text-zinc-500 mt-1 leading-relaxed",children:t.note})]},t.k))}),e.jsxs("div",{className:"rounded-lg border border-zinc-700 bg-zinc-900/40 px-4 py-3",children:[e.jsx("p",{className:"text-xs text-zinc-500",children:l("contracts.inpTermsEmailNote")}),e.jsx("p",{className:"text-sm font-medium text-zinc-200 mt-0.5 break-all",children:Fe||"â"})]}),e.jsxs("label",{className:"flex items-start gap-3 cursor-pointer select-none py-2",children:[e.jsx("input",{type:"checkbox",className:"mt-1 h-5 w-5 accent-orange-500",checked:V,onChange:e=>{q(e.target.checked),$e(t=>({...t,terms_summary_shown_at:e.target.checked?(new Date).toISOString():null,terms_summary_language:e.target.checked?"tr":null}))}}),e.jsx("span",{className:"text-sm text-zinc-300",children:l("contracts.inpTermsAck")})]}),e.jsxs("div",{className:"flex gap-3",children:[e.jsxs(s,{variant:"outline",onClick:()=>D("preview"),children:[e.jsx(Y,{className:"w-4 h-4 mr-1"})," ",l("contracts.inpTermsBack")]}),e.jsxs(s,{size:"lg",onClick:()=>D("ceremony"),disabled:!V,children:[l("contracts.inpTermsNext")," ",e.jsx(X,{className:"w-4 h-4 ml-1"})]})]})]}),"ceremony"===A&&e.jsxs("div",{className:"space-y-5",children:[e.jsxs("div",{className:"rounded-lg border border-zinc-700 bg-zinc-900/40 px-4 py-3 space-y-2",children:[e.jsxs("div",{className:"flex flex-wrap items-end gap-3",children:[e.jsxs("div",{className:"flex-1 min-w-[180px]",children:[e.jsx(r,{className:"text-xs text-zinc-500",children:l("contracts.inpPlaceLabel")}),e.jsx(i,{className:"h-11 mt-1",value:re.place_of_signing||"",onChange:e=>{pe("place_of_signing",e.target.value),rt("manual")}})]}),e.jsxs("div",{className:"min-w-[120px]",children:[e.jsx(r,{className:"text-xs text-zinc-500",children:l("contracts.inpDateLabel")}),e.jsx("p",{className:"h-11 flex items-center text-sm text-zinc-300",children:(new Date).toLocaleDateString("fi-FI")})]}),e.jsxs(s,{variant:"outline",className:"h-11",onClick:dt,disabled:it,children:[it?e.jsx(Q,{className:"w-4 h-4 mr-1 animate-spin"}):null,l("contracts.inpUseDeviceLocation")]})]}),"device"===nt&&e.jsx("p",{className:"text-xs text-emerald-400",children:l("contracts.inpPlaceFromDevice")}),ct&&e.jsx("p",{className:"text-xs text-amber-400",children:l(ct)})]}),e.jsx("p",{className:"text-sm text-zinc-400",children:l("contracts.inpCeremonyHelp")}),e.jsxs("div",{className:"grid gap-4 lg:grid-cols-2",children:[e.jsxs("div",{className:"space-y-3",children:[e.jsxs("div",{children:[e.jsxs(r,{className:"text-sm text-zinc-400",children:[l("contracts.inpCustomerName")," *"]}),e.jsx(i,{className:"h-12 text-base",value:Be,onChange:e=>Ie(e.target.value),autoComplete:"off"})]}),e.jsxs("div",{children:[e.jsx(r,{className:"text-sm text-zinc-400",children:l("contracts.inpCustomerRole")}),e.jsx("p",{className:"h-12 flex items-center rounded-md border border-zinc-800 bg-zinc-950/40 px-3 text-base text-zinc-300",children:re.signer_title||"â"}),e.jsx("p",{className:"text-xs text-zinc-500 mt-1",children:l("contracts.inpCustomerRoleLocked")})]}),e.jsxs("div",{children:[e.jsxs(r,{className:"text-sm text-zinc-400",children:[l("contracts.inpCustomerEmail")," *"]}),e.jsx(i,{className:"h-12 text-base",type:"email",value:Fe,onCh
1ange:e=>qe(e.target.value),autoComplete:"off"}),e.jsxs("p",{className:"text-xs text-zinc-500 mt-1 flex items-center gap-1",children:[e.jsx(J,{className:"w-3 h-3"})," ",l("contracts.inpCustomerEmailHelp")]})]}),e.jsxs("label",{className:"flex items-start gap-3 text-sm cursor-pointer rounded-xl border border-zinc-700 bg-zinc-950/40 p-3",children:[e.jsx("input",{type:"checkbox",checked:ve,onChange:e=>{return t=e.target.checked,ke(t),void Le("authority_confirmed_at",t);var t},className:"mt-0.5 h-5 w-5 accent-orange-500"}),e.jsx("span",{className:"text-zinc-300",children:_})]})]}),e.jsxs("div",{className:"space-y-3",children:[e.jsxs("div",{children:[e.jsxs(r,{className:"text-sm text-zinc-400",children:[l("contracts.inpProviderName")," *"]}),e.jsx(i,{className:"h-12 text-base",value:He,onChange:e=>Ue(e.target.value),autoComplete:"off"}),e.jsx("p",{className:"text-xs text-zinc-500 mt-1",children:l("contracts.inpProviderNameHelp")})]}),e.jsxs("div",{className:"flex flex-col",children:[e.jsxs(r,{className:"text-sm text-zinc-400 mb-1",children:[l("contracts.inpIdVerification")," *"]}),e.jsxs("select",{className:Ge,value:Ae,onChange:e=>{return t=e.target.value,De(t),void Le("id_verification_selected_at",""!==t);var t},children:[e.jsx("option",{value:"",children:l("contracts.inpIdVerificationSelect")}),w.map(t=>e.jsx("option",{value:t.value,children:t.labelFi},t.value))]})]}),e.jsxs("label",{className:"flex items-start gap-3 text-sm cursor-pointer rounded-xl border border-zinc-700 bg-zinc-950/40 p-3",children:[e.jsx("input",{type:"checkbox",checked:Te,onChange:e=>{return t=e.target.checked,Ee(t),void Le("witness_confirmed_at",t);var t},className:"mt-0.5 h-5 w-5 accent-orange-500"}),e.jsx("span",{className:"text-zinc-300",children:z})]})]})]}),e.jsxs("div",{className:"grid gap-4 lg:grid-cols-2",children:[e.jsxs("div",{children:[e.jsxs(r,{className:"text-sm text-zinc-400 mb-1 block",children:[l("contracts.inpCustomerSignature")," *"]}),e.jsx(Ke,{ref:st,height:200,clearLabel:l("contracts.sigClear"),hint:l("contracts.sigHint"),onChange:e=>tt(t=>({...t,customer:e}))})]}),e.jsxs("div",{children:[e.jsxs(r,{className:"text-sm text-zinc-400 mb-1 block",children:[l("contracts.inpProviderSignature")," *"]}),e.jsx(Ke,{ref:at,height:200,clearLabel:l("contracts.sigClear"),hint:l("contracts.sigHint"),onChange:e=>tt(t=>({...t,provider:e}))})]})]}),e.jsxs("label",{className:"flex items-start gap-3 text-sm cursor-pointer rounded-xl border border-zinc-700 bg-zinc-950/40 p-4",children:[e.jsx("input",{type:"checkbox",checked:je,onChange:e=>{return t=e.target.checked,ye(t),void Le("consent_confirmed_at",t);var t},className:"mt-0.5 h-5 w-5 accent-orange-500"}),e.jsx("span",{className:"text-zinc-300",children:k})]}),gt&&e.jsxs("div",{className:"rounded-lg bg-red-500/10 border border-red-500/20 text-red-400 px-4 py-3 text-sm space-y-2",children:[e.jsxs("p",{className:"flex items-center gap-2",children:[e.jsx(Z,{className:"w-4 h-4 shrink-0"})," ",l("contracts.inpFailed"),": ",gt]}),e.jsxs("div",{className:"flex gap-2",children:[e.jsx(s,{size:"sm",variant:"outline",onClick:Nt,disabled:ut,children:l("contracts.inpRetry")}),yt.current.contract&&!yt.current.signedRow&&e.jsxs(s,{size:"sm",variant:"ghost",className:"text-red-400",onClick:async()=>{const e=yt.current;if(e.contract&&!e.signedRow&&window.confirm(l("contracts.inpVoidConfirm")))try{await g.voidContract(e.contract.id),R?.(),p()}catch(t){ft(t.message)}},disabled:ut,children:[e.jsx(ee,{className:"w-3.5 h-3.5 mr-1"})," ",l("contracts.inpVoidDraft")]})]})]}),e.jsxs("div",{className:"flex flex-wrap gap-3 items-center",children:[e.jsxs(s,{variant:"outline",onClick:()=>D("preview"),disabled:ut||!!yt.current.contract,children:[e.jsx(Y,{className:"w-4 h-4 mr-1"})," ",l("contracts.back")]}),e.jsxs(s,{size:"lg",className:"h-12 px-6 text-base",onClick:Nt,disabled:!vt||ut,children:[ut?e.jsx(Q,{className:"w-4 h-4 mr-2 animate-spin"}):e.jsx(G,{className:"w-4 h-4 mr-2"}),l(ut&&pt?`contracts.inpStage_${pt}`:"contracts.inpCompleteBtn")]})]})]}),"done"===A&&e.jsxs("div",{className:"rounded-xl border border-emerald-500/40 bg-emerald-500/10 p-6 space-y-3",children:[e.jsxs("p",{className:"font-semibold flex items-center gap-2 text-emerald-400",children:[e.jsx(te,{className:"w-5 h-5"})," ",l("contracts.inpDoneTitle")]}),e.jsx("p",{className:"text-sm text-zinc-300",children:l("contracts.inpDoneEmailNote",{email:Fe.trim()})}),e.jsxs("div",{className:"flex gap-3",children:[bt&&e.jsxs(s,{onClick:()=>window.open(bt,"_blank","noopener"),children:[e.jsx(se,{className:"w-4 h-4 mr-1"})," ",l("contracts.downloadSignedBtn")]}),e.jsx(s,{variant:"outline",onClick:p,children:l("contracts.inpClose")})]})]})]})}const st="h-9 rounded-md border border-zinc-700 bg-zinc-900 px-2 text-sm text-zinc-200 focus:outline-none focus:ring-1 focus:ring-orange-500",at=/^[a-z0-9][a-z0-9-]*$/,nt=["text","number","date","email"],rt={key:"",label:"",type:"text",required:!1,default:"",source:""},it=e=>
1e?new Date(e).toLocaleString("fi-FI"):"â";function lt(e){return{slug:e?.slug||"",title:e?.title||"",language:e?.language||"fi",bodyMd:e?.body_md||"",variables:(e?.variables||[]).map(e=>({...rt,...e,default:e.default??"",source:e.source??""}))}}function ct(e){return e.filter(e=>""!==e.key.trim()).map(e=>{const t={key:e.key.trim(),label:e.label.trim()||e.key.trim(),type:e.type,required:!!e.required};return""!==e.default.trim()&&(t.default=e.default.trim()),""!==e.source.trim()&&(t.source=e.source.trim()),t})}function ot({t:a}){const[n,l]=t.useState([]),[c,o]=t.useState(!0),[d,m]=t.useState(null),[u,x]=t.useState(null),[p,g]=t.useState({}),[f,b]=t.useState(null),[j,y]=t.useState(!1),[v,N]=t.useState(null),[_,w]=t.useState(!1),z=t.useCallback(async()=>{o(!0);try{l(await h.listActiveTemplates())}catch(e){m({type:"error",text:e.message})}finally{o(!1)}},[]);t.useEffect(()=>{z()},[z]),t.useEffect(()=>()=>{v&&URL.revokeObjectURL(v)},[v]);const k=async e=>{w(!0),m(null);try{const t=e.variables||[],s={};for(const e of t)e?.key&&(s[e.key]=null!=e.default&&""!==String(e.default).trim()?String(e.default):`{{${e.key}}}`);const a=await Ve({template:{title:e.title,body_md:e.body_md,variables:t},values:s});N(URL.createObjectURL(new Blob([a],{type:"application/pdf"})))}catch(t){m({type:"error",text:`${a("contracts.tplPreviewFailed")}: ${t.message}`})}finally{w(!1)}},S=(e,t)=>b(s=>({...s,[e]:t})),C=(e,t,s)=>b(a=>({...a,variables:a.variables.map((a,n)=>n===e?{...a,[t]:s}:a)}));return e.jsxs("div",{className:"space-y-4",children:[e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsxs("div",{children:[e.jsxs("h2",{className:"text-sm font-semibold flex items-center gap-2",children:[e.jsx(ae,{className:"w-4 h-4 text-orange-500"})," ",a("contracts.tplTitle")]}),e.jsx("p",{className:"text-xs text-zinc-500 mt-1",children:a("contracts.tplSubtitle")})]}),e.jsxs(s,{size:"sm",onClick:()=>b(lt(null)),children:[e.jsx(ne,{className:"w-4 h-4 mr-1"})," ",a("contracts.tplNew")]})]}),d&&e.jsx("div",{className:"rounded-lg px-4 py-2 text-sm "+("ok"===d.type?"bg-emerald-500/10 text-emerald-400 border border-emerald-500/20":"bg-red-500/10 text-red-400 border border-red-500/20"),children:d.text}),e.jsx("div",{className:"rounded-xl border border-zinc-800 bg-zinc-900 overflow-x-auto",children:e.jsxs("table",{className:"w-full text-sm",children:[e.jsx("thead",{className:"text-xs text-zinc-500 border-b border-zinc-800",children:e.jsxs("tr",{children:[e.jsx("th",{className:"text-left p-3",children:a("contracts.tplColSlug")}),e.jsx("th",{className:"text-left",children:a("contracts.tplColTitle")}),e.jsx("th",{className:"text-left",children:a("contracts.tplColVersion")}),e.jsx("th",{className:"text-left",children:a("contracts.tplColLang")}),e.jsx("th",{className:"text-left",children:a("contracts.tplColCreated")}),e.jsx("th",{className:"text-right pr-3",children:a("contracts.tplColActions")})]})}),e.jsxs("tbody",{children:[c&&e.jsx("tr",{children:e.jsx("td",{colSpan:6,className:"p-6 text-center text-zinc-600",children:"â¦"})}),!c&&0===n.length&&e.jsx("tr",{children:e.jsx("td",{colSpan:6,className:"p-6 text-center text-zinc-600",children:a("contracts.tplNone")})}),n.map(t=>e.jsx(dt,{row:t,t:a,versionsOpen:u===t.slug,versionRows:p[t.slug],previewBusy:_,onToggleVersions:()=>(async e=>{if(u!==e){if(x(e),!p[e])try{const t=await h.listTemplateVersions(e);g(s=>({...s,[e]:t}))}catch(t){m({type:"error",text:t.message})}}else x(null)})(t.slug),onEdit:()=>b(lt(t)),onArchive:()=>(async e=>{if(window.confirm(a("contracts.tplArchiveConfirm",{slug:e.slug})))try{await h.archiveTemplate(e.slug),m({type:"ok",text:a("contracts.tplArchivedMsg",{slug:e.slug})}),await z()}catch(t){m({type:"error",text:t.message})}})(t),onPreview:()=>k(t)},t.id))]})]})}),v&&e.jsx("iframe",{title:"template-preview",src:v,className:"w-full h-[62vh] rounded-xl border border-zinc-700 bg-white"}),f&&e.jsxs("div",{className:"rounded-xl border border-zinc-800 bg-zinc-900 p-5 space-y-4",children:[e.jsx("h3",{className:"text-sm font-semibold",children:f.slug?a("contracts.tplEditorEdit",{slug:f.slug}):a("contracts.tplEditorNew")}),e.jsxs("div",{className:"flex flex-wrap gap-3",children:[e.jsxs("div",{className:"flex flex-col",children:[e.jsx(r,{className:"text-xs text-zinc-500 mb-1",children:a("contracts.tplSlug")}),e.jsx(i,{className:"w-56 font-mono",value:f.slug,onChange:e=>S("slug",e.target.value)}),e.jsx("p",{className:"text-[10px] text-zinc-600 mt-1",children:a("contracts.tplSlugHelp")})]}),e.jsxs("div",{className:"flex flex-col flex-1 min-w-[220px]",children:[e.jsx(r,{className:"text-xs text-zinc-500 mb-1",children:a("contracts.tplTitleField")}),e.jsx(i,{value:f.title,onChange:e=>S("title",e.target.value)})]}),e.jsxs("div",{className:"flex flex-col",children:[e.jsx(r,{className:"text-xs text-zinc-500 mb-1",children:a("contracts.tplLang")}),e.jsxs("select",{className:st,value:f.language,onChange:e=>S("language",e.target.value),children:[e.jsx("option",{value:"fi",children:"fi"}),e.jsx("option",{value:"en",children:"en"})]})]})]}),e.jsxs("div",{className:"flex flex-col",children:[e.jsx(r,{className:"text-xs text-zinc-500 mb-1",children:a("contracts.tplBody")}),e.jsx("textarea",{className:"min-h-[320px] rounded-md border border-zinc-700 bg-zinc-950 p-3 text-sm font-mono text-zinc-200 focus:outline-none focus:ring-1 focus:ring-orange-500",value:f.bodyMd,onChange:e=>S("bodyMd",e.target.value),spellCheck:!1}),e.jsx("p",{className:"text-[10px] text-zinc-600 mt-1",children:a("contracts.tplBodyHelp")})]}),e.jsxs("div",{children:[e.jsxs("div",{className:"flex items-center justify-between mb-2",children:[e.jsx(r,{className:"text-xs text-zinc-500",children:a("contracts.tplVars")}),e.jsxs(s,{size:"sm",variant:"outline",onClick:()=>S("variables",[...f.variables,{...rt}]),children:[e.jsx(ne,{className:"w-3.5 h-3.5 mr-1"})," ",a("contracts.tplAddVar")]})]}),e.jsx("div",{className:"space-y-2",children:f.variables.map((t,n)=>e.jsxs("div",{className:"flex flex-wrap items-center gap-2 text-xs",children:[e.jsx(i,{className:"w-44 font-mono h-8",placeholder:a("contracts.tplVarKey"),value:t.key,onChange:e=>C(n,"key",e.target.value)}),e.jsx(i,{className:"w-56 h-8",placeholder:a("contracts.tplVarLabel"),value:t.label,onChange:e=>C(n,"label",e.target.value)}),e.jsx("select",{className:`${st}
1 h-8`,value:t.type,onChange:e=>C(n,"type",e.target.value),children:nt.map(t=>e.jsx("option",{value:t,children:t},t))}),e.jsxs("label",{className:"flex items-center gap-1 text-zinc-400 cursor-pointer",children:[e.jsx("input",{type:"checkbox",checked:!!t.required,onChange:e=>C(n,"required",e.target.checked),className:"accent-orange-500"}),a("contracts.tplVarRequired")]}),e.jsx(i,{className:"w-32 h-8",placeholder:a("contracts.tplVarDefault"),value:t.default,onChange:e=>C(n,"default",e.target.value)}),e.jsx(i,{className:"w-48 h-8 font-mono",placeholder:a("contracts.tplVarSource"),value:t.source,onChange:e=>C(n,"source",e.target.value)}),e.jsx(s,{size:"sm",variant:"ghost",className:"text-red-400 h-8",onClick:()=>S("variables",f.variables.filter((e,t)=>t!==n)),children:e.jsx(re,{className:"w-3.5 h-3.5"})})]},n))}),e.jsx("p",{className:"text-[10px] text-zinc-600 mt-1",children:a("contracts.tplVarSourceHelp")})]}),e.jsxs("div",{className:"flex gap-3",children:[e.jsxs(s,{onClick:async()=>{if(f)if(m(null),at.test(f.slug.trim())&&f.title.trim()&&f.bodyMd.trim()){y(!0);try{const e=await h.saveTemplate({slug:f.slug.trim(),title:f.title.trim(),language:f.language,bodyMd:f.bodyMd,variables:ct(f.variables)});m({type:"ok",text:a("contracts.tplSavedMsg",{slug:e.slug,version:e.version})}),b(null),g(t=>({...t,[e.slug]:void 0})),await z()}catch(e){m({type:"error",text:e.message})}finally{y(!1)}}else m({type:"error",text:a("contracts.tplNeedFields")})},disabled:j,children:[j?e.jsx(Q,{className:"w-4 h-4 mr-1 animate-spin"}):e.jsx(ie,{className:"w-4 h-4 mr-1"}),a(j?"contracts.tplSaving":"contracts.tplSave")]}),e.jsxs(s,{variant:"outline",disabled:_,onClick:()=>k({title:f.title,body_md:f.bodyMd,variables:ct(f.variables)}),children:[e.jsx(le,{className:"w-4 h-4 mr-1"})," ",a("contracts.tplPreview")]}),e.jsx(s,{variant:"ghost",onClick:()=>b(null),children:a("contracts.back")})]})]})]})}function dt({row:t,t:a,versionsOpen:n,versionRows:r,previewBusy:i,onToggleVersions:l,onEdit:c,onArchive:o,onPreview:d}){return e.jsxs(e.Fragment,{children:[e.jsxs("tr",{className:"border-b border-zinc-800/60 hover:bg-zinc-800/30",children:[e.jsx("td",{className:"p-3 font-mono text-xs",children:t.slug}),e.jsx("td",{children:t.title}),e.jsxs("td",{children:["v",t.version]}),e.jsx("td",{className:"uppercase text-xs text-zinc-400",children:t.language}),e.jsx("td",{className:"text-zinc-400 text-xs",children:it(t.created_at)}),e.jsx("td",{className:"pr-3",children:e.jsxs("div",{className:"flex items-center justify-end gap-1",children:[e.jsx(s,{size:"sm",variant:"ghost",title:a("contracts.tplPreview"),onClick:d,disabled:i,children:e.jsx(le,{className:"w-3.5 h-3.5"})}),e.jsx(s,{size:"sm",variant:"ghost",title:a("contracts.tplEdit"),onClick:c,children:e.jsx(ae,{className:"w-3.5 h-3.5"})}),e.jsxs(s,{size:"sm",variant:"ghost",title:a("contracts.tplVersions"),onClick:l,children:[e.jsx(ce,{className:"w-3.5 h-3.5"}),n?e.jsx(oe,{className:"w-3 h-3"}):e.jsx(de,{className:"w-3 h-3"})]}),e.jsx(s,{size:"sm",variant:"ghost",className:"text-red-400",title:a("contracts.tplArchive"),onClick:o,children:e.jsx(me,{className:"w-3.5 h-3.5"})})]})})]}),n&&e.jsx("tr",{className:"border-b border-zinc-800/60 bg-zinc-950/40",children:e.jsx("td",{colSpan:6,className:"p-4 text-xs",children:r?r.map(t=>e.jsxs("div",{className:"flex items-center gap-3 py-1 border-b border-zinc-800/40 last:border-0",children:[e.jsxs("span",{className:"font-mono w-10",children:["v",t.version]}),e.jsx("span",{className:"flex-1 truncate",children:t.title}),e.jsx("span",{className:t.is_active?"text-emerald-400":"text-zinc-600",children:t.is_active?a("contracts.tplActive"):a("contracts.tplInactive")}),e.jsx("span",{className:"text-zinc-500",children:it(t.created_at)})]},t.id)):e.jsx("p",{className:"text-zinc-600",children:"â¦"})})})]})}const mt=e=>e?new Date(e).toLocaleDateString("fi-FI"):"â",ut="h-9 rounded-md border border-zinc-700 bg-zinc-900 px-2 text-sm text-zinc-200 focus:outline-none focus:ring-1 focus:ring-orange-500",xt={draft:"bg-zinc-500/15 text-zinc-400 border border-zinc-500/25",sent:"bg-sky-500/15 text-sky-400 border border-sky-500/25",viewed:"bg-amber-500/15 text-amber-400 border border-amber-500/25",signed:"bg-emerald-500/15 text-emerald-400 border border-emerald-500/25",declined:"bg-red-500/15 text-red-400 border border-red-500/25",expired:"bg-orange-500/15 text-orange-400 border border-orange-500/25",voided:"bg-zinc-500/15 text-zinc-500 border border-zinc-500/25"},pt={draft:e.jsx(ae,{className:"w-3 h-3"}),sent:e.jsx(ge,{className:"w-3 h-3"}),viewed:e.jsx(le,{className:"w-3 h-3"}),signed:e.jsx(te,{className:"w-3 h-3"}),declined:e.jsx(be,{className:"w-3 h-3"}),expired:e.jsx(Z,{className:"w-3 h-3"}),voided:e.jsx(ee,{className:"w-3 h-3"})};function ht({status:t,t:s}
1){return e.jsxs("span",{className:`inline-flex items-center gap-1 px-2 py-0.5 rounded-full text-xs font-medium ${xt[t]||xt.draft}`,children:[pt[t],s(`contracts.st_${t}`)]})}const gt={remote:"bg-zinc-500/15 text-zinc-400 border border-zinc-500/25",in_person:"bg-violet-500/15 text-violet-400 border border-violet-500/25"};function ft({method:t,t:s}){const a="in_person"===t?"in_person":"remote";return e.jsxs("span",{className:`inline-flex items-center gap-1 px-2 py-0.5 rounded-full text-[10px] font-medium ${gt[a]}`,children:["in_person"===a?e.jsx(G,{className:"w-3 h-3"}):e.jsx(ge,{className:"w-3 h-3"}),s(`contracts.method_${a}`)]})}function bt(){const{t:a,language:n}=l(),[c,o]=t.useState("contracts"),[d,m]=t.useState(!1),[u,x]=t.useState([]),[p,h]=t.useState(!0),[f,b]=t.useState(null),[j,y]=t.useState(""),[v,N]=t.useState(""),[_,w]=t.useState(""),[z,k]=t.useState([]),[S,C]=t.useState(null),[T,P]=t.useState(""),[E,A]=t.useState(""),[D,M]=t.useState(""),[$,L]=t.useState(""),[B,I]=t.useState(null),[F,V]=t.useState(!1),q=t.useRef(null),[H,U]=t.useState(null),[O,K]=t.useState({}),[Y,W]=t.useState(null),X=t.useCallback(async()=>{h(!0),b(null);try{const e={search:j,status:v||void 0};_&&(e.restaurantId=Number(_)),x(await g.listContracts(e))}catch(e){b(e.message)}finally{h(!1)}},[j,v,_]);t.useEffect(()=>{X()},[X]),t.useEffect(()=>{g.listActiveRestaurants().then(k).catch(()=>k([]))},[]);const Q=async e=>{try{const t=await g.downloadUrl(e);window.open(t,"_blank","noopener")}catch(t){window.alert(t.message)}};return e.jsxs("div",{className:"p-6 max-w-7xl mx-auto text-zinc-200",children:[e.jsxs("div",{className:"flex items-center justify-between mb-6",children:[e.jsxs("div",{children:[e.jsxs("h1",{className:"text-2xl font-bold flex items-center gap-2",children:[e.jsx(ue,{className:"w-6 h-6 text-orange-500"})," ",a("contracts.title")]}),e.jsx("p",{className:"text-sm text-zinc-500 mt-1",children:a("contracts.subtitle")})]}),e.jsxs("div",{className:"flex items-center gap-2",children:[!d&&e.jsxs(s,{size:"sm",onClick:()=>{o("contracts"),m(!0)},children:[e.jsx(G,{className:"w-4 h-4 mr-1"})," ",a("contracts.inpStart")]}),e.jsxs(s,{variant:"outline",size:"sm",onClick:X,disabled:p,children:[e.jsx(xe,{className:"w-4 h-4 mr-1 "+(p?"animate-spin":"")})," ",a("contracts.refresh")]})]})]}),d?e.jsx(tt,{t:a,language:n,restaurants:z,onClose:()=>m(!1),onCompleted:X}):e.jsxs(e.Fragment,{children:[e.jsx("div",{className:"flex items-center gap-1 mb-4 border-b border-zinc-800",children:["contracts","templates"].map(t=>e.jsx("button",{type:"button",onClick:()=>o(t),className:"px-4 py-2 text-sm border-b-2 -mb-px transition-colors "+(c===t?"border-orange-500 text-orange-400":"border-transparent text-zinc-500 hover:text-zinc-300"),children:a(`contracts.tab_${t}`)},t))}),"templates"===c?e.jsx(ot,{t:a}):e.jsxs(e.Fragment,{children:[S&&e.jsx("div",{className:"mb-4 rounded-lg px-4 py-2 text-sm "+("ok"===S.type?"bg-emerald-500/10 text-emerald-400 border border-emerald-500/20":"bg-red-500/10 text-red-400 border border-red-500/20"),children:S.text}),e.jsxs("div",{className:"rounded-xl border border-zinc-800 bg-zinc-900 p-5 mb-6",children:[e.jsxs("h2",{className:"text-sm font-semibold flex items-center gap-2 mb-3",children:[e.jsx(pe,{className:"w-4 h-4 text-orange-500"})," ",a("contracts.createTitle")]}),e.jsx("p",{className:"text-xs text-zinc-500 mb-3",children:a("contracts.createHelp")}),e.jsxs("div",{className:"flex flex-wrap items-end gap-3",children:[e.jsxs("div",{className:"flex flex-col",children:[e.jsx(r,{className:"text-xs text-zinc-500",children:a("contracts.fRestaurant")}),e.jsxs("select",{className:`${ut} w-56`,value:T,onChange:e=>P(e.target.value),children:[e.jsx("option",{value:"",children:a("contracts.selectRestaurant")}),z.map(t=>e.jsx("option",{value:t.id,children:t.name},t.id))]})]}),e.jsxs("div",{children:[e.jsx(r,{className:"text-xs text-zinc-500",children:a("contracts.fTitle")}),e.jsx(i,{value:E,onChange:e=>A(e.target.value),className:"w-64"})]}),e.jsxs("div",{children:[e.jsx(r,{className:"text-xs text-zinc-500",children:a("contracts.fDescription")}),e.jsx(i,{value:D,onChange:e=>M(e.target.value),className:"w-64"})]}),e.jsxs("div",{children:[e.jsx(r,{className:"text-xs text-zinc-500",children:a("contracts.fExpiry")}),e.jsx(i,{type:"date",value:$,onChange:e=>L(e.target.value),className:"w-40"})]}),e.jsxs("div",{children:[e.jsx(r,{className:"text-xs text-zinc-500",children:a("contracts.fPdf")}),e.jsx("input",{ref:q,type:"file",accept:"application/pdf",onChange:e=>
1I(e.target.files?.[0]||null),className:"block text-sm text-zinc-400 file:mr-2 file:rounded-md file:border-0 file:bg-zinc-800 file:px-3 file:py-2 file:text-sm file:text-zinc-200"})]}),e.jsxs(s,{onClick:async()=>{if(T)if(E.trim())if(B){V(!0),C(null);try{await g.createContract({restaurantId:Number(T),title:E.trim(),description:D.trim()||null,expiresAt:$?new Date(`${$}T23:59:59`).toISOString():null,file:B}),C({type:"ok",text:a("contracts.createdMsg",{title:E.trim()})}),A(""),M(""),L(""),I(null),q.current&&(q.current.value=""),await X()}catch(e){C({type:"error",text:e.message})}finally{V(!1)}}else C({type:"error",text:a("contracts.needPdf")});else C({type:"error",text:a("contracts.needTitle")});else C({type:"error",text:a("contracts.needRestaurant")})},disabled:F,children:[e.jsx(ue,{className:"w-4 h-4 mr-1"})," ",a(F?"contracts.creating":"contracts.createBtn")]})]})]}),e.jsxs("div",{className:"flex flex-wrap items-center gap-3 mb-3",children:[e.jsxs("div",{className:"relative",children:[e.jsx(he,{className:"w-4 h-4 absolute left-2 top-1/2 -translate-y-1/2 text-zinc-500"}),e.jsx(i,{placeholder:a("contracts.search"),value:j,onChange:e=>y(e.target.value),className:"pl-8 w-64"})]}),e.jsxs("select",{className:`${ut} max-w-[220px]`,value:_,onChange:e=>w(e.target.value),children:[e.jsx("option",{value:"",children:a("contracts.allRestaurants")}),z.map(t=>e.jsx("option",{value:t.id,children:t.name},t.id))]}),e.jsxs("select",{className:ut,value:v,onChange:e=>N(e.target.value),children:[e.jsx("option",{value:"",children:a("contracts.allStatuses")}),R.map(t=>e.jsx("option",{value:t,children:a(`contracts.st_${t}`)},t))]})]}),e.jsx("div",{className:"rounded-xl border border-zinc-800 bg-zinc-900 overflow-x-auto",children:e.jsxs("table",{className:"w-full text-sm",children:[e.jsx("thead",{className:"text-xs text-zinc-500 border-b border-zinc-800",children:e.jsxs("tr",{children:[e.jsx("th",{className:"text-left p-3",children:a("contracts.colTitle")}),e.jsx("th",{className:"text-left",children:a("contracts.colRestaurant")}),e.jsx("th",{className:"text-left",children:a("contracts.colStatus")}),e.jsx("th",{className:"text-left",children:a("contracts.colSent")}),e.jsx("th",{className:"text-left",children:a("contracts.colSigned")}),e.jsx("th",{className:"text-left",children:a("contracts.colExpiry")}),e.jsx("th",{className:"text-right pr-3",children:a("contracts.colActions")})]})}),e.jsxs("tbody",{children:[p&&e.jsx("tr",{children:e.jsx("td",{colSpan:7,className:"p-6 text-center text-zinc-600",children:"â¦"})}),f&&e.jsx("tr",{children:e.jsx("td",{colSpan:7,className:"p-6 text-center text-red-400",children:f})}),!p&&!f&&0===u.length&&e.jsx("tr",{children:e.jsx("td",{colSpan:7,className:"p-6 text-center text-zinc-600",children:a("contracts.noContracts")})}),u.map(t=>{const s=O[t.id];return e.jsx(yt,{contract:t,t:a,expanded:H===t.id,detail:s,voidable:(n=t.status,["draft","sent","viewed"].includes(n)),onToggle:()=>(async e=>{if(H!==e.id){if(U(e.id),!O[e.id]){K(t=>({...t,[e.id]:{events:[],loading:!0}}));try{const t=await g.getEvents(e.id);K(s=>({...s,[e.id]:{events:t,loading:!1}}))}catch{K(t=>({...t,[e.id]:{events:[],loading:!1}}))}}}else U(null)})(t),onSend:()=>(async e=>{if(window.confirm(a("contracts.confirmSend",{title:e.title})))try{await g.sendContract(e.id),C({type:"ok",text:a("contracts.sentMsg",{title:e.title})}),await X()}catch(t){window.alert(t.message)}})(t),onVoid:()=>(async e=>{if(window.confirm(a("contracts.confirmVoid",{title:e.title})))try{await g.voidContract(e.id),C({type:"ok",text:a("contracts.voidedMsg",{title:e.title})}),await X()}catch(t){window.alert(t.message)}})(t),onDownload:Q,onResendEmail:()=>(async e=>{if(window.confirm(a("contracts.confirmResendEmail",{email:e.signer_email||""}))){W(e.id);try{await g.resendSignedEmail(e.id),C({type:"ok",text:a("contracts.emailResentMsg",{email:e.signer_email||""})});const t=await g.getEvents(e.id);K(s=>({...s,[e.id]:{events:t,loading:!1}}))}catch(t){C({type:"error",text:t.message})}finally{W(null)}}})(t),resending:Y===t.id},t.id);var n})]})]})})]})]})]})}const jt={sent:"bg-emerald-500/15 text-emerald-400 border border-emerald-500/25",failed:"bg-red-500/15 text-red-400 border border-red-500/25",pending:"bg-zinc-500/15 text-zinc-400 border border-zinc-500/25"};function yt({contract:t,t:a,expanded:n,detail:r,voidable:i,onToggle:l,onSend:c,onVoid:o,onDownload:d,onResendEmail:m,resending:u}){const x=t.signed_path?A(r?.events):null;return e.jsxs(e.Fragment,{children:[e.jsxs("tr",{className:"border-b border-zinc-800/60 hover:bg-zinc-800/30",children:[e.jsxs("td",{className:"p-3",children:[e.jsx("span",{className:"font-medium",children:t.title})," ",e.jsx(ft,{method:t.signing_method,t:a}),t.description?e.jsx("span",{className:"block text-xs text-zinc-500",children:t.description}):null]}),e.jsx("td",{children:t.restaurants?.name||t.restaurant_id}),e.jsx("td",{children:e.jsx(ht,{status:t.status,t:a})}),e.jsx("td",{className:"text-zinc-400 text-xs",children:mt(t.sent_at)}),e.jsx("td",{className:"text-zinc-400 text-xs",children:mt(t.signed_at)}),e.jsx("td",{className:"text-zinc-400 text-xs",children:mt(t.expires_at)}),e.jsx("td",{className:"pr-3",children:e.jsxs("div",{className:"flex items-center justify-end gap-1",children:["draft"===t.status&&e.jsx(s,{size:"sm",variant:"ghost",className:"text-sky-400",title:a("contracts.send"),onClick:c,children:e.jsx(ge,{className:"w-3.5 h-3.5"})}),t.original_path&&e.jsxs(s,{size:"sm",variant:"ghost",title:a("contracts.downloadOriginal"),onClick:()=>d(t.original_path),children:[e.jsx(se,{className:"w-3.5 h-3.5"})," ",e.jsx("span",{className:"text-[10px]",children:"PDF"})]}),t.signed_path&&e.jsxs(s,{size:"sm",variant:"ghost",className:"text-emerald-400",title:a("contracts.downloadSigned"),onClick:()=>d(t.signed_path),children:[e.jsx(se,{className:"w-3.5 h-3.5"})," ",e.jsx(te,{className:"w-3 h-3"})]}),i&&e.jsx(s,{size:"sm",variant:"ghost",className:"text-red-400",title:a("contracts.void"),onClick:o,children:e.jsx(ee,{className:"w-3.5 h-3.5"})}),e.jsx(s,{size:"sm",variant:"ghost",title:a("contracts.details"),onClick:l,children:n?e.jsx(oe,{className:"w-3.5 h-3.5"}):e.jsx(de,{className:"w-3.5 h-3.5"})})]})})]}),n&&e.jsx("tr",{className:"border-b border-zinc-800/60 bg-zinc-950/40",children:e.jsx("td",{colSpan:7,className:"p-4",children:e.jsxs("div",{className:"grid gap-4 md:grid-cols-2",children:[e.jsxs("div",{className:"text-xs space-y-1",children:[e.jsx("p",{className:"text-zinc-500 font-semibold uppercase tracking-wider mb-1",children:a("contracts.signerInfo")}),e.jsxs("p",{children:[e.jsxs("span",{className:"text-zinc-500",children:[a("contracts.signerName"),":"]})," ",t.signer_name||"â"]}),e.jsxs("p",{children:[e.jsxs("span",{className:"text-zinc-500",children:[a("contracts.signerEmail"),":"]})," ",t.signer_email||"â"]}),"in_person"===t.signing_method&&t.provider_signer_name?e.jsxs("p",{children:[e.jsxs("span",{className:"text-zinc-500",children:[a("contracts.providerSigner"),":"]})," ",t.provider_signer_name]}):null,e.jsxs("p",{children:[e.jsx("span",{className:"text-zinc-500",children:"IP:"})," ",t.signer_ip||"â"]}
1),e.jsxs("p",{className:"break-all",children:[e.jsx("span",{className:"text-zinc-500",children:"UA:"})," ",t.signer_user_agent||"â"]}),t.decline_reason?e.jsxs("p",{children:[e.jsxs("span",{className:"text-zinc-500",children:[a("contracts.declineReason"),":"]})," ",t.decline_reason]}):null,e.jsx("p",{className:"text-zinc-500 font-semibold uppercase tracking-wider mt-3 mb-1",children:a("contracts.hashes")}),e.jsxs("p",{className:"break-all font-mono",children:[e.jsxs("span",{className:"text-zinc-500 font-sans",children:[a("contracts.originalSha"),":"]})," ",t.original_sha256||"â"]}),e.jsxs("p",{className:"break-all font-mono",children:[e.jsxs("span",{className:"text-zinc-500 font-sans",children:[a("contracts.signedSha"),":"]})," ",t.signed_sha256||"â"]}),x&&e.jsxs(e.Fragment,{children:[e.jsx("p",{className:"text-zinc-500 font-semibold uppercase tracking-wider mt-3 mb-1",children:a("contracts.emailCopy")}),e.jsxs("div",{className:"flex items-center gap-2 flex-wrap",children:[e.jsxs("span",{className:`inline-flex items-center gap-1 px-2 py-0.5 rounded-full text-xs font-medium ${jt[x]}`,children:[e.jsx(J,{className:"w-3 h-3"})," ",a(`contracts.email_${x}`)]}),e.jsx("span",{className:"text-zinc-500",children:t.signer_email||"â"}),e.jsxs(s,{size:"sm",variant:"ghost",className:"text-sky-400 h-6",onClick:m,disabled:u||!t.signer_email,children:[e.jsx(ge,{className:"w-3 h-3 mr-1"})," ",a(u?"contracts.emailResending":"contracts.resendEmail")]})]})]})]}),e.jsxs("div",{className:"text-xs",children:[e.jsxs("p",{className:"text-zinc-500 font-semibold uppercase tracking-wider mb-1 flex items-center gap-1",children:[e.jsx(fe,{className:"w-3 h-3"})," ",a("contracts.events")]}),r?.loading&&e.jsx("p",{className:"text-zinc-600",children:"â¦"}),!r?.loading&&0===(r?.events||[]).length&&e.jsx("p",{className:"text-zinc-600",children:"â"}),(r?.events||[]).map(t=>{return e.jsxs("div",{className:"flex items-start gap-2 py-1 border-b border-zinc-800/40 last:border-0",children:[e.jsx("span",{className:"text-zinc-400 w-28 shrink-0",children:a(`contracts.ev_${t.event}`)}),e.jsx("span",{className:"text-zinc-500",children:(s=t.created_at,s?new Date(s).toLocaleString("fi-FI"):"â")}),e.jsx("span",{className:"text-zinc-500 truncate",children:t.actor_email||t.actor_type}),t.ip?e.jsx("span",{className:"text-zinc-600",children:t.ip}):null]},t.id);var s})]})]})})})]})}export{ht as ContractStatusBadge,bt as default};
Line numbers count LF bytes from the start of the resource, as the search results do. Vendor segments are library code the classifier recognised; they are stored but not indexed. Bytes are shown as Latin1 characters, one per byte.