1import{r as d,j as e,a as Wt}from"./vendor-react-qMXAD-5A.js";import{$ as Zt,t as Jt,a0 as Yt,u as B,bB as Xt,bA as es,bY as ts,w as F,v as yt,J as ss,K as ns,O as as,Q as rs,aa as I,a3 as C,ac as ie,ah as vt,S as z,x as G,y as Q,z as W,A as b,Z as is,b0 as Ve,a7 as ls,aj as Ze,B as O,ap as os,aq as ds,E as cs,aE as us,ak as ms,c1 as hs,bU as xs,bg as ps,bf as gs,bT as fs,a_ as js,aZ as ys,bj as Je,bk as Ye,bl as Xe,bm as et,bn as tt,bo as st,bp as nt,bq as at,V as vs,bV as ks,bZ as bs,q as Z,a4 as Ts}from"./index-Dp9GWWpY.js";import{a as ws,u as Cs}from"./use-live-relative-time-Ooo5lm8Q.js";import{c as rt,e as Ns}from"./activity-utils-C9AuX5Kx.js";import{u as Ds,F as Ss,a as f,b as j,c as p,d as D,e as v,t as Is,o as kt,h as it,g as $s,s as w,f as bt}from"./types-Px1COjo6.js";import{RichTextEditor as Es}from"./rich-text-editor-D8tWykTZ.js";import{D as _}from"./date-time-picker-CzNlF6tP.js";import{T as Tt}from"./time-select-C6spr0z_.js";import{U as Vs}from"./upload-BBKfaRix.js";import"./vendor-tiptap-c7Is3LQG.js";import"./vendor-recharts-Ny0Rn5XZ.js";import"./vendor-leaflet-CS_EXk35.js";import"./list-DOH_tgTS.js";import"./minus-C82ql9de.js";import"./calendar-DZg880A3.js";import"./addMonths-Bn3dRSDw.js";import"./isBefore-Zv4bxGZH.js";import"./subDays-B5LM3MjX.js";import"./popover-DozeYRFf.js";import"./scroll-area-C19Ih-Nj.js";const wt="__none__",K="info",Ue="__kontor__",Us=kt({title:w().min(1,"Tittel er påkrevd"),description:w().optional(),type:bt(["kalender","todo","superoffice"]),kind:w().min(1,"Kategori er påkrevd"),entityId:w().optional(),assignedUserId:w().min(1,"Eier er påkrevd"),startTime:w().optional(),endTime:w().optional(),deadline:w().optional(),location:w().optional(),billable:it().optional().default(!1),billingStatus:w().optional().default("nei"),reminder:w().optional().default("none"),allDay:it().optional().default(!1),recurrence:kt({pattern:bt(["daglig","ukentlig","månedlig","årlig"]),endDate:w().optional()}).optional(),participantIds:$s(w()).optional().default([]),notifySlack:it().optional().default(!1)});function Me(c,x,T,$){let S=c;const l=q=>{if(!q)return"";try{return C(new Date(q),"d. MMMM yyyy",{locale:Ts})}catch{return""}},g={kundenavn:x.name||"",kontaktperson:x.primaryContact||x.name||"",fornavn:x.firstName||(x.name?x.name.split(" ")[0]:""),leveringsadresse:x.deliveryAddress?[x.deliveryAddress,x.deliveryPostalCode,x.deliveryCity].filter(Boolean).join(", "):"(Ingen leveringsadresse registrert)",telefon:x.phone||"",epost:x.email||"",adresse:x.address||"",postnummer:x.postalCode||"",poststed:x.city||"",orgnr:x.orgNumber||"",dato:new Date().toLocaleDateString("nb-NO",{day:"numeric",month:"long",year:"numeric"}),saksnummer:"",sakstittel:"",nøkkelinfo:x.keyInfo||"",hastighetsoverride_utloper:l($?.expiresAt),hastighetsoverride_satt:l($?.setAt)};for(const[q,J]of Object.entries(g))S=S.replace(new RegExp(`\\{\\{${q}\\}\\}`,"gi"),J),S=S.replace(new RegExp(`\\{${q}\\}`,"gi"),J);return S}function Ms(c,x){if(!c.startTime)return!1;try{const T=typeof c.startTime=="string"?ie(c.startTime):new Date(c.startTime);if(bs(T,x))return!0;if(c.endTime){const $=typeof c.endTime=="string"?ie(c.endTime):new Date(c.endTime);return x>=T&&x<=$}return!1}catch{return!1}}function Ct(c){if(!c)return"";try{return C(typeof c=="string"?ie(c):c,"yyyy-MM-dd'T'HH:mm")}catch{return""}}function Fs(c){if(!c)return"";try{if(typeof c=="string")return C(ie(c),"yyyy-MM-dd");const x=c.getUTCFullYear(),T=String(c.getUTCMonth()+1).padStart(2,"0"),$=String(c.getUTCDate()).padStart(2,"0");return`${x}-${T}-${$}`}catch{return""}}function sn({open:c,onOpenChange:x,defaultEntityId:T,entityName:$,caseId:S,initialActivity:l,prefillValues:g,creationSource:q="standard",onDelete:J,onCopy:Fe}){const y=!!l,{user:Oe}=Zt(),{toast:E}=Jt(),{activeCategories:Nt,isAbsenceKind:Dt,getCategoryLabel:St}=Yt("activity_kind"),[lt,ke]=d.useState(""),[be,Ke]=d.useState(!1),[Te,le]=d.useState([]),[Le,ot]=d.useState(!1),[Y,X]=d.useState(!1),[A,ee]=d.useState(""),Pe=d.useRef(null),It=d.useRef(null),[$t,oe]=d.useState(!1),Re=d.useRef(null),[_e,L]=d.useState("idle"),[V,H]=d.useState(null),de=
1d.useRef(null),qe=d.useRef(!1),[N,te]=d.useState(!1),[Et,we]=d.useState(!1),[Vt,Ce]=d.useState(!1),[Ne,ce]=d.useState([]),[Ut,Ae]=d.useState([]),[ue,He]=d.useState(null),[Mt,Be]=d.useState(!1),me=d.useRef(null),P=d.useRef(null),U=d.useRef(null),se=d.useRef(null),[Ft,ne]=d.useState(!1),[ze,he]=d.useState(""),[Ot,xe]=d.useState(!1),[dt,De]=d.useState(null),Kt=ws(dt),Lt=d.useMemo(()=>y&&l?`activity-draft-${l.id}`:"activity-draft-new",[y,l?.id]),{saveDraft:Pt,clearDraft:pe,loadDraft:ct}=Cs(Lt),{data:ge}=B({queryKey:["/api/entities"]}),{visibleUsers:Se,kontorUser:fe}=Xt(),{data:ut}=B({queryKey:["/api/activity-templates"]}),{data:Rt}=B({queryKey:["/api/activities"]}),{data:_t}=B({queryKey:["/api/user-preferences"]}),{data:Ie}=B({queryKey:["/api/system-settings","default_case_entity_id"],queryFn:async()=>{const t=await fetch("/api/system-settings/default_case_entity_id",{credentials:"include"});if(t.status===404)return{key:"default_case_entity_id",value:""};if(!t.ok)throw new Error("Failed to fetch");return t.json()},enabled:!T});es();const je=ts(_t?.uiPreferences,q),$e=d.useRef(je);$e.current=je;const a=Ds({resolver:Is(Us),defaultValues:{title:"",description:"",type:"kalender",kind:je,entityId:T||"",assignedUserId:Oe?.id||K,startTime:"",endTime:"",deadline:"",location:"",billable:!1,billingStatus:"nei",reminder:"none",allDay:!1,recurrence:void 0,participantIds:[]}}),ae=a.watch("entityId"),ye=a.watch("location"),{data:Ee}=B({queryKey:["/api/entities",ae,"uisp-override-info"],queryFn:async()=>{if(!ae)return{expiresAt:null,setAt:null};const t=await fetch(`/api/entities/${ae}/uisp-override-info`,{credentials:"include"});return t.ok?t.json():{expiresAt:null,setAt:null}},enabled:!!ae,staleTime:300*1e3}),{data:mt}=B({queryKey:["/api/delivery-addresses",{entityId:ae}],enabled:!!ae});function qt(t){const s=t.trim(),n=s.match(/^(-?\d{1,3}(?:\.\d+)?)\s*,\s*(-?\d{1,3}(?:\.\d+)?)$/);if(n){const r=parseFloat(n[1]),i=parseFloat(n[2]);if(r>=-90&&r<=90&&i>=-180&&i<=180)return{lat:r,lng:i}}try{const r=new URL(s),i=r.searchParams.get("q");if(i){const u=i.match(/^(-?\d+\.?\d*),(-?\d+\.?\d*)$/);if(u){const m=parseFloat(u[1]),k=parseFloat(u[2]);if(m>=-90&&m<=90&&k>=-180&&k<=180)return{lat:m,lng:k}}}const o=r.pathname.match(/@(-?\d+\.?\d*),(-?\d+\.?\d*)/);if(o){const u=parseFloat(o[1]),m=parseFloat(o[2]);if(u>=-90&&u<=90&&m>=-180&&m<=180)return{lat:u,lng:m}}}catch{}return null}d.useEffect(()=>{if(de.current&&clearTimeout(de.current),qe.current){qe.current=!1;return}if(!ye||!ye.trim()){L("idle"),H(null);return}const t=qt(ye);if(t){H({lat:t.lat,lng:t.lng}),L("found");return}return L("loading"),de.current=setTimeout(async()=>{try{const s=await fetch("/api/lookup/geocode",{method:"POST",credentials:"include",headers:{"Content-Type":"application/json"},body:JSON.stringify({address:ye})});if(!s.ok)throw new Error("Request failed");const n=await s.json();n.lat&&n.lng?(H({lat:n.lat,lng:n.lng}),L("found")):(H(null),L("not_found"))}catch{H(null),L("not_found")}},800),()=>{de.current&&clearTimeout(de.current)}},[ye]),d.useEffect(()=>{c||(L("idle"),H(null))},[c]),d.useEffect(()=>{if(c){if(xe(!1),y&&l){const t=l.description||"",s=ct(),n=s?.text&&s.text!==t?s.text:t;a.reset({title:l.title||"",description:n,type:l.type||"kalender",kind:l.kind||$e.current,entityId:l.entityId||"",assignedUserId:fe&&l.assignedUserId===fe.id?Ue:l.assignedUserId||K,startTime:Ct(l.startTime),endTime:Ct(l.endTime),deadline:Fs(l.deadline),location:l.location||"",billable:l.billable||!1,billingStatus:l.billingStatus||"nei",reminder:l.reminder||"none",allDay:l.allDay||!1,recurrence:l.recurrence||void 0,participantIds:l.participants?.map(r=>r.userId)||l.participantIds||[]}),te(l.status==="fullført"),s?.text&&s.text!==t&&(xe(!0),De(s.savedAt||null))}else{te(!1);const t=g?.description??"",s=ct(),n=s?.text&&s.text!==t?s.text:t;a.reset({title:g?.title??"",description:n,type:g?.type??"kalender",kind:g?.kind??$e.current,entityId:g?.entityId??T??Ie?.value??"",assignedUserId:g?.assignedUserId??Oe?.id??K,startTime:g?.startTime??"",endTime:g?.endTime??"",deadline:g?.deadline??"",location:g?.location??"",billable:g?.billable??!1,billingStatus:g?.billingStatus??"nei",reminder:g?.reminder??"none",allDay:g?.allDay??!1,recurrence:g?.recurrence??void 0,participantIds:g?.participantIds??[]}),s?.text&&s.text!==t&&(xe(!0),De(s.savedAt||null))}ke(""),Ke(!1),le([]),X(!1),ee(""),oe(!1),Ce(!1)}},[c,T,y,l,fe]),d.useEffect(()=>{c&&!y&&!g?.kind&&!a.formState.dirtyFields.kind&&a.setValue("kind",je)},[je,c,y,g?.kind,a]),d.useEffect(()=>{c&&!y&&Ie?.value&&!g?.entityId&&!T&&(a.getValues("entityId")||a.setValue("entity
1Id",Ie.value))},[c,y,Ie?.value,T,g?.entityId]),d.useEffect(()=>{const t=s=>{Pe.current&&!Pe.current.contains(s.target)&&X(!1),Re.current&&!Re.current.contains(s.target)&&oe(!1)};return document.addEventListener("mousedown",t),()=>document.removeEventListener("mousedown",t)},[]),d.useEffect(()=>{y&&l?.id&&c?F("GET",`/api/activities/${l.id}/attachments`).then(t=>t.json()).then(t=>ce(Array.isArray(t)?t:[])).catch(()=>ce([])):c||(ce([]),Ae([]))},[y,l?.id,c]);const At=async t=>{if(!t||!l?.id)return;const s=Array.from(t);Ae(n=>[...n,...s]);for(const n of s)try{const r=await F("POST","/api/uploads/request-url",{name:n.name,size:n.size,contentType:n.type});if(!r.ok)throw new Error("Kunne ikke hente opplastingslenke");const{uploadURL:i,objectPath:o}=await r.json();if(!(await fetch(i,{method:"PUT",headers:{"Content-Type":n.type},body:n})).ok)throw new Error("Opplasting til lagring feilet");await F("POST",`/api/activities/${l.id}/attachments`,{fileName:n.name,originalName:n.name,mimeType:n.type,size:n.size,objectPath:o});const k=await(await F("GET",`/api/activities/${l.id}/attachments`)).json();ce(Array.isArray(k)?k:[])}catch(r){E({title:"Feil",description:r?.message||`Kunne ikke laste opp ${n.name}`,variant:"destructive"})}Ae([])},ht=async t=>{try{await F("DELETE",`/api/attachments/${t}`),ce(s=>s.filter(n=>n.id!==t))}catch{E({title:"Feil",description:"Kunne ikke slette vedlegget",variant:"destructive"})}},Ge=yt({mutationFn:async t=>{const{sendInvitationEmail:s,sendInvitationSms:n,notifySlack:r,...i}=t;return F("POST","/api/activities",{...i,description:i.description?i.description.replace(/\/objects\/uploads\//g,"/api/i/").replace(/\/api\/media\/uploads\//g,"/api/i/"):null,entityId:i.entityId||null,assignedUserId:i.assignedUserId===K?null:i.assignedUserId===Ue?fe?.id??null:i.assignedUserId||null,startTime:i.type==="todo"?null:i.startTime?new Date(i.startTime).toISOString():null,endTime:i.type==="todo"?null:i.endTime?new Date(i.endTime).toISOString():null,deadline:i.type==="todo"&&i.deadline?new Date(i.deadline.slice(0,10)+"T00:00:00").toISOString():i.deadline?new Date(i.deadline).toISOString():null,location:i.location||null,locationGps:V?`${V.lat},${V.lng}`:null,kind:i.kind,billable:i.billable||!1,billingStatus:i.billingStatus||"nei",reminder:i.reminder||"none",recurrence:i.recurrence||null,participantIds:i.participantIds||[],sendInvitationEmail:!!s,sendInvitationSms:!!n,status:N?"fullført":"planlagt",...S?{caseId:S}:{}})},onSuccess:async(t,s)=>{if(pe(),Z.invalidateQueries({queryKey:["/api/activities"]}),Z.invalidateQueries({queryKey:["/api/stats"]}),T&&Z.invalidateQueries({queryKey:["/api/entities",T]}),S&&Z.invalidateQueries({queryKey:["/api/cases",S]}),pt(),E({title:"Aktivitet opprettet",description:"Den nye aktiviteten ble opprettet"}),s.notifySlack&&s.assignedUserId){const n=m=>m instanceof Date?m:m?new Date(m):null,r=n(s.startTime),i=n(s.deadline),o=r?C(r,"d. MMM yyyy HH:mm"):i?C(i,"d. MMM yyyy"):"",u=`*${s.title}*${o?` 2Tid: ${o}`:""}${s.location?` 3Sted: ${s.location}`:""}`;F("POST","/api/slack/notify-user",{userId:s.assignedUserId,message:u}).catch(()=>{})}},onError:()=>{E({title:"Feil",description:"Kunne ikke opprette aktiviteten. Prøv igjen.",variant:"destructive"})}}),Qe=yt({mutationFn:async t=>{if(!l?.id)throw new Error("initialActivity.id mangler â kan ikke lagre");const{sendInvitationEmail:s,sendInvitationSms:n,...r}=t;let i,o,u;try{i=r.type==="todo"?null:r.startTime?new Date(r.startTime).toISOString():null}catch(h){throw new Error(`Ugyldig startdato: "${r.startTime}" (${h instanceof Error?h.message:h})`)}try{o=r.type==="todo"?null:r.endTime?new Date(r.endTime).toISOString():null}catch(h){throw new Error(`Ugyldig sluttdato: "${r.endTime}" (${h instanceof Error?h.message:h})`)}try{u=r.type==="todo"&&r.deadline?new Date(r.deadline.slice(0,10)+"T00:00:00").toISOString():r.deadline?new Date(r.deadline).toISOString():null}catch(h){throw new Error(`Ugyldig frist: "${r.deadline}" (${h instanceof Error?h.message:h})`)}const m={...r,description:r.description?r.description.replace(/\/objects\/uploads\//g,"/api/i/").replace(/\/api\/media\/uploads\//g,"/api/i/"):null,entityId:r.entityId||null,assignedUserId:r.assignedUserId===K?null:r.assignedUserId===Ue?fe?.id??null:r.assignedUserId||null,startTime:i,endTime:o,deadline:u,location:r.location||null,locationGps:V?`${V.lat},${V.lng}`:r.location&&r.location===l?.location?l?.locationGps??null:null,kind:r.kind,billable:r.billable||!1,billingStatus:r.billingStatus||"nei",reminder:r.reminder||"none",recurrence:r.recurrence||null,participantIds:r.participantIds||[],status:N?"fullført":"planlagt"};return console.log("[editMutation] PATCH body for",l.id,m),(await F("PATCH",`/api/activities/${l.id}`,m)).json()},onSuccess:async t=>{pe(),Z.setQueriesData({queryKey:["/api/activities"]},s=>s&&(Array.isArray(s)?s.map(n=>n.id===t.id?{...n,...t}:n):s.id===t.id?{...s,...t}:s)),Z.invalidateQueries({queryKey:["/api/stats"]}),l?.entityId&&Z.invalidateQueries({queryKey:["/api/entities",l.entityId]}),ve(),E({title:"Aktivitet lagret",description:"Endringene ble lagret"})},onError:t=>{const s=t instanceof Error?`: ${t.message}`:"";console.error("[editMutation] feil:",t),E({title:"Feil",description:`Kunne ikke lagre aktiviteten${s}`,variant:"destructive"})}}),Ht=t=>{if(!y||!l)return;P.current&&clearTimeout(P.current),U.current&&U.current.abort();const s=new AbortController;U.current=s,se.current=t,P.current=setTimeout(async()=>{try{const n=t.replace(/\/objects\/uploads\//g,"/api/i/").replace(/\/api\/media\/uploads\//g,"/api/i/");if(!(await F("PATCH",`/api/activities/${l.id}`,{description:n},{signal:s.signal})).ok)return;se.current=null,a.resetField("description",{defaultValue:t}),me.current&&clearTimeout(me.current),Be(!0),me.current=setTimeout(()=>Be(!1),2e3)}catch(n){if(n instanceof DOMException&&n.name==="AbortError")return;se.current=null}},400)},xt=()=>{if(!P.current)return null;clearTimeout(P.current),P.current=null,U.current&&(U.current.abort(),U.current=null);const t=se.current;return t!==null&&(a.setValue("description",t,{shouldDirty:!0}),se.current=null),t},ve=()=>
3{pe(),x(!1),a.reset({title:"",description:"",type:"kalender",kind:$e.current,entityId:T||"",assignedUserId:Oe?.id||K,startTime:"",endTime:"",deadline:"",location:"",billable:!1,billingStatus:"nei",reminder:"none",allDay:!1,recurrence:void 0,participantIds:[]}),te(!1),xe(!1),De(null),ke(""),Ke(!1),le([]),ot(!1),we(!1),Ce(!1),Be(!1),me.current&&clearTimeout(me.current),P.current&&clearTimeout(P.current),U.current&&(U.current.abort(),U.current=null),se.current=null,ne(!1),he("")},Bt=()=>{Fe&&(Fe(a.getValues()),ve())},zt=()=>{J&&(ve(),J())},pt=()=>{if(y){xt();const t=N!==(l?.status==="fullført");if(a.formState.isDirty||t){we(!0);return}}ve()},gt=t=>{const s=xt();if(t.type==="kalender"&&!t.startTime){E({title:"Dato mangler",description:"Kalenderaktiviteter må ha en startdato",variant:"destructive"});return}if(t.type==="todo"&&!t.deadline){E({title:"Frist mangler",description:"Oppgaver må ha en frist (deadline)",variant:"destructive"});return}if(t.startTime&&t.endTime&&t.endTime<t.startTime){E({title:"Ugyldig tidspunkt",description:"Slutt-tid kan ikke være før start-tid",variant:"destructive"});return}y?Qe.mutate({...t,...s!==null?{description:s}:{}}):Ge.mutate({...t,sendInvitationEmail:be&&Te.includes("email"),sendInvitationSms:be&&Te.includes("sms")})},R=a.watch("startTime"),ft=a.watch("endTime"),Gt=a.watch("kind"),Qt=R&&ft&&ft<R,M=!a.watch("assignedUserId")||a.watch("assignedUserId")===K||a.watch("assignedUserId")==="",jt=ut?.filter(t=>(Array.isArray(t.kinds)&&t.kinds.length>0?t.kinds:[t.kind]).includes(Gt))||[];return e.jsxs(e.Fragment,{children:[e.jsxs(ss,{open:c,onOpenChange:t=>{t?x(t):pt()},children:[e.jsxs(ns,{className:"sm:max-w-2xl max-h-[90vh] flex flex-col p-4 gap-0",style:N?{backgroundColor:"#C1E5D4"}:void 0,onInteractOutside:t=>{ue&&t.preventDefault()},children:[e.jsx(as,{className:"pb-2",children:e.jsxs("div",{className:"flex items-center gap-2 pr-8 min-w-0",children:[e.jsx(rs,{className:"flex-1 min-w-0 truncate",children:y?"Rediger aktivitet":$?`Ny aktivitet for ${$}`:"Ny aktivitet"}),y&&!M&&e.jsxs(e.Fragment,{children:[e.jsxs("label",{className:"flex items-center gap-1.5 cursor-pointer select-none shrink-0","data-testid":"header-billing-skal-faktureres",children:[e.jsx(I,{checked:a.watch("billingStatus")==="skal_faktureres",onCheckedChange:t=>a.setValue("billingStatus",t?"skal_faktureres":"nei",{shouldDirty:!0}),"data-testid":"checkbox-header-billing-skal",className:"bg-background"}),e.jsx("span",{className:"text-sm text-muted-foreground whitespace-nowrap",children:"Skal faktureres"})]}),e.jsxs("label",{className:"flex items-center gap-1.5 cursor-pointer select-none shrink-0","data-testid":"header-billing-fakturert",children:[e.jsx(I,{checked:a.watch("billingStatus")==="fakturert",onCheckedChange:t=>a.setValue("billingStatus",t?"fakturert":"nei",{shouldDirty:!0}),"data-testid":"checkbox-header-billing-fakturert",className:"bg-background"}),e.jsx("span",{className:"text-sm text-muted-foreground whitespace-nowrap",children:"Fakturert"})]})]}),y&&l?.createdByUser?.name&&(()=>{const t=l.createdByUser.name,s=t.trim().split(/\s+/);let n;s[0].includes("-")?n=s[0].split("-").map(o=>o[0]).join("").slice(0,2).toUpperCase():n=s.map(o=>o[0]).join("").slice(0,2).toUpperCase();const r=l.createdAt,i=r?(()=>{try{const o=r;return C(typeof o=="string"?ie(o):new Date(o),"d. MMM yyyy HH:mm")}catch{return""}})():"";return e.jsx("div",{className:"h-7 w-7 rounded-full bg-muted text-muted-foreground flex items-center justify-center text-xs font-semibold shrink-0 cursor-default",title:`Opprettet av ${t}${i?` · ${i}`:""}`,"data-testid":"creator-initials",children:n})})()]})}),e.jsx(Ss,{...a,children:e.jsxs("form",{onSubmit:a.handleSubmit(gt),className:"space-y-1.5 overflow-y-auto flex-1 px-1",children:[e.jsx(f,{control:a.control,name:"title",render:({field:t})=>e.jsxs(j,{children:[e.jsx(p,{className:"text-xs",children:"Tittel"}),e.jsx(D,{children:e.jsx(vt,{className:"h-8 text-sm",placeholder:"Beskriv aktiviteten...",...t,"data-testid":"input-activity-title"})}),e.jsx(v,{})]})}),e.jsxs("div",{className:"grid grid-cols-1 sm:grid-cols-2 gap-2",children:[!M&&e.jsx(f,{control:a.control,name:"type",render:({field:t})=>e.jsxs(j,{children:[e.jsx(p,{className:"text-xs",children:"Type"}),e.jsxs(z,{onValueChange:t.onChange,value:t.value,children:[e.jsx(D,{children:e.jsx(G,{className:"h-8 text-sm","data-testid":"select-activity-type",children:e.jsx(Q,{placeholder:"Velg type"})})}),e.jsxs(W,{children:[e.jsx(b,{value:"kalender",children:"Kalender"}),e.jsx(b,{value:"todo",children:"Oppgave"})]})]}),e.jsx(v,{})]})}),!M&&e.jsx(f,{control:a.control,name:"kind",render:({field:t})=>e.jsxs(j,{children:[e.jsx(p,{className:"text-xs",children:"Kategori"}),e.jsxs(z,{onValueChange:s=>
3{t.onChange(s),ke("")},value:t.value,children:[e.jsx(D,{children:e.jsx(G,{className:"h-8 text-sm","data-testid":"select-activity-kind",children:e.jsx(Q,{placeholder:"Velg kategori"})})}),e.jsx(W,{children:Nt.filter(s=>!s.isSystem).map(s=>e.jsx(b,{value:s.value,children:s.label},s.value))})]}),e.jsx(v,{})]})}),e.jsx(f,{control:a.control,name:"assignedUserId",render:({field:t})=>e.jsxs(j,{children:[e.jsx("div",{className:"flex items-center gap-2",children:e.jsx(p,{className:"text-xs",children:"Eier"})}),e.jsxs(z,{onValueChange:s=>t.onChange(s),value:t.value||K,children:[e.jsx(D,{children:e.jsx(G,{className:"h-8 text-sm","data-testid":"select-activity-user",children:e.jsx(Q,{placeholder:"Velg bruker"})})}),e.jsxs(W,{children:[Se?.map(s=>e.jsx(b,{value:s.id,children:s.name},s.id)),e.jsx(b,{value:Ue,children:"Kontor"}),e.jsx(b,{value:K,children:"Info (ingen eier)"})]})]}),e.jsx(v,{})]})}),!M&&e.jsx(f,{control:a.control,name:"entityId",render:({field:t})=>{const s=ge?.find(i=>i.id===t.value),n=A.length>=2?(ge?.filter(i=>i.name.toLowerCase().includes(A.toLowerCase()))||[]).slice(0,50):[],r=i=>{const o=i===wt?"":i;t.onChange(o);const u=ge?.find(m=>m.id===o);if(u&<){const m=a.getValues("title"),k=a.getValues("description");m&&a.setValue("title",Me(m,u,void 0,Ee),{shouldValidate:!0,shouldDirty:!0}),k&&a.setValue("description",Me(k,u,void 0,Ee),{shouldValidate:!0,shouldDirty:!0})}X(!1),ee("")};return e.jsxs(j,{children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(p,{className:"text-xs",children:"Kunde/Linkpunkt"}),t.value&&e.jsx("button",{type:"button",className:"text-muted-foreground hover:text-foreground",onClick:()=>window.open(`/kunder/${t.value}`,"_blank"),"data-testid":"button-open-entity-tab",children:e.jsx(is,{className:"h-3 w-3"})})]}),e.jsxs("div",{className:"relative",ref:Pe,children:[e.jsx(D,{children:e.jsxs("div",{className:"relative",children:[e.jsx("input",{ref:It,className:"flex h-8 w-full rounded-md border border-input bg-background px-3 py-1.5 text-sm ring-offset-background placeholder:text-muted-foreground focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring focus-visible:ring-offset-2",placeholder:"Søk etter kunde/linkpunkt...",value:Y?A:s?.name||"",onMouseDown:()=>{Y||(ee(""),X(!0))},onChange:i=>{ee(i.target.value),Y||X(!0)},onFocus:()=>{Y||(ee(""),X(!0))},"data-testid":"input-activity-entity-search",autoComplete:"off"}),t.value&&!Y&&e.jsx("button",{type:"button",className:"absolute right-2 top-1/2 -translate-y-1/2 text-muted-foreground hover:text-foreground",onClick:()=>{t.onChange(""),ee("")},"data-testid":"clear-activity-entity",children:e.jsx(Ve,{className:"h-4 w-4"})})]})}),Y&&e.jsxs("div",{className:"absolute z-50 w-full mt-1 bg-popover border rounded-md shadow-md max-h-[200px] overflow-y-auto",children:[e.jsx("button",{type:"button",className:"w-full text-left px-3 py-2 text-sm hover:bg-accent cursor-pointer text-muted-foreground",onClick:()=>r(wt),"data-testid":"option-activity-entity-none",children:"Ingen kunde"}),A.length>=2&&n.length>0&&e.jsxs(e.Fragment,{children:[e.jsxs("div",{className:"px-3 py-1 text-xs text-muted-foreground border-t",children:[n.length," treff"]}),n.map(i=>e.jsxs("button",{type:"button",className:`w-full text-left px-3 py-2 text-sm hover:bg-accent cursor-pointer flex items-center gap-2 ${t.value===i.id?"bg-accent":""}`,onClick:()=>r(i.id),"data-testid":`option-activity-entity-${i.id}`,children:[e.jsx(ls,{className:`h-3 w-3 ${t.value===i.id?"opacity-100":"opacity-0"}`}),i.name,i.type==="linkpunkt"&&e.jsx("span",{className:"text-xs text-muted-foreground ml-1",children:"(Linkpunkt)"})]},i.id))]}),A.length>=2&&n.length===0&&e.jsx("div",{className:"px-3 py-3 text-sm text-center text-muted-foreground border-t",children:"Ingen kunder/linkpunkts funnet"}),A.length>0&&A.length<2&&e.jsx("div",{className:"px-3 py-3 text-sm text-center text-muted-foreground border-t",children:"Skriv minst 2 tegn for å søke"})]})]}),e.jsx(v,{})]})}})]}),!M&&jt.length>0&&e.jsxs("div",{children:[e.jsx(p,{children:"Mal"}),e.jsxs(z,{value:lt,onValueChange:t=>{ke(t);const s=ut?.find(n=>n.id===t);if(s){let n=s.name,r=s.defaultDescription||"";const i=a.getValues("entityId"),o=i?ge?.find(u=>u.id===i):null;if(o&&(n=Me(n,o,void 0,Ee),r=Me(r,o,void 0,Ee)),a.setValue("title",n,{shouldValidate:!0,shouldDirty:!0}),a.setValue("billable",s.billableDefault||!1,{shouldValidate:!0,shouldDirty:!0}),a.setValue("billingStatus",s.billableDefault?"skal_faktureres":"nei",{shouldValidate:!0,shouldDirty:!0}),r&&a.setValue("description",r,{shouldValidate:!0,shouldDirty:!0}),s.defaultDuration){let u=a.getValues("startTime");if(!u){const h=new Date;h.setMinutes(Math.ceil(h.getMinutes()/15)*15,0,0),u=C(h,"yyyy-MM-dd'T'HH:mm"),a.setValue("startTime",u,{shouldValidate:!0,shouldDirty:!0})}const m=new Date(u),k=new Date(m.getTime()+s.defaultDuration*6e4);a.setValue("endTime",C(k,"yyyy-MM-dd'T'HH:mm"),{shouldValidate:!0,shouldDirty:!0})}}},children:[e.jsx(G,{className:"h-9","data-testid":"select-activity-template",children:e.jsx(Q,{placeholder:"Velg mal (valgfritt)..."})}),e.jsx(W,{children:jt.map(t=>e.jsx(b,{value:t.id,children:t.name},t.id))})]})]}),M?e.jsxs("div",{className:"grid grid-cols-2 gap-2",children:[e.jsx(f,{control:a.control,name:"startTime",render:({field:t})=>e.jsxs(j,{children:[e.jsx(p,{children:"Fra dato"}
3),e.jsx(_,{value:t.value?t.value.split("T")[0]:"",onChange:s=>{const n=s?s.split("T")[0]:"";if(t.onChange(n?`${n}T00:00`:""),n){const r=a.getValues("endTime");if(!r)a.setValue("endTime",`${n}T23:59`);else if(r.split("T")[0]<n){const o=r.split("T")[1]||"23:59";a.setValue("endTime",`${n}T${o}`)}}},showTime:!1,"data-testid":"input-activity-info-start-date"}),e.jsx(v,{})]})}),e.jsx(f,{control:a.control,name:"endTime",render:({field:t})=>e.jsxs(j,{children:[e.jsx(p,{children:"Til dato"}),e.jsx(_,{value:t.value?t.value.split("T")[0]:"",onChange:s=>{const n=s?s.split("T")[0]:"";t.onChange(n?`${n}T23:59`:"")},showTime:!1,"data-testid":"input-activity-info-end-date"}),e.jsx(v,{})]})})]}):a.watch("type")==="todo"?e.jsx(f,{control:a.control,name:"deadline",render:({field:t})=>e.jsxs(j,{children:[e.jsx(p,{children:"Frist"}),e.jsx(_,{value:t.value||"",onChange:t.onChange,showTime:!1,placeholder:"Velg frist...","data-testid":"input-activity-deadline"}),e.jsx(v,{})]})}):a.watch("allDay")?e.jsxs("div",{className:"grid grid-cols-2 gap-2",children:[e.jsx(f,{control:a.control,name:"startTime",render:({field:t})=>e.jsxs(j,{children:[e.jsx(p,{children:"Fra dato"}),e.jsx(_,{value:t.value?t.value.split("T")[0]:"",onChange:s=>{const n=s?s.split("T")[0]:"";if(t.onChange(n?`${n}T00:00`:""),n){const r=a.getValues("endTime");if(!r)a.setValue("endTime",`${n}T23:59`);else if(r.split("T")[0]<n){const o=r.split("T")[1]||"23:59";a.setValue("endTime",`${n}T${o}`)}}},showTime:!1,"data-testid":"input-activity-start-date"}),e.jsx(v,{})]})}),e.jsx(f,{control:a.control,name:"endTime",render:({field:t})=>e.jsxs(j,{children:[e.jsx(p,{children:"Til dato"}),e.jsx(_,{value:t.value?t.value.split("T")[0]:"",onChange:s=>{const n=s?s.split("T")[0]:"";t.onChange(n?`${n}T23:59`:"")},showTime:!1,"data-testid":"input-activity-end-date"}),e.jsx(v,{})]})})]}):e.jsxs("div",{className:"grid grid-cols-3 gap-2",children:[e.jsx(f,{control:a.control,name:"startTime",render:({field:t})=>e.jsxs(j,{children:[e.jsx(p,{className:"text-xs",children:"Dato"}),e.jsx(_,{value:t.value?t.value.split("T")[0]:"",onChange:s=>{const n=s?s.split("T")[0]:"",r=t.value?t.value.split("T")[1]:"08:00",i=n?`${n}T${r||"08:00"}`:"";if(t.onChange(i),i){const o=a.getValues("endTime");if(o){const u=o.split("T")[1]||"09:00",m=`${n}T${u}`;if(m<i){const k=new Date(new Date(i).getTime()+36e5);a.setValue("endTime",C(k,"yyyy-MM-dd'T'HH:mm"))}else a.setValue("endTime",m)}else{const u=new Date(new Date(i).getTime()+36e5);a.setValue("endTime",C(u,"yyyy-MM-dd'T'HH:mm"))}}},showTime:!1,"data-testid":"input-activity-start-date"}),e.jsx(v,{})]})}),e.jsx(f,{control:a.control,name:"startTime",render:({field:t})=>{const s=t.value&&t.value.split("T")[1]||"";return e.jsxs(j,{children:[e.jsx(p,{className:"text-xs",children:"Start"}),e.jsx(D,{children:e.jsx(Tt,{value:s,onChange:n=>{if(!n)return;const i=`${t.value?t.value.split("T")[0]:C(new Date,"yyyy-MM-dd")}T${n}`;t.onChange(i);const o=a.getValues("endTime");if(!o||o<=i){const u=new Date(new Date(i).getTime()+36e5);a.setValue("endTime",C(u,"yyyy-MM-dd'T'HH:mm"))}},"data-testid":"input-activity-start-time"})}),e.jsx(v,{})]})}}),e.jsx(f,{control:a.control,name:"endTime",render:({field:t})=>{const s=t.value&&t.value.split("T")[1]||"";return e.jsxs(j,{children:[e.jsx(p,{className:"text-xs",children:"Slutt"}),e.jsx(D,{children:e.jsx(Tt,{value:s,onChange:n=>{if(!n)return;const i=`${R?R.split("T")[0]:t.value?t.value.split("T")[0]:C(new Date,"yyyy-MM-dd")}T${n}`;R&&i<R||t.onChange(i)},"data-testid":"input-activity-end"})}),e.jsx(v,{})]})}})]}),Qt&&e.jsxs("p",{className:"text-xs text-destructive flex items-center gap-1",children:[e.jsx(Ze,{className:"h-3 w-3"}),"Slutt-tid kan ikke være før start-tid"]}),(()=>{const t=a.watch("assignedUserId"),s=a.watch("startTime");if(!t||!s)return null;try{const n=ie(s),r=Rt?.filter(m=>{if(m.assignedUserId!==t)return!1;const k=m.kind;return Dt(k)?Ms(m,n):!1})||[];if(r.length===0)return null;const i=r[0].kind,o=St(i),u=Se?.find(m=>m.id===t)?.name||"Brukeren";return e.jsxs("div",{className:"flex items-center gap-2 text-amber-600 dark:text-amber-400 bg-amber-50 dark:bg-amber-950/30 p-2 rounded text-xs","data-testid":"absence-conflict-warning",children:[e.jsx(Ze,{className:"h-4 w-4 flex-shrink-0"}),e.jsxs("span",{children:[u," har ",o.toLowerCase()," denne dagen"]})]})}catch{return null}})(),!M&&!y&&e.jsx(f,{control:a.control,name:"billingStatus",render:({field:t})=>e.jsxs(j,{children:[e.jsxs("div",{className:"flex items-center gap-4",children:[e.jsx(p,{className:"text-sm whitespace-nowrap mb-0",children:"Fakturering"}),e.jsxs("label",{className:"flex items-center gap-1.5 cursor-pointer select-none","data-testid":"label-billing-skal-faktureres",children:[e.jsx(I,{checked:t.value==="skal_faktureres",onCheckedChange:s=>t.onChange(s?"skal_faktureres":"nei"),"data-testid":"checkbox-billing-skal-faktureres"}),e.jsx("span",{className:"text-sm",children:"Skal faktureres"})]}),e.jsxs("label",{className:"flex items-center gap-1.5 cursor-pointer select-none","data-testid":"label-billing-fakturert",children:[e.jsx(I,{checked:t.value==="fakturert",onCheckedChange:s=>t.onChange(s?"fakturert":"nei"),"data-testid":"checkbox-billing-fakturert"}),e.jsx("span",{className:"text-sm",children:"Fakturert"})]})]}),e.jsx(v,{})]})}),!M&&e.jsx(O,{type:"button",variant:"ghost",size:"sm",onClick:()=>ot(!Le),className:"w-full text-muted-foreground","data-testid":"button-activity-show-advanced",children:Le?e.jsxs(e.Fragment,{children:[e.jsx(os,{className:"h-4 w-4 mr-1"}),"Vis mindre"]}):e.jsxs(e.Fragment,{children:[e.jsx(ds,{className:"h-4 w-4 mr-1"}),"Vis mer"]})}),Le&&!M&&e.jsxs("div",{className:"space-y-3 border-t pt-3",children:[a.watch("type")==="kalender"&&e.jsx(f,{control:a.control,name:"allDay",render:({field:t})=>e.jsxs(j,{className:"flex items-center gap-2 space-y-0",children:[e.jsx(D,{children:e.jsx(I,{checked:t.value,onCheckedChange:s=>{if(t.onChange(s),s){const n=a.getValues("startTime"),r=n?n.split("T")[0]:"";r&&(a.setValue("startTime",`${r}T00:00`,{shouldDirty:!0}),a.setValue("endTime",`${r}T23:59`,{shouldDirty:!0}))}},"data-testid":"checkbox-activity-allday"})}),e.jsx(p,{className:"text-sm font-normal cursor-pointer",children:"Hele dagen"})]})}),a.watch("type")==="kalender"&&!a.watch("allDay")&&e.jsx("div",{children:e.jsx(f,{control:a.control,name:"endTime",render:({field:t})=>e.jsxs(j,{children:[e.jsx(p,{children:"Sluttdato (annen dag)"}),e.jsx(_,{value:t.value||"",onChange:s=>{s&&R&&s<R||t.onChange(s)},"data-testid":"input-activity-end-different-day"}),e.jsx("p",{className:"text-xs text-muted-foreground mt-1",children:"Bruk dette feltet for å sette en sluttdato på en annen dag enn startdatoen"}),e.jsx(v,{})]})})}),e.jsxs("div",{className:"grid grid-cols-1 sm:grid-cols-2 gap-2",children:[e.jsx(f,{control:a.control,name:"location",render:({field:t})=>{const s=a.getValues("entityId"),n=ge?.find(h=>h.id===s),r=n?[n.deliveryAddress,n.deliveryPostalCode,n.deliveryCity].filter(
3Boolean).join(", "):"",i=n?[n.address,n.postalCode,n.city].filter(Boolean).join(", "):"",o=[];if(r&&o.push({label:"",address:r}),mt)for(const h of mt){const re=[h.address,h.postalCode,h.city].filter(Boolean).join(", ");re&&!o.some(We=>We.address===re)&&o.push({label:h.label||"",address:re})}const u=o.length>0,m=i.length>0,k=$t&&s&&(u||m);return e.jsxs(j,{className:"sm:col-span-2",children:[e.jsx(p,{children:"Sted"}),e.jsxs("div",{className:"relative",ref:Re,children:[e.jsx(D,{children:e.jsx(vt,{placeholder:"Adresse / lokasjon...",...t,onFocus:()=>oe(!0),onBlur:()=>{t.onBlur()},"data-testid":"input-activity-location"})}),k&&e.jsx("div",{className:"absolute z-50 w-full mt-1 bg-popover border rounded-md shadow-md max-h-[200px] overflow-y-auto",children:u?o.map((h,re)=>e.jsxs("button",{type:"button",className:"w-full text-left px-3 py-2 text-sm hover:bg-accent cursor-pointer border-b last:border-b-0",onMouseDown:We=>{We.preventDefault(),a.setValue("location",h.address,{shouldValidate:!0,shouldDirty:!0}),oe(!1)},"data-testid":`suggestion-activity-location-${re}`,children:[h.label?e.jsxs("span",{className:"font-medium",children:[h.label,": "]}):null,e.jsx("span",{children:h.address})]},re)):m?e.jsx("button",{type:"button",className:"w-full text-left px-3 py-2 text-sm hover:bg-accent cursor-pointer",onMouseDown:h=>{h.preventDefault(),a.setValue("location",i,{shouldValidate:!0,shouldDirty:!0}),oe(!1)},"data-testid":"suggestion-activity-location-fallback",children:e.jsxs("span",{className:"text-muted-foreground",children:["Leveringsadresse mangler â vil du bruke ",e.jsx("span",{className:"text-foreground font-medium",children:i}),"?"]})}):null})]}),e.jsx(v,{})]})}}),e.jsx(f,{control:a.control,name:"participantIds",render:({field:t})=>e.jsxs(j,{children:[e.jsx(p,{children:"Deltakere"}),e.jsxs(z,{value:"",onValueChange:s=>{s&&!(t.value||[]).includes(s)&&t.onChange([...t.value||[],s])},children:[e.jsx(G,{"data-testid":"select-activity-participants",children:e.jsx(Q,{placeholder:t.value?.length?`${t.value.length} valgt`:"Legg til deltaker..."})}),e.jsx(W,{children:Se?.filter(s=>!(t.value||[]).includes(s.id)&&s.id!==a.watch("assignedUserId")).map(s=>e.jsx(b,{value:s.id,children:s.name},s.id))})]}),(t.value||[]).length>0&&e.jsx("div",{className:"flex flex-wrap gap-1 mt-1",children:(t.value||[]).map(s=>{const n=Se?.find(r=>r.id===s);return n?e.jsxs(cs,{variant:"secondary",className:"gap-1",children:[n.name,e.jsx(Ve,{className:"h-3 w-3 cursor-pointer",onClick:()=>t.onChange(t.value?.filter(r=>r!==s))})]},s):null})}),e.jsx(v,{})]})})]}),e.jsxs("div",{"data-testid":"location-map-section",children:[_e==="loading"&&e.jsxs("div",{className:"flex items-center gap-1.5 text-xs text-muted-foreground mb-1","data-testid":"location-geo-loading",children:[e.jsx(us,{className:"h-3 w-3 animate-spin"}),"Søker etter adresse pÃ¥ kartâ¦"]}),_e==="not_found"&&e.jsxs("div",{className:"flex items-center gap-1.5 text-xs text-amber-600 dark:text-amber-400 mb-1","data-testid":"location-geo-not-found",children:[e.jsx(Ze,{className:"h-3 w-3"}),"Adressen ble ikke funnet pÃ¥ kart"]}),_e==="found"&&V&&e.jsxs("div",{className:"flex items-center gap-1.5 text-xs text-green-600 dark:text-green-400 mb-1","data-testid":"location-geo-found",children:[e.jsx(ms,{className:"h-3 w-3"}),"Adresse funnet pÃ¥ kart"]}),e.jsx(hs,{lat:V?.lat??null,lng:V?.lng??null,onLocationPicked:(t,s)=>{H({lat:t,lng:s}),L("found")},onAddressResolved:t=>{qe.current=!0,a.setValue("location",t,{shouldValidate:!0,shouldDirty:!0})}})]}),e.jsx(f,{control:a.control,name:"recurrence",render:({field:t})=>e.jsxs(j,{className:"flex items-center gap-2 space-y-0",children:[e.jsx(p,{className:"font-normal whitespace-nowrap",children:"Gjentakelse:"}),e.jsxs(z,{value:t.value?.pattern||"none",onValueChange:s=>{s&&s!=="none"?t.onChange({pattern:s,endDate:t.value?.endDate}):t.onChange(void 0)},children:[e.jsx(G,{className:"w-32","data-testid":"select-activity-recurrence",children:e.jsx(Q,{placeholder:"Ingen"})}),e.jsxs(W,{children:[e.jsx(b,{value:"none",children:"Ingen"}),e.jsx(b,{value:"daglig",children:"Daglig"}),e.jsx(b,{value:"ukentlig",children:"Ukentlig"}),e.jsx(b,{value:"mÃ¥nedlig",children:"MÃ¥nedlig"}),e.jsx(b,{value:"Ã¥rlig",children:"Ã
rlig"})]})]})]})}),a.watch("recurrence")?.pattern&&e.jsx(f,{control:a.control,name:"recurrence",render:({field:t})=>e.jsxs(j,{children:[e.jsx(p,{className:"text-xs",children:"Gjenta til"}),e.jsx(_,{value:t.value?.endDate||"",onChange:s=>
3t.onChange({...t.value,endDate:s}),showTime:!1,placeholder:"Velg sluttdato...","data-testid":"input-activity-recurrence-end"}),e.jsx(v,{})]})}),e.jsx(f,{control:a.control,name:"reminder",render:({field:t})=>e.jsxs(j,{children:[e.jsx(p,{children:"Påminnelse"}),e.jsxs(z,{onValueChange:t.onChange,value:t.value||"none",children:[e.jsx(D,{children:e.jsx(G,{"data-testid":"select-activity-reminder",children:e.jsx(Q,{placeholder:"Velg..."})})}),e.jsxs(W,{children:[e.jsx(b,{value:"none",children:"Ingen"}),e.jsx(b,{value:"at_start",children:"Ved start"}),e.jsx(b,{value:"15min",children:"15 min før"}),e.jsx(b,{value:"1hour",children:"1 time før"}),e.jsx(b,{value:"1day",children:"1 dag før"})]})]}),e.jsx(v,{})]})}),a.watch("entityId")&&e.jsxs("div",{className:"space-y-2 border rounded-md p-3",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(I,{checked:be,onCheckedChange:t=>{Ke(!!t),t||le([])},"data-testid":"checkbox-send-invitation"}),e.jsx("span",{className:"text-sm font-medium",children:"Send invitasjon til kunde"})]}),be&&e.jsxs("div",{className:"flex items-center gap-4 ml-6",children:[e.jsxs("label",{className:"flex items-center gap-1.5 text-sm",children:[e.jsx(I,{checked:Te.includes("email"),onCheckedChange:t=>{le(s=>t?[...s,"email"]:s.filter(n=>n!=="email"))},"data-testid":"checkbox-invite-email"}),"E-post"]}),e.jsxs("label",{className:"flex items-center gap-1.5 text-sm",children:[e.jsx(I,{checked:Te.includes("sms"),onCheckedChange:t=>{le(s=>t?[...s,"sms"]:s.filter(n=>n!=="sms"))},"data-testid":"checkbox-invite-sms"}),"SMS"]})]})]})]}),e.jsx(f,{control:a.control,name:"description",render:({field:t})=>e.jsxs(j,{children:[e.jsx(p,{children:"Beskrivelse"}),e.jsx(D,{children:e.jsx("div",{onClick:s=>{const n=s.target;if(n.tagName==="IMG"){const r=n.src;r&&He({srcs:[r],index:0})}},children:e.jsx(Es,{value:t.value||"",onChange:s=>{t.onChange(s),Pt(s,!1)},onTaskItemToggle:y?Ht:void 0,placeholder:"Legg til beskrivelse...",minHeight:"64px",quickTextContext:"activities","data-testid":"input-activity-description"})})}),Ot&&e.jsxs("div",{className:"flex items-center gap-2 flex-wrap","data-testid":"text-draft-restored",children:[e.jsxs("span",{className:"text-xs text-muted-foreground",children:["Utkast gjenopprettet",dt?` (${Kt})`:""]}),e.jsxs("button",{type:"button",onClick:()=>{pe(),xe(!1),De(null),a.setValue("description","")},className:"text-xs text-destructive hover:underline flex items-center gap-1","data-testid":"button-discard-draft",children:[e.jsx(xs,{className:"h-3 w-3"}),"Forkast utkast"]})]}),Mt&&e.jsx("p",{className:"text-xs text-muted-foreground","data-testid":"text-checkbox-autosaved",children:"Avkrysning lagret automatisk"}),e.jsx(v,{})]})}),y&&e.jsxs("div",{children:[e.jsx("p",{className:"text-sm font-medium mb-1",children:"Vedlegg"}),Ne.filter(t=>(t.mimeType||"").startsWith("image/")).length>0&&e.jsx("div",{className:"grid grid-cols-4 gap-2 mb-2",children:Ne.filter(t=>(t.mimeType||"").startsWith("image/")).map((t,s)=>{const n=Ne.filter(r=>(r.mimeType||"").startsWith("image/"));return e.jsxs("div",{className:"relative group",children:[e.jsx("button",{type:"button",className:"aspect-square rounded-md overflow-hidden border w-full",onClick:()=>He({srcs:n.map(r=>`/api/attachments/${r.id}/download`),index:s,filenames:n.map(r=>r.originalName)}),children:e.jsx("img",{src:`/api/attachments/${t.id}/download`,alt:t.originalName,className:"w-full h-full object-cover"})}),e.jsx(O,{type:"button",variant:"ghost",size:"icon",className:"absolute top-0.5 right-0.5 invisible group-hover:visible bg-background/80",onClick:()=>ht(t.id),"data-testid":`delete-image-attachment-${t.id}`,children:e.jsx(Ve,{className:"h-3 w-3"})})]},t.id)})}),e.jsxs("div",{className:"space-y-1",children:[Ne.filter(t=>!(t.mimeType||"").startsWith("image/")).map(t=>e.jsxs("div",{className:"flex items-center gap-2 text-sm p-1.5 rounded border",children:[e.jsx(ps,{className:"h-3.5 w-3.5 flex-shrink-0 text-muted-foreground"}),e.jsx("span",{className:"truncate flex-1",children:t.originalName}),e.jsxs("span",{className:"text-xs text-muted-foreground",children:[(t.size/1024).toFixed(0)," KB"]}
3),e.jsx("a",{href:`/api/attachments/${t.id}/download`,target:"_blank",rel:"noreferrer",children:e.jsx(O,{type:"button",variant:"ghost",size:"icon",children:e.jsx(gs,{className:"h-3 w-3"})})}),e.jsx(O,{type:"button",variant:"ghost",size:"icon",onClick:()=>ht(t.id),"data-testid":`delete-attachment-${t.id}`,children:e.jsx(Ve,{className:"h-3 w-3"})})]},t.id)),Ut.map((t,s)=>e.jsxs("div",{className:"flex items-center gap-2 text-sm p-1.5 rounded border opacity-50",children:[e.jsx(Vs,{className:"h-3.5 w-3.5 flex-shrink-0 animate-pulse"}),e.jsx("span",{className:"truncate flex-1",children:t.name}),e.jsx("span",{className:"text-xs",children:"Laster opp..."})]},s))]}),e.jsxs("label",{className:"mt-2 inline-flex items-center gap-1.5 text-sm cursor-pointer text-muted-foreground hover:text-foreground",children:[e.jsx(fs,{className:"h-3.5 w-3.5"}),e.jsx("span",{children:"Legg til fil"}),e.jsx("input",{type:"file",multiple:!0,className:"hidden",onChange:t=>At(t.target.files),"data-testid":"input-activity-file"})]})]}),y?e.jsx("div",{className:"space-y-2",children:e.jsxs("div",{className:"flex items-center gap-2",children:[J&&e.jsxs(O,{type:"button",variant:"outline",size:"sm",className:"bg-background text-destructive border-destructive/40 hover:bg-destructive hover:text-destructive-foreground",onClick:()=>Ce(!0),"data-testid":"button-delete-activity",children:[e.jsx(js,{className:"h-4 w-4 mr-1"}),"Slett"]}),Fe&&e.jsxs(O,{type:"button",variant:"outline",size:"sm",className:"bg-background",onClick:Bt,"data-testid":"button-copy-activity",children:[e.jsx(ys,{className:"h-4 w-4 mr-1"}),"Kopier"]}),e.jsx("div",{className:"flex-1"}),e.jsxs("label",{htmlFor:"activity-completed-check",className:`flex items-center gap-2 px-3 py-1.5 rounded-md border cursor-pointer select-none transition-colors ${N?"bg-green-600 border-green-600 text-white":"border-input bg-background text-foreground hover:bg-muted"}`,children:[e.jsx(I,{id:"activity-completed-check",checked:N,onCheckedChange:t=>{if(t&&!N){const s=a.getValues("description")||"";if(rt(s)>0){ne(!0);return}}te(!!t)},className:N?"border-white data-[state=checked]:bg-white data-[state=checked]:text-green-600":"","data-testid":"checkbox-activity-completed"}),e.jsx("span",{className:"text-sm font-medium",children:"Utført"})]}),e.jsx(O,{type:"submit",disabled:Qe.isPending,"data-testid":"button-submit-activity",children:Qe.isPending?"Lagrer...":"Lagre endringer"})]})}):e.jsxs("div",{className:"flex items-center justify-between gap-3",children:[e.jsxs("label",{className:"flex items-center gap-2 cursor-pointer select-none",children:[e.jsx(I,{id:"activity-completed-check-create",checked:N,onCheckedChange:t=>{if(t&&!N){const s=a.getValues("description")||"";if(rt(s)>0){ne(!0);return}}te(!!t)},className:N?"border-white data-[state=checked]:bg-white data-[state=checked]:text-green-600":"","data-testid":"checkbox-activity-completed-create"}),e.jsx("span",{className:"text-sm font-medium",children:"Utført"})]}),e.jsx(O,{type:"submit",disabled:Ge.isPending,"data-testid":"button-submit-activity",children:Ge.isPending?"Oppretter...":"Opprett aktivitet"})]})]})})]}),e.jsx(Je,{open:Et,onOpenChange:we,children:e.jsxs(Ye,{children:[e.jsxs(Xe,{children:[e.jsx(et,{children:"Ulagrede endringer"}),e.jsx(tt,{children:"Du har ulagrede endringer. Hva vil du gjøre?"})]}),e.jsxs(st,{children:[e.jsx(nt,{onClick:()=>we(!1),"data-testid":"button-unsaved-cancel",children:"Fortsett å redigere"}),e.jsx(O,{variant:"outline",onClick:()=>{pe(),ve()},"data-testid":"button-unsaved-discard",children:"Forkast endringer"}),e.jsx(at,{onClick:()=>a.handleSubmit(gt)(),"data-testid":"button-unsaved-save",children:"Lagre og lukk"})]})]})}),e.jsx(Je,{open:Vt,onOpenChange:Ce,children:e.jsxs(Ye,{children:[e.jsxs(Xe,{children:[e.jsx(et,{children:"Slett aktivitet"}),e.jsx(tt,{children:"Er du sikker på at du vil slette denne aktiviteten? Dette kan ikke angres."})]}),e.jsxs(st,{children:[e.jsx(nt,{"data-testid":"button-delete-cancel",children:"Avbryt"}),e.jsx(at,{onClick:zt,className:"bg-destructive text-destructive-foreground hover:bg-destructive/90","data-testid":"button-delete-confirm",children:"Slett"})]})]})}),e.jsx(Je,{open:Ft,onOpenChange:t=>{t||(ne(!1),he(""))},children:e.jsxs(Ye,{children:[e.jsxs(Xe,{children:[e.jsx(et,{children:"Ubesvarte sjekklistepunkter"}),e.jsxs(tt,{children:["Det er ",rt(a.getValues("description")||"")," ubesvarte punkter i sjekklisten. Du kan gå tilbake og fullføre sjekklisten, eller fullføre likevel med en begrunnelse."]})]}),e.jsxs("div",{className:"px-6 pb-2",children:[e.jsx("label",{className:"text-sm font-medium",children:"Begrunnelse for å fullføre likevel (påkrevd)"}),e.jsx(vs,{value:ze,onChange:t=>he(t.target.value),placeholder:"Skriv en kort begrunnelse...",className:"mt-1.5 min-h-[80px]","data-testid":"input-checklist-override-comment"})]}),e.jsxs(st,{children:[e.jsx(nt,{onClick:()=>{ne(!1),he("")},"data-testid":"button-checklist-warning-back",children:"Gå tilbake"}),e.jsx(at,{disabled:!ze.trim(),onClick:()=>{const t=a.getValues("description")||"",s=`<p><strong>Fullført med ubesvarte sjekklistepunkter:</strong> ${Ns(ze.trim())}</p>`;a.setValue("description",t+s,{shouldDirty:!0}),te(!0),ne(!1),he("")},"data-testid":"button-checklist-warning-confirm",children:"Fullfør likevel"})]})]})})]}),ue&&Wt.createPortal(e.jsx(ks,{srcs:ue.srcs,initialIndex:ue.index,filenames:ue.filenames,onClose:()=>He(null)}),document.body)]})}
3export{sn as CreateActivityDialog};
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.