From b8d58dac81a730a5140f7700a4bc0b80de115456 Mon Sep 17 00:00:00 2001 From: Lichun Date: Tue, 18 Nov 2025 15:14:34 +0000 Subject: [PATCH] set VLM toggle default to off --- frontend/src/pages/UploadPage/UploadPage.tsx | 2 +- .../assets/{AdminPage-BGisxcwl.js => AdminPage-C8Qwkg88.js} | 2 +- .../{ExportModal-CGhKFoOs.js => ExportModal-x1pUTnT7.js} | 2 +- .../static/assets/{index-C5On3c4S.js => index-7oBZSGHr.js} | 4 ++-- .../static/assets/{index-vuiGcTrC.js => index-Bx3ZvIBj.js} | 4 ++-- .../static/assets/{index-Rlfiitbv.js => index-CcfIBRoF.js} | 6 +++--- .../static/assets/{index-BzZTDKPD.js => index-Dz4vX1uX.js} | 2 +- .../assets/{jszip.min-D6OY4_4u.js => jszip.min-Csqqcm8m.js} | 2 +- .../assets/{useAdmin-CnId_VLW.js => useAdmin-CrA3XozJ.js} | 2 +- py_backend/static/index.html | 2 +- 10 files changed, 14 insertions(+), 14 deletions(-) rename py_backend/static/assets/{AdminPage-BGisxcwl.js => AdminPage-C8Qwkg88.js} (99%) rename py_backend/static/assets/{ExportModal-CGhKFoOs.js => ExportModal-x1pUTnT7.js} (99%) rename py_backend/static/assets/{index-C5On3c4S.js => index-7oBZSGHr.js} (98%) rename py_backend/static/assets/{index-vuiGcTrC.js => index-Bx3ZvIBj.js} (99%) rename py_backend/static/assets/{index-Rlfiitbv.js => index-CcfIBRoF.js} (99%) rename py_backend/static/assets/{index-BzZTDKPD.js => index-Dz4vX1uX.js} (99%) rename py_backend/static/assets/{jszip.min-D6OY4_4u.js => jszip.min-Csqqcm8m.js} (99%) rename py_backend/static/assets/{useAdmin-CnId_VLW.js => useAdmin-CrA3XozJ.js} (65%) diff --git a/frontend/src/pages/UploadPage/UploadPage.tsx b/frontend/src/pages/UploadPage/UploadPage.tsx index 3f3f1921..a6a95e15 100644 --- a/frontend/src/pages/UploadPage/UploadPage.tsx +++ b/frontend/src/pages/UploadPage/UploadPage.tsx @@ -53,7 +53,7 @@ export default function UploadPage() { const [imageType, setImageType] = useState('crisis_map'); const [countries, setCountries] = useState([]); const [title, setTitle] = useState(''); - const [isManualMode, setIsManualMode] = useState(false); + const [isManualMode, setIsManualMode] = useState(true); // Drone metadata fields const [centerLon, setCenterLon] = useState(''); diff --git a/py_backend/static/assets/AdminPage-BGisxcwl.js b/py_backend/static/assets/AdminPage-C8Qwkg88.js similarity index 99% rename from py_backend/static/assets/AdminPage-BGisxcwl.js rename to py_backend/static/assets/AdminPage-C8Qwkg88.js index 98afcb42..d5db255a 100644 --- a/py_backend/static/assets/AdminPage-BGisxcwl.js +++ b/py_backend/static/assets/AdminPage-C8Qwkg88.js @@ -1,4 +1,4 @@ -import{r as i,j as a,N as K,H as Je,O as h,z as j,I as re,_ as Ge,n as d,J as y}from"./index-Rlfiitbv.js";import{u as Ve}from"./useAdmin-CnId_VLW.js";const We="_adminContainer_j11pf_5",qe="_adminHeader_j11pf_13",Ke="_adminSection_j11pf_20",Ye="_modelSelectionArea_j11pf_29",Qe="_modelSelectionRow_j11pf_36",Xe="_modelsTable_j11pf_89",Ze="_promptSubsection_j11pf_97",ea="_promptSubsectionTitle_j11pf_109",aa="_modelCode_j11pf_152",la="_modelId_j11pf_157",sa="_modelActions_j11pf_163",oa="_addModelButtonContainer_j11pf_169",ta="_addModelForm_j11pf_177",ia="_addModelFormTitle_j11pf_185",da="_addModelFormGrid_j11pf_193",na="_addModelFormField_j11pf_206",ra="_addModelFormCheckbox_j11pf_250",ca="_addModelFormActions_j11pf_268",ma="_modalOverlay_j11pf_277",ha="_modalContent_j11pf_291",pa="_modalBody_j11pf_302",_a="_modalTitle_j11pf_312",ua="_modalText_j11pf_320",xa="_modalTextLeft_j11pf_332",ja="_modalButtons_j11pf_355",va="_modalForm_j11pf_363",ga="_formField_j11pf_372",fa="_formLabel_j11pf_376",ba="_formInput_j11pf_385",ya="_textarea_j11pf_407",l={adminContainer:We,adminHeader:qe,adminSection:Ke,modelSelectionArea:Ye,modelSelectionRow:Qe,modelsTable:Xe,promptSubsection:Ze,promptSubsectionTitle:ea,modelCode:aa,modelId:la,modelActions:sa,addModelButtonContainer:oa,addModelForm:ta,addModelFormTitle:ia,addModelFormGrid:da,addModelFormField:na,addModelFormCheckbox:ra,addModelFormActions:ca,modalOverlay:ma,modalContent:ha,modalBody:pa,modalTitle:_a,modalText:ua,modalTextLeft:xa,modalButtons:ja,modalForm:va,formField:ga,formLabel:fa,formInput:ba,textarea:ya},I="selectedVlmModel";function Ca(){const{isAuthenticated:v,isLoading:ce,login:me,logout:he,verifyToken:Y}=Ve(),[E,Q]=i.useState(""),[X,g]=i.useState(""),[Z,ee]=i.useState(!1),[N,S]=i.useState([]),[pe,C]=i.useState(""),[_e,M]=i.useState(""),[ae,P]=i.useState([]),[ue,L]=i.useState([]),[xe,B]=i.useState([]),[je,k]=i.useState(!1),[O,D]=i.useState(null),[U,f]=i.useState({schema_id:"",title:"",version:"",schema:{}}),[ve,w]=i.useState(!1),[ge,T]=i.useState(!1),[fe,z]=i.useState(null),[F,R]=i.useState(null),[n,c]=i.useState({p_code:"",label:"",metadata_instructions:"",image_type:"crisis_map",is_active:!1}),[le,H]=i.useState(!1),[be,J]=i.useState(!1),[G,V]=i.useState(null),[t,m]=i.useState({m_code:"",label:"",model_type:"custom",provider:"huggingface",model_id:"",is_available:!1,is_fallback:!1}),[ye,A]=i.useState(!1),[Ne,W]=i.useState(!1),[Se,_]=i.useState(!1),[se,oe]=i.useState(""),[Ce,Me]=i.useState(""),[ke,u]=i.useState(""),[we,$]=i.useState(""),x=i.useCallback(()=>{fetch("/api/models").then(e=>{if(!e.ok)throw new Error(`HTTP ${e.status}: ${e.statusText}`);return e.json()}).then(e=>{if(console.log("Models data received:",e),e&&Array.isArray(e.models)){S(e.models);const s=localStorage.getItem(I);if(e.models.length>0)if(s==="random")C("random");else if(s&&e.models.find(o=>o.m_code===s&&o.is_available))C(s);else{const o=e.models.find(r=>r.is_available)||e.models[0];C(o.m_code),localStorage.setItem(I,o.m_code)}fetch("/api/admin/fallback-model",{headers:{Authorization:`Bearer ${localStorage.getItem("adminToken")}`}}).then(o=>{if(!o.ok)throw new Error(`HTTP ${o.status}: ${o.statusText}`);return o.json()}).then(o=>{if(console.log("Fallback model data received:",o),o.fallback_model)M(o.fallback_model.m_code);else{const r=e.models.find(p=>p.m_code==="STUB_MODEL"&&p.is_available);M(r?"STUB_MODEL":"")}}).catch(o=>{console.error("Error fetching fallback model:",o);const r=e.models.find(p=>p.m_code==="STUB_MODEL"&&p.is_available);M(r?"STUB_MODEL":"")})}else console.error("Expected models object but got:",e),S([])}).catch(e=>{console.error("Error fetching models:",e),S([])})},[]),b=i.useCallback(()=>{console.log("=== fetchPrompts called ==="),fetch("/api/prompts").then(e=>{if(!e.ok)throw new Error(`HTTP ${e.status}: ${e.statusText}`);return e.json()}).then(e=>{console.log("Prompts data received:",e),Array.isArray(e)?P(e):(console.error("Expected array but got:",e),P([])),console.log("State update triggered with:",e||[])}).catch(e=>{console.error("Error fetching prompts:",e),P([])})},[]),te=i.useCallback(()=>{fetch("/api/image-types").then(e=>{if(!e.ok)throw new Error(`HTTP ${e.status}: ${e.statusText}`);return e.json()}).then(e=>{console.log("Image types data received:",e),Array.isArray(e)?L(e):(console.error("Expected array but got:",e),L([]))}).catch(e=>{console.error("Error fetching image types:",e),L([])})},[]),q=i.useCallback(()=>{console.log("=== fetchSchemas called ==="),fetch("/api/schemas",{headers:{Authorization:`Bearer ${localStorage.getItem("adminToken")}`}}).then(e=>{if(!e.ok)throw new Error(`HTTP ${e.status}: ${e.statusText}`);return e.json()}).then(e=>{console.log("Schemas data received:",e),Array.isArray(e)?B(e):(console.error("Expected array but got:",e),B([]))}).catch(e=>{console.error("Error fetching schemas:",e),B([])})},[]);i.useEffect(()=>{v&&(x(),b(),te(),q())},[v,x,b,te,q]),i.useEffect(()=>{v&&Y()},[v,Y]);const ie=e=>{R(e),c({p_code:e.p_code,label:e.label||"",metadata_instructions:e.metadata_instructions||"",image_type:e.image_type||"crisis_map",is_active:e.is_active||!1}),w(!0)},Te=async()=>{try{if(!F){alert("No prompt selected for editing");return}const e=await fetch(`/api/prompts/${F.p_code}`,{method:"PUT",headers:{"Content-Type":"application/json"},body:JSON.stringify({label:n.label,metadata_instructions:n.metadata_instructions,image_type:n.image_type,is_active:n.is_active})});if(e.ok)b(),w(!1),R(null),c({p_code:"",label:"",metadata_instructions:"",image_type:"crisis_map",is_active:!1});else{const s=await e.json();alert(`Failed to update prompt: ${s.error||"Unknown error"}`)}}catch{alert("Error updating prompt")}},de=async(e,s)=>{try{const o=await fetch(`/api/prompts/${e}/toggle-active?image_type=${s}`,{method:"POST",headers:{"Content-Type":"application/json"}});if(o.ok)b();else{const r=await o.json();alert(`Failed to toggle prompt active status: ${r.detail||"Unknown error"}`)}}catch{alert("Error toggling prompt active status")}},ne=e=>{z(e),c({p_code:"",label:"",metadata_instructions:"",image_type:e,is_active:!1}),T(!0)},Fe=async()=>{try{const e=await fetch("/api/prompts",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(n)});if(e.ok)b(),T(!1),z(null),c({p_code:"",label:"",metadata_instructions:"",image_type:"crisis_map",is_active:!1});else{const s=await e.json();alert(`Failed to create prompt: ${s.detail||"Unknown error"}`)}}catch{alert("Error creating prompt")}},Ae=e=>{D(e),f({schema_id:e.schema_id,title:e.title,version:e.version,schema:e.schema}),k(!0)},$e=async()=>{try{if(!O){alert("No schema selected for editing");return}const e=await fetch(`/api/schemas/${O.schema_id}`,{method:"PUT",headers:{"Content-Type":"application/json",Authorization:`Bearer ${localStorage.getItem("adminToken")}`},body:JSON.stringify(U)});if(e.ok)q(),k(!1),D(null),f({schema_id:"",title:"",version:"",schema:{}});else{const s=await e.json();alert(`Failed to save schema: ${s.detail||"Unknown error"}`)}}catch(e){console.error("Error saving schema:",e),alert("Error saving schema")}},Ie=()=>{k(!1),D(null),f({schema_id:"",title:"",version:"",schema:{}})},Ee=async(e,s)=>{try{const o=await fetch(`/api/models/${e}/toggle`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({is_available:!s})});if(o.ok)S(r=>(r||[]).map(p=>p.m_code===e?{...p,is_available:!s}:p));else{const r=await o.json();alert(`Failed to toggle model availability: ${r.error||"Unknown error"}`)}}catch{alert("Error toggling model availability")}},Pe=e=>{C(e),e==="random"?localStorage.setItem(I,"random"):localStorage.setItem(I,e)},Le=async e=>{try{const s=await fetch(`/api/admin/models/${e}`,{method:"PUT",headers:{"Content-Type":"application/json",Authorization:`Bearer ${localStorage.getItem("adminToken")}`},body:JSON.stringify({is_fallback:!0})});if(s.ok)M(e),x();else{const o=await s.json();alert(`Failed to set fallback model: ${o.detail||"Unknown error"}`)}}catch{alert("Error setting fallback model")}},Be=async()=>{try{const e=await fetch("/api/admin/models",{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${localStorage.getItem("adminToken")}`},body:JSON.stringify(t)});if(e.ok){const s=` +import{r as i,j as a,N as K,H as Je,O as h,z as j,I as re,_ as Ge,n as d,J as y}from"./index-CcfIBRoF.js";import{u as Ve}from"./useAdmin-CrA3XozJ.js";const We="_adminContainer_j11pf_5",qe="_adminHeader_j11pf_13",Ke="_adminSection_j11pf_20",Ye="_modelSelectionArea_j11pf_29",Qe="_modelSelectionRow_j11pf_36",Xe="_modelsTable_j11pf_89",Ze="_promptSubsection_j11pf_97",ea="_promptSubsectionTitle_j11pf_109",aa="_modelCode_j11pf_152",la="_modelId_j11pf_157",sa="_modelActions_j11pf_163",oa="_addModelButtonContainer_j11pf_169",ta="_addModelForm_j11pf_177",ia="_addModelFormTitle_j11pf_185",da="_addModelFormGrid_j11pf_193",na="_addModelFormField_j11pf_206",ra="_addModelFormCheckbox_j11pf_250",ca="_addModelFormActions_j11pf_268",ma="_modalOverlay_j11pf_277",ha="_modalContent_j11pf_291",pa="_modalBody_j11pf_302",_a="_modalTitle_j11pf_312",ua="_modalText_j11pf_320",xa="_modalTextLeft_j11pf_332",ja="_modalButtons_j11pf_355",va="_modalForm_j11pf_363",ga="_formField_j11pf_372",fa="_formLabel_j11pf_376",ba="_formInput_j11pf_385",ya="_textarea_j11pf_407",l={adminContainer:We,adminHeader:qe,adminSection:Ke,modelSelectionArea:Ye,modelSelectionRow:Qe,modelsTable:Xe,promptSubsection:Ze,promptSubsectionTitle:ea,modelCode:aa,modelId:la,modelActions:sa,addModelButtonContainer:oa,addModelForm:ta,addModelFormTitle:ia,addModelFormGrid:da,addModelFormField:na,addModelFormCheckbox:ra,addModelFormActions:ca,modalOverlay:ma,modalContent:ha,modalBody:pa,modalTitle:_a,modalText:ua,modalTextLeft:xa,modalButtons:ja,modalForm:va,formField:ga,formLabel:fa,formInput:ba,textarea:ya},I="selectedVlmModel";function Ca(){const{isAuthenticated:v,isLoading:ce,login:me,logout:he,verifyToken:Y}=Ve(),[E,Q]=i.useState(""),[X,g]=i.useState(""),[Z,ee]=i.useState(!1),[N,S]=i.useState([]),[pe,C]=i.useState(""),[_e,M]=i.useState(""),[ae,P]=i.useState([]),[ue,L]=i.useState([]),[xe,B]=i.useState([]),[je,k]=i.useState(!1),[O,D]=i.useState(null),[U,f]=i.useState({schema_id:"",title:"",version:"",schema:{}}),[ve,w]=i.useState(!1),[ge,T]=i.useState(!1),[fe,z]=i.useState(null),[F,R]=i.useState(null),[n,c]=i.useState({p_code:"",label:"",metadata_instructions:"",image_type:"crisis_map",is_active:!1}),[le,H]=i.useState(!1),[be,J]=i.useState(!1),[G,V]=i.useState(null),[t,m]=i.useState({m_code:"",label:"",model_type:"custom",provider:"huggingface",model_id:"",is_available:!1,is_fallback:!1}),[ye,A]=i.useState(!1),[Ne,W]=i.useState(!1),[Se,_]=i.useState(!1),[se,oe]=i.useState(""),[Ce,Me]=i.useState(""),[ke,u]=i.useState(""),[we,$]=i.useState(""),x=i.useCallback(()=>{fetch("/api/models").then(e=>{if(!e.ok)throw new Error(`HTTP ${e.status}: ${e.statusText}`);return e.json()}).then(e=>{if(console.log("Models data received:",e),e&&Array.isArray(e.models)){S(e.models);const s=localStorage.getItem(I);if(e.models.length>0)if(s==="random")C("random");else if(s&&e.models.find(o=>o.m_code===s&&o.is_available))C(s);else{const o=e.models.find(r=>r.is_available)||e.models[0];C(o.m_code),localStorage.setItem(I,o.m_code)}fetch("/api/admin/fallback-model",{headers:{Authorization:`Bearer ${localStorage.getItem("adminToken")}`}}).then(o=>{if(!o.ok)throw new Error(`HTTP ${o.status}: ${o.statusText}`);return o.json()}).then(o=>{if(console.log("Fallback model data received:",o),o.fallback_model)M(o.fallback_model.m_code);else{const r=e.models.find(p=>p.m_code==="STUB_MODEL"&&p.is_available);M(r?"STUB_MODEL":"")}}).catch(o=>{console.error("Error fetching fallback model:",o);const r=e.models.find(p=>p.m_code==="STUB_MODEL"&&p.is_available);M(r?"STUB_MODEL":"")})}else console.error("Expected models object but got:",e),S([])}).catch(e=>{console.error("Error fetching models:",e),S([])})},[]),b=i.useCallback(()=>{console.log("=== fetchPrompts called ==="),fetch("/api/prompts").then(e=>{if(!e.ok)throw new Error(`HTTP ${e.status}: ${e.statusText}`);return e.json()}).then(e=>{console.log("Prompts data received:",e),Array.isArray(e)?P(e):(console.error("Expected array but got:",e),P([])),console.log("State update triggered with:",e||[])}).catch(e=>{console.error("Error fetching prompts:",e),P([])})},[]),te=i.useCallback(()=>{fetch("/api/image-types").then(e=>{if(!e.ok)throw new Error(`HTTP ${e.status}: ${e.statusText}`);return e.json()}).then(e=>{console.log("Image types data received:",e),Array.isArray(e)?L(e):(console.error("Expected array but got:",e),L([]))}).catch(e=>{console.error("Error fetching image types:",e),L([])})},[]),q=i.useCallback(()=>{console.log("=== fetchSchemas called ==="),fetch("/api/schemas",{headers:{Authorization:`Bearer ${localStorage.getItem("adminToken")}`}}).then(e=>{if(!e.ok)throw new Error(`HTTP ${e.status}: ${e.statusText}`);return e.json()}).then(e=>{console.log("Schemas data received:",e),Array.isArray(e)?B(e):(console.error("Expected array but got:",e),B([]))}).catch(e=>{console.error("Error fetching schemas:",e),B([])})},[]);i.useEffect(()=>{v&&(x(),b(),te(),q())},[v,x,b,te,q]),i.useEffect(()=>{v&&Y()},[v,Y]);const ie=e=>{R(e),c({p_code:e.p_code,label:e.label||"",metadata_instructions:e.metadata_instructions||"",image_type:e.image_type||"crisis_map",is_active:e.is_active||!1}),w(!0)},Te=async()=>{try{if(!F){alert("No prompt selected for editing");return}const e=await fetch(`/api/prompts/${F.p_code}`,{method:"PUT",headers:{"Content-Type":"application/json"},body:JSON.stringify({label:n.label,metadata_instructions:n.metadata_instructions,image_type:n.image_type,is_active:n.is_active})});if(e.ok)b(),w(!1),R(null),c({p_code:"",label:"",metadata_instructions:"",image_type:"crisis_map",is_active:!1});else{const s=await e.json();alert(`Failed to update prompt: ${s.error||"Unknown error"}`)}}catch{alert("Error updating prompt")}},de=async(e,s)=>{try{const o=await fetch(`/api/prompts/${e}/toggle-active?image_type=${s}`,{method:"POST",headers:{"Content-Type":"application/json"}});if(o.ok)b();else{const r=await o.json();alert(`Failed to toggle prompt active status: ${r.detail||"Unknown error"}`)}}catch{alert("Error toggling prompt active status")}},ne=e=>{z(e),c({p_code:"",label:"",metadata_instructions:"",image_type:e,is_active:!1}),T(!0)},Fe=async()=>{try{const e=await fetch("/api/prompts",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(n)});if(e.ok)b(),T(!1),z(null),c({p_code:"",label:"",metadata_instructions:"",image_type:"crisis_map",is_active:!1});else{const s=await e.json();alert(`Failed to create prompt: ${s.detail||"Unknown error"}`)}}catch{alert("Error creating prompt")}},Ae=e=>{D(e),f({schema_id:e.schema_id,title:e.title,version:e.version,schema:e.schema}),k(!0)},$e=async()=>{try{if(!O){alert("No schema selected for editing");return}const e=await fetch(`/api/schemas/${O.schema_id}`,{method:"PUT",headers:{"Content-Type":"application/json",Authorization:`Bearer ${localStorage.getItem("adminToken")}`},body:JSON.stringify(U)});if(e.ok)q(),k(!1),D(null),f({schema_id:"",title:"",version:"",schema:{}});else{const s=await e.json();alert(`Failed to save schema: ${s.detail||"Unknown error"}`)}}catch(e){console.error("Error saving schema:",e),alert("Error saving schema")}},Ie=()=>{k(!1),D(null),f({schema_id:"",title:"",version:"",schema:{}})},Ee=async(e,s)=>{try{const o=await fetch(`/api/models/${e}/toggle`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({is_available:!s})});if(o.ok)S(r=>(r||[]).map(p=>p.m_code===e?{...p,is_available:!s}:p));else{const r=await o.json();alert(`Failed to toggle model availability: ${r.error||"Unknown error"}`)}}catch{alert("Error toggling model availability")}},Pe=e=>{C(e),e==="random"?localStorage.setItem(I,"random"):localStorage.setItem(I,e)},Le=async e=>{try{const s=await fetch(`/api/admin/models/${e}`,{method:"PUT",headers:{"Content-Type":"application/json",Authorization:`Bearer ${localStorage.getItem("adminToken")}`},body:JSON.stringify({is_fallback:!0})});if(s.ok)M(e),x();else{const o=await s.json();alert(`Failed to set fallback model: ${o.detail||"Unknown error"}`)}}catch{alert("Error setting fallback model")}},Be=async()=>{try{const e=await fetch("/api/admin/models",{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${localStorage.getItem("adminToken")}`},body:JSON.stringify(t)});if(e.ok){const s=` Model "${t.label}" added successfully! ⚠️ IMPORTANT: Model will NOT work until you complete these steps: diff --git a/py_backend/static/assets/ExportModal-CGhKFoOs.js b/py_backend/static/assets/ExportModal-x1pUTnT7.js similarity index 99% rename from py_backend/static/assets/ExportModal-CGhKFoOs.js rename to py_backend/static/assets/ExportModal-x1pUTnT7.js index 84e49821..5d0cb3b7 100644 --- a/py_backend/static/assets/ExportModal-CGhKFoOs.js +++ b/py_backend/static/assets/ExportModal-x1pUTnT7.js @@ -1 +1 @@ -import{r as n,D as O,j as e,z as c,n as o,O as B,J as b,P as G,_ as M,L as A,S as P}from"./index-Rlfiitbv.js";const q=({title:m,titleId:u,...x})=>n.createElement("svg",Object.assign({xmlns:"http://www.w3.org/2000/svg","aria-hidden":"true",viewBox:"0 0 24 24",fill:"currentColor",width:"1em",height:"1em","aria-labelledby":u},x),m?n.createElement("title",{id:u},m):null,n.createElement("g",{clipPath:"url(#filter-line_svg__a)"},n.createElement("path",{d:"M9 13.5 4 6H3V4h18v2h-1l-5 7.5V22H9v-8.5ZM6.404 6 11 12.894V20h2v-7.106L17.596 6H6.404Z"})),n.createElement("defs",null,n.createElement("clipPath",{id:"filter-line_svg__a"},n.createElement("path",{d:"M0 0h24v24H0z"}))));function ie({sources:m,types:u,regions:x,countries:T,imageTypes:z,isLoadingFilters:s=!1}){const[h,_]=n.useState(!1),[S,p]=n.useState(""),{search:I,setSearch:g,srcFilter:E,setSrcFilter:v,catFilter:j,setCatFilter:f,regionFilter:y,setRegionFilter:C,countryFilter:k,setCountryFilter:N,imageTypeFilter:F,setImageTypeFilter:w,uploadTypeFilter:d,setUploadTypeFilter:a,generatedMethodFilter:r,setGeneratedMethodFilter:i,clearAllFilters:W}=O();return n.useEffect(()=>{p(I)},[I]),e.jsxs("div",{className:"mb-6 space-y-4",children:[e.jsxs("div",{className:"flex flex-wrap items-center gap-4",children:[e.jsx(c,{withInternalPadding:!0,className:"bg-white/20 backdrop-blur-sm rounded-md p-2",children:e.jsx(o,{name:"toggle-filters",variant:"secondary",onClick:()=>_(!h),className:"whitespace-nowrap",title:h?"Hide Filters":"Show Filters",children:e.jsx(q,{className:"w-4 h-4"})})}),e.jsx(c,{withInternalPadding:!0,className:"bg-white/20 backdrop-blur-sm rounded-md p-2 flex-1 min-w-[300px]",children:e.jsx(B,{name:"search",placeholder:"Search",value:S,onChange:l=>p(l||""),onKeyDown:l=>{l.key==="Enter"&&g(S)}})}),e.jsx(c,{withInternalPadding:!0,className:"bg-white/20 backdrop-blur-sm rounded-md p-2",children:e.jsx(o,{name:"clear-filters",variant:"secondary",onClick:W,children:"Clear Filters"})})]}),h&&e.jsx("div",{className:"bg-white/20 backdrop-blur-sm rounded-md p-4",children:e.jsxs("div",{className:"grid grid-cols-2 md:grid-cols-3 gap-4",children:[e.jsx(c,{withInternalPadding:!0,className:"p-2",children:e.jsx(b,{name:"source",placeholder:s?"Loading...":"All Sources",options:m,value:E||null,onChange:l=>v(l||""),keySelector:l=>l.s_code,labelSelector:l=>l.label,required:!1,disabled:s})}),e.jsx(c,{withInternalPadding:!0,className:"p-2",children:e.jsx(b,{name:"category",placeholder:s?"Loading...":"All Categories",options:u,value:j||null,onChange:l=>f(l||""),keySelector:l=>l.t_code,labelSelector:l=>l.label,required:!1,disabled:s})}),e.jsx(c,{withInternalPadding:!0,className:"p-2",children:e.jsx(b,{name:"region",placeholder:s?"Loading...":"All Regions",options:x,value:y||null,onChange:l=>C(l||""),keySelector:l=>l.r_code,labelSelector:l=>l.label,required:!1,disabled:s})}),e.jsx(c,{withInternalPadding:!0,className:"p-2",children:e.jsx(G,{name:"country",placeholder:s?"Loading...":"All Countries",options:T,value:k?[k]:[],onChange:l=>N(l[0]||""),keySelector:l=>l.c_code,labelSelector:l=>l.label,disabled:s})}),e.jsx(c,{withInternalPadding:!0,className:"p-2",children:e.jsx(b,{name:"imageType",placeholder:s?"Loading...":"All Image Types",options:z,value:F||null,onChange:l=>w(l||""),keySelector:l=>l.image_type,labelSelector:l=>l.label,required:!1,disabled:s})}),e.jsx(c,{withInternalPadding:!0,className:"p-2",children:e.jsx(b,{name:"uploadType",placeholder:"All Upload Types",options:[{key:"single",label:"Single Upload"},{key:"multiple",label:"Multiple Upload"}],value:d||null,onChange:l=>a(l||""),keySelector:l=>l.key,labelSelector:l=>l.label,required:!1,disabled:!1})}),e.jsx(c,{withInternalPadding:!0,className:"p-2",children:e.jsx(b,{name:"generatedMethod",placeholder:"All Generated Methods",options:[{key:"manual",label:"Manual"},{key:"generated",label:"Generated"}],value:r||null,onChange:l=>i(l||""),keySelector:l=>l.key,labelSelector:l=>l.label,required:!1,disabled:!1})})]})})]})}const V="_fullSizeModalOverlay_cyz3b_1",D="_fullSizeModalContent_cyz3b_29",H="_ratingWarningContent_cyz3b_53",R="_ratingWarningTitle_cyz3b_65",U="_exportModeSection_cyz3b_133",Y="_splitConfigSection_cyz3b_143",Z="_splitConfigTitle_cyz3b_153",$="_splitInputsContainer_cyz3b_167",J="_splitInputGroup_cyz3b_183",K="_splitInputLabel_cyz3b_197",Q="_splitInput_cyz3b_167",X="_splitTotal_cyz3b_247",L="_splitTotalError_cyz3b_261",ee="_checkboxesContainer_cyz3b_271",le="_ratingWarningButtons_cyz3b_289",te="_singleExportMessage_cyz3b_309",ae="_navigateButtonContainer_cyz3b_333",se="_loadingOverlay_cyz3b_349",t={fullSizeModalOverlay:V,fullSizeModalContent:D,ratingWarningContent:H,ratingWarningTitle:R,exportModeSection:U,splitConfigSection:Y,splitConfigTitle:Z,splitInputsContainer:$,splitInputGroup:J,splitInputLabel:K,splitInput:Q,splitTotal:X,splitTotalError:L,checkboxesContainer:ee,ratingWarningButtons:le,singleExportMessage:te,navigateButtonContainer:ae,loadingOverlay:se};function re({isOpen:m,onClose:u,onExport:x,crisisMapsCount:T,droneImagesCount:z,isLoading:s=!1,exportSuccess:h=!1,variant:_="bulk",onNavigateAndExport:S}){const[p,I]=n.useState("standard"),[g,E]=n.useState(80),[v,j]=n.useState(10),[f,y]=n.useState(10),[C,k]=n.useState(!0),[N,F]=n.useState(!0),w=()=>{if(_==="single"){x(p,["crisis_map","drone_image"]);return}if(!C&&!N){alert("Please select at least one image type to export.");return}const a=[];C&&a.push("crisis_map"),N&&a.push("drone_image"),x(p,a)},d=()=>{u()};return m?_==="single"?e.jsx("div",{className:t.fullSizeModalOverlay,onClick:d,children:e.jsxs("div",{className:t.fullSizeModalContent,onClick:a=>a.stopPropagation(),children:[s&&e.jsx("div",{className:t.loadingOverlay,children:e.jsxs("div",{className:"flex flex-col items-center gap-4",children:[e.jsx(M,{className:"text-ifrcRed"}),e.jsx("div",{className:"text-lg font-medium",children:"Exporting..."}),e.jsx("div",{className:"text-sm text-gray-600",children:"This might take a few seconds"})]})}),h&&e.jsx("div",{className:t.loadingOverlay,children:e.jsxs("div",{className:"flex flex-col items-center gap-4",children:[e.jsx("div",{className:"text-lg font-medium",children:"Export Successful!"}),e.jsx("div",{className:"text-sm text-gray-600",children:"Your dataset has been downloaded"}),e.jsx(o,{name:"close-export-success",onClick:d,className:"mt-4",children:"Close"})]})}),e.jsxs("div",{className:t.ratingWarningContent,children:[e.jsx("h3",{className:t.ratingWarningTitle,children:"Export Single Item"}),e.jsxs("div",{className:t.singleExportMessage,children:[e.jsx("p",{children:"This only exports the 1 item currently on display."}),e.jsx("p",{children:'You may export the entire dataset from the "list view" here:'})]}),e.jsx("div",{className:t.navigateButtonContainer,children:e.jsx(o,{name:"navigate-to-list",variant:"secondary",onClick:S,children:"Navigate to List View"})}),e.jsxs("div",{className:t.ratingWarningButtons,children:[e.jsx(o,{name:"continue-export",onClick:w,disabled:s,children:s?e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(M,{className:"text-white"}),"Exporting..."]}):"Continue"}),e.jsx(o,{name:"cancel-export",variant:"tertiary",onClick:d,disabled:s,children:"Cancel"})]})]})]})}):e.jsx("div",{className:t.fullSizeModalOverlay,onClick:d,children:e.jsxs("div",{className:t.fullSizeModalContent,onClick:a=>a.stopPropagation(),children:[s&&e.jsx("div",{className:t.loadingOverlay,children:e.jsxs("div",{className:"flex flex-col items-center gap-4",children:[e.jsx(M,{className:"text-ifrcRed"}),e.jsx("div",{className:"text-lg font-medium",children:"Exporting..."}),e.jsx("div",{className:"text-sm text-gray-600",children:"This might take a few seconds"})]})}),h&&e.jsx("div",{className:t.loadingOverlay,children:e.jsxs("div",{className:"flex flex-col items-center gap-4",children:[e.jsx("div",{className:"text-lg font-medium",children:"Export Successful!"}),e.jsx("div",{className:"text-sm text-gray-600",children:"Your dataset has been downloaded"}),e.jsx(o,{name:"close-export-success",onClick:d,className:"mt-4",children:"Close"})]})}),e.jsxs("div",{className:t.ratingWarningContent,children:[e.jsx("h3",{className:t.ratingWarningTitle,children:"Export Dataset"}),e.jsx("div",{className:t.exportModeSection,children:e.jsx(A,{name:"export-mode",value:p,onChange:a=>{(a==="standard"||a==="fine-tuning")&&I(a)},options:[{key:"standard",label:"Standard"},{key:"fine-tuning",label:"Fine-tuning"}],keySelector:a=>a.key,labelSelector:a=>a.label,disabled:s})}),p==="fine-tuning"&&e.jsxs("div",{className:t.splitConfigSection,children:[e.jsx("div",{className:t.splitConfigTitle,children:"Dataset Split Configuration"}),e.jsxs("div",{className:t.splitInputsContainer,children:[e.jsxs("div",{className:t.splitInputGroup,children:[e.jsx("label",{htmlFor:"train-split",className:t.splitInputLabel,children:"Train (%)"}),e.jsx("input",{id:"train-split",type:"number",min:"0",max:"100",value:g,onChange:a=>{const r=parseInt(a.target.value)||0,i=100-r;i>=0&&(E(r),v+f>i&&(j(Math.floor(i/2)),y(i-Math.floor(i/2))))},className:t.splitInput,disabled:s})]}),e.jsxs("div",{className:t.splitInputGroup,children:[e.jsx("label",{htmlFor:"test-split",className:t.splitInputLabel,children:"Test (%)"}),e.jsx("input",{id:"test-split",type:"number",min:"0",max:"100",value:v,onChange:a=>{const r=parseInt(a.target.value)||0,i=100-g-r;i>=0&&(j(r),y(i))},className:t.splitInput,disabled:s})]}),e.jsxs("div",{className:t.splitInputGroup,children:[e.jsx("label",{htmlFor:"val-split",className:t.splitInputLabel,children:"Val (%)"}),e.jsx("input",{id:"val-split",type:"number",min:"0",max:"100",value:f,onChange:a=>{const r=parseInt(a.target.value)||0,i=100-g-r;i>=0&&(y(r),j(i))},className:t.splitInput,disabled:s})]})]}),g+v+f!==100&&e.jsx("div",{className:t.splitTotal,children:e.jsx("span",{className:t.splitTotalError,children:"Must equal 100%"})})]}),e.jsxs("div",{className:t.checkboxesContainer,children:[e.jsx("div",{className:"flex items-center gap-3",children:e.jsx(P,{name:"crisis-maps",label:`Crisis Maps (${T} images)`,value:C,onChange:a=>k(a),disabled:s})}),e.jsx("div",{className:"flex items-center gap-3",children:e.jsx(P,{name:"drone-images",label:`Drone Images (${z} images)`,value:N,onChange:a=>F(a),disabled:s})})]}),e.jsxs("div",{className:t.ratingWarningButtons,children:[e.jsx(o,{name:"confirm-export",onClick:w,disabled:s,children:s?e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(M,{className:"text-white"}),"Exporting..."]}):"Export Selected"}),e.jsx(o,{name:"cancel-export",variant:"tertiary",onClick:d,disabled:s,children:"Cancel"})]})]})]})}):null}export{re as E,ie as F}; +import{r as n,D as O,j as e,z as c,n as o,O as B,J as b,P as G,_ as M,L as A,S as P}from"./index-CcfIBRoF.js";const q=({title:m,titleId:u,...x})=>n.createElement("svg",Object.assign({xmlns:"http://www.w3.org/2000/svg","aria-hidden":"true",viewBox:"0 0 24 24",fill:"currentColor",width:"1em",height:"1em","aria-labelledby":u},x),m?n.createElement("title",{id:u},m):null,n.createElement("g",{clipPath:"url(#filter-line_svg__a)"},n.createElement("path",{d:"M9 13.5 4 6H3V4h18v2h-1l-5 7.5V22H9v-8.5ZM6.404 6 11 12.894V20h2v-7.106L17.596 6H6.404Z"})),n.createElement("defs",null,n.createElement("clipPath",{id:"filter-line_svg__a"},n.createElement("path",{d:"M0 0h24v24H0z"}))));function ie({sources:m,types:u,regions:x,countries:T,imageTypes:z,isLoadingFilters:s=!1}){const[h,_]=n.useState(!1),[S,p]=n.useState(""),{search:I,setSearch:g,srcFilter:E,setSrcFilter:v,catFilter:j,setCatFilter:f,regionFilter:y,setRegionFilter:C,countryFilter:k,setCountryFilter:N,imageTypeFilter:F,setImageTypeFilter:w,uploadTypeFilter:d,setUploadTypeFilter:a,generatedMethodFilter:r,setGeneratedMethodFilter:i,clearAllFilters:W}=O();return n.useEffect(()=>{p(I)},[I]),e.jsxs("div",{className:"mb-6 space-y-4",children:[e.jsxs("div",{className:"flex flex-wrap items-center gap-4",children:[e.jsx(c,{withInternalPadding:!0,className:"bg-white/20 backdrop-blur-sm rounded-md p-2",children:e.jsx(o,{name:"toggle-filters",variant:"secondary",onClick:()=>_(!h),className:"whitespace-nowrap",title:h?"Hide Filters":"Show Filters",children:e.jsx(q,{className:"w-4 h-4"})})}),e.jsx(c,{withInternalPadding:!0,className:"bg-white/20 backdrop-blur-sm rounded-md p-2 flex-1 min-w-[300px]",children:e.jsx(B,{name:"search",placeholder:"Search",value:S,onChange:l=>p(l||""),onKeyDown:l=>{l.key==="Enter"&&g(S)}})}),e.jsx(c,{withInternalPadding:!0,className:"bg-white/20 backdrop-blur-sm rounded-md p-2",children:e.jsx(o,{name:"clear-filters",variant:"secondary",onClick:W,children:"Clear Filters"})})]}),h&&e.jsx("div",{className:"bg-white/20 backdrop-blur-sm rounded-md p-4",children:e.jsxs("div",{className:"grid grid-cols-2 md:grid-cols-3 gap-4",children:[e.jsx(c,{withInternalPadding:!0,className:"p-2",children:e.jsx(b,{name:"source",placeholder:s?"Loading...":"All Sources",options:m,value:E||null,onChange:l=>v(l||""),keySelector:l=>l.s_code,labelSelector:l=>l.label,required:!1,disabled:s})}),e.jsx(c,{withInternalPadding:!0,className:"p-2",children:e.jsx(b,{name:"category",placeholder:s?"Loading...":"All Categories",options:u,value:j||null,onChange:l=>f(l||""),keySelector:l=>l.t_code,labelSelector:l=>l.label,required:!1,disabled:s})}),e.jsx(c,{withInternalPadding:!0,className:"p-2",children:e.jsx(b,{name:"region",placeholder:s?"Loading...":"All Regions",options:x,value:y||null,onChange:l=>C(l||""),keySelector:l=>l.r_code,labelSelector:l=>l.label,required:!1,disabled:s})}),e.jsx(c,{withInternalPadding:!0,className:"p-2",children:e.jsx(G,{name:"country",placeholder:s?"Loading...":"All Countries",options:T,value:k?[k]:[],onChange:l=>N(l[0]||""),keySelector:l=>l.c_code,labelSelector:l=>l.label,disabled:s})}),e.jsx(c,{withInternalPadding:!0,className:"p-2",children:e.jsx(b,{name:"imageType",placeholder:s?"Loading...":"All Image Types",options:z,value:F||null,onChange:l=>w(l||""),keySelector:l=>l.image_type,labelSelector:l=>l.label,required:!1,disabled:s})}),e.jsx(c,{withInternalPadding:!0,className:"p-2",children:e.jsx(b,{name:"uploadType",placeholder:"All Upload Types",options:[{key:"single",label:"Single Upload"},{key:"multiple",label:"Multiple Upload"}],value:d||null,onChange:l=>a(l||""),keySelector:l=>l.key,labelSelector:l=>l.label,required:!1,disabled:!1})}),e.jsx(c,{withInternalPadding:!0,className:"p-2",children:e.jsx(b,{name:"generatedMethod",placeholder:"All Generated Methods",options:[{key:"manual",label:"Manual"},{key:"generated",label:"Generated"}],value:r||null,onChange:l=>i(l||""),keySelector:l=>l.key,labelSelector:l=>l.label,required:!1,disabled:!1})})]})})]})}const V="_fullSizeModalOverlay_cyz3b_1",D="_fullSizeModalContent_cyz3b_29",H="_ratingWarningContent_cyz3b_53",R="_ratingWarningTitle_cyz3b_65",U="_exportModeSection_cyz3b_133",Y="_splitConfigSection_cyz3b_143",Z="_splitConfigTitle_cyz3b_153",$="_splitInputsContainer_cyz3b_167",J="_splitInputGroup_cyz3b_183",K="_splitInputLabel_cyz3b_197",Q="_splitInput_cyz3b_167",X="_splitTotal_cyz3b_247",L="_splitTotalError_cyz3b_261",ee="_checkboxesContainer_cyz3b_271",le="_ratingWarningButtons_cyz3b_289",te="_singleExportMessage_cyz3b_309",ae="_navigateButtonContainer_cyz3b_333",se="_loadingOverlay_cyz3b_349",t={fullSizeModalOverlay:V,fullSizeModalContent:D,ratingWarningContent:H,ratingWarningTitle:R,exportModeSection:U,splitConfigSection:Y,splitConfigTitle:Z,splitInputsContainer:$,splitInputGroup:J,splitInputLabel:K,splitInput:Q,splitTotal:X,splitTotalError:L,checkboxesContainer:ee,ratingWarningButtons:le,singleExportMessage:te,navigateButtonContainer:ae,loadingOverlay:se};function re({isOpen:m,onClose:u,onExport:x,crisisMapsCount:T,droneImagesCount:z,isLoading:s=!1,exportSuccess:h=!1,variant:_="bulk",onNavigateAndExport:S}){const[p,I]=n.useState("standard"),[g,E]=n.useState(80),[v,j]=n.useState(10),[f,y]=n.useState(10),[C,k]=n.useState(!0),[N,F]=n.useState(!0),w=()=>{if(_==="single"){x(p,["crisis_map","drone_image"]);return}if(!C&&!N){alert("Please select at least one image type to export.");return}const a=[];C&&a.push("crisis_map"),N&&a.push("drone_image"),x(p,a)},d=()=>{u()};return m?_==="single"?e.jsx("div",{className:t.fullSizeModalOverlay,onClick:d,children:e.jsxs("div",{className:t.fullSizeModalContent,onClick:a=>a.stopPropagation(),children:[s&&e.jsx("div",{className:t.loadingOverlay,children:e.jsxs("div",{className:"flex flex-col items-center gap-4",children:[e.jsx(M,{className:"text-ifrcRed"}),e.jsx("div",{className:"text-lg font-medium",children:"Exporting..."}),e.jsx("div",{className:"text-sm text-gray-600",children:"This might take a few seconds"})]})}),h&&e.jsx("div",{className:t.loadingOverlay,children:e.jsxs("div",{className:"flex flex-col items-center gap-4",children:[e.jsx("div",{className:"text-lg font-medium",children:"Export Successful!"}),e.jsx("div",{className:"text-sm text-gray-600",children:"Your dataset has been downloaded"}),e.jsx(o,{name:"close-export-success",onClick:d,className:"mt-4",children:"Close"})]})}),e.jsxs("div",{className:t.ratingWarningContent,children:[e.jsx("h3",{className:t.ratingWarningTitle,children:"Export Single Item"}),e.jsxs("div",{className:t.singleExportMessage,children:[e.jsx("p",{children:"This only exports the 1 item currently on display."}),e.jsx("p",{children:'You may export the entire dataset from the "list view" here:'})]}),e.jsx("div",{className:t.navigateButtonContainer,children:e.jsx(o,{name:"navigate-to-list",variant:"secondary",onClick:S,children:"Navigate to List View"})}),e.jsxs("div",{className:t.ratingWarningButtons,children:[e.jsx(o,{name:"continue-export",onClick:w,disabled:s,children:s?e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(M,{className:"text-white"}),"Exporting..."]}):"Continue"}),e.jsx(o,{name:"cancel-export",variant:"tertiary",onClick:d,disabled:s,children:"Cancel"})]})]})]})}):e.jsx("div",{className:t.fullSizeModalOverlay,onClick:d,children:e.jsxs("div",{className:t.fullSizeModalContent,onClick:a=>a.stopPropagation(),children:[s&&e.jsx("div",{className:t.loadingOverlay,children:e.jsxs("div",{className:"flex flex-col items-center gap-4",children:[e.jsx(M,{className:"text-ifrcRed"}),e.jsx("div",{className:"text-lg font-medium",children:"Exporting..."}),e.jsx("div",{className:"text-sm text-gray-600",children:"This might take a few seconds"})]})}),h&&e.jsx("div",{className:t.loadingOverlay,children:e.jsxs("div",{className:"flex flex-col items-center gap-4",children:[e.jsx("div",{className:"text-lg font-medium",children:"Export Successful!"}),e.jsx("div",{className:"text-sm text-gray-600",children:"Your dataset has been downloaded"}),e.jsx(o,{name:"close-export-success",onClick:d,className:"mt-4",children:"Close"})]})}),e.jsxs("div",{className:t.ratingWarningContent,children:[e.jsx("h3",{className:t.ratingWarningTitle,children:"Export Dataset"}),e.jsx("div",{className:t.exportModeSection,children:e.jsx(A,{name:"export-mode",value:p,onChange:a=>{(a==="standard"||a==="fine-tuning")&&I(a)},options:[{key:"standard",label:"Standard"},{key:"fine-tuning",label:"Fine-tuning"}],keySelector:a=>a.key,labelSelector:a=>a.label,disabled:s})}),p==="fine-tuning"&&e.jsxs("div",{className:t.splitConfigSection,children:[e.jsx("div",{className:t.splitConfigTitle,children:"Dataset Split Configuration"}),e.jsxs("div",{className:t.splitInputsContainer,children:[e.jsxs("div",{className:t.splitInputGroup,children:[e.jsx("label",{htmlFor:"train-split",className:t.splitInputLabel,children:"Train (%)"}),e.jsx("input",{id:"train-split",type:"number",min:"0",max:"100",value:g,onChange:a=>{const r=parseInt(a.target.value)||0,i=100-r;i>=0&&(E(r),v+f>i&&(j(Math.floor(i/2)),y(i-Math.floor(i/2))))},className:t.splitInput,disabled:s})]}),e.jsxs("div",{className:t.splitInputGroup,children:[e.jsx("label",{htmlFor:"test-split",className:t.splitInputLabel,children:"Test (%)"}),e.jsx("input",{id:"test-split",type:"number",min:"0",max:"100",value:v,onChange:a=>{const r=parseInt(a.target.value)||0,i=100-g-r;i>=0&&(j(r),y(i))},className:t.splitInput,disabled:s})]}),e.jsxs("div",{className:t.splitInputGroup,children:[e.jsx("label",{htmlFor:"val-split",className:t.splitInputLabel,children:"Val (%)"}),e.jsx("input",{id:"val-split",type:"number",min:"0",max:"100",value:f,onChange:a=>{const r=parseInt(a.target.value)||0,i=100-g-r;i>=0&&(y(r),j(i))},className:t.splitInput,disabled:s})]})]}),g+v+f!==100&&e.jsx("div",{className:t.splitTotal,children:e.jsx("span",{className:t.splitTotalError,children:"Must equal 100%"})})]}),e.jsxs("div",{className:t.checkboxesContainer,children:[e.jsx("div",{className:"flex items-center gap-3",children:e.jsx(P,{name:"crisis-maps",label:`Crisis Maps (${T} images)`,value:C,onChange:a=>k(a),disabled:s})}),e.jsx("div",{className:"flex items-center gap-3",children:e.jsx(P,{name:"drone-images",label:`Drone Images (${z} images)`,value:N,onChange:a=>F(a),disabled:s})})]}),e.jsxs("div",{className:t.ratingWarningButtons,children:[e.jsx(o,{name:"confirm-export",onClick:w,disabled:s,children:s?e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(M,{className:"text-white"}),"Exporting..."]}):"Export Selected"}),e.jsx(o,{name:"cancel-export",variant:"tertiary",onClick:d,disabled:s,children:"Cancel"})]})]})]})}):null}export{re as E,ie as F}; diff --git a/py_backend/static/assets/index-C5On3c4S.js b/py_backend/static/assets/index-7oBZSGHr.js similarity index 98% rename from py_backend/static/assets/index-C5On3c4S.js rename to py_backend/static/assets/index-7oBZSGHr.js index 9c78bd31..05b7a978 100644 --- a/py_backend/static/assets/index-C5On3c4S.js +++ b/py_backend/static/assets/index-7oBZSGHr.js @@ -1,2 +1,2 @@ -const __vite__mapDeps=(i,m=__vite__mapDeps,d=(m.f||(m.f=["assets/jszip.min-D6OY4_4u.js","assets/index-Rlfiitbv.js","assets/index-BzCX1Bzq.css"])))=>i.map(i=>d[i]); -import{j as t,z as b,n as w,v as Oe,w as Me,x as Le,B as Re,r as c,D as Je,N as ze,_ as fe,L as We,F as Ue,G as Ae}from"./index-Rlfiitbv.js";import{u as Be}from"./useAdmin-CnId_VLW.js";import{F as He,E as Ve}from"./ExportModal-CGhKFoOs.js";const Ge="_paginatorContainer_1l5ti_1",Ze="_paginationControls_1l5ti_19",he={paginatorContainer:Ge,paginationControls:Ze};function qe({currentPage:N,totalPages:f,onPageChange:$,className:H=""}){if(f<=1)return null;const h=(()=>{const y=[];if(f<=5)for(let x=1;x<=f;x++)y.push(x);else{let x=Math.max(1,N-2);const S=Math.min(f,x+5-1);S===f&&(x=Math.max(1,S-5+1));for(let T=x;T<=S;T++)y.push(T)}return y})();return t.jsx("div",{className:`${he.paginatorContainer} ${H}`,children:t.jsxs("div",{className:he.paginationControls,children:[t.jsx(b,{withInternalPadding:!0,className:"bg-white/20 backdrop-blur-sm rounded-md p-2",children:t.jsxs(w,{name:"prev-page",variant:"tertiary",size:1,onClick:()=>$(Math.max(1,N-1)),disabled:N===1,title:"Previous page",children:[t.jsx(Oe,{className:"w-4 h-4"}),t.jsx("span",{className:"hidden sm:inline",children:"Previous"})]})}),t.jsxs("div",{className:"flex items-center gap-1",children:[h[0]>1&&t.jsxs(t.Fragment,{children:[t.jsx(b,{withInternalPadding:!0,className:"bg-white/20 backdrop-blur-sm rounded-md p-2",children:t.jsx(w,{name:"page-1",variant:"tertiary",size:1,onClick:()=>$(1),children:"1"})}),h[0]>2&&t.jsx(b,{withInternalPadding:!0,className:"bg-white/20 backdrop-blur-sm rounded-md p-2",children:t.jsx("span",{className:"px-2 text-gray-500",children:"..."})})]}),h.map(y=>t.jsx(b,{withInternalPadding:!0,className:"bg-white/20 backdrop-blur-sm rounded-md p-2",children:t.jsx(w,{name:`page-${y}`,variant:N===y?"primary":"tertiary",size:1,onClick:()=>$(y),children:y})},y)),h[h.length-1]$(f),children:f})})]})]}),t.jsx(b,{withInternalPadding:!0,className:"bg-white/20 backdrop-blur-sm rounded-md p-2",children:t.jsxs(w,{name:"next-page",variant:"tertiary",size:1,onClick:()=>$(Math.min(f,N+1)),disabled:N===f,title:"Next page",children:[t.jsx("span",{className:"hidden sm:inline",children:"Next"}),t.jsx(Me,{className:"w-4 h-4"})]})})]})})}const Ke="_tabSelector_o9y1f_1",Qe="_metadataTags_o9y1f_8",Xe="_metadataTag_o9y1f_8",Ye="_metadataTagSource_o9y1f_32",et="_metadataTagType_o9y1f_43",tt="_mapItem_o9y1f_54",at="_mapItemImage_o9y1f_72",st="_mapItemContent_o9y1f_92",it="_mapItemTitle_o9y1f_97",nt="_mapItemMetadata_o9y1f_105",lt="_fullSizeModalOverlay_o9y1f_134",rt="_fullSizeModalContent_o9y1f_148",ot="_ratingWarningContent_o9y1f_159",ct="_ratingWarningTitle_o9y1f_165",dt="_ratingWarningText_o9y1f_172",mt="_ratingWarningButtons_o9y1f_179",p={tabSelector:Ke,metadataTags:Qe,metadataTag:Xe,metadataTagSource:Ye,metadataTagType:et,mapItem:tt,mapItemImage:at,mapItemContent:st,mapItemTitle:it,mapItemMetadata:nt,fullSizeModalOverlay:lt,fullSizeModalContent:rt,ratingWarningContent:ot,ratingWarningTitle:ct,ratingWarningText:dt,ratingWarningButtons:mt};function ft(){const N=Le(),f=Re(),{isAuthenticated:$}=Be(),[H,ne]=c.useState("explore"),[h,y]=c.useState([]),{search:F,srcFilter:x,catFilter:S,regionFilter:T,countryFilter:L,imageTypeFilter:R,uploadTypeFilter:J,generatedMethodFilter:I,showReferenceExamples:E,setShowReferenceExamples:xe}=Je(),[K,_e]=c.useState([]),[Q,ye]=c.useState([]),[le,je]=c.useState([]),[Ne,ve]=c.useState([]),[re,be]=c.useState([]),[we,oe]=c.useState(!0),[z,ce]=c.useState(!0),[Se,X]=c.useState(!1),[Te,Y]=c.useState(!1),[Ie,ee]=c.useState(!1),[te,ae]=c.useState(null),[Ee,V]=c.useState(!1),[G,de]=c.useState(""),[se,me]=c.useState(!1),[W,ge]=c.useState(1),[C]=c.useState(10),[Z,pe]=c.useState(0),[Ce,ue]=c.useState(0),$e=[{key:"explore",label:"List"},{key:"mapDetails",label:"Carousel"}],U=c.useCallback(()=>{ce(!0),ae(null);const e=100,s=1,l=new URLSearchParams({page:s.toString(),limit:e.toString(),include_count:"true"});F&&l.append("search",F),x&&l.append("source",x),S&&l.append("event_type",S),T&&l.append("region",T),L&&l.append("country",L),R&&l.append("image_type",R),J&&l.append("upload_type",J),E&&l.append("starred_only","true"),fetch(`/api/images/grouped?${l.toString()}`).then(o=>{if(!o.ok)throw new Error(`Failed to fetch images: ${o.status} ${o.statusText}`);return o.json()}).then(o=>{console.log("ExplorePage: Fetched captions:",{data:o,fetchPage:s,fetchLimit:e,currentPage:W,itemsPerPage:C,generatedMethodFilter:I});let m=[],_=0;if(o.items&&typeof o.total_count=="number")m=o.items,_=m.length;else if(Array.isArray(o))m=o,_=o.length;else throw new Error("Unexpected response format");if(console.log("ExplorePage: After parsing response:",{itemsCount:m.length,totalCount:_,generatedMethodFilter:I,backendTotalCount:o.items?o.total_count:"N/A"}),I){const P=m.length;m=m.filter(q=>I==="manual"?q.model==="manual":I==="generated"?q.model!=="manual":!0),_=m.length,console.log("ExplorePage: After client-side filtering:",{beforeFilterCount:P,afterFilterCount:m.length})}const A=(W-1)*C,B=A+C;m=m.slice(A,B),console.log("ExplorePage: After client-side pagination:",{startIndex:A,endIndex:B,finalItemsCount:m.length,currentPage:W,itemsPerPage:C,totalCount:_,totalPages:Math.ceil(_/C)}),y(m),pe(_),ue(Math.ceil(_/C)),ae(null)}).catch(o=>{console.error("ExplorePage: Error fetching captions:",o),ae(o instanceof Error?o.message:"Failed to load images. Please try again later."),y([]),pe(0),ue(0)}).finally(()=>{ce(!1)})},[W,F,x,S,T,L,R,J,I,E,C]);c.useEffect(()=>{U()},[U]),c.useEffect(()=>{ge(1)},[F,x,S,T,L,R,J,I,E]),c.useEffect(()=>{const e=()=>{document.hidden||U()};return document.addEventListener("visibilitychange",e),()=>{document.removeEventListener("visibilitychange",e)}},[U]),c.useEffect(()=>{new URLSearchParams(f.search).get("export")==="true"&&(X(!0),N("/explore",{replace:!0}))},[f.search,N,F,x,S,T,L,R,I,E]),c.useEffect(()=>{oe(!0),Promise.all([fetch("/api/sources").then(e=>{if(!e.ok)throw new Error(`HTTP ${e.status}: ${e.statusText}`);return e.json()}),fetch("/api/types").then(e=>{if(!e.ok)throw new Error(`HTTP ${e.status}: ${e.statusText}`);return e.json()}),fetch("/api/regions").then(e=>{if(!e.ok)throw new Error(`HTTP ${e.status}: ${e.statusText}`);return e.json()}),fetch("/api/countries").then(e=>{if(!e.ok)throw new Error(`HTTP ${e.status}: ${e.statusText}`);return e.json()}),fetch("/api/image-types").then(e=>{if(!e.ok)throw new Error(`HTTP ${e.status}: ${e.statusText}`);return e.json()})]).then(([e,s,l,o,m])=>{_e(e),ye(s),je(l),ve(o),be(m)}).catch(()=>{}).finally(()=>{oe(!1)})},[]);const k=h,Fe=async(e,s="fine-tuning")=>{if(e.length===0){alert("No images to export");return}Y(!0),ee(!1);try{const l=(await Ae(async()=>{const{default:i}=await import("./jszip.min-D6OY4_4u.js").then(D=>D.j);return{default:i}},__vite__mapDeps([0,1,2]))).default,o=new l,m=e.filter(i=>i.image_type==="crisis_map"),_=e.filter(i=>i.image_type==="drone_image");if(m.length>0){const i=o.folder("crisis_maps_dataset"),D=i?.folder("images");if(D){let O=1;for(const a of m)try{const v=a.image_count&&a.image_count>1?a.all_image_ids||[a.image_id]:[a.image_id],ie=v.map(async(n,j)=>{try{const r=await fetch(`/api/images/${n}/file`);if(!r.ok)throw new Error(`Failed to fetch image ${n}`);const d=await r.blob(),g=a.file_key.split(".").pop()||"jpg",u=`${String(O).padStart(4,"0")}_${String(j+1).padStart(2,"0")}.${g}`;return D.file(u,d),{success:!0,fileName:u,imageId:n}}catch(r){return console.error(`Failed to process image ${n}:`,r),{success:!1,fileName:"",imageId:n}}}),M=(await Promise.all(ie)).filter(n=>n.success);if(M.length>0){if(s==="fine-tuning"){const n=M.map(d=>`images/${d.fileName}`),j=Math.random(),r={image:n.length===1?n[0]:n,caption:a.edited||a.generated||"",metadata:{image_id:v,title:a.title,source:a.source,event_type:a.event_type,image_type:a.image_type,countries:a.countries,starred:a.starred,image_count:a.image_count||1}};if(!i)continue;if(j<.8){const d=i.file("train.jsonl");if(d){const g=await d.async("string").then(u=>JSON.parse(u||"[]")).catch(()=>[]);g.push(r),i.file("train.jsonl",JSON.stringify(g,null,2))}else i.file("train.jsonl",JSON.stringify([r],null,2))}else if(j<.9){const d=i.file("test.jsonl");if(d){const g=await d.async("string").then(u=>JSON.parse(u||"[]")).catch(()=>[]);g.push(r),i.file("test.jsonl",JSON.stringify(g,null,2))}else i.file("test.jsonl",JSON.stringify([r],null,2))}else{const d=i.file("val.jsonl");if(d){const g=await d.async("string").then(u=>JSON.parse(u||"[]")).catch(()=>[]);g.push(r),i.file("val.jsonl",JSON.stringify(g,null,2))}else i.file("val.jsonl",JSON.stringify([r],null,2))}}else{const n=M.map(r=>`images/${r.fileName}`),j={image:n.length===1?n[0]:n,caption:a.edited||a.generated||"",metadata:{image_id:v,title:a.title,source:a.source,event_type:a.event_type,image_type:a.image_type,countries:a.countries,starred:a.starred,image_count:a.image_count||1}};i&&i.file(`${String(O).padStart(4,"0")}.json`,JSON.stringify(j,null,2))}O++}}catch(v){console.error(`Failed to process caption ${a.image_id}:`,v)}}}if(_.length>0){const i=o.folder("drone_images_dataset"),D=i?.folder("images");if(D){let O=1;for(const a of _)try{const v=a.image_count&&a.image_count>1?a.all_image_ids||[a.image_id]:[a.image_id],ie=v.map(async(n,j)=>{try{const r=await fetch(`/api/images/${n}/file`);if(!r.ok)throw new Error(`Failed to fetch image ${n}`);const d=await r.blob(),g=a.file_key.split(".").pop()||"jpg",u=`${String(O).padStart(4,"0")}_${String(j+1).padStart(2,"0")}.${g}`;return D.file(u,d),{success:!0,fileName:u,imageId:n}}catch(r){return console.error(`Failed to process image ${n}:`,r),{success:!1,fileName:"",imageId:n}}}),M=(await Promise.all(ie)).filter(n=>n.success);if(M.length>0){if(s==="fine-tuning"){const n=M.map(d=>`images/${d.fileName}`),j=Math.random(),r={image:n.length===1?n[0]:n,caption:a.edited||a.generated||"",metadata:{image_id:v,title:a.title,source:a.source,event_type:a.event_type,image_type:a.image_type,countries:a.countries,starred:a.starred,image_count:a.image_count||1}};if(!i)continue;if(j<.8){const d=i.file("train.jsonl");if(d){const g=await d.async("string").then(u=>JSON.parse(u||"[]")).catch(()=>[]);g.push(r),i.file("train.jsonl",JSON.stringify(g,null,2))}else i.file("train.jsonl",JSON.stringify([r],null,2))}else if(j<.9){const d=i.file("test.jsonl");if(d){const g=await d.async("string").then(u=>JSON.parse(u||"[]")).catch(()=>[]);g.push(r),i.file("test.jsonl",JSON.stringify(g,null,2))}else i.file("test.jsonl",JSON.stringify([r],null,2))}else{const d=i.file("val.jsonl");if(d){const g=await d.async("string").then(u=>JSON.parse(u||"[]")).catch(()=>[]);g.push(r),i.file("val.jsonl",JSON.stringify(g,null,2))}else i.file("val.jsonl",JSON.stringify([r],null,2))}}else{const n=M.map(r=>`images/${r.fileName}`),j={image:n.length===1?n[0]:n,caption:a.edited||a.generated||"",metadata:{image_id:v,title:a.title,source:a.source,event_type:a.event_type,image_type:a.image_type,countries:a.countries,starred:a.starred,image_count:a.image_count||1}};i&&i.file(`${String(O).padStart(4,"0")}.json`,JSON.stringify(j,null,2))}O++}}catch(v){console.error(`Failed to process caption ${a.image_id}:`,v)}}}const A=await o.generateAsync({type:"blob"}),B=URL.createObjectURL(A),P=document.createElement("a");P.href=B,P.download=`datasets_${s}_${new Date().toISOString().split("T")[0]}.zip`,document.body.appendChild(P),P.click(),document.body.removeChild(P),URL.revokeObjectURL(B);const q=(m.length||0)+(_.length||0);console.log(`Exported ${s} datasets with ${q} total images:`),m.length>0&&console.log(`- Crisis maps: ${m.length} images`),_.length>0&&console.log(`- Drone images: ${_.length} images`),ee(!0)}catch(l){console.error("Export failed:",l),alert("Failed to export dataset. Please try again.")}finally{Y(!1)}},ke=e=>{de(e),V(!0)},Pe=async()=>{if(G){me(!0);try{console.log("Deleting image with ID:",G),(await fetch(`/api/images/${G}`,{method:"DELETE"})).ok?(y(s=>s.filter(l=>l.image_id!==G)),V(!1),de("")):(console.error("Delete failed"),alert("Failed to delete image. Please try again."))}catch(e){console.error("Delete failed:",e),alert("Failed to delete image. Please try again.")}finally{me(!1)}}};return t.jsxs(ze,{children:[z?t.jsx("div",{className:"flex flex-col items-center justify-center min-h-[60vh]",children:t.jsxs("div",{className:"flex flex-col items-center gap-4",children:[t.jsx(fe,{className:"text-ifrcRed"}),t.jsx("div",{children:"Loading examples..."})]})}):t.jsxs("div",{className:"max-w-7xl mx-auto",children:[t.jsxs("div",{className:p.tabSelector,children:[t.jsx(We,{name:"explore-view",value:H,onChange:e=>{(e==="explore"||e==="mapDetails")&&(ne(e),e==="mapDetails"&&h.length>0&&(h[0]?.image_id&&h[0].image_id!=="undefined"&&h[0].image_id!=="null"?N(`/map/${h[0].image_id}`):console.error("Invalid image_id for navigation:",h[0]?.image_id)))},options:$e,keySelector:e=>e.key,labelSelector:e=>e.label}),t.jsxs("div",{className:"flex items-center gap-2 ml-auto",children:[t.jsx(b,{withInternalPadding:!0,className:"bg-white/20 backdrop-blur-sm rounded-md p-2",children:t.jsxs(w,{name:"reference-examples",variant:E?"primary":"secondary",onClick:()=>xe(!E),className:"whitespace-nowrap",children:[t.jsx("span",{className:"mr-2",children:E?t.jsx("span",{className:"text-yellow-400",children:"★"}):t.jsx("span",{className:"text-yellow-400",children:"☆"})}),"Reference Examples"]})}),t.jsx(w,{name:"export-dataset",variant:"secondary",onClick:()=>X(!0),children:"Export"})]})]}),H==="explore"?t.jsxs("div",{className:"space-y-6",children:[t.jsx("div",{className:"mb-6 space-y-4",children:t.jsx("div",{className:"flex flex-wrap items-center gap-4",children:t.jsx(b,{withInternalPadding:!0,className:"bg-white/20 backdrop-blur-sm rounded-md p-2 flex-1 min-w-[300px]",children:t.jsx(He,{sources:K,types:Q,regions:le,countries:Ne,imageTypes:re,isLoadingFilters:we})})})}),t.jsxs("div",{className:"space-y-4",children:[t.jsx("div",{className:"flex justify-between items-center",children:t.jsxs("p",{className:"text-sm text-gray-600",children:[k.length," of ",Z," examples"]})}),z&&t.jsx("div",{className:"text-center py-12",children:t.jsxs("div",{className:"flex flex-col items-center gap-4",children:[t.jsx(fe,{className:"text-ifrcRed"}),t.jsx("div",{children:"Loading examples..."})]})}),!z&&te&&t.jsx("div",{className:"text-center py-12",children:t.jsx(b,{withInternalPadding:!0,className:"bg-red-50 border border-red-200 rounded-md max-w-2xl mx-auto",children:t.jsxs("div",{className:"flex flex-col items-center gap-4",children:[t.jsx("div",{className:"text-red-800 font-semibold text-lg",children:"Failed to Load Images"}),t.jsx("div",{className:"text-red-700",children:te}),t.jsx(w,{name:"retry-fetch",variant:"primary",onClick:()=>U(),children:"Retry"})]})})}),!z&&!te&&t.jsxs("div",{className:"space-y-4",children:[k.map(e=>t.jsxs("div",{className:"flex items-center gap-4",children:[t.jsxs("div",{className:`${p.mapItem} flex-1`,onClick:()=>{console.log("ExplorePage: Clicking on image with ID:",e.image_id),console.log("ExplorePage: Image data:",e),e.image_id&&e.image_id!=="undefined"&&e.image_id!=="null"?(console.log("ExplorePage: Navigating to:",`/map/${e.image_id}`),console.log("ExplorePage: Full navigation URL:",`/#/map/${e.image_id}`),N(`/map/${e.image_id}`)):(console.error("Invalid image_id for navigation:",e.image_id),console.error("Full item data:",JSON.stringify(e,null,2)),alert(`Cannot navigate: Invalid image ID (${e.image_id})`))},children:[t.jsx("div",{className:p.mapItemImage,style:{width:"120px",height:"80px"},children:e.thumbnail_url?t.jsxs(t.Fragment,{children:[console.log("ExplorePage: Using thumbnail for fast loading:",e.thumbnail_url),t.jsx("img",{src:e.thumbnail_url,alt:e.file_key,onError:s=>{console.error("ExplorePage: Thumbnail failed to load, falling back to original:",e.thumbnail_url);const l=s.target;e.image_url?l.src=e.image_url:(l.style.display="none",l.parentElement.innerHTML="Img")},onLoad:()=>console.log("ExplorePage: Thumbnail loaded successfully:",e.thumbnail_url)})]}):e.image_url?t.jsxs(t.Fragment,{children:[console.log("ExplorePage: No thumbnail available, using original image:",e.image_url),t.jsx("img",{src:e.image_url,alt:e.file_key,onError:s=>{console.error("ExplorePage: Original image failed to load:",e.image_url);const l=s.target;l.style.display="none",l.parentElement.innerHTML="Img"},onLoad:()=>console.log("ExplorePage: Original image loaded successfully:",e.image_url)})]}):t.jsxs(t.Fragment,{children:[console.log("ExplorePage: No image_url or thumbnail provided for item:",e),"'Img'"]})}),t.jsxs("div",{className:p.mapItemContent,children:[t.jsx("h3",{className:p.mapItemTitle,children:t.jsxs("div",{className:"flex items-center gap-2",children:[t.jsx("span",{children:e.title||"Untitled"}),e.starred&&t.jsx("span",{className:"text-red-500 text-lg",title:"Starred image",children:"★"})]})}),t.jsx("div",{className:p.mapItemMetadata,children:t.jsxs("div",{className:p.metadataTags,children:[e.image_type!=="drone_image"&&t.jsx("span",{className:p.metadataTagSource,children:e.source&&e.source.includes(", ")?e.source.split(", ").map(s=>K.find(l=>l.s_code===s.trim())?.label||s.trim()).join(", "):K.find(s=>s.s_code===e.source)?.label||e.source}),t.jsx("span",{className:p.metadataTagType,children:e.event_type&&e.event_type.includes(", ")?e.event_type.split(", ").map(s=>Q.find(l=>l.t_code===s.trim())?.label||s.trim()).join(", "):Q.find(s=>s.t_code===e.event_type)?.label||e.event_type}),t.jsx("span",{className:p.metadataTag,children:re.find(s=>s.image_type===e.image_type)?.label||e.image_type}),t.jsx("span",{className:p.metadataTag,children:e.model==="manual"?"Manual":"Generated"}),e.image_count&&e.image_count>1&&t.jsxs("span",{className:p.metadataTag,title:`Multi-upload with ${e.image_count} images`,children:["📷 ",e.image_count]}),(!e.image_count||e.image_count<=1)&&t.jsx("span",{className:p.metadataTag,title:"Single Upload",children:"Single"}),e.countries&&e.countries.length>0&&t.jsxs(t.Fragment,{children:[t.jsx("span",{className:p.metadataTag,children:le.find(s=>s.r_code===e.countries[0].r_code)?.label||"Unknown Region"}),t.jsx("span",{className:p.metadataTag,children:e.countries.map(s=>s.label).join(", ")})]})]})})]})]}),$&&t.jsx(b,{withInternalPadding:!0,className:"bg-white/20 backdrop-blur-sm rounded-md p-2",children:t.jsx(w,{name:`delete-${e.image_id}`,variant:"tertiary",size:1,className:"bg-red-50 hover:bg-red-100 text-red-700 border border-red-200 hover:border-red-300",onClick:()=>ke(e.image_id),title:"Delete","aria-label":"Delete saved image",children:t.jsx(Ue,{className:"w-4 h-4"})})})]},e.image_id)),!k.length&&t.jsx("div",{className:"text-center py-12",children:t.jsx("p",{className:"text-gray-500",children:"No examples found."})}),!z&&Z>0&&t.jsx(qe,{currentPage:W,totalPages:Ce,totalItems:Z,itemsPerPage:C,onPageChange:ge})]})]})]}):t.jsx("div",{className:"space-y-6",children:t.jsxs("div",{className:"text-center py-12",children:[t.jsx("p",{className:"text-gray-500",children:"Map Details view coming soon..."}),t.jsx("p",{className:"text-sm text-gray-400 mt-2",children:"This will show detailed information about individual maps"})]})})]}),Ee&&t.jsx("div",{className:p.fullSizeModalOverlay,onClick:()=>V(!1),children:t.jsx("div",{className:p.fullSizeModalContent,onClick:e=>e.stopPropagation(),children:t.jsxs("div",{className:p.ratingWarningContent,children:[t.jsx("h3",{className:p.ratingWarningTitle,children:"Delete Image?"}),t.jsx("p",{className:p.ratingWarningText,children:"This action cannot be undone. Are you sure you want to delete this saved image and all related data?"}),t.jsxs("div",{className:p.ratingWarningButtons,children:[t.jsx(w,{name:"confirm-delete",variant:"secondary",onClick:Pe,disabled:se,children:se?"Deleting...":"Delete"}),t.jsx(w,{name:"cancel-delete",variant:"tertiary",onClick:()=>V(!1),disabled:se,children:"Cancel"})]})]})})}),t.jsx(Ve,{isOpen:Se,onClose:()=>{X(!1),ee(!1),Y(!1)},onExport:(e,s)=>{const l=k.filter(o=>s.includes(o.image_type));Fe(l,e)},filteredCount:k.length,totalCount:Z,hasFilters:!!(F||x||S||T||L||R||J||I||E),crisisMapsCount:k.filter(e=>e.image_type==="crisis_map").length,droneImagesCount:k.filter(e=>e.image_type==="drone_image").length,isLoading:Te,exportSuccess:Ie})]})}export{ft as default}; +const __vite__mapDeps=(i,m=__vite__mapDeps,d=(m.f||(m.f=["assets/jszip.min-Csqqcm8m.js","assets/index-CcfIBRoF.js","assets/index-BzCX1Bzq.css"])))=>i.map(i=>d[i]); +import{j as t,z as b,n as w,v as Oe,w as Me,x as Le,B as Re,r as c,D as Je,N as ze,_ as fe,L as We,F as Ue,G as Ae}from"./index-CcfIBRoF.js";import{u as Be}from"./useAdmin-CrA3XozJ.js";import{F as He,E as Ve}from"./ExportModal-x1pUTnT7.js";const Ge="_paginatorContainer_1l5ti_1",Ze="_paginationControls_1l5ti_19",he={paginatorContainer:Ge,paginationControls:Ze};function qe({currentPage:N,totalPages:f,onPageChange:$,className:H=""}){if(f<=1)return null;const h=(()=>{const y=[];if(f<=5)for(let x=1;x<=f;x++)y.push(x);else{let x=Math.max(1,N-2);const S=Math.min(f,x+5-1);S===f&&(x=Math.max(1,S-5+1));for(let T=x;T<=S;T++)y.push(T)}return y})();return t.jsx("div",{className:`${he.paginatorContainer} ${H}`,children:t.jsxs("div",{className:he.paginationControls,children:[t.jsx(b,{withInternalPadding:!0,className:"bg-white/20 backdrop-blur-sm rounded-md p-2",children:t.jsxs(w,{name:"prev-page",variant:"tertiary",size:1,onClick:()=>$(Math.max(1,N-1)),disabled:N===1,title:"Previous page",children:[t.jsx(Oe,{className:"w-4 h-4"}),t.jsx("span",{className:"hidden sm:inline",children:"Previous"})]})}),t.jsxs("div",{className:"flex items-center gap-1",children:[h[0]>1&&t.jsxs(t.Fragment,{children:[t.jsx(b,{withInternalPadding:!0,className:"bg-white/20 backdrop-blur-sm rounded-md p-2",children:t.jsx(w,{name:"page-1",variant:"tertiary",size:1,onClick:()=>$(1),children:"1"})}),h[0]>2&&t.jsx(b,{withInternalPadding:!0,className:"bg-white/20 backdrop-blur-sm rounded-md p-2",children:t.jsx("span",{className:"px-2 text-gray-500",children:"..."})})]}),h.map(y=>t.jsx(b,{withInternalPadding:!0,className:"bg-white/20 backdrop-blur-sm rounded-md p-2",children:t.jsx(w,{name:`page-${y}`,variant:N===y?"primary":"tertiary",size:1,onClick:()=>$(y),children:y})},y)),h[h.length-1]$(f),children:f})})]})]}),t.jsx(b,{withInternalPadding:!0,className:"bg-white/20 backdrop-blur-sm rounded-md p-2",children:t.jsxs(w,{name:"next-page",variant:"tertiary",size:1,onClick:()=>$(Math.min(f,N+1)),disabled:N===f,title:"Next page",children:[t.jsx("span",{className:"hidden sm:inline",children:"Next"}),t.jsx(Me,{className:"w-4 h-4"})]})})]})})}const Ke="_tabSelector_o9y1f_1",Qe="_metadataTags_o9y1f_8",Xe="_metadataTag_o9y1f_8",Ye="_metadataTagSource_o9y1f_32",et="_metadataTagType_o9y1f_43",tt="_mapItem_o9y1f_54",at="_mapItemImage_o9y1f_72",st="_mapItemContent_o9y1f_92",it="_mapItemTitle_o9y1f_97",nt="_mapItemMetadata_o9y1f_105",lt="_fullSizeModalOverlay_o9y1f_134",rt="_fullSizeModalContent_o9y1f_148",ot="_ratingWarningContent_o9y1f_159",ct="_ratingWarningTitle_o9y1f_165",dt="_ratingWarningText_o9y1f_172",mt="_ratingWarningButtons_o9y1f_179",p={tabSelector:Ke,metadataTags:Qe,metadataTag:Xe,metadataTagSource:Ye,metadataTagType:et,mapItem:tt,mapItemImage:at,mapItemContent:st,mapItemTitle:it,mapItemMetadata:nt,fullSizeModalOverlay:lt,fullSizeModalContent:rt,ratingWarningContent:ot,ratingWarningTitle:ct,ratingWarningText:dt,ratingWarningButtons:mt};function ft(){const N=Le(),f=Re(),{isAuthenticated:$}=Be(),[H,ne]=c.useState("explore"),[h,y]=c.useState([]),{search:F,srcFilter:x,catFilter:S,regionFilter:T,countryFilter:L,imageTypeFilter:R,uploadTypeFilter:J,generatedMethodFilter:I,showReferenceExamples:E,setShowReferenceExamples:xe}=Je(),[K,_e]=c.useState([]),[Q,ye]=c.useState([]),[le,je]=c.useState([]),[Ne,ve]=c.useState([]),[re,be]=c.useState([]),[we,oe]=c.useState(!0),[z,ce]=c.useState(!0),[Se,X]=c.useState(!1),[Te,Y]=c.useState(!1),[Ie,ee]=c.useState(!1),[te,ae]=c.useState(null),[Ee,V]=c.useState(!1),[G,de]=c.useState(""),[se,me]=c.useState(!1),[W,ge]=c.useState(1),[C]=c.useState(10),[Z,pe]=c.useState(0),[Ce,ue]=c.useState(0),$e=[{key:"explore",label:"List"},{key:"mapDetails",label:"Carousel"}],U=c.useCallback(()=>{ce(!0),ae(null);const e=100,s=1,l=new URLSearchParams({page:s.toString(),limit:e.toString(),include_count:"true"});F&&l.append("search",F),x&&l.append("source",x),S&&l.append("event_type",S),T&&l.append("region",T),L&&l.append("country",L),R&&l.append("image_type",R),J&&l.append("upload_type",J),E&&l.append("starred_only","true"),fetch(`/api/images/grouped?${l.toString()}`).then(o=>{if(!o.ok)throw new Error(`Failed to fetch images: ${o.status} ${o.statusText}`);return o.json()}).then(o=>{console.log("ExplorePage: Fetched captions:",{data:o,fetchPage:s,fetchLimit:e,currentPage:W,itemsPerPage:C,generatedMethodFilter:I});let m=[],_=0;if(o.items&&typeof o.total_count=="number")m=o.items,_=m.length;else if(Array.isArray(o))m=o,_=o.length;else throw new Error("Unexpected response format");if(console.log("ExplorePage: After parsing response:",{itemsCount:m.length,totalCount:_,generatedMethodFilter:I,backendTotalCount:o.items?o.total_count:"N/A"}),I){const P=m.length;m=m.filter(q=>I==="manual"?q.model==="manual":I==="generated"?q.model!=="manual":!0),_=m.length,console.log("ExplorePage: After client-side filtering:",{beforeFilterCount:P,afterFilterCount:m.length})}const A=(W-1)*C,B=A+C;m=m.slice(A,B),console.log("ExplorePage: After client-side pagination:",{startIndex:A,endIndex:B,finalItemsCount:m.length,currentPage:W,itemsPerPage:C,totalCount:_,totalPages:Math.ceil(_/C)}),y(m),pe(_),ue(Math.ceil(_/C)),ae(null)}).catch(o=>{console.error("ExplorePage: Error fetching captions:",o),ae(o instanceof Error?o.message:"Failed to load images. Please try again later."),y([]),pe(0),ue(0)}).finally(()=>{ce(!1)})},[W,F,x,S,T,L,R,J,I,E,C]);c.useEffect(()=>{U()},[U]),c.useEffect(()=>{ge(1)},[F,x,S,T,L,R,J,I,E]),c.useEffect(()=>{const e=()=>{document.hidden||U()};return document.addEventListener("visibilitychange",e),()=>{document.removeEventListener("visibilitychange",e)}},[U]),c.useEffect(()=>{new URLSearchParams(f.search).get("export")==="true"&&(X(!0),N("/explore",{replace:!0}))},[f.search,N,F,x,S,T,L,R,I,E]),c.useEffect(()=>{oe(!0),Promise.all([fetch("/api/sources").then(e=>{if(!e.ok)throw new Error(`HTTP ${e.status}: ${e.statusText}`);return e.json()}),fetch("/api/types").then(e=>{if(!e.ok)throw new Error(`HTTP ${e.status}: ${e.statusText}`);return e.json()}),fetch("/api/regions").then(e=>{if(!e.ok)throw new Error(`HTTP ${e.status}: ${e.statusText}`);return e.json()}),fetch("/api/countries").then(e=>{if(!e.ok)throw new Error(`HTTP ${e.status}: ${e.statusText}`);return e.json()}),fetch("/api/image-types").then(e=>{if(!e.ok)throw new Error(`HTTP ${e.status}: ${e.statusText}`);return e.json()})]).then(([e,s,l,o,m])=>{_e(e),ye(s),je(l),ve(o),be(m)}).catch(()=>{}).finally(()=>{oe(!1)})},[]);const k=h,Fe=async(e,s="fine-tuning")=>{if(e.length===0){alert("No images to export");return}Y(!0),ee(!1);try{const l=(await Ae(async()=>{const{default:i}=await import("./jszip.min-Csqqcm8m.js").then(D=>D.j);return{default:i}},__vite__mapDeps([0,1,2]))).default,o=new l,m=e.filter(i=>i.image_type==="crisis_map"),_=e.filter(i=>i.image_type==="drone_image");if(m.length>0){const i=o.folder("crisis_maps_dataset"),D=i?.folder("images");if(D){let O=1;for(const a of m)try{const v=a.image_count&&a.image_count>1?a.all_image_ids||[a.image_id]:[a.image_id],ie=v.map(async(n,j)=>{try{const r=await fetch(`/api/images/${n}/file`);if(!r.ok)throw new Error(`Failed to fetch image ${n}`);const d=await r.blob(),g=a.file_key.split(".").pop()||"jpg",u=`${String(O).padStart(4,"0")}_${String(j+1).padStart(2,"0")}.${g}`;return D.file(u,d),{success:!0,fileName:u,imageId:n}}catch(r){return console.error(`Failed to process image ${n}:`,r),{success:!1,fileName:"",imageId:n}}}),M=(await Promise.all(ie)).filter(n=>n.success);if(M.length>0){if(s==="fine-tuning"){const n=M.map(d=>`images/${d.fileName}`),j=Math.random(),r={image:n.length===1?n[0]:n,caption:a.edited||a.generated||"",metadata:{image_id:v,title:a.title,source:a.source,event_type:a.event_type,image_type:a.image_type,countries:a.countries,starred:a.starred,image_count:a.image_count||1}};if(!i)continue;if(j<.8){const d=i.file("train.jsonl");if(d){const g=await d.async("string").then(u=>JSON.parse(u||"[]")).catch(()=>[]);g.push(r),i.file("train.jsonl",JSON.stringify(g,null,2))}else i.file("train.jsonl",JSON.stringify([r],null,2))}else if(j<.9){const d=i.file("test.jsonl");if(d){const g=await d.async("string").then(u=>JSON.parse(u||"[]")).catch(()=>[]);g.push(r),i.file("test.jsonl",JSON.stringify(g,null,2))}else i.file("test.jsonl",JSON.stringify([r],null,2))}else{const d=i.file("val.jsonl");if(d){const g=await d.async("string").then(u=>JSON.parse(u||"[]")).catch(()=>[]);g.push(r),i.file("val.jsonl",JSON.stringify(g,null,2))}else i.file("val.jsonl",JSON.stringify([r],null,2))}}else{const n=M.map(r=>`images/${r.fileName}`),j={image:n.length===1?n[0]:n,caption:a.edited||a.generated||"",metadata:{image_id:v,title:a.title,source:a.source,event_type:a.event_type,image_type:a.image_type,countries:a.countries,starred:a.starred,image_count:a.image_count||1}};i&&i.file(`${String(O).padStart(4,"0")}.json`,JSON.stringify(j,null,2))}O++}}catch(v){console.error(`Failed to process caption ${a.image_id}:`,v)}}}if(_.length>0){const i=o.folder("drone_images_dataset"),D=i?.folder("images");if(D){let O=1;for(const a of _)try{const v=a.image_count&&a.image_count>1?a.all_image_ids||[a.image_id]:[a.image_id],ie=v.map(async(n,j)=>{try{const r=await fetch(`/api/images/${n}/file`);if(!r.ok)throw new Error(`Failed to fetch image ${n}`);const d=await r.blob(),g=a.file_key.split(".").pop()||"jpg",u=`${String(O).padStart(4,"0")}_${String(j+1).padStart(2,"0")}.${g}`;return D.file(u,d),{success:!0,fileName:u,imageId:n}}catch(r){return console.error(`Failed to process image ${n}:`,r),{success:!1,fileName:"",imageId:n}}}),M=(await Promise.all(ie)).filter(n=>n.success);if(M.length>0){if(s==="fine-tuning"){const n=M.map(d=>`images/${d.fileName}`),j=Math.random(),r={image:n.length===1?n[0]:n,caption:a.edited||a.generated||"",metadata:{image_id:v,title:a.title,source:a.source,event_type:a.event_type,image_type:a.image_type,countries:a.countries,starred:a.starred,image_count:a.image_count||1}};if(!i)continue;if(j<.8){const d=i.file("train.jsonl");if(d){const g=await d.async("string").then(u=>JSON.parse(u||"[]")).catch(()=>[]);g.push(r),i.file("train.jsonl",JSON.stringify(g,null,2))}else i.file("train.jsonl",JSON.stringify([r],null,2))}else if(j<.9){const d=i.file("test.jsonl");if(d){const g=await d.async("string").then(u=>JSON.parse(u||"[]")).catch(()=>[]);g.push(r),i.file("test.jsonl",JSON.stringify(g,null,2))}else i.file("test.jsonl",JSON.stringify([r],null,2))}else{const d=i.file("val.jsonl");if(d){const g=await d.async("string").then(u=>JSON.parse(u||"[]")).catch(()=>[]);g.push(r),i.file("val.jsonl",JSON.stringify(g,null,2))}else i.file("val.jsonl",JSON.stringify([r],null,2))}}else{const n=M.map(r=>`images/${r.fileName}`),j={image:n.length===1?n[0]:n,caption:a.edited||a.generated||"",metadata:{image_id:v,title:a.title,source:a.source,event_type:a.event_type,image_type:a.image_type,countries:a.countries,starred:a.starred,image_count:a.image_count||1}};i&&i.file(`${String(O).padStart(4,"0")}.json`,JSON.stringify(j,null,2))}O++}}catch(v){console.error(`Failed to process caption ${a.image_id}:`,v)}}}const A=await o.generateAsync({type:"blob"}),B=URL.createObjectURL(A),P=document.createElement("a");P.href=B,P.download=`datasets_${s}_${new Date().toISOString().split("T")[0]}.zip`,document.body.appendChild(P),P.click(),document.body.removeChild(P),URL.revokeObjectURL(B);const q=(m.length||0)+(_.length||0);console.log(`Exported ${s} datasets with ${q} total images:`),m.length>0&&console.log(`- Crisis maps: ${m.length} images`),_.length>0&&console.log(`- Drone images: ${_.length} images`),ee(!0)}catch(l){console.error("Export failed:",l),alert("Failed to export dataset. Please try again.")}finally{Y(!1)}},ke=e=>{de(e),V(!0)},Pe=async()=>{if(G){me(!0);try{console.log("Deleting image with ID:",G),(await fetch(`/api/images/${G}`,{method:"DELETE"})).ok?(y(s=>s.filter(l=>l.image_id!==G)),V(!1),de("")):(console.error("Delete failed"),alert("Failed to delete image. Please try again."))}catch(e){console.error("Delete failed:",e),alert("Failed to delete image. Please try again.")}finally{me(!1)}}};return t.jsxs(ze,{children:[z?t.jsx("div",{className:"flex flex-col items-center justify-center min-h-[60vh]",children:t.jsxs("div",{className:"flex flex-col items-center gap-4",children:[t.jsx(fe,{className:"text-ifrcRed"}),t.jsx("div",{children:"Loading examples..."})]})}):t.jsxs("div",{className:"max-w-7xl mx-auto",children:[t.jsxs("div",{className:p.tabSelector,children:[t.jsx(We,{name:"explore-view",value:H,onChange:e=>{(e==="explore"||e==="mapDetails")&&(ne(e),e==="mapDetails"&&h.length>0&&(h[0]?.image_id&&h[0].image_id!=="undefined"&&h[0].image_id!=="null"?N(`/map/${h[0].image_id}`):console.error("Invalid image_id for navigation:",h[0]?.image_id)))},options:$e,keySelector:e=>e.key,labelSelector:e=>e.label}),t.jsxs("div",{className:"flex items-center gap-2 ml-auto",children:[t.jsx(b,{withInternalPadding:!0,className:"bg-white/20 backdrop-blur-sm rounded-md p-2",children:t.jsxs(w,{name:"reference-examples",variant:E?"primary":"secondary",onClick:()=>xe(!E),className:"whitespace-nowrap",children:[t.jsx("span",{className:"mr-2",children:E?t.jsx("span",{className:"text-yellow-400",children:"★"}):t.jsx("span",{className:"text-yellow-400",children:"☆"})}),"Reference Examples"]})}),t.jsx(w,{name:"export-dataset",variant:"secondary",onClick:()=>X(!0),children:"Export"})]})]}),H==="explore"?t.jsxs("div",{className:"space-y-6",children:[t.jsx("div",{className:"mb-6 space-y-4",children:t.jsx("div",{className:"flex flex-wrap items-center gap-4",children:t.jsx(b,{withInternalPadding:!0,className:"bg-white/20 backdrop-blur-sm rounded-md p-2 flex-1 min-w-[300px]",children:t.jsx(He,{sources:K,types:Q,regions:le,countries:Ne,imageTypes:re,isLoadingFilters:we})})})}),t.jsxs("div",{className:"space-y-4",children:[t.jsx("div",{className:"flex justify-between items-center",children:t.jsxs("p",{className:"text-sm text-gray-600",children:[k.length," of ",Z," examples"]})}),z&&t.jsx("div",{className:"text-center py-12",children:t.jsxs("div",{className:"flex flex-col items-center gap-4",children:[t.jsx(fe,{className:"text-ifrcRed"}),t.jsx("div",{children:"Loading examples..."})]})}),!z&&te&&t.jsx("div",{className:"text-center py-12",children:t.jsx(b,{withInternalPadding:!0,className:"bg-red-50 border border-red-200 rounded-md max-w-2xl mx-auto",children:t.jsxs("div",{className:"flex flex-col items-center gap-4",children:[t.jsx("div",{className:"text-red-800 font-semibold text-lg",children:"Failed to Load Images"}),t.jsx("div",{className:"text-red-700",children:te}),t.jsx(w,{name:"retry-fetch",variant:"primary",onClick:()=>U(),children:"Retry"})]})})}),!z&&!te&&t.jsxs("div",{className:"space-y-4",children:[k.map(e=>t.jsxs("div",{className:"flex items-center gap-4",children:[t.jsxs("div",{className:`${p.mapItem} flex-1`,onClick:()=>{console.log("ExplorePage: Clicking on image with ID:",e.image_id),console.log("ExplorePage: Image data:",e),e.image_id&&e.image_id!=="undefined"&&e.image_id!=="null"?(console.log("ExplorePage: Navigating to:",`/map/${e.image_id}`),console.log("ExplorePage: Full navigation URL:",`/#/map/${e.image_id}`),N(`/map/${e.image_id}`)):(console.error("Invalid image_id for navigation:",e.image_id),console.error("Full item data:",JSON.stringify(e,null,2)),alert(`Cannot navigate: Invalid image ID (${e.image_id})`))},children:[t.jsx("div",{className:p.mapItemImage,style:{width:"120px",height:"80px"},children:e.thumbnail_url?t.jsxs(t.Fragment,{children:[console.log("ExplorePage: Using thumbnail for fast loading:",e.thumbnail_url),t.jsx("img",{src:e.thumbnail_url,alt:e.file_key,onError:s=>{console.error("ExplorePage: Thumbnail failed to load, falling back to original:",e.thumbnail_url);const l=s.target;e.image_url?l.src=e.image_url:(l.style.display="none",l.parentElement.innerHTML="Img")},onLoad:()=>console.log("ExplorePage: Thumbnail loaded successfully:",e.thumbnail_url)})]}):e.image_url?t.jsxs(t.Fragment,{children:[console.log("ExplorePage: No thumbnail available, using original image:",e.image_url),t.jsx("img",{src:e.image_url,alt:e.file_key,onError:s=>{console.error("ExplorePage: Original image failed to load:",e.image_url);const l=s.target;l.style.display="none",l.parentElement.innerHTML="Img"},onLoad:()=>console.log("ExplorePage: Original image loaded successfully:",e.image_url)})]}):t.jsxs(t.Fragment,{children:[console.log("ExplorePage: No image_url or thumbnail provided for item:",e),"'Img'"]})}),t.jsxs("div",{className:p.mapItemContent,children:[t.jsx("h3",{className:p.mapItemTitle,children:t.jsxs("div",{className:"flex items-center gap-2",children:[t.jsx("span",{children:e.title||"Untitled"}),e.starred&&t.jsx("span",{className:"text-red-500 text-lg",title:"Starred image",children:"★"})]})}),t.jsx("div",{className:p.mapItemMetadata,children:t.jsxs("div",{className:p.metadataTags,children:[e.image_type!=="drone_image"&&t.jsx("span",{className:p.metadataTagSource,children:e.source&&e.source.includes(", ")?e.source.split(", ").map(s=>K.find(l=>l.s_code===s.trim())?.label||s.trim()).join(", "):K.find(s=>s.s_code===e.source)?.label||e.source}),t.jsx("span",{className:p.metadataTagType,children:e.event_type&&e.event_type.includes(", ")?e.event_type.split(", ").map(s=>Q.find(l=>l.t_code===s.trim())?.label||s.trim()).join(", "):Q.find(s=>s.t_code===e.event_type)?.label||e.event_type}),t.jsx("span",{className:p.metadataTag,children:re.find(s=>s.image_type===e.image_type)?.label||e.image_type}),t.jsx("span",{className:p.metadataTag,children:e.model==="manual"?"Manual":"Generated"}),e.image_count&&e.image_count>1&&t.jsxs("span",{className:p.metadataTag,title:`Multi-upload with ${e.image_count} images`,children:["📷 ",e.image_count]}),(!e.image_count||e.image_count<=1)&&t.jsx("span",{className:p.metadataTag,title:"Single Upload",children:"Single"}),e.countries&&e.countries.length>0&&t.jsxs(t.Fragment,{children:[t.jsx("span",{className:p.metadataTag,children:le.find(s=>s.r_code===e.countries[0].r_code)?.label||"Unknown Region"}),t.jsx("span",{className:p.metadataTag,children:e.countries.map(s=>s.label).join(", ")})]})]})})]})]}),$&&t.jsx(b,{withInternalPadding:!0,className:"bg-white/20 backdrop-blur-sm rounded-md p-2",children:t.jsx(w,{name:`delete-${e.image_id}`,variant:"tertiary",size:1,className:"bg-red-50 hover:bg-red-100 text-red-700 border border-red-200 hover:border-red-300",onClick:()=>ke(e.image_id),title:"Delete","aria-label":"Delete saved image",children:t.jsx(Ue,{className:"w-4 h-4"})})})]},e.image_id)),!k.length&&t.jsx("div",{className:"text-center py-12",children:t.jsx("p",{className:"text-gray-500",children:"No examples found."})}),!z&&Z>0&&t.jsx(qe,{currentPage:W,totalPages:Ce,totalItems:Z,itemsPerPage:C,onPageChange:ge})]})]})]}):t.jsx("div",{className:"space-y-6",children:t.jsxs("div",{className:"text-center py-12",children:[t.jsx("p",{className:"text-gray-500",children:"Map Details view coming soon..."}),t.jsx("p",{className:"text-sm text-gray-400 mt-2",children:"This will show detailed information about individual maps"})]})})]}),Ee&&t.jsx("div",{className:p.fullSizeModalOverlay,onClick:()=>V(!1),children:t.jsx("div",{className:p.fullSizeModalContent,onClick:e=>e.stopPropagation(),children:t.jsxs("div",{className:p.ratingWarningContent,children:[t.jsx("h3",{className:p.ratingWarningTitle,children:"Delete Image?"}),t.jsx("p",{className:p.ratingWarningText,children:"This action cannot be undone. Are you sure you want to delete this saved image and all related data?"}),t.jsxs("div",{className:p.ratingWarningButtons,children:[t.jsx(w,{name:"confirm-delete",variant:"secondary",onClick:Pe,disabled:se,children:se?"Deleting...":"Delete"}),t.jsx(w,{name:"cancel-delete",variant:"tertiary",onClick:()=>V(!1),disabled:se,children:"Cancel"})]})]})})}),t.jsx(Ve,{isOpen:Se,onClose:()=>{X(!1),ee(!1),Y(!1)},onExport:(e,s)=>{const l=k.filter(o=>s.includes(o.image_type));Fe(l,e)},filteredCount:k.length,totalCount:Z,hasFilters:!!(F||x||S||T||L||R||J||I||E),crisisMapsCount:k.filter(e=>e.image_type==="crisis_map").length,droneImagesCount:k.filter(e=>e.image_type==="drone_image").length,isLoading:Te,exportSuccess:Ie})]})}export{ft as default}; diff --git a/py_backend/static/assets/index-vuiGcTrC.js b/py_backend/static/assets/index-Bx3ZvIBj.js similarity index 99% rename from py_backend/static/assets/index-vuiGcTrC.js rename to py_backend/static/assets/index-Bx3ZvIBj.js index d607723d..d367123e 100644 --- a/py_backend/static/assets/index-vuiGcTrC.js +++ b/py_backend/static/assets/index-Bx3ZvIBj.js @@ -1,2 +1,2 @@ -const __vite__mapDeps=(i,m=__vite__mapDeps,d=(m.f||(m.f=["assets/jszip.min-D6OY4_4u.js","assets/index-Rlfiitbv.js","assets/index-BzCX1Bzq.css"])))=>i.map(i=>d[i]); -import{K as aa,x as ta,r as d,D as sa,j as a,N as ae,n as F,_ as Ie,L as ia,z as P,v as oe,w as re,F as na,M as oa,G as ra}from"./index-Rlfiitbv.js";import{u as la}from"./useAdmin-CnId_VLW.js";import{F as ca,E as da}from"./ExportModal-CGhKFoOs.js";const ga="_tabSelector_usssr_1",ma="_imageContainer_usssr_12",ua="_imagePlaceholder_usssr_33",pa="_metadataTags_usssr_45",fa="_metadataTag_usssr_45",ha="_captionContainer_usssr_67",_a="_captionText_usssr_74",xa="_gridLayout_usssr_131",ya="_detailsSection_usssr_155",va="_loadingContainer_usssr_161",ja="_errorContainer_usssr_171",wa="_fullSizeModalOverlay_usssr_205",Ia="_fullSizeModalContent_usssr_219",Na="_ratingWarningContent_usssr_230",Ca="_ratingWarningTitle_usssr_236",ba="_ratingWarningText_usssr_243",Sa="_ratingWarningButtons_usssr_250",ka="_carouselContainer_usssr_365",Da="_carouselImageWrapper_usssr_370",Ma="_carouselImage_usssr_370",La="_carouselNavigation_usssr_393",Fa="_carouselButton_usssr_405",Ta="_carouselIndicators_usssr_429",Ea="_carouselIndicator_usssr_429",$a="_carouselIndicatorActive_usssr_458",Pa="_singleImageContainer_usssr_488",Ra="_viewImageButtonContainer_usssr_494",m={tabSelector:ga,imageContainer:ma,imagePlaceholder:ua,metadataTags:pa,metadataTag:fa,captionContainer:ha,captionText:_a,gridLayout:xa,detailsSection:ya,loadingContainer:va,errorContainer:ja,fullSizeModalOverlay:wa,fullSizeModalContent:Ia,ratingWarningContent:Na,ratingWarningTitle:Ca,ratingWarningText:ba,ratingWarningButtons:Sa,carouselContainer:ka,carouselImageWrapper:Da,carouselImage:Ma,carouselNavigation:La,carouselButton:Fa,carouselIndicators:Ta,carouselIndicator:Ea,carouselIndicatorActive:$a,singleImageContainer:Pa,viewImageButtonContainer:Ra};function it(){const{mapId:u}=aa(),y=ta(),{isAuthenticated:le}=la(),[ce,Ne]=d.useState("mapDetails"),[e,te]=d.useState(null),[O,A]=d.useState(!0),[de,U]=d.useState(null),[ge,Ce]=d.useState([]),[me,be]=d.useState([]),[ue,Se]=d.useState([]),[pe,ke]=d.useState([]),[De,Me]=d.useState([]),[Le,Fe]=d.useState(!1),[Te,Ee]=d.useState(!1),[J,K]=d.useState(!1),[$e,Z]=d.useState(!1),[fe,Q]=d.useState(!1),[Pe,se]=d.useState(!1),[Re,ie]=d.useState(!1),[Aa,za]=d.useState("standard"),[R,Oa]=d.useState(80),[G,Ua]=d.useState(10),[Ba,Wa]=d.useState(10),[Ja,Ga]=d.useState(!0),[Va,Ha]=d.useState(!0),[B,X]=d.useState(!1),[Ae,he]=d.useState(!1),[ze,_e]=d.useState(null),[Oe,V]=d.useState(!1),[x,H]=d.useState([]),[L,z]=d.useState(0),[q,xe]=d.useState(!1),{search:p,setSearch:qa,srcFilter:v,setSrcFilter:Ka,catFilter:j,setCatFilter:Za,regionFilter:w,setRegionFilter:Qa,countryFilter:I,setCountryFilter:Xa,imageTypeFilter:N,setImageTypeFilter:Ya,uploadTypeFilter:C,setUploadTypeFilter:et,generatedMethodFilter:f,showReferenceExamples:k,setShowReferenceExamples:Ue,clearAllFilters:Be}=sa(),We=[{key:"explore",label:"List"},{key:"mapDetails",label:"Carousel"}],Y=d.useCallback(async t=>{if(!(!t||t==="undefined"||t==="null"||t.trim()===""))try{const i=new URLSearchParams;p&&i.append("search",p),v&&i.append("source",v),j&&i.append("event_type",j),w&&i.append("region",w),I&&i.append("country",I),N&&i.append("image_type",N),C&&i.append("upload_type",C),k&&i.append("starred_only","true");const l=await fetch(`/api/images/grouped?${i.toString()}`);if(l.ok){let s=await l.json();s.items&&(s=s.items),f&&(s=s.filter(o=>f==="manual"?o.model==="manual":f==="generated"?o.model!=="manual":!0)),console.log("Server response for upload_type=multiple:",{url:`/api/images/grouped?${i.toString()}`,count:s.length,images:s.map(o=>({image_id:o.image_id,image_count:o.image_count,all_image_ids:o.all_image_ids,all_image_ids_length:o.all_image_ids?.length}))});const n=s.findIndex(o=>o.image_id===t);console.log("Navigation availability check (server-side):",{filteredImagesCount:s.length,currentIndex:n,currentId:t,uploadTypeFilter:C,hasPrevious:s.length>1&&n>0,hasNext:s.length>1&&n({image_id:o.image_id,image_count:o.image_count,all_image_ids:o.all_image_ids,image_type:o.image_type}))}),Fe(s.length>1&&n>0),Ee(s.length>1&&n{console.log("fetchAllImages called with imageIds:",t),xe(!0);try{const i=t.map(async s=>{const n=await fetch(`/api/images/${s}`);if(!n.ok)throw new Error(`Failed to fetch image ${s}`);return n.json()}),l=await Promise.all(i);H(l),z(0),console.log("fetchAllImages: Loaded",l.length,"images")}catch(i){console.error("fetchAllImages error:",i),U(i instanceof Error?i.message:"Failed to load all images")}finally{xe(!1)}},[]),ye=d.useCallback(async t=>{if(console.log("fetchMapData called with id:",t),console.log("fetchMapData id type:",typeof t),!t||t==="undefined"||t==="null"||t.trim()===""){console.log("fetchMapData: Invalid ID detected:",t),U("Invalid Map ID"),A(!1);return}if(!/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i.test(t)){console.log("fetchMapData: Invalid UUID format:",t),U("Invalid Map ID format"),A(!1);return}console.log("fetchMapData: Making API call for id:",t),K(!0),A(!0);try{const l=await fetch(`/api/images/${t}`);if(!l.ok)throw new Error("Map not found");const s=await l.json();if(te(s),s.all_image_ids&&s.all_image_ids.length>1)await ne(s.all_image_ids);else if(s.image_count&&s.image_count>1){console.log("Multi-upload detected but no all_image_ids, trying grouped endpoint");try{const n=await fetch("/api/images/grouped");if(n.ok){const r=(await n.json()).find(g=>g.all_image_ids&&g.all_image_ids.includes(s.image_id));r&&r.all_image_ids?await ne(r.all_image_ids):(H([s]),z(0))}else H([s]),z(0)}catch(n){console.error("Failed to fetch from grouped endpoint:",n),H([s]),z(0)}}else H([s]),z(0);await Y(t)}catch(l){U(l instanceof Error?l.message:"Unknown error occurred")}finally{A(!1),K(!1)}},[Y,ne]),Je=d.useCallback(()=>{x.length>1&&z(t=>t>0?t-1:x.length-1)},[x.length]),Ge=d.useCallback(()=>{x.length>1&&z(t=>t{t>=0&&t{const i=t||(x.length>0?x[L]:e);if(i){V(!0),_e(i),he(!0);try{const l=new Image;l.onload=()=>{V(!1)},l.onerror=()=>{V(!1)},l.src=i.image_url}catch(l){console.error("Error preloading full-size image:",l),V(!1)}}},[x,L,e]),He=d.useCallback(()=>{he(!1),_e(null),V(!1)},[]);d.useEffect(()=>{if(console.log("MapDetailsPage: mapId from useParams:",u),console.log("MapDetailsPage: mapId type:",typeof u),console.log("MapDetailsPage: mapId value:",u),!u||u==="undefined"||u==="null"||u.trim()===""||u===void 0||u===null){console.log("MapDetailsPage: Invalid mapId, setting error"),U("Map ID is required"),A(!1);return}if(!/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i.test(u)){console.log("MapDetailsPage: Invalid UUID format:",u),U("Invalid Map ID format"),A(!1);return}console.log("MapDetailsPage: Fetching data for mapId:",u),ye(u)},[u,ye]),d.useEffect(()=>{if(!e||O||B)return;if(!u||u==="undefined"||u==="null"||u.trim()===""){console.log("Auto-navigation skipped: Invalid mapId");return}if(!/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i.test(u)){console.log("Auto-navigation skipped: Invalid mapId format");return}(()=>{const l=!p||e.title?.toLowerCase().includes(p.toLowerCase())||e.generated?.toLowerCase().includes(p.toLowerCase())||e.source?.toLowerCase().includes(p.toLowerCase())||e.event_type?.toLowerCase().includes(p.toLowerCase()),s=!v||e.source===v,n=!j||e.event_type===j,o=!w||e.countries.some(M=>M.r_code===w),r=!I||e.countries.some(M=>M.c_code===I),g=!N||e.image_type===N,_=!f||f==="manual"&&e.model==="manual"||f==="generated"&&e.model!=="manual",T=!k||e.starred===!0,E=l&&s&&n&&o&&r&&g&&_&&T;return console.log("Auto-navigation check:",{mapId:u,search:p,srcFilter:v,catFilter:j,regionFilter:w,countryFilter:I,imageTypeFilter:N,generatedMethodFilter:f,showReferenceExamples:k,matchesSearch:l,matchesSource:s,matchesCategory:n,matchesRegion:o,matchesCountry:r,matchesImageType:g,matchesReferenceExamples:T,matches:E}),E})()||(console.log("Current map does not match filters, looking for first matching item"),fetch("/api/images").then(l=>l.json()).then(l=>{console.log("Auto-navigation: Received images from API:",l.length),console.log("Auto-navigation: First few images:",l.slice(0,3).map(n=>({image_id:n.image_id,title:n.title})));const s=l.find(n=>{const o=!p||n.title?.toLowerCase().includes(p.toLowerCase())||n.generated?.toLowerCase().includes(p.toLowerCase())||n.source?.toLowerCase().includes(p.toLowerCase())||n.event_type?.toLowerCase().includes(p.toLowerCase()),r=!v||n.source===v,g=!j||n.event_type===j,_=!w||n.countries?.some(S=>S.r_code===w),T=!I||n.countries?.some(S=>S.c_code===I),E=!N||n.image_type===N,M=!f||f==="manual"&&n.model==="manual"||f==="generated"&&n.model!=="manual",h=!k||n.starred===!0;return o&&r&&g&&_&&T&&E&&M&&h});console.log("Auto-navigation: Found first matching image:",s?{image_id:s.image_id,title:s.title,source:s.source}:"No matching image found"),s&&s.image_id&&s.image_id!=="undefined"&&s.image_id!=="null"&&s.image_id.trim()!==""&&s.image_id!==u&&(/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i.test(s.image_id)?(console.log("Auto-navigating to:",s.image_id),y(`/map/${s.image_id}`)):console.error("Auto-navigation blocked: Invalid image_id format:",s.image_id))}).catch(console.error))},[e,p,v,j,w,I,N,f,k,u,y,O,B]);const je=async t=>{if(!J){K(!0);try{const i=new URLSearchParams;p&&i.append("search",p),v&&i.append("source",v),j&&i.append("event_type",j),w&&i.append("region",w),I&&i.append("country",I),N&&i.append("image_type",N),C&&i.append("upload_type",C),k&&i.append("starred_only","true");const l=await fetch(`/api/images/grouped?${i.toString()}`);if(l.ok){let s=await l.json();s.items&&(s=s.items),f&&(s=s.filter(g=>f==="manual"?g.model==="manual":f==="generated"?g.model!=="manual":!0));const n=s.findIndex(g=>g.image_id===u);if(n===-1){console.error("Current image not found in filtered list");return}let o;t==="previous"?o=n>0?n-1:s.length-1:o=n{console.log("=== NAVIGATION USEEFFECT TRIGGERED ==="),console.log("Navigation useEffect triggered:",{map:!!e,mapId:u,loading:O,isDeleting:B,uploadTypeFilter:C,allFilters:{search:p,srcFilter:v,catFilter:j,regionFilter:w,countryFilter:I,imageTypeFilter:N,uploadTypeFilter:C,generatedMethodFilter:f,showReferenceExamples:k}}),e&&u&&!O&&!B?(console.log("Calling checkNavigationAvailability with:",u),Y(u)):console.log("NOT calling checkNavigationAvailability because:",{map:!!e,mapId:!!u,loading:O,isDeleting:B})},[e,u,p,v,j,w,I,N,C,f,k,O,B,Y]),d.useEffect(()=>{Promise.all([fetch("/api/sources").then(t=>t.json()),fetch("/api/types").then(t=>t.json()),fetch("/api/image-types").then(t=>t.json()),fetch("/api/regions").then(t=>t.json()),fetch("/api/countries").then(t=>t.json())]).then(([t,i,l,s,n])=>{Ce(t),be(i),Se(l),ke(s),Me(n)}).catch(console.error)},[]);const qe=async()=>{e&&Z(!0)},Ke=async()=>{if(e)try{(await fetch(`/api/images/${e.image_id}`,{method:"PUT",headers:{"Content-Type":"application/json"},body:JSON.stringify({starred:!e.starred})})).ok?te(i=>i?{...i,starred:!i.starred}:null):console.error("Failed to toggle starred status")}catch(t){console.error("Error toggling starred status:",t)}},Ze=async()=>{if(e){X(!0);try{if(console.log("Deleting image with ID:",e.image_id),(await fetch(`/api/images/${e.image_id}`,{method:"DELETE"})).ok){te(i=>i?{...i,starred:!i.starred}:null),Z(!1);try{const i=await fetch("/api/images/grouped");if(i.ok){const s=(await i.json()).filter(o=>{const r=!p||o.title?.toLowerCase().includes(p.toLowerCase())||o.generated?.toLowerCase().includes(p.toLowerCase())||o.source?.toLowerCase().includes(p.toLowerCase())||o.event_type?.toLowerCase().includes(p.toLowerCase()),g=!v||o.source===v,_=!j||o.event_type===j,T=!w||o.countries?.some(b=>b.r_code===w),E=!I||o.countries?.some(b=>b.c_code===I),M=!N||o.image_type===N,h=!C||C==="single"&&(!o.image_count||o.image_count<=1)||C==="multiple"&&o.image_count&&o.image_count>1,S=!f||f==="manual"&&o.model==="manual"||f==="generated"&&o.model!=="manual",D=!k||o.starred===!0;return r&&g&&_&&T&&E&&M&&h&&S&&D}),n=s.filter(o=>o.image_id!==e.image_id);if(n.length>0){const o=s.findIndex(g=>g.image_id===e.image_id);let r;if(o===s.length-1?r=o-1:r=o,console.log("Navigation target:",{currentIndex:o,targetIndex:r,targetId:n[r]?.image_id}),r>=0&&r{A(!0);try{const t=new URLSearchParams;p&&t.append("search",p),v&&t.append("source",v),j&&t.append("event_type",j),w&&t.append("region",w),I&&t.append("country",I),N&&t.append("image_type",N),C&&t.append("upload_type",C),k&&t.append("starred_only","true");const i=await fetch(`/api/images/grouped?${t.toString()}`);if(i.ok){let l=await i.json();if(l.items&&(l=l.items),f&&(l=l.filter(s=>f==="manual"?s.model==="manual":f==="generated"?s.model!=="manual":!0)),l.length>0){const s=l[0];s&&s.image_id&&y(`/map/${s.image_id}`)}else y("/explore")}}catch(t){console.error("Failed to navigate to matching image:",t),y("/explore")}finally{A(!1)}},[p,v,j,w,I,N,C,f,k,y]),c=d.useMemo(()=>{if(!e)return null;if(!p&&!v&&!j&&!w&&!I&&!N&&!C&&!f&&!k)return e;const t=!p||e.title?.toLowerCase().includes(p.toLowerCase())||e.generated?.toLowerCase().includes(p.toLowerCase())||e.source?.toLowerCase().includes(p.toLowerCase())||e.event_type?.toLowerCase().includes(p.toLowerCase()),i=!v||e.source===v,l=!j||e.event_type===j,s=!w||e.countries.some(E=>E.r_code===w),n=!I||e.countries.some(E=>E.c_code===I),o=!N||e.image_type===N,r=!C||C==="single"&&(!e.image_count||e.image_count<=1)&&(!e.all_image_ids||e.all_image_ids.length<=1)||C==="multiple"&&(e.image_count&&e.image_count>1||e.all_image_ids&&e.all_image_ids.length>1),g=!f||f==="manual"&&e.model==="manual"||f==="generated"&&e.model!=="manual",_=!k||e.starred===!0,T=t&&i&&l&&s&&n&&o&&r&&g&&_;return!T&&(p||v||j||w||I||N||C||f||k)?(setTimeout(()=>{we()},100),e):T?e:null},[e,p,v,j,w,I,N,C,f,k,we]),Qe=()=>{if(!e)return;if(!e.all_image_ids||e.all_image_ids.length<=1){const s=`/upload?step=1&contribute=true&imageIds=${[e.image_id].join(",")}`;y(s);return}const i=`/upload?step=1&contribute=true&imageIds=${e.all_image_ids.join(",")}`;y(i)},$=(t,i)=>({image:`images/${i}`,caption:t.edited||t.generated||"",metadata:{image_id:t.image_count&&t.image_count>1?t.all_image_ids||[t.image_id]:t.image_id,title:t.title,source:t.source,event_type:t.event_type,image_type:t.image_type,countries:t.countries,starred:t.starred,image_count:t.image_count||1}}),Xe=async t=>{if(e){se(!0),ie(!1);try{const i=(await ra(async()=>{const{default:r}=await import("./jszip.min-D6OY4_4u.js").then(g=>g.j);return{default:r}},__vite__mapDeps([0,1,2]))).default,l=new i;if(e.image_type==="crisis_map"){const r=l.folder("crisis_maps_dataset"),g=r?.folder("images");if(g)try{const _=e.image_count&&e.image_count>1?e.all_image_ids||[e.image_id]:[e.image_id],T=_.map(async(h,S)=>{try{const D=await fetch(`/api/images/${h}/file`);if(!D.ok)throw new Error(`Failed to fetch image ${h}`);const b=await D.blob(),ee=e.file_key.split(".").pop()||"jpg",W=`0001_${String(S+1).padStart(2,"0")}.${ee}`;return g.file(W,b),{success:!0,fileName:W,imageId:h}}catch(D){return console.error(`Failed to process image ${h}:`,D),{success:!1,fileName:"",imageId:h}}}),M=(await Promise.all(T)).filter(h=>h.success);if(M.length===0)throw new Error("No images could be processed");if(t==="fine-tuning"){const h=[],S=[],D=[],b=M.map(ea=>`images/${ea.fileName}`),ee=Math.random(),W={image:b.length===1?b[0]:b,caption:e.edited||e.generated||"",metadata:{image_id:_,title:e.title,source:e.source,event_type:e.event_type,image_type:e.image_type,countries:e.countries,starred:e.starred,image_count:e.image_count||1}};ee`images/${D.fileName}`),S={image:h.length===1?h[0]:h,caption:e.edited||e.generated||"",metadata:{image_id:_,title:e.title,source:e.source,event_type:e.event_type,image_type:e.image_type,countries:e.countries,starred:e.starred,image_count:e.image_count||1}};r&&r.file("0001.json",JSON.stringify(S,null,2))}}catch(_){throw console.error(`Failed to process image ${e.image_id}:`,_),_}}else if(e.image_type==="drone_image"){const r=l.folder("drone_images_dataset"),g=r?.folder("images");if(g)try{const _=await fetch(`/api/images/${e.image_id}/file`);if(!_.ok)throw new Error(`Failed to fetch image ${e.image_id}`);const T=await _.blob(),M=`0001.${e.file_key.split(".").pop()||"jpg"}`;if(g.file(M,T),t==="fine-tuning"){const h=[],S=[],D=[];if(String(e?.image_type)==="crisis_map"){const b=Math.random();b1?e.all_image_ids||[e.image_id]:e.image_id,title:e.title,source:e.source,event_type:e.event_type,image_type:e.image_type,countries:e.countries,starred:e.starred,image_count:e.image_count||1}};r&&r.file("0001.json",JSON.stringify(h,null,2))}}catch(_){throw console.error(`Failed to process image ${e.image_id}:`,_),_}}else{const r=l.folder("generic_dataset"),g=r?.folder("images");if(g)try{const _=await fetch(`/api/images/${e.image_id}/file`);if(!_.ok)throw new Error(`Failed to fetch image ${e.image_id}`);const T=await _.blob(),M=`0001.${e.file_key.split(".").pop()||"jpg"}`;if(g.file(M,T),t==="fine-tuning"){const h=[],S=[],D=[];if(String(e?.image_type)==="crisis_map"){const b=Math.random();b1?e.all_image_ids||[e.image_id]:e.image_id,title:e.title,source:e.source,event_type:e.event_type,image_type:e.image_type,countries:e.countries,starred:e.starred,image_count:e.image_count||1}};r&&r.file("0001.json",JSON.stringify(h,null,2))}}catch(_){throw console.error(`Failed to process image ${e.image_id}:`,_),_}}const s=await l.generateAsync({type:"blob"}),n=URL.createObjectURL(s),o=document.createElement("a");o.href=n,o.download=`dataset_${e.image_type}_${e.image_id}_${t}_${new Date().toISOString().split("T")[0]}.zip`,document.body.appendChild(o),o.click(),document.body.removeChild(o),URL.revokeObjectURL(n),console.log(`Exported ${e.image_type} dataset with 1 image in ${t} mode`),ie(!0)}catch(i){console.error("Export failed:",i),alert("Failed to export dataset. Please try again.")}finally{se(!1)}}},Ye=/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i;return!u||u==="undefined"||u==="null"||u.trim()===""||!Ye.test(u)?a.jsx(ae,{children:a.jsxs("div",{className:"flex flex-col items-center gap-4 text-center py-12",children:[a.jsx("div",{className:"text-4xl",children:"⚠️"}),a.jsx("div",{className:"text-xl font-semibold",children:"Invalid Map ID"}),a.jsx("div",{children:"The map ID provided is not valid."}),a.jsxs("div",{className:"text-sm text-gray-500 mt-2",children:['Debug Info: mapId = "',u,'" (type: ',typeof u,")"]}),a.jsx(F,{name:"back-to-explore",variant:"secondary",onClick:()=>y("/explore"),children:"Return to Explore"})]})}):O?a.jsx(ae,{children:a.jsx("div",{className:m.loadingContainer,children:a.jsxs("div",{className:"flex flex-col items-center gap-4",children:[a.jsx(Ie,{className:"text-ifrcRed"}),a.jsx("div",{children:"Loading map details..."})]})})}):de||!e?a.jsx(ae,{children:a.jsx("div",{className:m.errorContainer,children:a.jsxs("div",{className:"flex flex-col items-center gap-4 text-center",children:[a.jsx("div",{className:"text-4xl",children:"⚠️"}),a.jsx("div",{className:"text-xl font-semibold",children:"Unable to load map"}),a.jsx("div",{children:de||"Map not found"}),a.jsx(F,{name:"back-to-explore",variant:"secondary",onClick:()=>y("/explore"),children:"Return to Explore"})]})})}):a.jsxs(ae,{children:[a.jsxs("div",{className:"max-w-7xl mx-auto",children:[a.jsxs("div",{className:m.tabSelector,children:[a.jsx(ia,{name:"map-details-view",value:ce,onChange:t=>{(t==="mapDetails"||t==="explore")&&(Ne(t),t==="explore"&&y("/explore"))},options:We,keySelector:t=>t.key,labelSelector:t=>t.label}),a.jsxs("div",{className:"flex items-center gap-2 ml-auto",children:[a.jsx(P,{withInternalPadding:!0,className:"bg-white/20 backdrop-blur-sm rounded-md p-2",children:a.jsxs(F,{name:"reference-examples",variant:k?"primary":"secondary",onClick:()=>Ue(!k),className:"whitespace-nowrap",children:[a.jsx("span",{className:"mr-2",children:k?a.jsx("span",{className:"text-yellow-400",children:"★"}):a.jsx("span",{className:"text-yellow-400",children:"☆"})}),"Reference Examples"]})}),a.jsx(F,{name:"export-dataset",variant:"secondary",onClick:()=>Q(!0),children:"Export"})]})]}),a.jsx(ca,{sources:ge,types:me,regions:pe,countries:De,imageTypes:ue,isLoadingFilters:!1}),ce==="mapDetails"?a.jsx("div",{className:"relative",children:c?a.jsxs(a.Fragment,{children:[a.jsxs("div",{className:m.gridLayout,children:[a.jsxs(P,{heading:a.jsxs("div",{className:"flex items-center gap-2",children:[a.jsx("span",{children:c.title||"Map Image"}),c.starred&&a.jsx("span",{className:"text-red-500 text-xl",title:"Starred image",children:"★"})]}),headingLevel:2,withHeaderBorder:!0,withInternalPadding:!0,spacing:"comfortable",children:[a.jsx("div",{className:m.imageContainer,children:e?.image_count&&e.image_count>1||x.length>1?a.jsxs("div",{className:m.carouselContainer,children:[a.jsx("div",{className:m.carouselImageWrapper,children:q?a.jsxs("div",{className:m.imagePlaceholder,children:[a.jsx(Ie,{className:"text-ifrcRed"}),a.jsx("div",{children:"Loading images..."})]}):x[L]?.detail_url?a.jsx("img",{src:x[L].detail_url,alt:x[L].file_key,className:m.carouselImage,onError:t=>{console.log("MapDetailsPage: Detail image failed to load, falling back to original:",x[L].detail_url);const i=t.target;x[L].image_url&&(i.src=x[L].image_url)},onLoad:()=>console.log("MapDetailsPage: Detail image loaded successfully:",x[L].detail_url)}):x[L]?.image_url?a.jsx("img",{src:x[L].image_url,alt:x[L].file_key,className:m.carouselImage,onLoad:()=>console.log("MapDetailsPage: Original image loaded successfully:",x[L].image_url)}):a.jsx("div",{className:m.imagePlaceholder,children:"No image available"})}),a.jsxs("div",{className:m.carouselNavigation,children:[a.jsx(F,{name:"previous-image",variant:"tertiary",size:1,onClick:Je,disabled:q,className:m.carouselButton,children:a.jsx(oe,{className:"w-4 h-4"})}),a.jsx("div",{className:m.carouselIndicators,children:x.map((t,i)=>a.jsx("button",{onClick:()=>Ve(i),className:`${m.carouselIndicator} ${i===L?m.carouselIndicatorActive:""}`,disabled:q,children:i+1},i))}),a.jsx(F,{name:"next-image",variant:"tertiary",size:1,onClick:Ge,disabled:q,className:m.carouselButton,children:a.jsx(re,{className:"w-4 h-4"})})]}),a.jsx("div",{className:m.viewImageButtonContainer,children:a.jsx(F,{name:"view-full-size-carousel",variant:"secondary",size:1,onClick:()=>ve(x[L]),disabled:q||!x[L]?.image_url,children:"View Image"})})]}):a.jsxs("div",{className:m.singleImageContainer,children:[c.detail_url?a.jsx("img",{src:c.detail_url,alt:c.file_key,onError:t=>{console.log("MapDetailsPage: Detail image failed to load, falling back to original:",c.detail_url);const i=t.target;c.image_url&&(i.src=c.image_url)},onLoad:()=>console.log("MapDetailsPage: Detail image loaded successfully:",c.detail_url)}):c.image_url?a.jsx("img",{src:c.image_url,alt:c.file_key,onLoad:()=>console.log("MapDetailsPage: Original image loaded successfully:",c.image_url)}):a.jsx("div",{className:m.imagePlaceholder,children:"No image available"}),a.jsx("div",{className:m.viewImageButtonContainer,children:a.jsx(F,{name:"view-full-size-single",variant:"secondary",size:1,onClick:()=>ve(c),disabled:!c.image_url,children:"View Image"})})]})}),a.jsx(P,{withInternalPadding:!0,className:"bg-white/20 backdrop-blur-sm rounded-md p-2",children:a.jsxs("div",{className:m.metadataTags,children:[c.image_type!=="drone_image"&&a.jsx("span",{className:m.metadataTag,children:ge.find(t=>t.s_code===c.source)?.label||c.source}),a.jsx("span",{className:m.metadataTag,children:me.find(t=>t.t_code===c.event_type)?.label||c.event_type}),a.jsx("span",{className:m.metadataTag,children:ue.find(t=>t.image_type===c.image_type)?.label||c.image_type}),a.jsx("span",{className:m.metadataTag,children:c.model==="manual"?"Manual":"Generated"}),c.countries&&c.countries.length>0&&a.jsxs(a.Fragment,{children:[a.jsx("span",{className:m.metadataTag,children:pe.find(t=>t.r_code===c.countries[0].r_code)?.label||"Unknown Region"}),a.jsx("span",{className:m.metadataTag,children:c.countries.map(t=>t.label).join(", ")})]}),c.image_count&&c.image_count>1&&a.jsxs("span",{className:m.metadataTag,title:`Multi-upload with ${c.image_count} images`,children:["📷 ",c.image_count]}),(!c.image_count||c.image_count<=1)&&a.jsx("span",{className:m.metadataTag,title:"Single Upload",children:"Single"})]})})]}),a.jsx("div",{className:m.detailsSection,children:c.edited&&c.edited.includes("Description:")||c.generated&&c.generated.includes("Description:")?a.jsx(P,{heading:"Interpretation",headingLevel:3,withHeaderBorder:!0,withInternalPadding:!0,spacing:"comfortable",children:a.jsx("div",{className:m.captionContainer,children:a.jsx("div",{className:m.captionText,children:(c.edited||c.generated||"").split(/(Description:|Analysis:|Recommended Actions:)/).map((l,s)=>l.trim()===""?null:l==="Description:"||l==="Analysis:"||l==="Recommended Actions:"?a.jsx("h4",{className:"font-semibold text-gray-800 mt-4 mb-2",children:l},s):a.jsx("p",{className:"mb-2",children:l.trim()},s))})})}):a.jsx(P,{heading:"Description",headingLevel:3,withHeaderBorder:!0,withInternalPadding:!0,spacing:"comfortable",children:a.jsx("div",{className:m.captionContainer,children:c.generated||c.edited?a.jsx("div",{className:m.captionText,children:a.jsx("p",{children:c.edited||c.generated})}):a.jsx("p",{children:"— no caption yet —"})})})})]}),a.jsx("div",{className:"flex items-center justify-center mt-8",children:a.jsx(P,{withInternalPadding:!0,className:"bg-white/20 backdrop-blur-sm rounded-lg p-4",children:a.jsxs("div",{className:"flex items-center gap-4",children:[Le&&a.jsx(P,{withInternalPadding:!0,className:"rounded-md p-2",children:a.jsx(F,{name:"previous-item",variant:"tertiary",size:1,className:`bg-white/90 hover:bg-white shadow-lg border border-gray-200 ${J?"opacity-50 cursor-not-allowed":"hover:scale-110"}`,onClick:()=>je("previous"),disabled:J,children:a.jsxs("div",{className:"flex items-center gap-1",children:[a.jsxs("div",{className:"flex -space-x-1",children:[a.jsx(oe,{className:"w-4 h-4"}),a.jsx(oe,{className:"w-4 h-4"})]}),a.jsx("span",{className:"font-semibold",children:"Previous"})]})})}),le&&a.jsx(P,{withInternalPadding:!0,className:"rounded-md p-2",children:a.jsx(F,{name:"delete",variant:"tertiary",size:1,className:"bg-red-50 hover:bg-red-100 text-red-700 border border-red-200 hover:border-red-300",onClick:qe,title:"Delete","aria-label":"Delete saved image",children:a.jsx(na,{className:"w-4 h-4"})})}),a.jsx(P,{withInternalPadding:!0,className:"rounded-md p-2",children:a.jsx(F,{name:"contribute",onClick:Qe,children:"Contribute"})}),le&&a.jsx(P,{withInternalPadding:!0,className:"rounded-md p-2",children:a.jsx(F,{name:"toggle-star",variant:"tertiary",size:1,className:`${e?.starred?"bg-red-100 hover:bg-red-200 text-red-800 border-2 border-red-400":"bg-gray-100 hover:bg-gray-200 text-gray-600 border-2 border-gray-300"} w-16 h-8 rounded-full transition-all duration-200 flex items-center justify-center`,onClick:Ke,title:e?.starred?"Unstar image":"Star image","aria-label":e?.starred?"Unstar image":"Star image",children:a.jsx("span",{className:`text-lg transition-all duration-200 ${e?.starred?"text-red-600":"text-gray-500"}`,children:e?.starred?"★":"☆"})})}),Te&&a.jsx(P,{withInternalPadding:!0,className:"rounded-md p-2",children:a.jsx(F,{name:"next-item",variant:"tertiary",size:1,className:`bg-white/90 hover:bg-white shadow-lg border border-gray-200 ${J?"opacity-50 cursor-not-allowed":"hover:scale-110"}`,onClick:()=>je("next"),disabled:J,children:a.jsxs("div",{className:"flex items-center gap-1",children:[a.jsx("span",{className:"font-semibold",children:"Next"}),a.jsxs("div",{className:"flex -space-x-1",children:[a.jsx(re,{className:"w-4 h-4"}),a.jsx(re,{className:"w-4 h-4"})]})]})})})]})})})]}):a.jsxs("div",{className:"text-center py-12",children:[a.jsx("div",{className:"text-xl font-semibold text-gray-600 mb-4",children:"No matches found"}),a.jsx("div",{className:"mt-4",children:a.jsx(F,{name:"clear-filters",variant:"secondary",onClick:Be,children:"Clear Filters"})})]})}):null]}),$e&&a.jsx("div",{className:m.fullSizeModalOverlay,onClick:()=>Z(!1),children:a.jsx("div",{className:m.fullSizeModalContent,onClick:t=>t.stopPropagation(),children:a.jsxs("div",{className:m.ratingWarningContent,children:[a.jsx("h3",{className:m.ratingWarningTitle,children:"Delete Image?"}),a.jsx("p",{className:m.ratingWarningText,children:"This action cannot be undone. Are you sure you want to delete this saved image and all related data?"}),a.jsxs("div",{className:m.ratingWarningButtons,children:[a.jsx(F,{name:"confirm-delete",variant:"secondary",onClick:Ze,children:"Delete"}),a.jsx(F,{name:"cancel-delete",variant:"tertiary",onClick:()=>Z(!1),children:"Cancel"})]})]})})}),fe&&a.jsx(da,{isOpen:fe,onClose:()=>{Q(!1),ie(!1),se(!1)},onExport:(t,i)=>{i.includes(e.image_type)&&Xe(t)},filteredCount:1,totalCount:1,hasFilters:!1,crisisMapsCount:e.image_type==="crisis_map"?1:0,droneImagesCount:e.image_type==="drone_image"?1:0,isLoading:Pe,exportSuccess:Re,variant:"single",onNavigateToList:()=>{Q(!1),y("/explore")},onNavigateAndExport:()=>{Q(!1),y("/explore?export=true")}}),a.jsx(oa,{isOpen:Ae,imageUrl:ze?.image_url||null,preview:null,selectedImageData:null,onClose:He,isLoading:Oe})]})}export{it as default}; +const __vite__mapDeps=(i,m=__vite__mapDeps,d=(m.f||(m.f=["assets/jszip.min-Csqqcm8m.js","assets/index-CcfIBRoF.js","assets/index-BzCX1Bzq.css"])))=>i.map(i=>d[i]); +import{K as aa,x as ta,r as d,D as sa,j as a,N as ae,n as F,_ as Ie,L as ia,z as P,v as oe,w as re,F as na,M as oa,G as ra}from"./index-CcfIBRoF.js";import{u as la}from"./useAdmin-CrA3XozJ.js";import{F as ca,E as da}from"./ExportModal-x1pUTnT7.js";const ga="_tabSelector_usssr_1",ma="_imageContainer_usssr_12",ua="_imagePlaceholder_usssr_33",pa="_metadataTags_usssr_45",fa="_metadataTag_usssr_45",ha="_captionContainer_usssr_67",_a="_captionText_usssr_74",xa="_gridLayout_usssr_131",ya="_detailsSection_usssr_155",va="_loadingContainer_usssr_161",ja="_errorContainer_usssr_171",wa="_fullSizeModalOverlay_usssr_205",Ia="_fullSizeModalContent_usssr_219",Na="_ratingWarningContent_usssr_230",Ca="_ratingWarningTitle_usssr_236",ba="_ratingWarningText_usssr_243",Sa="_ratingWarningButtons_usssr_250",ka="_carouselContainer_usssr_365",Da="_carouselImageWrapper_usssr_370",Ma="_carouselImage_usssr_370",La="_carouselNavigation_usssr_393",Fa="_carouselButton_usssr_405",Ta="_carouselIndicators_usssr_429",Ea="_carouselIndicator_usssr_429",$a="_carouselIndicatorActive_usssr_458",Pa="_singleImageContainer_usssr_488",Ra="_viewImageButtonContainer_usssr_494",m={tabSelector:ga,imageContainer:ma,imagePlaceholder:ua,metadataTags:pa,metadataTag:fa,captionContainer:ha,captionText:_a,gridLayout:xa,detailsSection:ya,loadingContainer:va,errorContainer:ja,fullSizeModalOverlay:wa,fullSizeModalContent:Ia,ratingWarningContent:Na,ratingWarningTitle:Ca,ratingWarningText:ba,ratingWarningButtons:Sa,carouselContainer:ka,carouselImageWrapper:Da,carouselImage:Ma,carouselNavigation:La,carouselButton:Fa,carouselIndicators:Ta,carouselIndicator:Ea,carouselIndicatorActive:$a,singleImageContainer:Pa,viewImageButtonContainer:Ra};function it(){const{mapId:u}=aa(),y=ta(),{isAuthenticated:le}=la(),[ce,Ne]=d.useState("mapDetails"),[e,te]=d.useState(null),[O,A]=d.useState(!0),[de,U]=d.useState(null),[ge,Ce]=d.useState([]),[me,be]=d.useState([]),[ue,Se]=d.useState([]),[pe,ke]=d.useState([]),[De,Me]=d.useState([]),[Le,Fe]=d.useState(!1),[Te,Ee]=d.useState(!1),[J,K]=d.useState(!1),[$e,Z]=d.useState(!1),[fe,Q]=d.useState(!1),[Pe,se]=d.useState(!1),[Re,ie]=d.useState(!1),[Aa,za]=d.useState("standard"),[R,Oa]=d.useState(80),[G,Ua]=d.useState(10),[Ba,Wa]=d.useState(10),[Ja,Ga]=d.useState(!0),[Va,Ha]=d.useState(!0),[B,X]=d.useState(!1),[Ae,he]=d.useState(!1),[ze,_e]=d.useState(null),[Oe,V]=d.useState(!1),[x,H]=d.useState([]),[L,z]=d.useState(0),[q,xe]=d.useState(!1),{search:p,setSearch:qa,srcFilter:v,setSrcFilter:Ka,catFilter:j,setCatFilter:Za,regionFilter:w,setRegionFilter:Qa,countryFilter:I,setCountryFilter:Xa,imageTypeFilter:N,setImageTypeFilter:Ya,uploadTypeFilter:C,setUploadTypeFilter:et,generatedMethodFilter:f,showReferenceExamples:k,setShowReferenceExamples:Ue,clearAllFilters:Be}=sa(),We=[{key:"explore",label:"List"},{key:"mapDetails",label:"Carousel"}],Y=d.useCallback(async t=>{if(!(!t||t==="undefined"||t==="null"||t.trim()===""))try{const i=new URLSearchParams;p&&i.append("search",p),v&&i.append("source",v),j&&i.append("event_type",j),w&&i.append("region",w),I&&i.append("country",I),N&&i.append("image_type",N),C&&i.append("upload_type",C),k&&i.append("starred_only","true");const l=await fetch(`/api/images/grouped?${i.toString()}`);if(l.ok){let s=await l.json();s.items&&(s=s.items),f&&(s=s.filter(o=>f==="manual"?o.model==="manual":f==="generated"?o.model!=="manual":!0)),console.log("Server response for upload_type=multiple:",{url:`/api/images/grouped?${i.toString()}`,count:s.length,images:s.map(o=>({image_id:o.image_id,image_count:o.image_count,all_image_ids:o.all_image_ids,all_image_ids_length:o.all_image_ids?.length}))});const n=s.findIndex(o=>o.image_id===t);console.log("Navigation availability check (server-side):",{filteredImagesCount:s.length,currentIndex:n,currentId:t,uploadTypeFilter:C,hasPrevious:s.length>1&&n>0,hasNext:s.length>1&&n({image_id:o.image_id,image_count:o.image_count,all_image_ids:o.all_image_ids,image_type:o.image_type}))}),Fe(s.length>1&&n>0),Ee(s.length>1&&n{console.log("fetchAllImages called with imageIds:",t),xe(!0);try{const i=t.map(async s=>{const n=await fetch(`/api/images/${s}`);if(!n.ok)throw new Error(`Failed to fetch image ${s}`);return n.json()}),l=await Promise.all(i);H(l),z(0),console.log("fetchAllImages: Loaded",l.length,"images")}catch(i){console.error("fetchAllImages error:",i),U(i instanceof Error?i.message:"Failed to load all images")}finally{xe(!1)}},[]),ye=d.useCallback(async t=>{if(console.log("fetchMapData called with id:",t),console.log("fetchMapData id type:",typeof t),!t||t==="undefined"||t==="null"||t.trim()===""){console.log("fetchMapData: Invalid ID detected:",t),U("Invalid Map ID"),A(!1);return}if(!/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i.test(t)){console.log("fetchMapData: Invalid UUID format:",t),U("Invalid Map ID format"),A(!1);return}console.log("fetchMapData: Making API call for id:",t),K(!0),A(!0);try{const l=await fetch(`/api/images/${t}`);if(!l.ok)throw new Error("Map not found");const s=await l.json();if(te(s),s.all_image_ids&&s.all_image_ids.length>1)await ne(s.all_image_ids);else if(s.image_count&&s.image_count>1){console.log("Multi-upload detected but no all_image_ids, trying grouped endpoint");try{const n=await fetch("/api/images/grouped");if(n.ok){const r=(await n.json()).find(g=>g.all_image_ids&&g.all_image_ids.includes(s.image_id));r&&r.all_image_ids?await ne(r.all_image_ids):(H([s]),z(0))}else H([s]),z(0)}catch(n){console.error("Failed to fetch from grouped endpoint:",n),H([s]),z(0)}}else H([s]),z(0);await Y(t)}catch(l){U(l instanceof Error?l.message:"Unknown error occurred")}finally{A(!1),K(!1)}},[Y,ne]),Je=d.useCallback(()=>{x.length>1&&z(t=>t>0?t-1:x.length-1)},[x.length]),Ge=d.useCallback(()=>{x.length>1&&z(t=>t{t>=0&&t{const i=t||(x.length>0?x[L]:e);if(i){V(!0),_e(i),he(!0);try{const l=new Image;l.onload=()=>{V(!1)},l.onerror=()=>{V(!1)},l.src=i.image_url}catch(l){console.error("Error preloading full-size image:",l),V(!1)}}},[x,L,e]),He=d.useCallback(()=>{he(!1),_e(null),V(!1)},[]);d.useEffect(()=>{if(console.log("MapDetailsPage: mapId from useParams:",u),console.log("MapDetailsPage: mapId type:",typeof u),console.log("MapDetailsPage: mapId value:",u),!u||u==="undefined"||u==="null"||u.trim()===""||u===void 0||u===null){console.log("MapDetailsPage: Invalid mapId, setting error"),U("Map ID is required"),A(!1);return}if(!/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i.test(u)){console.log("MapDetailsPage: Invalid UUID format:",u),U("Invalid Map ID format"),A(!1);return}console.log("MapDetailsPage: Fetching data for mapId:",u),ye(u)},[u,ye]),d.useEffect(()=>{if(!e||O||B)return;if(!u||u==="undefined"||u==="null"||u.trim()===""){console.log("Auto-navigation skipped: Invalid mapId");return}if(!/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i.test(u)){console.log("Auto-navigation skipped: Invalid mapId format");return}(()=>{const l=!p||e.title?.toLowerCase().includes(p.toLowerCase())||e.generated?.toLowerCase().includes(p.toLowerCase())||e.source?.toLowerCase().includes(p.toLowerCase())||e.event_type?.toLowerCase().includes(p.toLowerCase()),s=!v||e.source===v,n=!j||e.event_type===j,o=!w||e.countries.some(M=>M.r_code===w),r=!I||e.countries.some(M=>M.c_code===I),g=!N||e.image_type===N,_=!f||f==="manual"&&e.model==="manual"||f==="generated"&&e.model!=="manual",T=!k||e.starred===!0,E=l&&s&&n&&o&&r&&g&&_&&T;return console.log("Auto-navigation check:",{mapId:u,search:p,srcFilter:v,catFilter:j,regionFilter:w,countryFilter:I,imageTypeFilter:N,generatedMethodFilter:f,showReferenceExamples:k,matchesSearch:l,matchesSource:s,matchesCategory:n,matchesRegion:o,matchesCountry:r,matchesImageType:g,matchesReferenceExamples:T,matches:E}),E})()||(console.log("Current map does not match filters, looking for first matching item"),fetch("/api/images").then(l=>l.json()).then(l=>{console.log("Auto-navigation: Received images from API:",l.length),console.log("Auto-navigation: First few images:",l.slice(0,3).map(n=>({image_id:n.image_id,title:n.title})));const s=l.find(n=>{const o=!p||n.title?.toLowerCase().includes(p.toLowerCase())||n.generated?.toLowerCase().includes(p.toLowerCase())||n.source?.toLowerCase().includes(p.toLowerCase())||n.event_type?.toLowerCase().includes(p.toLowerCase()),r=!v||n.source===v,g=!j||n.event_type===j,_=!w||n.countries?.some(S=>S.r_code===w),T=!I||n.countries?.some(S=>S.c_code===I),E=!N||n.image_type===N,M=!f||f==="manual"&&n.model==="manual"||f==="generated"&&n.model!=="manual",h=!k||n.starred===!0;return o&&r&&g&&_&&T&&E&&M&&h});console.log("Auto-navigation: Found first matching image:",s?{image_id:s.image_id,title:s.title,source:s.source}:"No matching image found"),s&&s.image_id&&s.image_id!=="undefined"&&s.image_id!=="null"&&s.image_id.trim()!==""&&s.image_id!==u&&(/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i.test(s.image_id)?(console.log("Auto-navigating to:",s.image_id),y(`/map/${s.image_id}`)):console.error("Auto-navigation blocked: Invalid image_id format:",s.image_id))}).catch(console.error))},[e,p,v,j,w,I,N,f,k,u,y,O,B]);const je=async t=>{if(!J){K(!0);try{const i=new URLSearchParams;p&&i.append("search",p),v&&i.append("source",v),j&&i.append("event_type",j),w&&i.append("region",w),I&&i.append("country",I),N&&i.append("image_type",N),C&&i.append("upload_type",C),k&&i.append("starred_only","true");const l=await fetch(`/api/images/grouped?${i.toString()}`);if(l.ok){let s=await l.json();s.items&&(s=s.items),f&&(s=s.filter(g=>f==="manual"?g.model==="manual":f==="generated"?g.model!=="manual":!0));const n=s.findIndex(g=>g.image_id===u);if(n===-1){console.error("Current image not found in filtered list");return}let o;t==="previous"?o=n>0?n-1:s.length-1:o=n{console.log("=== NAVIGATION USEEFFECT TRIGGERED ==="),console.log("Navigation useEffect triggered:",{map:!!e,mapId:u,loading:O,isDeleting:B,uploadTypeFilter:C,allFilters:{search:p,srcFilter:v,catFilter:j,regionFilter:w,countryFilter:I,imageTypeFilter:N,uploadTypeFilter:C,generatedMethodFilter:f,showReferenceExamples:k}}),e&&u&&!O&&!B?(console.log("Calling checkNavigationAvailability with:",u),Y(u)):console.log("NOT calling checkNavigationAvailability because:",{map:!!e,mapId:!!u,loading:O,isDeleting:B})},[e,u,p,v,j,w,I,N,C,f,k,O,B,Y]),d.useEffect(()=>{Promise.all([fetch("/api/sources").then(t=>t.json()),fetch("/api/types").then(t=>t.json()),fetch("/api/image-types").then(t=>t.json()),fetch("/api/regions").then(t=>t.json()),fetch("/api/countries").then(t=>t.json())]).then(([t,i,l,s,n])=>{Ce(t),be(i),Se(l),ke(s),Me(n)}).catch(console.error)},[]);const qe=async()=>{e&&Z(!0)},Ke=async()=>{if(e)try{(await fetch(`/api/images/${e.image_id}`,{method:"PUT",headers:{"Content-Type":"application/json"},body:JSON.stringify({starred:!e.starred})})).ok?te(i=>i?{...i,starred:!i.starred}:null):console.error("Failed to toggle starred status")}catch(t){console.error("Error toggling starred status:",t)}},Ze=async()=>{if(e){X(!0);try{if(console.log("Deleting image with ID:",e.image_id),(await fetch(`/api/images/${e.image_id}`,{method:"DELETE"})).ok){te(i=>i?{...i,starred:!i.starred}:null),Z(!1);try{const i=await fetch("/api/images/grouped");if(i.ok){const s=(await i.json()).filter(o=>{const r=!p||o.title?.toLowerCase().includes(p.toLowerCase())||o.generated?.toLowerCase().includes(p.toLowerCase())||o.source?.toLowerCase().includes(p.toLowerCase())||o.event_type?.toLowerCase().includes(p.toLowerCase()),g=!v||o.source===v,_=!j||o.event_type===j,T=!w||o.countries?.some(b=>b.r_code===w),E=!I||o.countries?.some(b=>b.c_code===I),M=!N||o.image_type===N,h=!C||C==="single"&&(!o.image_count||o.image_count<=1)||C==="multiple"&&o.image_count&&o.image_count>1,S=!f||f==="manual"&&o.model==="manual"||f==="generated"&&o.model!=="manual",D=!k||o.starred===!0;return r&&g&&_&&T&&E&&M&&h&&S&&D}),n=s.filter(o=>o.image_id!==e.image_id);if(n.length>0){const o=s.findIndex(g=>g.image_id===e.image_id);let r;if(o===s.length-1?r=o-1:r=o,console.log("Navigation target:",{currentIndex:o,targetIndex:r,targetId:n[r]?.image_id}),r>=0&&r{A(!0);try{const t=new URLSearchParams;p&&t.append("search",p),v&&t.append("source",v),j&&t.append("event_type",j),w&&t.append("region",w),I&&t.append("country",I),N&&t.append("image_type",N),C&&t.append("upload_type",C),k&&t.append("starred_only","true");const i=await fetch(`/api/images/grouped?${t.toString()}`);if(i.ok){let l=await i.json();if(l.items&&(l=l.items),f&&(l=l.filter(s=>f==="manual"?s.model==="manual":f==="generated"?s.model!=="manual":!0)),l.length>0){const s=l[0];s&&s.image_id&&y(`/map/${s.image_id}`)}else y("/explore")}}catch(t){console.error("Failed to navigate to matching image:",t),y("/explore")}finally{A(!1)}},[p,v,j,w,I,N,C,f,k,y]),c=d.useMemo(()=>{if(!e)return null;if(!p&&!v&&!j&&!w&&!I&&!N&&!C&&!f&&!k)return e;const t=!p||e.title?.toLowerCase().includes(p.toLowerCase())||e.generated?.toLowerCase().includes(p.toLowerCase())||e.source?.toLowerCase().includes(p.toLowerCase())||e.event_type?.toLowerCase().includes(p.toLowerCase()),i=!v||e.source===v,l=!j||e.event_type===j,s=!w||e.countries.some(E=>E.r_code===w),n=!I||e.countries.some(E=>E.c_code===I),o=!N||e.image_type===N,r=!C||C==="single"&&(!e.image_count||e.image_count<=1)&&(!e.all_image_ids||e.all_image_ids.length<=1)||C==="multiple"&&(e.image_count&&e.image_count>1||e.all_image_ids&&e.all_image_ids.length>1),g=!f||f==="manual"&&e.model==="manual"||f==="generated"&&e.model!=="manual",_=!k||e.starred===!0,T=t&&i&&l&&s&&n&&o&&r&&g&&_;return!T&&(p||v||j||w||I||N||C||f||k)?(setTimeout(()=>{we()},100),e):T?e:null},[e,p,v,j,w,I,N,C,f,k,we]),Qe=()=>{if(!e)return;if(!e.all_image_ids||e.all_image_ids.length<=1){const s=`/upload?step=1&contribute=true&imageIds=${[e.image_id].join(",")}`;y(s);return}const i=`/upload?step=1&contribute=true&imageIds=${e.all_image_ids.join(",")}`;y(i)},$=(t,i)=>({image:`images/${i}`,caption:t.edited||t.generated||"",metadata:{image_id:t.image_count&&t.image_count>1?t.all_image_ids||[t.image_id]:t.image_id,title:t.title,source:t.source,event_type:t.event_type,image_type:t.image_type,countries:t.countries,starred:t.starred,image_count:t.image_count||1}}),Xe=async t=>{if(e){se(!0),ie(!1);try{const i=(await ra(async()=>{const{default:r}=await import("./jszip.min-Csqqcm8m.js").then(g=>g.j);return{default:r}},__vite__mapDeps([0,1,2]))).default,l=new i;if(e.image_type==="crisis_map"){const r=l.folder("crisis_maps_dataset"),g=r?.folder("images");if(g)try{const _=e.image_count&&e.image_count>1?e.all_image_ids||[e.image_id]:[e.image_id],T=_.map(async(h,S)=>{try{const D=await fetch(`/api/images/${h}/file`);if(!D.ok)throw new Error(`Failed to fetch image ${h}`);const b=await D.blob(),ee=e.file_key.split(".").pop()||"jpg",W=`0001_${String(S+1).padStart(2,"0")}.${ee}`;return g.file(W,b),{success:!0,fileName:W,imageId:h}}catch(D){return console.error(`Failed to process image ${h}:`,D),{success:!1,fileName:"",imageId:h}}}),M=(await Promise.all(T)).filter(h=>h.success);if(M.length===0)throw new Error("No images could be processed");if(t==="fine-tuning"){const h=[],S=[],D=[],b=M.map(ea=>`images/${ea.fileName}`),ee=Math.random(),W={image:b.length===1?b[0]:b,caption:e.edited||e.generated||"",metadata:{image_id:_,title:e.title,source:e.source,event_type:e.event_type,image_type:e.image_type,countries:e.countries,starred:e.starred,image_count:e.image_count||1}};ee`images/${D.fileName}`),S={image:h.length===1?h[0]:h,caption:e.edited||e.generated||"",metadata:{image_id:_,title:e.title,source:e.source,event_type:e.event_type,image_type:e.image_type,countries:e.countries,starred:e.starred,image_count:e.image_count||1}};r&&r.file("0001.json",JSON.stringify(S,null,2))}}catch(_){throw console.error(`Failed to process image ${e.image_id}:`,_),_}}else if(e.image_type==="drone_image"){const r=l.folder("drone_images_dataset"),g=r?.folder("images");if(g)try{const _=await fetch(`/api/images/${e.image_id}/file`);if(!_.ok)throw new Error(`Failed to fetch image ${e.image_id}`);const T=await _.blob(),M=`0001.${e.file_key.split(".").pop()||"jpg"}`;if(g.file(M,T),t==="fine-tuning"){const h=[],S=[],D=[];if(String(e?.image_type)==="crisis_map"){const b=Math.random();b1?e.all_image_ids||[e.image_id]:e.image_id,title:e.title,source:e.source,event_type:e.event_type,image_type:e.image_type,countries:e.countries,starred:e.starred,image_count:e.image_count||1}};r&&r.file("0001.json",JSON.stringify(h,null,2))}}catch(_){throw console.error(`Failed to process image ${e.image_id}:`,_),_}}else{const r=l.folder("generic_dataset"),g=r?.folder("images");if(g)try{const _=await fetch(`/api/images/${e.image_id}/file`);if(!_.ok)throw new Error(`Failed to fetch image ${e.image_id}`);const T=await _.blob(),M=`0001.${e.file_key.split(".").pop()||"jpg"}`;if(g.file(M,T),t==="fine-tuning"){const h=[],S=[],D=[];if(String(e?.image_type)==="crisis_map"){const b=Math.random();b1?e.all_image_ids||[e.image_id]:e.image_id,title:e.title,source:e.source,event_type:e.event_type,image_type:e.image_type,countries:e.countries,starred:e.starred,image_count:e.image_count||1}};r&&r.file("0001.json",JSON.stringify(h,null,2))}}catch(_){throw console.error(`Failed to process image ${e.image_id}:`,_),_}}const s=await l.generateAsync({type:"blob"}),n=URL.createObjectURL(s),o=document.createElement("a");o.href=n,o.download=`dataset_${e.image_type}_${e.image_id}_${t}_${new Date().toISOString().split("T")[0]}.zip`,document.body.appendChild(o),o.click(),document.body.removeChild(o),URL.revokeObjectURL(n),console.log(`Exported ${e.image_type} dataset with 1 image in ${t} mode`),ie(!0)}catch(i){console.error("Export failed:",i),alert("Failed to export dataset. Please try again.")}finally{se(!1)}}},Ye=/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i;return!u||u==="undefined"||u==="null"||u.trim()===""||!Ye.test(u)?a.jsx(ae,{children:a.jsxs("div",{className:"flex flex-col items-center gap-4 text-center py-12",children:[a.jsx("div",{className:"text-4xl",children:"⚠️"}),a.jsx("div",{className:"text-xl font-semibold",children:"Invalid Map ID"}),a.jsx("div",{children:"The map ID provided is not valid."}),a.jsxs("div",{className:"text-sm text-gray-500 mt-2",children:['Debug Info: mapId = "',u,'" (type: ',typeof u,")"]}),a.jsx(F,{name:"back-to-explore",variant:"secondary",onClick:()=>y("/explore"),children:"Return to Explore"})]})}):O?a.jsx(ae,{children:a.jsx("div",{className:m.loadingContainer,children:a.jsxs("div",{className:"flex flex-col items-center gap-4",children:[a.jsx(Ie,{className:"text-ifrcRed"}),a.jsx("div",{children:"Loading map details..."})]})})}):de||!e?a.jsx(ae,{children:a.jsx("div",{className:m.errorContainer,children:a.jsxs("div",{className:"flex flex-col items-center gap-4 text-center",children:[a.jsx("div",{className:"text-4xl",children:"⚠️"}),a.jsx("div",{className:"text-xl font-semibold",children:"Unable to load map"}),a.jsx("div",{children:de||"Map not found"}),a.jsx(F,{name:"back-to-explore",variant:"secondary",onClick:()=>y("/explore"),children:"Return to Explore"})]})})}):a.jsxs(ae,{children:[a.jsxs("div",{className:"max-w-7xl mx-auto",children:[a.jsxs("div",{className:m.tabSelector,children:[a.jsx(ia,{name:"map-details-view",value:ce,onChange:t=>{(t==="mapDetails"||t==="explore")&&(Ne(t),t==="explore"&&y("/explore"))},options:We,keySelector:t=>t.key,labelSelector:t=>t.label}),a.jsxs("div",{className:"flex items-center gap-2 ml-auto",children:[a.jsx(P,{withInternalPadding:!0,className:"bg-white/20 backdrop-blur-sm rounded-md p-2",children:a.jsxs(F,{name:"reference-examples",variant:k?"primary":"secondary",onClick:()=>Ue(!k),className:"whitespace-nowrap",children:[a.jsx("span",{className:"mr-2",children:k?a.jsx("span",{className:"text-yellow-400",children:"★"}):a.jsx("span",{className:"text-yellow-400",children:"☆"})}),"Reference Examples"]})}),a.jsx(F,{name:"export-dataset",variant:"secondary",onClick:()=>Q(!0),children:"Export"})]})]}),a.jsx(ca,{sources:ge,types:me,regions:pe,countries:De,imageTypes:ue,isLoadingFilters:!1}),ce==="mapDetails"?a.jsx("div",{className:"relative",children:c?a.jsxs(a.Fragment,{children:[a.jsxs("div",{className:m.gridLayout,children:[a.jsxs(P,{heading:a.jsxs("div",{className:"flex items-center gap-2",children:[a.jsx("span",{children:c.title||"Map Image"}),c.starred&&a.jsx("span",{className:"text-red-500 text-xl",title:"Starred image",children:"★"})]}),headingLevel:2,withHeaderBorder:!0,withInternalPadding:!0,spacing:"comfortable",children:[a.jsx("div",{className:m.imageContainer,children:e?.image_count&&e.image_count>1||x.length>1?a.jsxs("div",{className:m.carouselContainer,children:[a.jsx("div",{className:m.carouselImageWrapper,children:q?a.jsxs("div",{className:m.imagePlaceholder,children:[a.jsx(Ie,{className:"text-ifrcRed"}),a.jsx("div",{children:"Loading images..."})]}):x[L]?.detail_url?a.jsx("img",{src:x[L].detail_url,alt:x[L].file_key,className:m.carouselImage,onError:t=>{console.log("MapDetailsPage: Detail image failed to load, falling back to original:",x[L].detail_url);const i=t.target;x[L].image_url&&(i.src=x[L].image_url)},onLoad:()=>console.log("MapDetailsPage: Detail image loaded successfully:",x[L].detail_url)}):x[L]?.image_url?a.jsx("img",{src:x[L].image_url,alt:x[L].file_key,className:m.carouselImage,onLoad:()=>console.log("MapDetailsPage: Original image loaded successfully:",x[L].image_url)}):a.jsx("div",{className:m.imagePlaceholder,children:"No image available"})}),a.jsxs("div",{className:m.carouselNavigation,children:[a.jsx(F,{name:"previous-image",variant:"tertiary",size:1,onClick:Je,disabled:q,className:m.carouselButton,children:a.jsx(oe,{className:"w-4 h-4"})}),a.jsx("div",{className:m.carouselIndicators,children:x.map((t,i)=>a.jsx("button",{onClick:()=>Ve(i),className:`${m.carouselIndicator} ${i===L?m.carouselIndicatorActive:""}`,disabled:q,children:i+1},i))}),a.jsx(F,{name:"next-image",variant:"tertiary",size:1,onClick:Ge,disabled:q,className:m.carouselButton,children:a.jsx(re,{className:"w-4 h-4"})})]}),a.jsx("div",{className:m.viewImageButtonContainer,children:a.jsx(F,{name:"view-full-size-carousel",variant:"secondary",size:1,onClick:()=>ve(x[L]),disabled:q||!x[L]?.image_url,children:"View Image"})})]}):a.jsxs("div",{className:m.singleImageContainer,children:[c.detail_url?a.jsx("img",{src:c.detail_url,alt:c.file_key,onError:t=>{console.log("MapDetailsPage: Detail image failed to load, falling back to original:",c.detail_url);const i=t.target;c.image_url&&(i.src=c.image_url)},onLoad:()=>console.log("MapDetailsPage: Detail image loaded successfully:",c.detail_url)}):c.image_url?a.jsx("img",{src:c.image_url,alt:c.file_key,onLoad:()=>console.log("MapDetailsPage: Original image loaded successfully:",c.image_url)}):a.jsx("div",{className:m.imagePlaceholder,children:"No image available"}),a.jsx("div",{className:m.viewImageButtonContainer,children:a.jsx(F,{name:"view-full-size-single",variant:"secondary",size:1,onClick:()=>ve(c),disabled:!c.image_url,children:"View Image"})})]})}),a.jsx(P,{withInternalPadding:!0,className:"bg-white/20 backdrop-blur-sm rounded-md p-2",children:a.jsxs("div",{className:m.metadataTags,children:[c.image_type!=="drone_image"&&a.jsx("span",{className:m.metadataTag,children:ge.find(t=>t.s_code===c.source)?.label||c.source}),a.jsx("span",{className:m.metadataTag,children:me.find(t=>t.t_code===c.event_type)?.label||c.event_type}),a.jsx("span",{className:m.metadataTag,children:ue.find(t=>t.image_type===c.image_type)?.label||c.image_type}),a.jsx("span",{className:m.metadataTag,children:c.model==="manual"?"Manual":"Generated"}),c.countries&&c.countries.length>0&&a.jsxs(a.Fragment,{children:[a.jsx("span",{className:m.metadataTag,children:pe.find(t=>t.r_code===c.countries[0].r_code)?.label||"Unknown Region"}),a.jsx("span",{className:m.metadataTag,children:c.countries.map(t=>t.label).join(", ")})]}),c.image_count&&c.image_count>1&&a.jsxs("span",{className:m.metadataTag,title:`Multi-upload with ${c.image_count} images`,children:["📷 ",c.image_count]}),(!c.image_count||c.image_count<=1)&&a.jsx("span",{className:m.metadataTag,title:"Single Upload",children:"Single"})]})})]}),a.jsx("div",{className:m.detailsSection,children:c.edited&&c.edited.includes("Description:")||c.generated&&c.generated.includes("Description:")?a.jsx(P,{heading:"Interpretation",headingLevel:3,withHeaderBorder:!0,withInternalPadding:!0,spacing:"comfortable",children:a.jsx("div",{className:m.captionContainer,children:a.jsx("div",{className:m.captionText,children:(c.edited||c.generated||"").split(/(Description:|Analysis:|Recommended Actions:)/).map((l,s)=>l.trim()===""?null:l==="Description:"||l==="Analysis:"||l==="Recommended Actions:"?a.jsx("h4",{className:"font-semibold text-gray-800 mt-4 mb-2",children:l},s):a.jsx("p",{className:"mb-2",children:l.trim()},s))})})}):a.jsx(P,{heading:"Description",headingLevel:3,withHeaderBorder:!0,withInternalPadding:!0,spacing:"comfortable",children:a.jsx("div",{className:m.captionContainer,children:c.generated||c.edited?a.jsx("div",{className:m.captionText,children:a.jsx("p",{children:c.edited||c.generated})}):a.jsx("p",{children:"— no caption yet —"})})})})]}),a.jsx("div",{className:"flex items-center justify-center mt-8",children:a.jsx(P,{withInternalPadding:!0,className:"bg-white/20 backdrop-blur-sm rounded-lg p-4",children:a.jsxs("div",{className:"flex items-center gap-4",children:[Le&&a.jsx(P,{withInternalPadding:!0,className:"rounded-md p-2",children:a.jsx(F,{name:"previous-item",variant:"tertiary",size:1,className:`bg-white/90 hover:bg-white shadow-lg border border-gray-200 ${J?"opacity-50 cursor-not-allowed":"hover:scale-110"}`,onClick:()=>je("previous"),disabled:J,children:a.jsxs("div",{className:"flex items-center gap-1",children:[a.jsxs("div",{className:"flex -space-x-1",children:[a.jsx(oe,{className:"w-4 h-4"}),a.jsx(oe,{className:"w-4 h-4"})]}),a.jsx("span",{className:"font-semibold",children:"Previous"})]})})}),le&&a.jsx(P,{withInternalPadding:!0,className:"rounded-md p-2",children:a.jsx(F,{name:"delete",variant:"tertiary",size:1,className:"bg-red-50 hover:bg-red-100 text-red-700 border border-red-200 hover:border-red-300",onClick:qe,title:"Delete","aria-label":"Delete saved image",children:a.jsx(na,{className:"w-4 h-4"})})}),a.jsx(P,{withInternalPadding:!0,className:"rounded-md p-2",children:a.jsx(F,{name:"contribute",onClick:Qe,children:"Contribute"})}),le&&a.jsx(P,{withInternalPadding:!0,className:"rounded-md p-2",children:a.jsx(F,{name:"toggle-star",variant:"tertiary",size:1,className:`${e?.starred?"bg-red-100 hover:bg-red-200 text-red-800 border-2 border-red-400":"bg-gray-100 hover:bg-gray-200 text-gray-600 border-2 border-gray-300"} w-16 h-8 rounded-full transition-all duration-200 flex items-center justify-center`,onClick:Ke,title:e?.starred?"Unstar image":"Star image","aria-label":e?.starred?"Unstar image":"Star image",children:a.jsx("span",{className:`text-lg transition-all duration-200 ${e?.starred?"text-red-600":"text-gray-500"}`,children:e?.starred?"★":"☆"})})}),Te&&a.jsx(P,{withInternalPadding:!0,className:"rounded-md p-2",children:a.jsx(F,{name:"next-item",variant:"tertiary",size:1,className:`bg-white/90 hover:bg-white shadow-lg border border-gray-200 ${J?"opacity-50 cursor-not-allowed":"hover:scale-110"}`,onClick:()=>je("next"),disabled:J,children:a.jsxs("div",{className:"flex items-center gap-1",children:[a.jsx("span",{className:"font-semibold",children:"Next"}),a.jsxs("div",{className:"flex -space-x-1",children:[a.jsx(re,{className:"w-4 h-4"}),a.jsx(re,{className:"w-4 h-4"})]})]})})})]})})})]}):a.jsxs("div",{className:"text-center py-12",children:[a.jsx("div",{className:"text-xl font-semibold text-gray-600 mb-4",children:"No matches found"}),a.jsx("div",{className:"mt-4",children:a.jsx(F,{name:"clear-filters",variant:"secondary",onClick:Be,children:"Clear Filters"})})]})}):null]}),$e&&a.jsx("div",{className:m.fullSizeModalOverlay,onClick:()=>Z(!1),children:a.jsx("div",{className:m.fullSizeModalContent,onClick:t=>t.stopPropagation(),children:a.jsxs("div",{className:m.ratingWarningContent,children:[a.jsx("h3",{className:m.ratingWarningTitle,children:"Delete Image?"}),a.jsx("p",{className:m.ratingWarningText,children:"This action cannot be undone. Are you sure you want to delete this saved image and all related data?"}),a.jsxs("div",{className:m.ratingWarningButtons,children:[a.jsx(F,{name:"confirm-delete",variant:"secondary",onClick:Ze,children:"Delete"}),a.jsx(F,{name:"cancel-delete",variant:"tertiary",onClick:()=>Z(!1),children:"Cancel"})]})]})})}),fe&&a.jsx(da,{isOpen:fe,onClose:()=>{Q(!1),ie(!1),se(!1)},onExport:(t,i)=>{i.includes(e.image_type)&&Xe(t)},filteredCount:1,totalCount:1,hasFilters:!1,crisisMapsCount:e.image_type==="crisis_map"?1:0,droneImagesCount:e.image_type==="drone_image"?1:0,isLoading:Pe,exportSuccess:Re,variant:"single",onNavigateToList:()=>{Q(!1),y("/explore")},onNavigateAndExport:()=>{Q(!1),y("/explore?export=true")}}),a.jsx(oa,{isOpen:Ae,imageUrl:ze?.image_url||null,preview:null,selectedImageData:null,onClose:He,isLoading:Oe})]})}export{it as default}; diff --git a/py_backend/static/assets/index-Rlfiitbv.js b/py_backend/static/assets/index-CcfIBRoF.js similarity index 99% rename from py_backend/static/assets/index-Rlfiitbv.js rename to py_backend/static/assets/index-CcfIBRoF.js index e5a5be32..833b861f 100644 --- a/py_backend/static/assets/index-Rlfiitbv.js +++ b/py_backend/static/assets/index-CcfIBRoF.js @@ -1,4 +1,4 @@ -const __vite__mapDeps=(i,m=__vite__mapDeps,d=(m.f||(m.f=["assets/index-BzZTDKPD.js","assets/index-B1uKTNcW.css","assets/index-C5On3c4S.js","assets/useAdmin-CnId_VLW.js","assets/ExportModal-CGhKFoOs.js","assets/ExportModal-BoB3JpqO.css","assets/index-C85X4vtS.css","assets/AdminPage-BGisxcwl.js","assets/AdminPage-VgSjQ50W.css","assets/index-vuiGcTrC.js","assets/index-tDgjKyWF.css"])))=>i.map(i=>d[i]); +const __vite__mapDeps=(i,m=__vite__mapDeps,d=(m.f||(m.f=["assets/index-Dz4vX1uX.js","assets/index-B1uKTNcW.css","assets/index-7oBZSGHr.js","assets/useAdmin-CrA3XozJ.js","assets/ExportModal-x1pUTnT7.js","assets/ExportModal-BoB3JpqO.css","assets/index-C85X4vtS.css","assets/AdminPage-C8Qwkg88.js","assets/AdminPage-VgSjQ50W.css","assets/index-Bx3ZvIBj.js","assets/index-tDgjKyWF.css"])))=>i.map(i=>d[i]); function Jg(e,n){for(var i=0;io[s]})}}}return Object.freeze(Object.defineProperty(e,Symbol.toStringTag,{value:"Module"}))}(function(){const n=document.createElement("link").relList;if(n&&n.supports&&n.supports("modulepreload"))return;for(const s of document.querySelectorAll('link[rel="modulepreload"]'))o(s);new MutationObserver(s=>{for(const u of s)if(u.type==="childList")for(const d of u.addedNodes)d.tagName==="LINK"&&d.rel==="modulepreload"&&o(d)}).observe(document,{childList:!0,subtree:!0});function i(s){const u={};return s.integrity&&(u.integrity=s.integrity),s.referrerPolicy&&(u.referrerPolicy=s.referrerPolicy),s.crossOrigin==="use-credentials"?u.credentials="include":s.crossOrigin==="anonymous"?u.credentials="omit":u.credentials="same-origin",u}function o(s){if(s.ep)return;s.ep=!0;const u=i(s);fetch(s.href,u)}})();var f4=typeof globalThis<"u"?globalThis:typeof window<"u"?window:typeof global<"u"?global:typeof self<"u"?self:{};function e0(e){return e&&e.__esModule&&Object.prototype.hasOwnProperty.call(e,"default")?e.default:e}var ld={exports:{}},Za={},ud={exports:{}},Ge={};/** * @license React * react.production.min.js @@ -161,8 +161,8 @@ ${i||"AI-generated recommended actions will appear here..."}`;N(_)}},[e,n,i,o]); `),M=T.findIndex(W=>W.startsWith("Description:")),$=T.findIndex(W=>W.startsWith("Analysis:")),F=T.findIndex(W=>W.startsWith("Recommended Actions:"));if(M!==-1&&$!==-1&&F!==-1){const W=T.slice(M+1,$).join(` `).trim(),de=T.slice($+1,F).join(` `).trim(),O=T.slice(F+1).join(` -`).trim();W!==e&&s(W),de!==n&&u(de),O!==i&&d(O)}}};return h.jsxs(on,{heading:"Generated Text",headingLevel:3,withHeaderBorder:!0,withInternalPadding:!0,children:[h.jsx("div",{className:"text-left space-y-4",children:h.jsx("div",{children:h.jsx(U2,{name:"generatedContent",value:w,onChange:S,rows:12,placeholder:o?"":"AI-generated content will appear here..."})})}),h.jsxs("div",{className:q.submitSection,children:[h.jsx(Ue,{name:"back",variant:"secondary",onClick:f,children:"Back"}),b&&x&&!o&&h.jsx(Ue,{name:"edit-ratings",variant:"secondary",onClick:x,children:"Edit Ratings"}),h.jsx(kf,{name:"delete",variant:"tertiary",onClick:g,title:"Delete",ariaLabel:"Delete uploaded image",children:h.jsx(_f,{})}),h.jsx(Ue,{name:"submit",onClick:y,disabled:m,children:"Submit"})]})]})}function xP({isOpen:e,imageUrl:n,preview:i,selectedImageData:o,onClose:s,isLoading:u=!1}){if(!e)return null;let d,f;return o?(d=URL.createObjectURL(o.file),f=`Image ${o.index+1}: ${o.file.name}`):(d=n||i||void 0,f="Full size map"),h.jsx("div",{className:q.fullSizeModalOverlay,onClick:s,children:h.jsxs("div",{className:q.fullSizeModalContent,onClick:g=>g.stopPropagation(),children:[h.jsx("div",{className:q.fullSizeModalHeader,children:h.jsx(Ue,{name:"close-modal",variant:"tertiary",size:1,onClick:s,children:"✕"})}),h.jsx("div",{className:q.fullSizeModalImage,children:u?h.jsxs("div",{className:q.loadingContainer,children:[h.jsx(Xo,{className:"text-ifrcRed"}),h.jsx("p",{className:q.loadingText,children:"Loading image..."})]}):h.jsx("img",{src:d,alt:f})})]})})}function bP({isOpen:e,onClose:n}){return e?h.jsx("div",{className:q.fullSizeModalOverlay,onClick:n,children:h.jsx("div",{className:q.fullSizeModalContent,onClick:i=>i.stopPropagation(),children:h.jsxs("div",{className:q.ratingWarningContent,children:[h.jsx("h3",{className:q.ratingWarningTitle,children:"Please Confirm Your Ratings"}),h.jsx("p",{className:q.ratingWarningText,children:'You must confirm your performance ratings before submitting. Please go back to the rating section and click "Confirm Ratings".'}),h.jsx("div",{className:q.ratingWarningButtons,children:h.jsx(Ue,{name:"close-warning",variant:"secondary",onClick:n,children:"Close"})})]})})}):null}function CP({isOpen:e,onConfirm:n,onCancel:i}){return e?h.jsx("div",{className:q.fullSizeModalOverlay,onClick:i,children:h.jsx("div",{className:q.fullSizeModalContent,onClick:o=>o.stopPropagation(),children:h.jsxs("div",{className:q.ratingWarningContent,children:[h.jsx("h3",{className:q.ratingWarningTitle,children:"Delete Image?"}),h.jsx("p",{className:q.ratingWarningText,children:"This action cannot be undone. Are you sure you want to delete this uploaded image?"}),h.jsxs("div",{className:q.ratingWarningButtons,children:[h.jsx(Ue,{name:"confirm-delete",variant:"secondary",onClick:n,children:"Delete"}),h.jsx(Ue,{name:"cancel-delete",variant:"tertiary",onClick:i,children:"Cancel"})]})]})})}):null}function SP({isOpen:e,onConfirm:n,onCancel:i}){return e?h.jsx("div",{className:q.fullSizeModalOverlay,onClick:i,children:h.jsx("div",{className:q.fullSizeModalContent,onClick:o=>o.stopPropagation(),children:h.jsxs("div",{className:q.ratingWarningContent,children:[h.jsx("h3",{className:q.ratingWarningTitle,children:"Leave Page?"}),h.jsx("p",{className:q.ratingWarningText,children:"Your uploaded image will be deleted if you leave this page. Are you sure you want to continue?"}),h.jsxs("div",{className:q.ratingWarningButtons,children:[h.jsx(Ue,{name:"confirm-navigation",variant:"secondary",onClick:n,children:"Leave Page"}),h.jsx(Ue,{name:"cancel-navigation",variant:"tertiary",onClick:i,children:"Stay"})]})]})})}):null}function _P({isOpen:e,fallbackInfo:n,onClose:i}){if(!e||!n)return null;const s=(u=>u.includes("quota")||u.includes("credits")?"API quota exceeded - you've used up your monthly free credits":u.includes("rate")||u.includes("429")?"Rate limit exceeded - too many requests":u.includes("loading")||u.includes("503")?"Model is currently loading or unavailable":u.includes("network")||u.includes("timeout")?"Network connection issue":u.includes("MODEL_UNAVAILABLE")?"Model service is temporarily unavailable":u)(n.reason);return h.jsx("div",{className:q.fullSizeModalOverlay,onClick:i,children:h.jsx("div",{className:q.fullSizeModalContent,onClick:u=>u.stopPropagation(),children:h.jsxs("div",{className:q.ratingWarningContent,children:[h.jsx("h3",{className:q.ratingWarningTitle,children:"⚠️ Model Changed"}),h.jsxs("p",{className:q.ratingWarningText,children:[h.jsx("strong",{children:n.originalModel})," is currently unavailable. We've automatically switched to ",h.jsx("strong",{children:n.fallbackModel})," to complete your request."]}),h.jsxs("div",{className:q.fallbackReasonBox,children:[h.jsx("p",{className:q.fallbackReasonTitle,children:"Reason:"}),h.jsx("p",{className:q.fallbackReasonText,children:s})]}),h.jsx("div",{className:q.ratingWarningButtons,children:h.jsx(Ue,{name:"close-fallback",variant:"secondary",onClick:i,children:"Got it"})})]})})})}function EP({isOpen:e,preprocessingInfo:n,onClose:i}){return!e||!n?null:h.jsx("div",{className:q.fullSizeModalOverlay,onClick:i,children:h.jsx("div",{className:q.fullSizeModalContent,onClick:o=>o.stopPropagation(),children:h.jsxs("div",{className:q.ratingWarningContent,children:[h.jsx("h3",{className:q.ratingWarningTitle,children:"File Converted"}),h.jsxs("p",{className:q.ratingWarningText,children:["Your file ",h.jsx("strong",{children:n.original_filename})," has been converted from",h.jsxs("strong",{children:[" ",n.original_mime_type]})," to",h.jsxs("strong",{children:[" ",n.processed_mime_type]})," for optimal processing.",h.jsx("br",{}),h.jsx("br",{}),"This conversion ensures your file is in the best format for our AI models to analyze."]}),h.jsx("div",{className:q.ratingWarningButtons,children:h.jsx(Ue,{name:"close-preprocessing",variant:"secondary",onClick:i,children:"Got it"})})]})})})}function NP({isOpen:e,isPreprocessing:n,preprocessingProgress:i,onConfirm:o,onCancel:s}){return e?h.jsx("div",{className:q.fullSizeModalOverlay,onClick:n?void 0:s,children:h.jsx("div",{className:q.fullSizeModalContent,onClick:u=>u.stopPropagation(),children:h.jsxs("div",{className:q.ratingWarningContent,children:[h.jsx("h3",{className:q.ratingWarningTitle,children:"File Conversion Required"}),h.jsx("p",{className:q.ratingWarningText,children:"The file you selected will be converted to PNG format. This ensures optimal compatibility and processing by our AI models."}),!n&&h.jsxs("div",{className:q.ratingWarningButtons,children:[h.jsx(Ue,{name:"confirm-preprocessing",variant:"secondary",onClick:o,children:"Convert File"}),h.jsx(Ue,{name:"cancel-preprocessing",variant:"tertiary",onClick:s,children:"Cancel"})]}),n&&h.jsxs("div",{className:q.preprocessingProgress,children:[h.jsx("p",{children:i}),h.jsx(Xo,{className:"text-ifrcRed"})]})]})})}):null}function kP({isOpen:e,unsupportedFile:n,onClose:i}){return!e||!n?null:h.jsx("div",{className:q.fullSizeModalOverlay,onClick:i,children:h.jsx("div",{className:q.fullSizeModalContent,onClick:o=>o.stopPropagation(),children:h.jsxs("div",{className:q.ratingWarningContent,children:[h.jsx("h3",{className:q.ratingWarningTitle,children:"Unsupported File Format"}),h.jsxs("p",{className:q.ratingWarningText,children:["The file ",h.jsx("strong",{children:n.name})," is not supported for upload.",h.jsx("br",{}),h.jsx("br",{}),h.jsx("strong",{children:"Supported formats:"}),h.jsx("br",{}),"• Images: JPEG, PNG, TIFF, HEIC, WebP, GIF",h.jsx("br",{}),"• Documents: PDF (will be converted to image)",h.jsx("br",{}),h.jsx("br",{}),h.jsx("strong",{children:"Recommendation:"})," Convert your file to JPEG or PNG format for best compatibility."]}),h.jsx("div",{className:q.ratingWarningButtons,children:h.jsx(Ue,{name:"close-unsupported",variant:"secondary",onClick:i,children:"Got it"})})]})})})}function jP({isOpen:e,oversizedFile:n,onClose:i,onCancel:o}){return!e||!n?null:h.jsx("div",{className:q.lightModalOverlay,onClick:o,children:h.jsx("div",{className:q.fullSizeModalContent,onClick:s=>s.stopPropagation(),children:h.jsxs("div",{className:q.ratingWarningContent,children:[h.jsx("h3",{className:q.ratingWarningTitle,children:"File Size Warning"}),h.jsxs("p",{className:q.ratingWarningText,children:["The file ",h.jsx("strong",{children:n.name})," is large (",(n.size/(1024*1024)).toFixed(1),"MB).",h.jsx("br",{}),h.jsx("br",{}),h.jsx("strong",{children:"Warning:"})," This file size might exceed the limits of the AI models we use.",h.jsx("br",{}),h.jsx("br",{}),"You can still proceed, but consider using a smaller file if you encounter issues."]}),h.jsxs("div",{className:q.ratingWarningButtons,children:[h.jsx(Ue,{name:"continue-size-warning",variant:"secondary",onClick:i,children:"Continue"}),h.jsx(Ue,{name:"cancel-size-warning",variant:"tertiary",onClick:o,children:"Cancel"})]})]})})})}const Jl="selectedVlmModel";function Xg(){let e,n;try{[e]=Bx(),n=ks()}catch(k){console.warn("Router context not available, using fallback:",k),e=new URLSearchParams,n=()=>{}}const[i,o]=v.useState(1),[s,u]=v.useState(!1),[d,f]=v.useState(!1),[g,y]=v.useState(!1),x=v.useRef(i),b=v.useRef(null),[m,w]=v.useState(null),[N,S]=v.useState(null),[_,T]=v.useState([]),[M,$]=v.useState(""),[F,W]=v.useState(""),[de,O]=v.useState(""),[K,ce]=v.useState("crisis_map"),[he,R]=v.useState([]),[H,G]=v.useState(""),[ee,pe]=v.useState(!1),[Ce,_e]=v.useState(""),[Z,le]=v.useState(""),[j,V]=v.useState(""),[oe,Se]=v.useState(""),[se,re]=v.useState(""),[te,Q]=v.useState(""),[Y,Je]=v.useState(""),[an,Ut]=v.useState(""),[ot,vt]=v.useState(!1),[lt,pt]=v.useState(""),[ct,dt]=v.useState(""),[yt,It]=v.useState([]),[sn,pn]=v.useState([]),[Ln,ai]=v.useState([]),[mn,gn]=v.useState([]),[Rr,Yn]=v.useState([]),[Ht,Yt]=v.useState([]),[Ct,wt]=v.useState(null),[ln,Vt]=v.useState([]),[yr,Ri]=v.useState(null),[si,Ar]=v.useState(""),[$r,Mn]=v.useState(""),[Fr,un]=v.useState(""),[Dn,zr]=v.useState(""),[wr,Ai]=v.useState({accuracy:50,context:50,usability:50}),[$i,Xn]=v.useState(!1),[xr,li]=v.useState(null),[On,P]=v.useState(!1),[I,U]=v.useState(!1),[X,ue]=v.useState(!1),[Te,De]=v.useState(!1),[ye,xe]=v.useState(null),[we,ve]=v.useState(!1),[Fe,He]=v.useState(null),[Tt,Ye]=v.useState(!1),[Qe,at]=v.useState(null),[Jn,vn]=v.useState(!1),[yn,qe]=v.useState(null),[Fi,cn]=v.useState(!1),[Hn,Ft]=v.useState(""),[ui,Ve]=v.useState(!1),[nt,Pt]=v.useState(null),[Br,We]=v.useState(!1),[br,ci]=v.useState(null),[da,Ur]=v.useState(0);x.current=i,b.current=Ct;const Cr=k=>!k||sn.length===0?k:sn.find(Ee=>Ee.s_code===k||Ee.label===k)?.s_code||k,zi=k=>{$(Cr(k||""))},yo=k=>W(k||""),Ru=k=>O(k||""),fa=k=>ce(k||""),ha=k=>R(Array.isArray(k)?k:[]),Is=k=>_e(k||""),pa=k=>le(k||""),Bi=k=>V(k||""),Au=k=>Se(k||""),ma=k=>re(k||""),tt=k=>Q(k||""),Rs=k=>Je(k||""),As=k=>Ut(k||""),ga=k=>vt(k||!1),$s=k=>pt(k||""),Fs=k=>dt(k||""),Ui=k=>o(k),va=v.useCallback(()=>{_.length>1&&Ur(k=>k>0?k-1:_.length-1)},[_.length]),wo=v.useCallback(()=>{_.length>1&&Ur(k=>k<_.length-1?k+1:0)},[_.length]),Sr=v.useCallback(k=>{k>=0&&k<_.length&&Ur(k)},[_.length]),er=()=>{if(_.length<5){const k=document.createElement("input");k.type="file",k.accept=".jpg,.jpeg,.png,.tiff,.tif,.heic,.heif,.webp,.gif,.pdf",k.onchange=ke=>{const Ee=ke.target;if(Ee.files&&Ee.files[0]){const Le=Ee.files[0];ya(Le)}},k.click()}},tr=k=>{T(ke=>{const Ee=ke.filter((Le,me)=>me!==k);return Ee.length===1?S(Ee[0]):Ee.length===0&&S(null),Ee}),It(ke=>ke.filter((Ee,Le)=>Le!==k))},Hi=(k,ke,Ee)=>{It(Le=>{const me=[...Le];return me[k]||(me[k]={source:"",eventType:"",epsg:"",countries:[],centerLon:"",centerLat:"",amslM:"",aglM:"",headingDeg:"",yawDeg:"",pitchDeg:"",rollDeg:"",rtkFix:!1,stdHM:"",stdVM:""}),ke==="source"?me[k]={...me[k],[ke]:Cr(Ee)}:me[k]={...me[k],[ke]:Ee},me})},di=k=>{const ke=["image/jpeg","image/jpg","image/png"],Ee=[".jpg",".jpeg",".png"];let Le=!ke.includes(k.type);if(!Le&&k.name){const me=k.name.toLowerCase().substring(k.name.lastIndexOf("."));Le=!Ee.includes(me)}return Le},nr=k=>{const ke=["text/html","text/css","application/javascript","application/json","text/plain","application/xml","text/xml","application/zip","application/x-zip-compressed","application/x-rar-compressed","application/x-7z-compressed","audio/","video/","text/csv","application/vnd.ms-excel","application/vnd.openxmlformats-officedocument.spreadsheetml.sheet","application/vnd.ms-powerpoint","application/vnd.openxmlformats-officedocument.presentationml.presentation","application/msword","application/vnd.openxmlformats-officedocument.wordprocessingml.document"];for(const Ee of ke)if(k.type.startsWith(Ee))return!0;if(k.name){const Ee=k.name.toLowerCase().substring(k.name.lastIndexOf("."));if([".html",".htm",".css",".js",".json",".txt",".xml",".zip",".rar",".7z",".csv",".xlsx",".xls",".pptx",".ppt",".docx",".doc",".mp3",".mp4",".avi",".mov"].includes(Ee))return!0}return!1},ya=k=>{if(k){if(console.log("File selected:",k.name,"Type:",k.type,"Size:",k.size),k.size/(1024*1024)>5&&(console.log("File too large, showing size warning modal"),ci(k),We(!0)),nr(k)){console.log("File format not supported at all, showing unsupported format modal"),Pt(k),Ve(!0);return}di(k)?(console.log("File needs preprocessing, showing modal"),qe(k),vn(!0)):(console.log("File does not need preprocessing, setting directly"),_.length===0?(S(k),T([k])):T(Ee=>[...Ee,k]))}},wa=k=>{if(k){if(console.log("File changed:",k.name,"Type:",k.type,"Size:",k.size),k.size/(1024*1024)>5&&(console.log("File too large, showing size warning modal"),ci(k),We(!0)),nr(k)){console.log("File format not supported at all, showing unsupported format modal"),Pt(k),Ve(!0);return}di(k)?(console.log("File needs preprocessing, showing modal"),qe(k),vn(!0)):(console.log("File does not need preprocessing, replacing last file"),_.length>1?(T(Ee=>{const Le=[...Ee];return Le[Le.length-1]=k,Le}),_.length===1&&S(k)):(S(k),T([k])))}};async function rr(k){const ke=await k.text();try{return ke?JSON.parse(ke):{}}catch{return{error:ke}}}function xa(k,ke){const Ee=k instanceof Error?k.message:`Failed to ${ke.toLowerCase()}`;alert(Ee)}async function ba(){if(_.length!==0){u(!0);try{_.length===1?await xo():await zs()}catch(k){xa(k,"Upload")}finally{u(!1)}}}async function xo(){console.log("DEBUG: Starting single image upload");const k=new FormData;if(k.append("file",_[0]),k.append("title",H),k.append("image_type",K),M&&k.append("source",M),F&&k.append("event_type",F),de&&k.append("epsg",de),he.length>0&&he.forEach(Le=>k.append("countries",Le)),K==="drone_image"&&(Ce&&k.append("center_lon",Ce),Z&&k.append("center_lat",Z),j&&k.append("amsl_m",j),oe&&k.append("agl_m",oe),se&&k.append("heading_deg",se),te&&k.append("yaw_deg",te),Y&&k.append("pitch_deg",Y),an&&k.append("roll_deg",an),ot&&k.append("rtk_fix",ot.toString()),lt&&k.append("std_h_m",lt),ct&&k.append("std_v_m",ct)),ee)k.append("model_name","manual");else{const Le=localStorage.getItem(Jl);Le&&k.append("model_name",Le)}const ke=await fetch("/api/images/",{method:"POST",body:k}),Ee=await rr(ke);if(!ke.ok)throw new Error(Ee.error||"Upload failed");console.log("DEBUG: Single upload response:",Ee),await Bs(Ee,!1)}async function zs(){console.log("DEBUG: Starting multi-image upload");const k=new FormData;_.forEach(me=>k.append("files",me)),k.append("title",H),k.append("image_type",K),yt.forEach((me,Re)=>{me.source&&k.append(`source_${Re}`,me.source),me.eventType&&k.append(`event_type_${Re}`,me.eventType),me.epsg&&k.append(`epsg_${Re}`,me.epsg),me.countries.length>0&&me.countries.forEach(Nt=>k.append(`countries_${Re}`,Nt)),K==="drone_image"&&(me.centerLon&&k.append(`center_lon_${Re}`,me.centerLon),me.centerLat&&k.append(`center_lat_${Re}`,me.centerLat),me.amslM&&k.append(`amsl_m_${Re}`,me.amslM),me.aglM&&k.append(`agl_m_${Re}`,me.aglM),me.headingDeg&&k.append(`heading_deg_${Re}`,me.headingDeg),me.yawDeg&&k.append(`yaw_deg_${Re}`,me.yawDeg),me.pitchDeg&&k.append(`pitch_deg_${Re}`,me.pitchDeg),me.rollDeg&&k.append(`roll_deg_${Re}`,me.rollDeg),me.rtkFix&&k.append(`rtk_fix_${Re}`,me.rtkFix.toString()),me.stdHM&&k.append(`std_h_m_${Re}`,me.stdHM),me.stdVM&&k.append(`std_v_m_${Re}`,me.stdVM))});const ke=localStorage.getItem(Jl);ke&&k.append("model_name",ke);const Ee=await fetch("/api/images/multi",{method:"POST",body:k}),Le=await rr(Ee);if(!Ee.ok)throw new Error(Le.error||"Upload failed");console.log("DEBUG: Multi upload response:",Le),await Bs(Le,!0)}async function Bs(k,ke){Ri(k.image_url),k.preprocessing_info&&typeof k.preprocessing_info=="object"&&"was_preprocessed"in k.preprocessing_info&&k.preprocessing_info.was_preprocessed===!0&&(at(k.preprocessing_info),Ye(!0));const Ee=k.image_id;if(!Ee)throw new Error("Upload failed: image_id not found");if(wt(Ee),ke)if(k.image_ids&&Array.isArray(k.image_ids)){const ft=k.image_ids;console.log("DEBUG: Storing image IDs for multi-upload:",ft),Vt(ft)}else console.log("DEBUG: Multi-upload but no image_ids found, using single ID"),Vt([Ee]);else console.log("DEBUG: Storing single image ID:",Ee),Vt([Ee]);const Le=k,me=Le.raw_json,Re=me?.fallback_used,Nt=me?.original_model,Rt=me?.fallback_reason,Lt=Le.model;Re&&Nt&&Rt&&(He({originalModel:Nt,fallbackModel:Lt,reason:Rt}),ve(!0));const Mt=Le.model==="manual",ir=me?.metadata;if(ir){const ft=ir.metadata||ir;if(ft&&typeof ft=="object"){const _r=[];if(ke){const St=ft.metadata_images;if(St&&typeof St=="object")for(let lr=1;lr<=_.length;lr++){const _o=`image${lr}`,Hr=St[_o];if(Hr&&typeof Hr=="object"){const Er=Hr,Fu=Er.source||"",zu=Mt?"":Cr(Fu);_r.push({source:zu,eventType:Er.type||"",epsg:Er.epsg||"",countries:Array.isArray(Er.countries)?Er.countries:[],centerLon:"",centerLat:"",amslM:"",aglM:"",headingDeg:"",yawDeg:"",pitchDeg:"",rollDeg:"",rtkFix:!1,stdHM:"",stdVM:""})}else _r.push({source:"",eventType:"",epsg:"",countries:[],centerLon:"",centerLat:"",amslM:"",aglM:"",headingDeg:"",yawDeg:"",pitchDeg:"",rollDeg:"",rtkFix:!1,stdHM:"",stdVM:""})}else{const lr=ft.source||"",Hr={source:Mt?"":Cr(lr),eventType:ft.type||"",epsg:ft.epsg||"",countries:Array.isArray(ft.countries)?ft.countries:[],centerLon:"",centerLat:"",amslM:"",aglM:"",headingDeg:"",yawDeg:"",pitchDeg:"",rollDeg:"",rtkFix:!1,stdHM:"",stdVM:""};for(let Er=0;Er<_.length;Er++)_r.push({...Hr})}}else{const St=ft.source||"",_o={source:Mt?"":Cr(St),eventType:ft.type||"",epsg:ft.epsg||"",countries:Array.isArray(ft.countries)?ft.countries:[],centerLon:"",centerLat:"",amslM:"",aglM:"",headingDeg:"",yawDeg:"",pitchDeg:"",rollDeg:"",rtkFix:!1,stdHM:"",stdVM:""};_r.push(_o)}if(It(_r),_r.length>0){const St=_r[0];if(Mt)G(""),$(""),W(""),O(""),R([]);else{if(ft&&typeof ft=="object"){const lr=ft.title;lr&&G(lr||"")}$(St.source||""),W(St.eventType||""),O(St.epsg||""),R(St.countries||[])}K==="drone_image"&&(_e(St.centerLon||""),le(St.centerLat||""),V(St.amslM||""),Se(St.aglM||""),re(St.headingDeg||""),Q(St.yawDeg||""),Je(St.pitchDeg||""),Ut(St.rollDeg||""),vt(St.rtkFix||!1),pt(St.stdHM||""),dt(St.stdVM||""))}}}else if(Mt)if(G(""),$(""),W(""),O(""),R([]),K==="drone_image"&&(_e(""),le(""),V(""),Se(""),re(""),Q(""),Je(""),Ut(""),vt(!1),pt(""),dt("")),ke){const ft={source:"",eventType:"",epsg:"",countries:[],centerLon:"",centerLat:"",amslM:"",aglM:"",headingDeg:"",yawDeg:"",pitchDeg:"",rollDeg:"",rtkFix:!1,stdHM:"",stdVM:""};It(Array(_.length).fill(null).map(()=>({...ft})))}else It([{source:"",eventType:"",epsg:"",countries:[],centerLon:"",centerLat:"",amslM:"",aglM:"",headingDeg:"",yawDeg:"",pitchDeg:"",rollDeg:"",rtkFix:!1,stdHM:"",stdVM:""}]);const or=me?.parsed,So=me?.metadata;let ar,sr,In;or&&(ar=or.description,sr=or.analysis,In=or.recommended_actions),!ar&&!sr&&!In&&So&&(ar=So.description,sr=So.analysis,In=So.recommended_actions),Mt?(Mn(ar||""),un(sr||""),zr(In||"")):(ar!=null&&Mn(ar),sr!=null&&un(sr),In!=null&&zr(In)),Le.generated?Ar(Le.generated):Mt&&Ar(""),Mt&&P(!0),Ui("2a")}async function Vi(){if(console.log("handleSubmit called with:",{uploadedImageId:Ct,title:H,draft:si}),!Ct)return alert("No image to submit");if(!On){U(!0);return}y(!0);try{const k=ln.length>0?ln:[Ct];console.log("DEBUG: Submit - Using image IDs:",k),console.log("DEBUG: Submit - uploadedImageIds:",ln),console.log("DEBUG: Submit - uploadedImageId:",Ct);for(let Re=0;Reg.stopPropagation(),children:[h.jsx("div",{className:q.fullSizeModalHeader,children:h.jsx(Ue,{name:"close-modal",variant:"tertiary",size:1,onClick:s,children:"✕"})}),h.jsx("div",{className:q.fullSizeModalImage,children:u?h.jsxs("div",{className:q.loadingContainer,children:[h.jsx(Xo,{className:"text-ifrcRed"}),h.jsx("p",{className:q.loadingText,children:"Loading image..."})]}):h.jsx("img",{src:d,alt:f})})]})})}function bP({isOpen:e,onClose:n}){return e?h.jsx("div",{className:q.fullSizeModalOverlay,onClick:n,children:h.jsx("div",{className:q.fullSizeModalContent,onClick:i=>i.stopPropagation(),children:h.jsxs("div",{className:q.ratingWarningContent,children:[h.jsx("h3",{className:q.ratingWarningTitle,children:"Please Confirm Your Ratings"}),h.jsx("p",{className:q.ratingWarningText,children:'You must confirm your performance ratings before submitting. Please go back to the rating section and click "Confirm Ratings".'}),h.jsx("div",{className:q.ratingWarningButtons,children:h.jsx(Ue,{name:"close-warning",variant:"secondary",onClick:n,children:"Close"})})]})})}):null}function CP({isOpen:e,onConfirm:n,onCancel:i}){return e?h.jsx("div",{className:q.fullSizeModalOverlay,onClick:i,children:h.jsx("div",{className:q.fullSizeModalContent,onClick:o=>o.stopPropagation(),children:h.jsxs("div",{className:q.ratingWarningContent,children:[h.jsx("h3",{className:q.ratingWarningTitle,children:"Delete Image?"}),h.jsx("p",{className:q.ratingWarningText,children:"This action cannot be undone. Are you sure you want to delete this uploaded image?"}),h.jsxs("div",{className:q.ratingWarningButtons,children:[h.jsx(Ue,{name:"confirm-delete",variant:"secondary",onClick:n,children:"Delete"}),h.jsx(Ue,{name:"cancel-delete",variant:"tertiary",onClick:i,children:"Cancel"})]})]})})}):null}function SP({isOpen:e,onConfirm:n,onCancel:i}){return e?h.jsx("div",{className:q.fullSizeModalOverlay,onClick:i,children:h.jsx("div",{className:q.fullSizeModalContent,onClick:o=>o.stopPropagation(),children:h.jsxs("div",{className:q.ratingWarningContent,children:[h.jsx("h3",{className:q.ratingWarningTitle,children:"Leave Page?"}),h.jsx("p",{className:q.ratingWarningText,children:"Your uploaded image will be deleted if you leave this page. Are you sure you want to continue?"}),h.jsxs("div",{className:q.ratingWarningButtons,children:[h.jsx(Ue,{name:"confirm-navigation",variant:"secondary",onClick:n,children:"Leave Page"}),h.jsx(Ue,{name:"cancel-navigation",variant:"tertiary",onClick:i,children:"Stay"})]})]})})}):null}function _P({isOpen:e,fallbackInfo:n,onClose:i}){if(!e||!n)return null;const s=(u=>u.includes("quota")||u.includes("credits")?"API quota exceeded - you've used up your monthly free credits":u.includes("rate")||u.includes("429")?"Rate limit exceeded - too many requests":u.includes("loading")||u.includes("503")?"Model is currently loading or unavailable":u.includes("network")||u.includes("timeout")?"Network connection issue":u.includes("MODEL_UNAVAILABLE")?"Model service is temporarily unavailable":u)(n.reason);return h.jsx("div",{className:q.fullSizeModalOverlay,onClick:i,children:h.jsx("div",{className:q.fullSizeModalContent,onClick:u=>u.stopPropagation(),children:h.jsxs("div",{className:q.ratingWarningContent,children:[h.jsx("h3",{className:q.ratingWarningTitle,children:"⚠️ Model Changed"}),h.jsxs("p",{className:q.ratingWarningText,children:[h.jsx("strong",{children:n.originalModel})," is currently unavailable. We've automatically switched to ",h.jsx("strong",{children:n.fallbackModel})," to complete your request."]}),h.jsxs("div",{className:q.fallbackReasonBox,children:[h.jsx("p",{className:q.fallbackReasonTitle,children:"Reason:"}),h.jsx("p",{className:q.fallbackReasonText,children:s})]}),h.jsx("div",{className:q.ratingWarningButtons,children:h.jsx(Ue,{name:"close-fallback",variant:"secondary",onClick:i,children:"Got it"})})]})})})}function EP({isOpen:e,preprocessingInfo:n,onClose:i}){return!e||!n?null:h.jsx("div",{className:q.fullSizeModalOverlay,onClick:i,children:h.jsx("div",{className:q.fullSizeModalContent,onClick:o=>o.stopPropagation(),children:h.jsxs("div",{className:q.ratingWarningContent,children:[h.jsx("h3",{className:q.ratingWarningTitle,children:"File Converted"}),h.jsxs("p",{className:q.ratingWarningText,children:["Your file ",h.jsx("strong",{children:n.original_filename})," has been converted from",h.jsxs("strong",{children:[" ",n.original_mime_type]})," to",h.jsxs("strong",{children:[" ",n.processed_mime_type]})," for optimal processing.",h.jsx("br",{}),h.jsx("br",{}),"This conversion ensures your file is in the best format for our AI models to analyze."]}),h.jsx("div",{className:q.ratingWarningButtons,children:h.jsx(Ue,{name:"close-preprocessing",variant:"secondary",onClick:i,children:"Got it"})})]})})})}function NP({isOpen:e,isPreprocessing:n,preprocessingProgress:i,onConfirm:o,onCancel:s}){return e?h.jsx("div",{className:q.fullSizeModalOverlay,onClick:n?void 0:s,children:h.jsx("div",{className:q.fullSizeModalContent,onClick:u=>u.stopPropagation(),children:h.jsxs("div",{className:q.ratingWarningContent,children:[h.jsx("h3",{className:q.ratingWarningTitle,children:"File Conversion Required"}),h.jsx("p",{className:q.ratingWarningText,children:"The file you selected will be converted to PNG format. This ensures optimal compatibility and processing by our AI models."}),!n&&h.jsxs("div",{className:q.ratingWarningButtons,children:[h.jsx(Ue,{name:"confirm-preprocessing",variant:"secondary",onClick:o,children:"Convert File"}),h.jsx(Ue,{name:"cancel-preprocessing",variant:"tertiary",onClick:s,children:"Cancel"})]}),n&&h.jsxs("div",{className:q.preprocessingProgress,children:[h.jsx("p",{children:i}),h.jsx(Xo,{className:"text-ifrcRed"})]})]})})}):null}function kP({isOpen:e,unsupportedFile:n,onClose:i}){return!e||!n?null:h.jsx("div",{className:q.fullSizeModalOverlay,onClick:i,children:h.jsx("div",{className:q.fullSizeModalContent,onClick:o=>o.stopPropagation(),children:h.jsxs("div",{className:q.ratingWarningContent,children:[h.jsx("h3",{className:q.ratingWarningTitle,children:"Unsupported File Format"}),h.jsxs("p",{className:q.ratingWarningText,children:["The file ",h.jsx("strong",{children:n.name})," is not supported for upload.",h.jsx("br",{}),h.jsx("br",{}),h.jsx("strong",{children:"Supported formats:"}),h.jsx("br",{}),"• Images: JPEG, PNG, TIFF, HEIC, WebP, GIF",h.jsx("br",{}),"• Documents: PDF (will be converted to image)",h.jsx("br",{}),h.jsx("br",{}),h.jsx("strong",{children:"Recommendation:"})," Convert your file to JPEG or PNG format for best compatibility."]}),h.jsx("div",{className:q.ratingWarningButtons,children:h.jsx(Ue,{name:"close-unsupported",variant:"secondary",onClick:i,children:"Got it"})})]})})})}function jP({isOpen:e,oversizedFile:n,onClose:i,onCancel:o}){return!e||!n?null:h.jsx("div",{className:q.lightModalOverlay,onClick:o,children:h.jsx("div",{className:q.fullSizeModalContent,onClick:s=>s.stopPropagation(),children:h.jsxs("div",{className:q.ratingWarningContent,children:[h.jsx("h3",{className:q.ratingWarningTitle,children:"File Size Warning"}),h.jsxs("p",{className:q.ratingWarningText,children:["The file ",h.jsx("strong",{children:n.name})," is large (",(n.size/(1024*1024)).toFixed(1),"MB).",h.jsx("br",{}),h.jsx("br",{}),h.jsx("strong",{children:"Warning:"})," This file size might exceed the limits of the AI models we use.",h.jsx("br",{}),h.jsx("br",{}),"You can still proceed, but consider using a smaller file if you encounter issues."]}),h.jsxs("div",{className:q.ratingWarningButtons,children:[h.jsx(Ue,{name:"continue-size-warning",variant:"secondary",onClick:i,children:"Continue"}),h.jsx(Ue,{name:"cancel-size-warning",variant:"tertiary",onClick:o,children:"Cancel"})]})]})})})}const Jl="selectedVlmModel";function Xg(){let e,n;try{[e]=Bx(),n=ks()}catch(k){console.warn("Router context not available, using fallback:",k),e=new URLSearchParams,n=()=>{}}const[i,o]=v.useState(1),[s,u]=v.useState(!1),[d,f]=v.useState(!1),[g,y]=v.useState(!1),x=v.useRef(i),b=v.useRef(null),[m,w]=v.useState(null),[N,S]=v.useState(null),[_,T]=v.useState([]),[M,$]=v.useState(""),[F,W]=v.useState(""),[de,O]=v.useState(""),[K,ce]=v.useState("crisis_map"),[he,R]=v.useState([]),[H,G]=v.useState(""),[ee,pe]=v.useState(!0),[Ce,_e]=v.useState(""),[Z,le]=v.useState(""),[j,V]=v.useState(""),[oe,Se]=v.useState(""),[se,re]=v.useState(""),[te,Q]=v.useState(""),[Y,Je]=v.useState(""),[an,Ut]=v.useState(""),[ot,vt]=v.useState(!1),[lt,pt]=v.useState(""),[ct,dt]=v.useState(""),[yt,It]=v.useState([]),[sn,pn]=v.useState([]),[Ln,ai]=v.useState([]),[mn,gn]=v.useState([]),[Rr,Yn]=v.useState([]),[Ht,Yt]=v.useState([]),[Ct,wt]=v.useState(null),[ln,Vt]=v.useState([]),[yr,Ri]=v.useState(null),[si,Ar]=v.useState(""),[$r,Mn]=v.useState(""),[Fr,un]=v.useState(""),[Dn,zr]=v.useState(""),[wr,Ai]=v.useState({accuracy:50,context:50,usability:50}),[$i,Xn]=v.useState(!1),[xr,li]=v.useState(null),[On,P]=v.useState(!1),[I,U]=v.useState(!1),[X,ue]=v.useState(!1),[Te,De]=v.useState(!1),[ye,xe]=v.useState(null),[we,ve]=v.useState(!1),[Fe,He]=v.useState(null),[Tt,Ye]=v.useState(!1),[Qe,at]=v.useState(null),[Jn,vn]=v.useState(!1),[yn,qe]=v.useState(null),[Fi,cn]=v.useState(!1),[Hn,Ft]=v.useState(""),[ui,Ve]=v.useState(!1),[nt,Pt]=v.useState(null),[Br,We]=v.useState(!1),[br,ci]=v.useState(null),[da,Ur]=v.useState(0);x.current=i,b.current=Ct;const Cr=k=>!k||sn.length===0?k:sn.find(Ee=>Ee.s_code===k||Ee.label===k)?.s_code||k,zi=k=>{$(Cr(k||""))},yo=k=>W(k||""),Ru=k=>O(k||""),fa=k=>ce(k||""),ha=k=>R(Array.isArray(k)?k:[]),Is=k=>_e(k||""),pa=k=>le(k||""),Bi=k=>V(k||""),Au=k=>Se(k||""),ma=k=>re(k||""),tt=k=>Q(k||""),Rs=k=>Je(k||""),As=k=>Ut(k||""),ga=k=>vt(k||!1),$s=k=>pt(k||""),Fs=k=>dt(k||""),Ui=k=>o(k),va=v.useCallback(()=>{_.length>1&&Ur(k=>k>0?k-1:_.length-1)},[_.length]),wo=v.useCallback(()=>{_.length>1&&Ur(k=>k<_.length-1?k+1:0)},[_.length]),Sr=v.useCallback(k=>{k>=0&&k<_.length&&Ur(k)},[_.length]),er=()=>{if(_.length<5){const k=document.createElement("input");k.type="file",k.accept=".jpg,.jpeg,.png,.tiff,.tif,.heic,.heif,.webp,.gif,.pdf",k.onchange=ke=>{const Ee=ke.target;if(Ee.files&&Ee.files[0]){const Le=Ee.files[0];ya(Le)}},k.click()}},tr=k=>{T(ke=>{const Ee=ke.filter((Le,me)=>me!==k);return Ee.length===1?S(Ee[0]):Ee.length===0&&S(null),Ee}),It(ke=>ke.filter((Ee,Le)=>Le!==k))},Hi=(k,ke,Ee)=>{It(Le=>{const me=[...Le];return me[k]||(me[k]={source:"",eventType:"",epsg:"",countries:[],centerLon:"",centerLat:"",amslM:"",aglM:"",headingDeg:"",yawDeg:"",pitchDeg:"",rollDeg:"",rtkFix:!1,stdHM:"",stdVM:""}),ke==="source"?me[k]={...me[k],[ke]:Cr(Ee)}:me[k]={...me[k],[ke]:Ee},me})},di=k=>{const ke=["image/jpeg","image/jpg","image/png"],Ee=[".jpg",".jpeg",".png"];let Le=!ke.includes(k.type);if(!Le&&k.name){const me=k.name.toLowerCase().substring(k.name.lastIndexOf("."));Le=!Ee.includes(me)}return Le},nr=k=>{const ke=["text/html","text/css","application/javascript","application/json","text/plain","application/xml","text/xml","application/zip","application/x-zip-compressed","application/x-rar-compressed","application/x-7z-compressed","audio/","video/","text/csv","application/vnd.ms-excel","application/vnd.openxmlformats-officedocument.spreadsheetml.sheet","application/vnd.ms-powerpoint","application/vnd.openxmlformats-officedocument.presentationml.presentation","application/msword","application/vnd.openxmlformats-officedocument.wordprocessingml.document"];for(const Ee of ke)if(k.type.startsWith(Ee))return!0;if(k.name){const Ee=k.name.toLowerCase().substring(k.name.lastIndexOf("."));if([".html",".htm",".css",".js",".json",".txt",".xml",".zip",".rar",".7z",".csv",".xlsx",".xls",".pptx",".ppt",".docx",".doc",".mp3",".mp4",".avi",".mov"].includes(Ee))return!0}return!1},ya=k=>{if(k){if(console.log("File selected:",k.name,"Type:",k.type,"Size:",k.size),k.size/(1024*1024)>5&&(console.log("File too large, showing size warning modal"),ci(k),We(!0)),nr(k)){console.log("File format not supported at all, showing unsupported format modal"),Pt(k),Ve(!0);return}di(k)?(console.log("File needs preprocessing, showing modal"),qe(k),vn(!0)):(console.log("File does not need preprocessing, setting directly"),_.length===0?(S(k),T([k])):T(Ee=>[...Ee,k]))}},wa=k=>{if(k){if(console.log("File changed:",k.name,"Type:",k.type,"Size:",k.size),k.size/(1024*1024)>5&&(console.log("File too large, showing size warning modal"),ci(k),We(!0)),nr(k)){console.log("File format not supported at all, showing unsupported format modal"),Pt(k),Ve(!0);return}di(k)?(console.log("File needs preprocessing, showing modal"),qe(k),vn(!0)):(console.log("File does not need preprocessing, replacing last file"),_.length>1?(T(Ee=>{const Le=[...Ee];return Le[Le.length-1]=k,Le}),_.length===1&&S(k)):(S(k),T([k])))}};async function rr(k){const ke=await k.text();try{return ke?JSON.parse(ke):{}}catch{return{error:ke}}}function xa(k,ke){const Ee=k instanceof Error?k.message:`Failed to ${ke.toLowerCase()}`;alert(Ee)}async function ba(){if(_.length!==0){u(!0);try{_.length===1?await xo():await zs()}catch(k){xa(k,"Upload")}finally{u(!1)}}}async function xo(){console.log("DEBUG: Starting single image upload");const k=new FormData;if(k.append("file",_[0]),k.append("title",H),k.append("image_type",K),M&&k.append("source",M),F&&k.append("event_type",F),de&&k.append("epsg",de),he.length>0&&he.forEach(Le=>k.append("countries",Le)),K==="drone_image"&&(Ce&&k.append("center_lon",Ce),Z&&k.append("center_lat",Z),j&&k.append("amsl_m",j),oe&&k.append("agl_m",oe),se&&k.append("heading_deg",se),te&&k.append("yaw_deg",te),Y&&k.append("pitch_deg",Y),an&&k.append("roll_deg",an),ot&&k.append("rtk_fix",ot.toString()),lt&&k.append("std_h_m",lt),ct&&k.append("std_v_m",ct)),ee)k.append("model_name","manual");else{const Le=localStorage.getItem(Jl);Le&&k.append("model_name",Le)}const ke=await fetch("/api/images/",{method:"POST",body:k}),Ee=await rr(ke);if(!ke.ok)throw new Error(Ee.error||"Upload failed");console.log("DEBUG: Single upload response:",Ee),await Bs(Ee,!1)}async function zs(){console.log("DEBUG: Starting multi-image upload");const k=new FormData;_.forEach(me=>k.append("files",me)),k.append("title",H),k.append("image_type",K),yt.forEach((me,Re)=>{me.source&&k.append(`source_${Re}`,me.source),me.eventType&&k.append(`event_type_${Re}`,me.eventType),me.epsg&&k.append(`epsg_${Re}`,me.epsg),me.countries.length>0&&me.countries.forEach(Nt=>k.append(`countries_${Re}`,Nt)),K==="drone_image"&&(me.centerLon&&k.append(`center_lon_${Re}`,me.centerLon),me.centerLat&&k.append(`center_lat_${Re}`,me.centerLat),me.amslM&&k.append(`amsl_m_${Re}`,me.amslM),me.aglM&&k.append(`agl_m_${Re}`,me.aglM),me.headingDeg&&k.append(`heading_deg_${Re}`,me.headingDeg),me.yawDeg&&k.append(`yaw_deg_${Re}`,me.yawDeg),me.pitchDeg&&k.append(`pitch_deg_${Re}`,me.pitchDeg),me.rollDeg&&k.append(`roll_deg_${Re}`,me.rollDeg),me.rtkFix&&k.append(`rtk_fix_${Re}`,me.rtkFix.toString()),me.stdHM&&k.append(`std_h_m_${Re}`,me.stdHM),me.stdVM&&k.append(`std_v_m_${Re}`,me.stdVM))});const ke=localStorage.getItem(Jl);ke&&k.append("model_name",ke);const Ee=await fetch("/api/images/multi",{method:"POST",body:k}),Le=await rr(Ee);if(!Ee.ok)throw new Error(Le.error||"Upload failed");console.log("DEBUG: Multi upload response:",Le),await Bs(Le,!0)}async function Bs(k,ke){Ri(k.image_url),k.preprocessing_info&&typeof k.preprocessing_info=="object"&&"was_preprocessed"in k.preprocessing_info&&k.preprocessing_info.was_preprocessed===!0&&(at(k.preprocessing_info),Ye(!0));const Ee=k.image_id;if(!Ee)throw new Error("Upload failed: image_id not found");if(wt(Ee),ke)if(k.image_ids&&Array.isArray(k.image_ids)){const ft=k.image_ids;console.log("DEBUG: Storing image IDs for multi-upload:",ft),Vt(ft)}else console.log("DEBUG: Multi-upload but no image_ids found, using single ID"),Vt([Ee]);else console.log("DEBUG: Storing single image ID:",Ee),Vt([Ee]);const Le=k,me=Le.raw_json,Re=me?.fallback_used,Nt=me?.original_model,Rt=me?.fallback_reason,Lt=Le.model;Re&&Nt&&Rt&&(He({originalModel:Nt,fallbackModel:Lt,reason:Rt}),ve(!0));const Mt=Le.model==="manual",ir=me?.metadata;if(ir){const ft=ir.metadata||ir;if(ft&&typeof ft=="object"){const _r=[];if(ke){const St=ft.metadata_images;if(St&&typeof St=="object")for(let lr=1;lr<=_.length;lr++){const _o=`image${lr}`,Hr=St[_o];if(Hr&&typeof Hr=="object"){const Er=Hr,Fu=Er.source||"",zu=Mt?"":Cr(Fu);_r.push({source:zu,eventType:Er.type||"",epsg:Er.epsg||"",countries:Array.isArray(Er.countries)?Er.countries:[],centerLon:"",centerLat:"",amslM:"",aglM:"",headingDeg:"",yawDeg:"",pitchDeg:"",rollDeg:"",rtkFix:!1,stdHM:"",stdVM:""})}else _r.push({source:"",eventType:"",epsg:"",countries:[],centerLon:"",centerLat:"",amslM:"",aglM:"",headingDeg:"",yawDeg:"",pitchDeg:"",rollDeg:"",rtkFix:!1,stdHM:"",stdVM:""})}else{const lr=ft.source||"",Hr={source:Mt?"":Cr(lr),eventType:ft.type||"",epsg:ft.epsg||"",countries:Array.isArray(ft.countries)?ft.countries:[],centerLon:"",centerLat:"",amslM:"",aglM:"",headingDeg:"",yawDeg:"",pitchDeg:"",rollDeg:"",rtkFix:!1,stdHM:"",stdVM:""};for(let Er=0;Er<_.length;Er++)_r.push({...Hr})}}else{const St=ft.source||"",_o={source:Mt?"":Cr(St),eventType:ft.type||"",epsg:ft.epsg||"",countries:Array.isArray(ft.countries)?ft.countries:[],centerLon:"",centerLat:"",amslM:"",aglM:"",headingDeg:"",yawDeg:"",pitchDeg:"",rollDeg:"",rtkFix:!1,stdHM:"",stdVM:""};_r.push(_o)}if(It(_r),_r.length>0){const St=_r[0];if(Mt)G(""),$(""),W(""),O(""),R([]);else{if(ft&&typeof ft=="object"){const lr=ft.title;lr&&G(lr||"")}$(St.source||""),W(St.eventType||""),O(St.epsg||""),R(St.countries||[])}K==="drone_image"&&(_e(St.centerLon||""),le(St.centerLat||""),V(St.amslM||""),Se(St.aglM||""),re(St.headingDeg||""),Q(St.yawDeg||""),Je(St.pitchDeg||""),Ut(St.rollDeg||""),vt(St.rtkFix||!1),pt(St.stdHM||""),dt(St.stdVM||""))}}}else if(Mt)if(G(""),$(""),W(""),O(""),R([]),K==="drone_image"&&(_e(""),le(""),V(""),Se(""),re(""),Q(""),Je(""),Ut(""),vt(!1),pt(""),dt("")),ke){const ft={source:"",eventType:"",epsg:"",countries:[],centerLon:"",centerLat:"",amslM:"",aglM:"",headingDeg:"",yawDeg:"",pitchDeg:"",rollDeg:"",rtkFix:!1,stdHM:"",stdVM:""};It(Array(_.length).fill(null).map(()=>({...ft})))}else It([{source:"",eventType:"",epsg:"",countries:[],centerLon:"",centerLat:"",amslM:"",aglM:"",headingDeg:"",yawDeg:"",pitchDeg:"",rollDeg:"",rtkFix:!1,stdHM:"",stdVM:""}]);const or=me?.parsed,So=me?.metadata;let ar,sr,In;or&&(ar=or.description,sr=or.analysis,In=or.recommended_actions),!ar&&!sr&&!In&&So&&(ar=So.description,sr=So.analysis,In=So.recommended_actions),Mt?(Mn(ar||""),un(sr||""),zr(In||"")):(ar!=null&&Mn(ar),sr!=null&&un(sr),In!=null&&zr(In)),Le.generated?Ar(Le.generated):Mt&&Ar(""),Mt&&P(!0),Ui("2a")}async function Vi(){if(console.log("handleSubmit called with:",{uploadedImageId:Ct,title:H,draft:si}),!Ct)return alert("No image to submit");if(!On){U(!0);return}y(!0);try{const k=ln.length>0?ln:[Ct];console.log("DEBUG: Submit - Using image IDs:",k),console.log("DEBUG: Submit - uploadedImageIds:",ln),console.log("DEBUG: Submit - uploadedImageId:",Ct);for(let Re=0;Re{P(!1),o(1),S(null),T([]),w(null),wt(null),Vt([]),Ri(null),G(""),$(""),W(""),O(""),R([]),_e(""),le(""),V(""),Se(""),re(""),Q(""),Je(""),Ut(""),vt(!1),pt(""),dt(""),Ai({accuracy:50,context:50,usability:50}),Ar(""),Mn(""),un(""),zr(""),It([]),ve(!1),He(null),Ye(!1),at(null),vn(!1),qe(null),cn(!1),Ft(""),Ve(!1),Pt(null),We(!1),ci(null),n("/upload",{replace:!0})},bo=v.useCallback(k=>{k==="/upload"||k==="/"||(b.current?(xe(k),De(!0)):n(k))},[n]);async function $u(){if(ye&&b.current)try{await fetch(`/api/images/${b.current}`,{method:"DELETE"}),De(!1),xe(null),n(ye)}catch(k){console.error("Failed to delete image before navigation:",k),De(!1),xe(null),n(ye)}}const Ca=async()=>{if(yn){cn(!0),Ft("Starting file conversion...");try{const k=new FormData;k.append("file",yn),k.append("preprocess_only","true"),Ft("Converting file format...");const ke=await fetch("/api/images/preprocess",{method:"POST",body:k});if(!ke.ok)throw new Error("Preprocessing failed");const Ee=await ke.json();Ft("Finalizing conversion...");const Le=atob(Ee.processed_content),me=new Uint8Array(Le.length);for(let Rt=0;Rt[...Rt,Re]),w(Nt),Ft("Conversion complete!"),setTimeout(()=>{vn(!1),qe(null),cn(!1),Ft("")},1e3)}catch(k){console.error("Preprocessing error:",k),Ft("Conversion failed. Please try again."),setTimeout(()=>{vn(!1),qe(null),cn(!1),Ft("")},2e3)}}},Co=()=>{vn(!1),qe(null),cn(!1),Ft("")},Sa=async k=>{f(!0);try{const ke=k.map(async Re=>{const Nt=await fetch(`/api/images/${Re}`);if(!Nt.ok)throw new Error(`Failed to fetch image ${Re}`);const Rt=await Nt.json(),Lt=await fetch(`/api/images/${Re}/file`);if(!Lt.ok)throw new Error(`Failed to fetch image file ${Re}`);const Mt=await Lt.blob(),ir=Rt.file_key.split("/").pop()||`contributed_${Re}.png`;return{file:new File([Mt],ir,{type:Mt.type}),imageData:Rt}}),Ee=await Promise.all(ke),Le=Ee.map(Re=>Re.file),me=Ee[0]?.imageData;T(Le),Vt(k),k.length===1&&wt(k[0]),Le.length>=1&&S(Le[0]),me?.image_type&&ce(me.image_type)}catch(ke){console.error("Failed to fetch contributed images:",ke),alert(`Failed to load contributed images: ${ke instanceof Error?ke.message:"Unknown error"}`)}finally{f(!1)}};return v.useEffect(()=>{Promise.all([fetch("/api/sources").then(k=>k.json()),fetch("/api/types").then(k=>k.json()),fetch("/api/spatial-references").then(k=>k.json()),fetch("/api/image-types").then(k=>k.json()),fetch("/api/countries").then(k=>k.json()),fetch("/api/models").then(k=>k.json())]).then(([k,ke,Ee,Le,me,Re])=>{!localStorage.getItem(Jl)&&Re?.length&&localStorage.setItem(Jl,Re[0].m_code),pn(k),ai(ke),gn(Ee),Yn(Le),Yt(me),k.length>0&&$(k[0].s_code),Le.length>0&&!e.get("imageType")&&!K&&ce(Le[0].image_type)})},[e,K]),v.useEffect(()=>(window.confirmNavigationIfNeeded=k=>{bo(k)},()=>{delete window.confirmNavigationIfNeeded}),[bo]),v.useEffect(()=>{const k=Le=>{if(b.current){const me="You have an uploaded image that will be deleted if you leave this page. Are you sure you want to leave?";return Le.preventDefault(),Le.returnValue=me,me}},ke=()=>{b.current&&fetch(`/api/images/${b.current}`,{method:"DELETE"}).catch(console.error)},Ee=Le=>{const me=Le.target,Re=me.closest("a[href]")||me.closest("[data-navigate]");if(Re&&b.current){const Nt=Re.getAttribute("href")||Re.getAttribute("data-navigate");Nt&&Nt!=="#"&&!Nt.startsWith("javascript:")&&!Nt.startsWith("mailto:")&&(Le.preventDefault(),Le.stopPropagation(),bo(Nt))}};return window.addEventListener("beforeunload",k),document.addEventListener("click",Ee,!0),()=>{window.removeEventListener("beforeunload",k),document.removeEventListener("click",Ee,!0),ke()}},[bo]),v.useEffect(()=>{if(!N){w(null);return}const k=URL.createObjectURL(N);return w(k),()=>URL.revokeObjectURL(k)},[N]),v.useEffect(()=>{const k=e.get("contribute"),ke=e.get("imageIds");if(k==="true"&&ke){const Ee=ke.split(",").filter(Le=>Le.trim());Ee.length>0&&Sa(Ee)}},[e]),v.useEffect(()=>{i==="2b"&&Ur(0)},[i]),h.jsxs(Iu,{children:[i!==3&&h.jsx("div",{className:"max-w-7xl mx-auto",children:h.jsxs("div",{className:q.uploadContainer,"data-step":i,children:[i===1&&!e.get("step")&&!d&&h.jsx(Kg,{files:_,file:N,preview:m,imageType:K,isManualMode:ee,onFileChange:ya,onRemoveImage:tr,onAddImage:er,onImageTypeChange:fa,onManualModeChange:pe,onChangeFile:wa}),i===1&&e.get("contribute")==="true"&&!d&&_.length>0&&h.jsx(Kg,{files:_,file:N,preview:m,imageType:K,isManualMode:ee,onFileChange:ya,onRemoveImage:tr,onAddImage:er,onImageTypeChange:fa,onManualModeChange:pe,onChangeFile:wa}),s&&h.jsxs("div",{className:q.loadingContainer,children:[h.jsx(Xo,{className:"text-ifrcRed"}),h.jsx("p",{className:q.loadingText,children:"Generating..."})]}),d&&h.jsxs("div",{className:q.loadingContainer,children:[h.jsx(Xo,{className:"text-ifrcRed"}),h.jsx("p",{className:q.loadingText,children:"Loading contribution..."})]}),(i===1&&!s&&!d||i===1&&e.get("contribute")==="true"&&!s&&!d&&_.length>0)&&h.jsx("div",{className:q.generateButtonContainer,children:yr?h.jsx(Ue,{name:"generate-from-url",onClick:ba,children:ee?"Start":"Generate Caption"}):h.jsx(Ue,{name:"generate",disabled:_.length===0,onClick:ba,children:ee?"Start":"Generate"})}),i==="2a"&&h.jsxs("div",{className:q.step2Layout,children:[h.jsx("div",{className:q.mapColumn,children:h.jsx(Yg,{files:_,imageUrl:yr,preview:m,onViewFullSize:k=>{li(k||null),Xn(!0)}})}),h.jsx("div",{className:q.contentColumn,children:h.jsxs("div",{className:q.metadataSectionCard,children:[h.jsx(vP,{files:_,imageType:K,title:H,source:M,eventType:F,epsg:de,countries:he,centerLon:Ce,centerLat:Z,amslM:j,aglM:oe,headingDeg:se,yawDeg:te,pitchDeg:Y,rollDeg:an,rtkFix:ot,stdHM:lt,stdVM:ct,metadataArray:yt,sources:sn,types:Ln,spatialReferences:mn,imageTypes:Rr,countriesOptions:Ht,onTitleChange:k=>G(k||""),onSourceChange:zi,onEventTypeChange:yo,onEpsgChange:Ru,onCountriesChange:ha,onCenterLonChange:Is,onCenterLatChange:pa,onAmslMChange:Bi,onAglMChange:Au,onHeadingDegChange:ma,onYawDegChange:tt,onPitchDegChange:Rs,onRollDegChange:As,onRtkFixChange:ga,onStdHMChange:$s,onStdVMChange:Fs,onImageTypeChange:fa,updateMetadataForImage:Hi}),h.jsxs("div",{className:q.confirmSection,children:[h.jsx(kf,{name:"delete",variant:"tertiary",onClick:fi,title:"Delete",ariaLabel:"Delete uploaded image",children:h.jsx(_f,{})}),h.jsx(Ue,{name:"confirm-metadata",onClick:()=>Ui("2b"),children:"Next"})]})]})})]}),i==="2b"&&h.jsxs("div",{className:q.step2bLayout,children:[g&&h.jsxs("div",{className:q.loadingContainer,children:[h.jsx(Xo,{className:"text-ifrcRed"}),h.jsx("p",{className:q.loadingText,children:"Submitting..."})]}),h.jsxs("div",{className:`${q.topRow} ${On?q.ratingHidden:""}`,children:[h.jsx("div",{className:q.imageSection,children:h.jsx(Yg,{files:_,imageUrl:yr,preview:m,onViewFullSize:k=>{li(k||null),Xn(!0)},currentImageIndex:da,onGoToPrevious:va,onGoToNext:wo,onGoToImage:Sr,showCarousel:!0})}),!On&&h.jsx("div",{className:q.metadataSectionCard,children:h.jsx(yP,{isPerformanceConfirmed:On,scores:wr,onScoreChange:(k,ke)=>Ai(Ee=>({...Ee,[k]:ke})),onConfirmRatings:()=>P(!0),onEditRatings:()=>P(!1)})})]}),h.jsx("div",{className:q.metadataSectionCard,children:h.jsx(wP,{description:$r,analysis:Fr,recommendedActions:Dn,isManualMode:ee,onDescriptionChange:k=>Mn(k||""),onAnalysisChange:k=>un(k||""),onRecommendedActionsChange:k=>zr(k||""),onBack:()=>Ui("2a"),onDelete:fi,onSubmit:Vi,onEditRatings:()=>P(!1),isPerformanceConfirmed:On,isSubmitting:g})})]})]})}),i===3&&h.jsxs("div",{className:q.successContainer,children:[h.jsx(kn,{level:2,className:q.successHeading,children:"Saved!"}),h.jsx("p",{className:q.successText,children:e.get("contribute")==="true"?"Your contribution has been successfully saved.":"Your caption has been successfully saved."}),h.jsx("div",{className:q.successButton,children:h.jsx(Ue,{name:"upload-another",onClick:()=>{qi()},children:"Upload Another"})})]}),h.jsx(xP,{isOpen:$i,imageUrl:yr,preview:m,selectedImageData:xr,onClose:()=>{Xn(!1),li(null)}}),h.jsx(bP,{isOpen:I,onClose:()=>U(!1)}),h.jsx(CP,{isOpen:X,onConfirm:hi,onCancel:()=>ue(!1)}),h.jsx(SP,{isOpen:Te,onConfirm:$u,onCancel:()=>De(!1)}),h.jsx(_P,{isOpen:we,fallbackInfo:Fe,onClose:()=>ve(!1)}),h.jsx(EP,{isOpen:Tt,preprocessingInfo:Qe,onClose:()=>Ye(!1)}),h.jsx(NP,{isOpen:Jn,isPreprocessing:Fi,preprocessingProgress:Hn,onConfirm:Ca,onCancel:Co}),h.jsx(kP,{isOpen:ui,unsupportedFile:nt,onClose:()=>Ve(!1)}),h.jsx(jP,{isOpen:Br,oversizedFile:br,onClose:()=>We(!1),onCancel:()=>We(!1)})]})}const TP="_helpContainer_1wavj_1",PP="_helpSection_1wavj_13",LP="_sectionHeader_1wavj_49",MP="_sectionTitle_1wavj_91",DP="_sectionContent_1wavj_105",OP="_guidelinesList_1wavj_119",IP="_buttonContainer_1wavj_181",ut={helpContainer:TP,helpSection:PP,sectionHeader:LP,sectionTitle:MP,sectionContent:DP,guidelinesList:OP,buttonContainer:IP};function RP(){const e=ks(),{setShowReferenceExamples:n}=cP(),i=()=>{e("/upload")},o=()=>{n(!0),e("/explore")},s=()=>{e("/analytics?view=crisis_maps")};return h.jsx(Iu,{className:"py-10",children:h.jsx("div",{className:ut.helpContainer,children:h.jsxs("div",{className:"space-y-8",children:[h.jsxs("div",{className:ut.helpSection,children:[h.jsx("div",{className:ut.sectionHeader,children:h.jsx(kn,{level:3,className:ut.sectionTitle,children:"Introduction"})}),h.jsx("div",{className:ut.sectionContent,children:"In collaboration with the IFRC, PromptAid Vision is a tool that generates textual descriptions of crisis maps/crisis drone images utiliing Visual language models. This prototype is for collecting data for the fine-tuning of our own models. We aim to utilize AI tools to support national societies with rapid decision making during emergencies."}),h.jsx("div",{className:ut.buttonContainer,children:h.jsx(Ue,{name:"upload-now",variant:"secondary",onClick:i,children:"Upload now →"})})]}),h.jsxs("div",{className:ut.helpSection,children:[h.jsx("div",{className:ut.sectionHeader,children:h.jsx(kn,{level:3,className:ut.sectionTitle,children:"Guidelines"})}),h.jsxs("div",{className:ut.sectionContent,children:["To make the process smoother, please follow the guidelines below:",h.jsxs("ul",{className:ut.guidelinesList,children:[h.jsx("li",{children:"Avoid uploading images that are not crisis maps/crisis drone images."}),h.jsx("li",{children:"Confirm the image details prior to modifying the description."}),h.jsx("li",{children:"Before the modification, please read the description generated and provide a rating via the rating sliders."}),h.jsx("li",{children:'Click the "Submit" button to save the description.'})]})]}),h.jsx("div",{className:ut.buttonContainer,children:h.jsx(Ue,{name:"see-examples",variant:"secondary",onClick:o,children:"See examples →"})})]}),h.jsxs("div",{className:ut.helpSection,children:[h.jsx("div",{className:ut.sectionHeader,children:h.jsx(kn,{level:3,className:ut.sectionTitle,children:"VLMs"})}),h.jsx("div",{className:ut.sectionContent,children:"PromptAid Vision uses a variety of Visual Language Models (VLMs). A random VLM is selected for each upload. Therefore feel free to delete and reupload. You can view performance details here:"}),h.jsx("div",{className:ut.buttonContainer,children:h.jsx(Ue,{name:"view-vlm-details",variant:"secondary",onClick:s,children:"View VLM details →"})})]}),h.jsxs("div",{className:ut.helpSection,children:[h.jsx("div",{className:ut.sectionHeader,children:h.jsx(kn,{level:3,className:ut.sectionTitle,children:"Dataset"})}),h.jsx("div",{className:ut.sectionContent,children:"All users are able to export the dataset. You could apply filters when exporting, and it have the option to organize based on model fine-tuning formats."}),h.jsx("div",{className:ut.buttonContainer,children:h.jsx(Ue,{name:"export-dataset",variant:"secondary",onClick:()=>{n(!1),e("/explore"),setTimeout(()=>{const u=document.querySelector('[name="export-dataset"]');u&&u.click()},100)},children:"Export dataset →"})})]}),h.jsxs("div",{className:ut.helpSection,children:[h.jsx("div",{className:ut.sectionHeader,children:h.jsx(kn,{level:3,className:ut.sectionTitle,children:"Contact us"})}),h.jsx("div",{className:ut.sectionContent,children:"Need help or have questions about PromptAid Vision? Our team is here to support you."}),h.jsx("div",{className:ut.buttonContainer,children:h.jsx(Ue,{name:"contact-support",variant:"secondary",disabled:!0,children:"Get in touch →"})})]})]})})})}const AP="_demoContainer_19wfc_1",$P="_section_19wfc_13",FP="_pageTitle_19wfc_33",zP="_description_19wfc_43",BP="_sectionHeader_19wfc_57",UP="_sectionTitle_19wfc_65",HP="_sectionDescription_19wfc_75",VP="_switchGrid_19wfc_87",qP="_switchItem_19wfc_99",WP="_switchLabel_19wfc_119",GP="_switchWrapper_19wfc_133",ZP="_stateDisplay_19wfc_147",QP="_nativeCheckboxLabel_19wfc_165",KP="_nativeCheckbox_19wfc_165",YP="_buttonToggle_19wfc_197",XP="_buttonToggleOff_19wfc_219",JP="_buttonToggleOn_19wfc_231",e4="_buttonToggleText_19wfc_253",fe={demoContainer:AP,section:$P,pageTitle:FP,description:zP,sectionHeader:BP,sectionTitle:UP,sectionDescription:HP,switchGrid:VP,switchItem:qP,switchLabel:WP,switchWrapper:GP,stateDisplay:ZP,nativeCheckboxLabel:QP,nativeCheckbox:KP,buttonToggle:YP,buttonToggleOff:XP,buttonToggleOn:JP,buttonToggleText:e4};function t4(){const[e,n]=v.useState("off"),[i,o]=v.useState("on"),[s,u]=v.useState(!1),[d,f]=v.useState(!0),[g,y]=v.useState(!1),[x,b]=v.useState(!0),[m,w]=v.useState(!1),[N,S]=v.useState(!0),[_,T]=v.useState(!1),[M,$]=v.useState(!1);return h.jsx(Iu,{className:"py-10",children:h.jsx("div",{className:fe.demoContainer,children:h.jsxs("div",{className:"space-y-12",children:[h.jsxs("div",{className:fe.section,children:[h.jsx(kn,{level:2,className:fe.pageTitle,children:"Switch Components Demo"}),h.jsx("p",{className:fe.description,children:"This page showcases all available switch/toggle implementations. Each switch is clearly labeled so you can easily identify and compare different UI patterns."})]}),h.jsxs("div",{className:fe.section,children:[h.jsxs("div",{className:fe.sectionHeader,children:[h.jsx(kn,{level:3,className:fe.sectionTitle,children:"1. SegmentInput Switches (IFRC UI)"}),h.jsx("p",{className:fe.sectionDescription,children:"Using SegmentInput component for binary on/off choices"})]}),h.jsxs("div",{className:fe.switchGrid,children:[h.jsxs("div",{className:fe.switchItem,children:[h.jsx("div",{className:fe.switchLabel,children:"Switch 1: SegmentInput (Off by default)"}),h.jsx(on,{withInternalPadding:!0,className:fe.switchWrapper,children:h.jsx(su,{name:"switch-1",value:e,onChange:F=>{(F==="on"||F==="off")&&n(F)},options:[{key:"off",label:"Off"},{key:"on",label:"On"}],keySelector:F=>F.key,labelSelector:F=>F.label})}),h.jsxs("div",{className:fe.stateDisplay,children:["State: ",h.jsx("strong",{children:e})]})]}),h.jsxs("div",{className:fe.switchItem,children:[h.jsx("div",{className:fe.switchLabel,children:"Switch 2: SegmentInput (On by default)"}),h.jsx(on,{withInternalPadding:!0,className:fe.switchWrapper,children:h.jsx(su,{name:"switch-2",value:i,onChange:F=>{(F==="on"||F==="off")&&o(F)},options:[{key:"off",label:"Off"},{key:"on",label:"On"}],keySelector:F=>F.key,labelSelector:F=>F.label})}),h.jsxs("div",{className:fe.stateDisplay,children:["State: ",h.jsx("strong",{children:i})]})]})]})]}),h.jsxs("div",{className:fe.section,children:[h.jsxs("div",{className:fe.sectionHeader,children:[h.jsx(kn,{level:3,className:fe.sectionTitle,children:"2. IFRC Checkbox Switches"}),h.jsx("p",{className:fe.sectionDescription,children:"Using Checkbox component from @ifrc-go/ui for on/off toggles"})]}),h.jsxs("div",{className:fe.switchGrid,children:[h.jsxs("div",{className:fe.switchItem,children:[h.jsx("div",{className:fe.switchLabel,children:"Switch 3: IFRC Checkbox (Off by default)"}),h.jsx(wd,{name:"switch-3",value:s,onChange:u,label:"Enable feature"}),h.jsxs("div",{className:fe.stateDisplay,children:["State: ",h.jsx("strong",{children:s?"On":"Off"})]})]}),h.jsxs("div",{className:fe.switchItem,children:[h.jsx("div",{className:fe.switchLabel,children:"Switch 4: IFRC Checkbox (On by default)"}),h.jsx(wd,{name:"switch-4",value:d,onChange:f,label:"Auto-save enabled"}),h.jsxs("div",{className:fe.stateDisplay,children:["State: ",h.jsx("strong",{children:d?"On":"Off"})]})]})]})]}),h.jsxs("div",{className:fe.section,children:[h.jsxs("div",{className:fe.sectionHeader,children:[h.jsx(kn,{level:3,className:fe.sectionTitle,children:"3. Native HTML Checkbox Switches"}),h.jsx("p",{className:fe.sectionDescription,children:'Using native HTML input[type="checkbox"] elements (as used in AdminPage)'})]}),h.jsxs("div",{className:fe.switchGrid,children:[h.jsxs("div",{className:fe.switchItem,children:[h.jsx("div",{className:fe.switchLabel,children:"Switch 5: Native Checkbox (Off by default)"}),h.jsxs("label",{className:fe.nativeCheckboxLabel,children:[h.jsx("input",{type:"checkbox",checked:g,onChange:F=>y(F.target.checked),className:fe.nativeCheckbox}),h.jsx("span",{children:"Available for use"})]}),h.jsxs("div",{className:fe.stateDisplay,children:["State: ",h.jsx("strong",{children:g?"On":"Off"})]})]}),h.jsxs("div",{className:fe.switchItem,children:[h.jsx("div",{className:fe.switchLabel,children:"Switch 6: Native Checkbox (On by default)"}),h.jsxs("label",{className:fe.nativeCheckboxLabel,children:[h.jsx("input",{type:"checkbox",checked:x,onChange:F=>b(F.target.checked),className:fe.nativeCheckbox}),h.jsx("span",{children:"RTK Fix Available"})]}),h.jsxs("div",{className:fe.stateDisplay,children:["State: ",h.jsx("strong",{children:x?"On":"Off"})]})]})]})]}),h.jsxs("div",{className:fe.section,children:[h.jsxs("div",{className:fe.sectionHeader,children:[h.jsx(kn,{level:3,className:fe.sectionTitle,children:"4. Custom CSS Toggle Switches"}),h.jsx("p",{className:fe.sectionDescription,children:"Custom-built toggle switch component with smooth animations"})]}),h.jsxs("div",{className:fe.switchGrid,children:[h.jsxs("div",{className:fe.switchItem,children:[h.jsx("div",{className:fe.switchLabel,children:"Switch 7: Custom Toggle (Off by default)"}),h.jsx(ls,{name:"switch-7",checked:m,onChange:w,label:"Enable notifications"}),h.jsxs("div",{className:fe.stateDisplay,children:["State: ",h.jsx("strong",{children:m?"On":"Off"})]})]}),h.jsxs("div",{className:fe.switchItem,children:[h.jsx("div",{className:fe.switchLabel,children:"Switch 8: Custom Toggle (On by default)"}),h.jsx(ls,{name:"switch-8",checked:N,onChange:S,label:"Dark mode"}),h.jsxs("div",{className:fe.stateDisplay,children:["State: ",h.jsx("strong",{children:N?"On":"Off"})]})]}),h.jsxs("div",{className:fe.switchItem,children:[h.jsx("div",{className:fe.switchLabel,children:"Switch 9: Custom Toggle (No label, Off by default)"}),h.jsx(ls,{name:"switch-9",checked:_,onChange:T}),h.jsxs("div",{className:fe.stateDisplay,children:["State: ",h.jsx("strong",{children:_?"On":"Off"})]})]})]})]}),h.jsxs("div",{className:fe.section,children:[h.jsxs("div",{className:fe.sectionHeader,children:[h.jsx(kn,{level:3,className:fe.sectionTitle,children:"5. Button-based Toggle Switch"}),h.jsx("p",{className:fe.sectionDescription,children:"Using a button element styled as a toggle switch"})]}),h.jsxs("div",{className:fe.switchItem,children:[h.jsx("div",{className:fe.switchLabel,children:"Switch 10: Button Toggle (Off by default)"}),h.jsx("button",{type:"button",className:`${fe.buttonToggle} ${M?fe.buttonToggleOn:fe.buttonToggleOff}`,onClick:()=>$(!M),children:h.jsx("span",{className:fe.buttonToggleText,children:M?"On":"Off"})}),h.jsxs("div",{className:fe.stateDisplay,children:["State: ",h.jsx("strong",{children:M?"On":"Off"})]})]})]}),h.jsxs("div",{className:fe.section,children:[h.jsxs("div",{className:fe.sectionHeader,children:[h.jsx(kn,{level:3,className:fe.sectionTitle,children:"6. Disabled Switch States"}),h.jsx("p",{className:fe.sectionDescription,children:"Examples of switches in disabled state"})]}),h.jsxs("div",{className:fe.switchGrid,children:[h.jsxs("div",{className:fe.switchItem,children:[h.jsx("div",{className:fe.switchLabel,children:"Disabled SegmentInput"}),h.jsx(on,{withInternalPadding:!0,className:fe.switchWrapper,children:h.jsx(su,{name:"disabled-segment",value:"on",onChange:()=>{},options:[{key:"off",label:"Off"},{key:"on",label:"On"}],keySelector:F=>F.key,labelSelector:F=>F.label,disabled:!0})})]}),h.jsxs("div",{className:fe.switchItem,children:[h.jsx("div",{className:fe.switchLabel,children:"Disabled IFRC Checkbox"}),h.jsx(wd,{name:"disabled-checkbox",value:!0,onChange:()=>{},label:"Disabled option",disabled:!0})]}),h.jsxs("div",{className:fe.switchItem,children:[h.jsx("div",{className:fe.switchLabel,children:"Disabled Custom Toggle"}),h.jsx(ls,{name:"disabled-custom",checked:!0,onChange:()=>{},label:"Disabled toggle",disabled:!0})]})]})]})]})})})}const n4=v.createContext(void 0),r4=({children:e})=>{const[n,i]=v.useState(!1),[o,s]=v.useState(!0),u=async()=>{const y=localStorage.getItem("adminToken");if(!y){i(!1),s(!1);return}try{(await fetch("/api/admin/verify",{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${y}`}})).ok?i(!0):(localStorage.removeItem("adminToken"),i(!1))}catch(x){console.error("Error verifying admin token:",x),localStorage.removeItem("adminToken"),i(!1)}finally{s(!1)}},d=async y=>{try{const x=await fetch("/api/admin/login",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({password:y})});if(x.ok){const b=await x.json();return localStorage.setItem("adminToken",b.access_token),i(!0),!0}else return!1}catch(x){return console.error("Login error:",x),!1}},f=()=>{localStorage.removeItem("adminToken"),i(!1)};v.useEffect(()=>{u()},[]);const g={isAuthenticated:n,isLoading:o,login:d,logout:f,verifyToken:u};return h.jsx(n4.Provider,{value:g,children:e})},i4=v.lazy(()=>Kn(()=>import("./index-BzZTDKPD.js"),__vite__mapDeps([0,1]))),o4=v.lazy(()=>Kn(()=>import("./index-C5On3c4S.js"),__vite__mapDeps([2,3,4,5,6]))),a4=v.lazy(()=>Kn(()=>import("./AdminPage-BGisxcwl.js"),__vite__mapDeps([7,3,8]))),s4=v.lazy(()=>Kn(()=>import("./index-vuiGcTrC.js"),__vite__mapDeps([9,3,4,5,10])));class l4 extends v.Component{constructor(n){super(n),this.state={hasError:!1}}static getDerivedStateFromError(){return{hasError:!0}}componentDidCatch(n,i){console.error("Error caught by boundary:",n,i)}render(){return this.state.hasError?h.jsxs("div",{style:{padding:"20px",textAlign:"center"},children:[h.jsx("h2",{children:"Something went wrong"}),h.jsx("p",{children:"Please refresh the page to try again."}),h.jsx("button",{onClick:()=>window.location.reload(),children:"Refresh Page"})]}):this.props.children}}const Pi=e=>{const n=e();return n.catch(()=>{}),n},u4=()=>{"requestIdleCallback"in window?requestIdleCallback(()=>{Pi(()=>Kn(()=>import("./index-BzZTDKPD.js"),__vite__mapDeps([0,1]))),Pi(()=>Kn(()=>import("./index-C5On3c4S.js"),__vite__mapDeps([2,3,4,5,6]))),Pi(()=>Kn(()=>import("./AdminPage-BGisxcwl.js"),__vite__mapDeps([7,3,8]))),Pi(()=>Kn(()=>import("./index-vuiGcTrC.js"),__vite__mapDeps([9,3,4,5,10])))}):setTimeout(()=>{Pi(()=>Kn(()=>import("./index-BzZTDKPD.js"),__vite__mapDeps([0,1]))),Pi(()=>Kn(()=>import("./index-C5On3c4S.js"),__vite__mapDeps([2,3,4,5,6]))),Pi(()=>Kn(()=>import("./AdminPage-BGisxcwl.js"),__vite__mapDeps([7,3,8]))),Pi(()=>Kn(()=>import("./index-vuiGcTrC.js"),__vite__mapDeps([9,3,4,5,10])))},1e3)};function c4(){const e=v.useMemo(()=>Ex([{element:h.jsx(Z2,{}),children:[{path:"/",element:h.jsx(Xg,{})},{path:"/upload",element:h.jsx(Xg,{})},{path:"/analytics",element:h.jsx(v.Suspense,{fallback:h.jsx("div",{children:"Loading Analytics..."}),children:h.jsx(i4,{})})},{path:"/explore",element:h.jsx(v.Suspense,{fallback:h.jsx("div",{children:"Loading Explore..."}),children:h.jsx(o4,{})})},{path:"/help",element:h.jsx(RP,{})},{path:"/demo",element:h.jsx(t4,{})},{path:"/admin",element:h.jsx(v.Suspense,{fallback:h.jsx("div",{children:"Loading Admin..."}),children:h.jsx(a4,{})})},{path:"/map/:mapId",element:h.jsx(v.Suspense,{fallback:h.jsx("div",{children:"Loading Map Details..."}),children:h.jsx(s4,{})})}]}],{basename:"/"}),[]),[n,i]=v.useState([]);v.useEffect(()=>{u4()},[]);const o=v.useCallback(g=>{i(y=>Qx([...y,g],x=>x.name)??y)},[i]),s=v.useCallback(g=>{i(y=>{const x=y.findIndex(m=>m.name===g);if(x===-1)return y;const b=[...y];return b.splice(x,1),b})},[i]),u=v.useCallback((g,y)=>{i(x=>{const b=x.findIndex(w=>w.name===g);if(b===-1)return x;const m=[...x];return m[b]={...m[b],...y},m})},[i]),d=v.useMemo(()=>({alerts:n,addAlert:o,removeAlert:s,updateAlert:u}),[n,o,s,u]),f=v.useMemo(()=>({languageNamespaceStatus:{},setLanguageNamespaceStatus:()=>{},currentLanguage:"en",setCurrentLanguage:()=>{},strings:{},setStrings:()=>{},registerNamespace:()=>{}}),[]);return h.jsx(l4,{children:h.jsx(Wx.Provider,{value:d,children:h.jsx(y0.Provider,{value:f,children:h.jsx(r4,{children:h.jsx(uP,{children:h.jsx(Ox,{router:e})})})})})})}function d4(){return h.jsx(c4,{})}console.log("React version at runtime:",v.version,"createContext exists?",!!v.createContext);X1.createRoot(document.getElementById("root")).render(h.jsx(v.StrictMode,{children:h.jsx(d4,{})}));export{Mb as A,ua as B,p4 as C,cP as D,v4 as E,_f as F,Kn as G,kn as H,q as I,io as J,h4 as K,su as L,xP as M,Iu as N,jt as O,qg as P,w4 as Q,E0 as R,wd as S,n4 as T,y4 as U,f4 as V,e0 as W,Xo as _,ze as a,Ot as b,C4 as c,S4 as d,m4 as e,Pb as f,S0 as g,b4 as h,x4 as i,h as j,gr as k,Jx as l,tN as m,Ue as n,Me as o,nb as p,cs as q,v as r,_0 as s,y0 as t,Bx as u,Ab as v,$b as w,ks as x,g4 as y,on as z}; +Recommended Actions: ${Dn}`,Ee={title:H,edited:ke,accuracy:wr.accuracy,context:wr.context,usability:wr.usability};console.log("Updating caption:",Ee);const Le=await fetch(`/api/images/${Ct}/caption`,{method:"PUT",headers:{"Content-Type":"application/json"},body:JSON.stringify(Ee)}),me=await rr(Le);if(!Le.ok)throw new Error(me.error||"Caption update failed");wt(null),Vt([]),Ui(3)}catch(k){xa(k,"Submit")}finally{y(!1)}}async function fi(){if(console.log("handleDelete called with uploadedImageId:",Ct),!Ct){alert("No image to delete. Please try refreshing the page.");return}ue(!0)}async function hi(){try{console.log("Deleting image with ID:",Ct);const k=await fetch(`/api/images/${Ct}`,{method:"DELETE"});if(!k.ok){const ke=await rr(k);throw new Error(ke.error||`Delete failed with status ${k.status}`)}ue(!1),qi()}catch(k){xa(k,"Delete")}}const qi=()=>{P(!1),o(1),S(null),T([]),w(null),wt(null),Vt([]),Ri(null),G(""),$(""),W(""),O(""),R([]),_e(""),le(""),V(""),Se(""),re(""),Q(""),Je(""),Ut(""),vt(!1),pt(""),dt(""),Ai({accuracy:50,context:50,usability:50}),Ar(""),Mn(""),un(""),zr(""),It([]),ve(!1),He(null),Ye(!1),at(null),vn(!1),qe(null),cn(!1),Ft(""),Ve(!1),Pt(null),We(!1),ci(null),n("/upload",{replace:!0})},bo=v.useCallback(k=>{k==="/upload"||k==="/"||(b.current?(xe(k),De(!0)):n(k))},[n]);async function $u(){if(ye&&b.current)try{await fetch(`/api/images/${b.current}`,{method:"DELETE"}),De(!1),xe(null),n(ye)}catch(k){console.error("Failed to delete image before navigation:",k),De(!1),xe(null),n(ye)}}const Ca=async()=>{if(yn){cn(!0),Ft("Starting file conversion...");try{const k=new FormData;k.append("file",yn),k.append("preprocess_only","true"),Ft("Converting file format...");const ke=await fetch("/api/images/preprocess",{method:"POST",body:k});if(!ke.ok)throw new Error("Preprocessing failed");const Ee=await ke.json();Ft("Finalizing conversion...");const Le=atob(Ee.processed_content),me=new Uint8Array(Le.length);for(let Rt=0;Rt[...Rt,Re]),w(Nt),Ft("Conversion complete!"),setTimeout(()=>{vn(!1),qe(null),cn(!1),Ft("")},1e3)}catch(k){console.error("Preprocessing error:",k),Ft("Conversion failed. Please try again."),setTimeout(()=>{vn(!1),qe(null),cn(!1),Ft("")},2e3)}}},Co=()=>{vn(!1),qe(null),cn(!1),Ft("")},Sa=async k=>{f(!0);try{const ke=k.map(async Re=>{const Nt=await fetch(`/api/images/${Re}`);if(!Nt.ok)throw new Error(`Failed to fetch image ${Re}`);const Rt=await Nt.json(),Lt=await fetch(`/api/images/${Re}/file`);if(!Lt.ok)throw new Error(`Failed to fetch image file ${Re}`);const Mt=await Lt.blob(),ir=Rt.file_key.split("/").pop()||`contributed_${Re}.png`;return{file:new File([Mt],ir,{type:Mt.type}),imageData:Rt}}),Ee=await Promise.all(ke),Le=Ee.map(Re=>Re.file),me=Ee[0]?.imageData;T(Le),Vt(k),k.length===1&&wt(k[0]),Le.length>=1&&S(Le[0]),me?.image_type&&ce(me.image_type)}catch(ke){console.error("Failed to fetch contributed images:",ke),alert(`Failed to load contributed images: ${ke instanceof Error?ke.message:"Unknown error"}`)}finally{f(!1)}};return v.useEffect(()=>{Promise.all([fetch("/api/sources").then(k=>k.json()),fetch("/api/types").then(k=>k.json()),fetch("/api/spatial-references").then(k=>k.json()),fetch("/api/image-types").then(k=>k.json()),fetch("/api/countries").then(k=>k.json()),fetch("/api/models").then(k=>k.json())]).then(([k,ke,Ee,Le,me,Re])=>{!localStorage.getItem(Jl)&&Re?.length&&localStorage.setItem(Jl,Re[0].m_code),pn(k),ai(ke),gn(Ee),Yn(Le),Yt(me),k.length>0&&$(k[0].s_code),Le.length>0&&!e.get("imageType")&&!K&&ce(Le[0].image_type)})},[e,K]),v.useEffect(()=>(window.confirmNavigationIfNeeded=k=>{bo(k)},()=>{delete window.confirmNavigationIfNeeded}),[bo]),v.useEffect(()=>{const k=Le=>{if(b.current){const me="You have an uploaded image that will be deleted if you leave this page. Are you sure you want to leave?";return Le.preventDefault(),Le.returnValue=me,me}},ke=()=>{b.current&&fetch(`/api/images/${b.current}`,{method:"DELETE"}).catch(console.error)},Ee=Le=>{const me=Le.target,Re=me.closest("a[href]")||me.closest("[data-navigate]");if(Re&&b.current){const Nt=Re.getAttribute("href")||Re.getAttribute("data-navigate");Nt&&Nt!=="#"&&!Nt.startsWith("javascript:")&&!Nt.startsWith("mailto:")&&(Le.preventDefault(),Le.stopPropagation(),bo(Nt))}};return window.addEventListener("beforeunload",k),document.addEventListener("click",Ee,!0),()=>{window.removeEventListener("beforeunload",k),document.removeEventListener("click",Ee,!0),ke()}},[bo]),v.useEffect(()=>{if(!N){w(null);return}const k=URL.createObjectURL(N);return w(k),()=>URL.revokeObjectURL(k)},[N]),v.useEffect(()=>{const k=e.get("contribute"),ke=e.get("imageIds");if(k==="true"&&ke){const Ee=ke.split(",").filter(Le=>Le.trim());Ee.length>0&&Sa(Ee)}},[e]),v.useEffect(()=>{i==="2b"&&Ur(0)},[i]),h.jsxs(Iu,{children:[i!==3&&h.jsx("div",{className:"max-w-7xl mx-auto",children:h.jsxs("div",{className:q.uploadContainer,"data-step":i,children:[i===1&&!e.get("step")&&!d&&h.jsx(Kg,{files:_,file:N,preview:m,imageType:K,isManualMode:ee,onFileChange:ya,onRemoveImage:tr,onAddImage:er,onImageTypeChange:fa,onManualModeChange:pe,onChangeFile:wa}),i===1&&e.get("contribute")==="true"&&!d&&_.length>0&&h.jsx(Kg,{files:_,file:N,preview:m,imageType:K,isManualMode:ee,onFileChange:ya,onRemoveImage:tr,onAddImage:er,onImageTypeChange:fa,onManualModeChange:pe,onChangeFile:wa}),s&&h.jsxs("div",{className:q.loadingContainer,children:[h.jsx(Xo,{className:"text-ifrcRed"}),h.jsx("p",{className:q.loadingText,children:"Generating..."})]}),d&&h.jsxs("div",{className:q.loadingContainer,children:[h.jsx(Xo,{className:"text-ifrcRed"}),h.jsx("p",{className:q.loadingText,children:"Loading contribution..."})]}),(i===1&&!s&&!d||i===1&&e.get("contribute")==="true"&&!s&&!d&&_.length>0)&&h.jsx("div",{className:q.generateButtonContainer,children:yr?h.jsx(Ue,{name:"generate-from-url",onClick:ba,children:ee?"Start":"Generate Caption"}):h.jsx(Ue,{name:"generate",disabled:_.length===0,onClick:ba,children:ee?"Start":"Generate"})}),i==="2a"&&h.jsxs("div",{className:q.step2Layout,children:[h.jsx("div",{className:q.mapColumn,children:h.jsx(Yg,{files:_,imageUrl:yr,preview:m,onViewFullSize:k=>{li(k||null),Xn(!0)}})}),h.jsx("div",{className:q.contentColumn,children:h.jsxs("div",{className:q.metadataSectionCard,children:[h.jsx(vP,{files:_,imageType:K,title:H,source:M,eventType:F,epsg:de,countries:he,centerLon:Ce,centerLat:Z,amslM:j,aglM:oe,headingDeg:se,yawDeg:te,pitchDeg:Y,rollDeg:an,rtkFix:ot,stdHM:lt,stdVM:ct,metadataArray:yt,sources:sn,types:Ln,spatialReferences:mn,imageTypes:Rr,countriesOptions:Ht,onTitleChange:k=>G(k||""),onSourceChange:zi,onEventTypeChange:yo,onEpsgChange:Ru,onCountriesChange:ha,onCenterLonChange:Is,onCenterLatChange:pa,onAmslMChange:Bi,onAglMChange:Au,onHeadingDegChange:ma,onYawDegChange:tt,onPitchDegChange:Rs,onRollDegChange:As,onRtkFixChange:ga,onStdHMChange:$s,onStdVMChange:Fs,onImageTypeChange:fa,updateMetadataForImage:Hi}),h.jsxs("div",{className:q.confirmSection,children:[h.jsx(kf,{name:"delete",variant:"tertiary",onClick:fi,title:"Delete",ariaLabel:"Delete uploaded image",children:h.jsx(_f,{})}),h.jsx(Ue,{name:"confirm-metadata",onClick:()=>Ui("2b"),children:"Next"})]})]})})]}),i==="2b"&&h.jsxs("div",{className:q.step2bLayout,children:[g&&h.jsxs("div",{className:q.loadingContainer,children:[h.jsx(Xo,{className:"text-ifrcRed"}),h.jsx("p",{className:q.loadingText,children:"Submitting..."})]}),h.jsxs("div",{className:`${q.topRow} ${On?q.ratingHidden:""}`,children:[h.jsx("div",{className:q.imageSection,children:h.jsx(Yg,{files:_,imageUrl:yr,preview:m,onViewFullSize:k=>{li(k||null),Xn(!0)},currentImageIndex:da,onGoToPrevious:va,onGoToNext:wo,onGoToImage:Sr,showCarousel:!0})}),!On&&h.jsx("div",{className:q.metadataSectionCard,children:h.jsx(yP,{isPerformanceConfirmed:On,scores:wr,onScoreChange:(k,ke)=>Ai(Ee=>({...Ee,[k]:ke})),onConfirmRatings:()=>P(!0),onEditRatings:()=>P(!1)})})]}),h.jsx("div",{className:q.metadataSectionCard,children:h.jsx(wP,{description:$r,analysis:Fr,recommendedActions:Dn,isManualMode:ee,onDescriptionChange:k=>Mn(k||""),onAnalysisChange:k=>un(k||""),onRecommendedActionsChange:k=>zr(k||""),onBack:()=>Ui("2a"),onDelete:fi,onSubmit:Vi,onEditRatings:()=>P(!1),isPerformanceConfirmed:On,isSubmitting:g})})]})]})}),i===3&&h.jsxs("div",{className:q.successContainer,children:[h.jsx(kn,{level:2,className:q.successHeading,children:"Saved!"}),h.jsx("p",{className:q.successText,children:e.get("contribute")==="true"?"Your contribution has been successfully saved.":"Your caption has been successfully saved."}),h.jsx("div",{className:q.successButton,children:h.jsx(Ue,{name:"upload-another",onClick:()=>{qi()},children:"Upload Another"})})]}),h.jsx(xP,{isOpen:$i,imageUrl:yr,preview:m,selectedImageData:xr,onClose:()=>{Xn(!1),li(null)}}),h.jsx(bP,{isOpen:I,onClose:()=>U(!1)}),h.jsx(CP,{isOpen:X,onConfirm:hi,onCancel:()=>ue(!1)}),h.jsx(SP,{isOpen:Te,onConfirm:$u,onCancel:()=>De(!1)}),h.jsx(_P,{isOpen:we,fallbackInfo:Fe,onClose:()=>ve(!1)}),h.jsx(EP,{isOpen:Tt,preprocessingInfo:Qe,onClose:()=>Ye(!1)}),h.jsx(NP,{isOpen:Jn,isPreprocessing:Fi,preprocessingProgress:Hn,onConfirm:Ca,onCancel:Co}),h.jsx(kP,{isOpen:ui,unsupportedFile:nt,onClose:()=>Ve(!1)}),h.jsx(jP,{isOpen:Br,oversizedFile:br,onClose:()=>We(!1),onCancel:()=>We(!1)})]})}const TP="_helpContainer_1wavj_1",PP="_helpSection_1wavj_13",LP="_sectionHeader_1wavj_49",MP="_sectionTitle_1wavj_91",DP="_sectionContent_1wavj_105",OP="_guidelinesList_1wavj_119",IP="_buttonContainer_1wavj_181",ut={helpContainer:TP,helpSection:PP,sectionHeader:LP,sectionTitle:MP,sectionContent:DP,guidelinesList:OP,buttonContainer:IP};function RP(){const e=ks(),{setShowReferenceExamples:n}=cP(),i=()=>{e("/upload")},o=()=>{n(!0),e("/explore")},s=()=>{e("/analytics?view=crisis_maps")};return h.jsx(Iu,{className:"py-10",children:h.jsx("div",{className:ut.helpContainer,children:h.jsxs("div",{className:"space-y-8",children:[h.jsxs("div",{className:ut.helpSection,children:[h.jsx("div",{className:ut.sectionHeader,children:h.jsx(kn,{level:3,className:ut.sectionTitle,children:"Introduction"})}),h.jsx("div",{className:ut.sectionContent,children:"In collaboration with the IFRC, PromptAid Vision is a tool that generates textual descriptions of crisis maps/crisis drone images utiliing Visual language models. This prototype is for collecting data for the fine-tuning of our own models. We aim to utilize AI tools to support national societies with rapid decision making during emergencies."}),h.jsx("div",{className:ut.buttonContainer,children:h.jsx(Ue,{name:"upload-now",variant:"secondary",onClick:i,children:"Upload now →"})})]}),h.jsxs("div",{className:ut.helpSection,children:[h.jsx("div",{className:ut.sectionHeader,children:h.jsx(kn,{level:3,className:ut.sectionTitle,children:"Guidelines"})}),h.jsxs("div",{className:ut.sectionContent,children:["To make the process smoother, please follow the guidelines below:",h.jsxs("ul",{className:ut.guidelinesList,children:[h.jsx("li",{children:"Avoid uploading images that are not crisis maps/crisis drone images."}),h.jsx("li",{children:"Confirm the image details prior to modifying the description."}),h.jsx("li",{children:"Before the modification, please read the description generated and provide a rating via the rating sliders."}),h.jsx("li",{children:'Click the "Submit" button to save the description.'})]})]}),h.jsx("div",{className:ut.buttonContainer,children:h.jsx(Ue,{name:"see-examples",variant:"secondary",onClick:o,children:"See examples →"})})]}),h.jsxs("div",{className:ut.helpSection,children:[h.jsx("div",{className:ut.sectionHeader,children:h.jsx(kn,{level:3,className:ut.sectionTitle,children:"VLMs"})}),h.jsx("div",{className:ut.sectionContent,children:"PromptAid Vision uses a variety of Visual Language Models (VLMs). A random VLM is selected for each upload. Therefore feel free to delete and reupload. You can view performance details here:"}),h.jsx("div",{className:ut.buttonContainer,children:h.jsx(Ue,{name:"view-vlm-details",variant:"secondary",onClick:s,children:"View VLM details →"})})]}),h.jsxs("div",{className:ut.helpSection,children:[h.jsx("div",{className:ut.sectionHeader,children:h.jsx(kn,{level:3,className:ut.sectionTitle,children:"Dataset"})}),h.jsx("div",{className:ut.sectionContent,children:"All users are able to export the dataset. You could apply filters when exporting, and it have the option to organize based on model fine-tuning formats."}),h.jsx("div",{className:ut.buttonContainer,children:h.jsx(Ue,{name:"export-dataset",variant:"secondary",onClick:()=>{n(!1),e("/explore"),setTimeout(()=>{const u=document.querySelector('[name="export-dataset"]');u&&u.click()},100)},children:"Export dataset →"})})]}),h.jsxs("div",{className:ut.helpSection,children:[h.jsx("div",{className:ut.sectionHeader,children:h.jsx(kn,{level:3,className:ut.sectionTitle,children:"Contact us"})}),h.jsx("div",{className:ut.sectionContent,children:"Need help or have questions about PromptAid Vision? Our team is here to support you."}),h.jsx("div",{className:ut.buttonContainer,children:h.jsx(Ue,{name:"contact-support",variant:"secondary",disabled:!0,children:"Get in touch →"})})]})]})})})}const AP="_demoContainer_19wfc_1",$P="_section_19wfc_13",FP="_pageTitle_19wfc_33",zP="_description_19wfc_43",BP="_sectionHeader_19wfc_57",UP="_sectionTitle_19wfc_65",HP="_sectionDescription_19wfc_75",VP="_switchGrid_19wfc_87",qP="_switchItem_19wfc_99",WP="_switchLabel_19wfc_119",GP="_switchWrapper_19wfc_133",ZP="_stateDisplay_19wfc_147",QP="_nativeCheckboxLabel_19wfc_165",KP="_nativeCheckbox_19wfc_165",YP="_buttonToggle_19wfc_197",XP="_buttonToggleOff_19wfc_219",JP="_buttonToggleOn_19wfc_231",e4="_buttonToggleText_19wfc_253",fe={demoContainer:AP,section:$P,pageTitle:FP,description:zP,sectionHeader:BP,sectionTitle:UP,sectionDescription:HP,switchGrid:VP,switchItem:qP,switchLabel:WP,switchWrapper:GP,stateDisplay:ZP,nativeCheckboxLabel:QP,nativeCheckbox:KP,buttonToggle:YP,buttonToggleOff:XP,buttonToggleOn:JP,buttonToggleText:e4};function t4(){const[e,n]=v.useState("off"),[i,o]=v.useState("on"),[s,u]=v.useState(!1),[d,f]=v.useState(!0),[g,y]=v.useState(!1),[x,b]=v.useState(!0),[m,w]=v.useState(!1),[N,S]=v.useState(!0),[_,T]=v.useState(!1),[M,$]=v.useState(!1);return h.jsx(Iu,{className:"py-10",children:h.jsx("div",{className:fe.demoContainer,children:h.jsxs("div",{className:"space-y-12",children:[h.jsxs("div",{className:fe.section,children:[h.jsx(kn,{level:2,className:fe.pageTitle,children:"Switch Components Demo"}),h.jsx("p",{className:fe.description,children:"This page showcases all available switch/toggle implementations. Each switch is clearly labeled so you can easily identify and compare different UI patterns."})]}),h.jsxs("div",{className:fe.section,children:[h.jsxs("div",{className:fe.sectionHeader,children:[h.jsx(kn,{level:3,className:fe.sectionTitle,children:"1. SegmentInput Switches (IFRC UI)"}),h.jsx("p",{className:fe.sectionDescription,children:"Using SegmentInput component for binary on/off choices"})]}),h.jsxs("div",{className:fe.switchGrid,children:[h.jsxs("div",{className:fe.switchItem,children:[h.jsx("div",{className:fe.switchLabel,children:"Switch 1: SegmentInput (Off by default)"}),h.jsx(on,{withInternalPadding:!0,className:fe.switchWrapper,children:h.jsx(su,{name:"switch-1",value:e,onChange:F=>{(F==="on"||F==="off")&&n(F)},options:[{key:"off",label:"Off"},{key:"on",label:"On"}],keySelector:F=>F.key,labelSelector:F=>F.label})}),h.jsxs("div",{className:fe.stateDisplay,children:["State: ",h.jsx("strong",{children:e})]})]}),h.jsxs("div",{className:fe.switchItem,children:[h.jsx("div",{className:fe.switchLabel,children:"Switch 2: SegmentInput (On by default)"}),h.jsx(on,{withInternalPadding:!0,className:fe.switchWrapper,children:h.jsx(su,{name:"switch-2",value:i,onChange:F=>{(F==="on"||F==="off")&&o(F)},options:[{key:"off",label:"Off"},{key:"on",label:"On"}],keySelector:F=>F.key,labelSelector:F=>F.label})}),h.jsxs("div",{className:fe.stateDisplay,children:["State: ",h.jsx("strong",{children:i})]})]})]})]}),h.jsxs("div",{className:fe.section,children:[h.jsxs("div",{className:fe.sectionHeader,children:[h.jsx(kn,{level:3,className:fe.sectionTitle,children:"2. IFRC Checkbox Switches"}),h.jsx("p",{className:fe.sectionDescription,children:"Using Checkbox component from @ifrc-go/ui for on/off toggles"})]}),h.jsxs("div",{className:fe.switchGrid,children:[h.jsxs("div",{className:fe.switchItem,children:[h.jsx("div",{className:fe.switchLabel,children:"Switch 3: IFRC Checkbox (Off by default)"}),h.jsx(wd,{name:"switch-3",value:s,onChange:u,label:"Enable feature"}),h.jsxs("div",{className:fe.stateDisplay,children:["State: ",h.jsx("strong",{children:s?"On":"Off"})]})]}),h.jsxs("div",{className:fe.switchItem,children:[h.jsx("div",{className:fe.switchLabel,children:"Switch 4: IFRC Checkbox (On by default)"}),h.jsx(wd,{name:"switch-4",value:d,onChange:f,label:"Auto-save enabled"}),h.jsxs("div",{className:fe.stateDisplay,children:["State: ",h.jsx("strong",{children:d?"On":"Off"})]})]})]})]}),h.jsxs("div",{className:fe.section,children:[h.jsxs("div",{className:fe.sectionHeader,children:[h.jsx(kn,{level:3,className:fe.sectionTitle,children:"3. Native HTML Checkbox Switches"}),h.jsx("p",{className:fe.sectionDescription,children:'Using native HTML input[type="checkbox"] elements (as used in AdminPage)'})]}),h.jsxs("div",{className:fe.switchGrid,children:[h.jsxs("div",{className:fe.switchItem,children:[h.jsx("div",{className:fe.switchLabel,children:"Switch 5: Native Checkbox (Off by default)"}),h.jsxs("label",{className:fe.nativeCheckboxLabel,children:[h.jsx("input",{type:"checkbox",checked:g,onChange:F=>y(F.target.checked),className:fe.nativeCheckbox}),h.jsx("span",{children:"Available for use"})]}),h.jsxs("div",{className:fe.stateDisplay,children:["State: ",h.jsx("strong",{children:g?"On":"Off"})]})]}),h.jsxs("div",{className:fe.switchItem,children:[h.jsx("div",{className:fe.switchLabel,children:"Switch 6: Native Checkbox (On by default)"}),h.jsxs("label",{className:fe.nativeCheckboxLabel,children:[h.jsx("input",{type:"checkbox",checked:x,onChange:F=>b(F.target.checked),className:fe.nativeCheckbox}),h.jsx("span",{children:"RTK Fix Available"})]}),h.jsxs("div",{className:fe.stateDisplay,children:["State: ",h.jsx("strong",{children:x?"On":"Off"})]})]})]})]}),h.jsxs("div",{className:fe.section,children:[h.jsxs("div",{className:fe.sectionHeader,children:[h.jsx(kn,{level:3,className:fe.sectionTitle,children:"4. Custom CSS Toggle Switches"}),h.jsx("p",{className:fe.sectionDescription,children:"Custom-built toggle switch component with smooth animations"})]}),h.jsxs("div",{className:fe.switchGrid,children:[h.jsxs("div",{className:fe.switchItem,children:[h.jsx("div",{className:fe.switchLabel,children:"Switch 7: Custom Toggle (Off by default)"}),h.jsx(ls,{name:"switch-7",checked:m,onChange:w,label:"Enable notifications"}),h.jsxs("div",{className:fe.stateDisplay,children:["State: ",h.jsx("strong",{children:m?"On":"Off"})]})]}),h.jsxs("div",{className:fe.switchItem,children:[h.jsx("div",{className:fe.switchLabel,children:"Switch 8: Custom Toggle (On by default)"}),h.jsx(ls,{name:"switch-8",checked:N,onChange:S,label:"Dark mode"}),h.jsxs("div",{className:fe.stateDisplay,children:["State: ",h.jsx("strong",{children:N?"On":"Off"})]})]}),h.jsxs("div",{className:fe.switchItem,children:[h.jsx("div",{className:fe.switchLabel,children:"Switch 9: Custom Toggle (No label, Off by default)"}),h.jsx(ls,{name:"switch-9",checked:_,onChange:T}),h.jsxs("div",{className:fe.stateDisplay,children:["State: ",h.jsx("strong",{children:_?"On":"Off"})]})]})]})]}),h.jsxs("div",{className:fe.section,children:[h.jsxs("div",{className:fe.sectionHeader,children:[h.jsx(kn,{level:3,className:fe.sectionTitle,children:"5. Button-based Toggle Switch"}),h.jsx("p",{className:fe.sectionDescription,children:"Using a button element styled as a toggle switch"})]}),h.jsxs("div",{className:fe.switchItem,children:[h.jsx("div",{className:fe.switchLabel,children:"Switch 10: Button Toggle (Off by default)"}),h.jsx("button",{type:"button",className:`${fe.buttonToggle} ${M?fe.buttonToggleOn:fe.buttonToggleOff}`,onClick:()=>$(!M),children:h.jsx("span",{className:fe.buttonToggleText,children:M?"On":"Off"})}),h.jsxs("div",{className:fe.stateDisplay,children:["State: ",h.jsx("strong",{children:M?"On":"Off"})]})]})]}),h.jsxs("div",{className:fe.section,children:[h.jsxs("div",{className:fe.sectionHeader,children:[h.jsx(kn,{level:3,className:fe.sectionTitle,children:"6. Disabled Switch States"}),h.jsx("p",{className:fe.sectionDescription,children:"Examples of switches in disabled state"})]}),h.jsxs("div",{className:fe.switchGrid,children:[h.jsxs("div",{className:fe.switchItem,children:[h.jsx("div",{className:fe.switchLabel,children:"Disabled SegmentInput"}),h.jsx(on,{withInternalPadding:!0,className:fe.switchWrapper,children:h.jsx(su,{name:"disabled-segment",value:"on",onChange:()=>{},options:[{key:"off",label:"Off"},{key:"on",label:"On"}],keySelector:F=>F.key,labelSelector:F=>F.label,disabled:!0})})]}),h.jsxs("div",{className:fe.switchItem,children:[h.jsx("div",{className:fe.switchLabel,children:"Disabled IFRC Checkbox"}),h.jsx(wd,{name:"disabled-checkbox",value:!0,onChange:()=>{},label:"Disabled option",disabled:!0})]}),h.jsxs("div",{className:fe.switchItem,children:[h.jsx("div",{className:fe.switchLabel,children:"Disabled Custom Toggle"}),h.jsx(ls,{name:"disabled-custom",checked:!0,onChange:()=>{},label:"Disabled toggle",disabled:!0})]})]})]})]})})})}const n4=v.createContext(void 0),r4=({children:e})=>{const[n,i]=v.useState(!1),[o,s]=v.useState(!0),u=async()=>{const y=localStorage.getItem("adminToken");if(!y){i(!1),s(!1);return}try{(await fetch("/api/admin/verify",{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${y}`}})).ok?i(!0):(localStorage.removeItem("adminToken"),i(!1))}catch(x){console.error("Error verifying admin token:",x),localStorage.removeItem("adminToken"),i(!1)}finally{s(!1)}},d=async y=>{try{const x=await fetch("/api/admin/login",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({password:y})});if(x.ok){const b=await x.json();return localStorage.setItem("adminToken",b.access_token),i(!0),!0}else return!1}catch(x){return console.error("Login error:",x),!1}},f=()=>{localStorage.removeItem("adminToken"),i(!1)};v.useEffect(()=>{u()},[]);const g={isAuthenticated:n,isLoading:o,login:d,logout:f,verifyToken:u};return h.jsx(n4.Provider,{value:g,children:e})},i4=v.lazy(()=>Kn(()=>import("./index-Dz4vX1uX.js"),__vite__mapDeps([0,1]))),o4=v.lazy(()=>Kn(()=>import("./index-7oBZSGHr.js"),__vite__mapDeps([2,3,4,5,6]))),a4=v.lazy(()=>Kn(()=>import("./AdminPage-C8Qwkg88.js"),__vite__mapDeps([7,3,8]))),s4=v.lazy(()=>Kn(()=>import("./index-Bx3ZvIBj.js"),__vite__mapDeps([9,3,4,5,10])));class l4 extends v.Component{constructor(n){super(n),this.state={hasError:!1}}static getDerivedStateFromError(){return{hasError:!0}}componentDidCatch(n,i){console.error("Error caught by boundary:",n,i)}render(){return this.state.hasError?h.jsxs("div",{style:{padding:"20px",textAlign:"center"},children:[h.jsx("h2",{children:"Something went wrong"}),h.jsx("p",{children:"Please refresh the page to try again."}),h.jsx("button",{onClick:()=>window.location.reload(),children:"Refresh Page"})]}):this.props.children}}const Pi=e=>{const n=e();return n.catch(()=>{}),n},u4=()=>{"requestIdleCallback"in window?requestIdleCallback(()=>{Pi(()=>Kn(()=>import("./index-Dz4vX1uX.js"),__vite__mapDeps([0,1]))),Pi(()=>Kn(()=>import("./index-7oBZSGHr.js"),__vite__mapDeps([2,3,4,5,6]))),Pi(()=>Kn(()=>import("./AdminPage-C8Qwkg88.js"),__vite__mapDeps([7,3,8]))),Pi(()=>Kn(()=>import("./index-Bx3ZvIBj.js"),__vite__mapDeps([9,3,4,5,10])))}):setTimeout(()=>{Pi(()=>Kn(()=>import("./index-Dz4vX1uX.js"),__vite__mapDeps([0,1]))),Pi(()=>Kn(()=>import("./index-7oBZSGHr.js"),__vite__mapDeps([2,3,4,5,6]))),Pi(()=>Kn(()=>import("./AdminPage-C8Qwkg88.js"),__vite__mapDeps([7,3,8]))),Pi(()=>Kn(()=>import("./index-Bx3ZvIBj.js"),__vite__mapDeps([9,3,4,5,10])))},1e3)};function c4(){const e=v.useMemo(()=>Ex([{element:h.jsx(Z2,{}),children:[{path:"/",element:h.jsx(Xg,{})},{path:"/upload",element:h.jsx(Xg,{})},{path:"/analytics",element:h.jsx(v.Suspense,{fallback:h.jsx("div",{children:"Loading Analytics..."}),children:h.jsx(i4,{})})},{path:"/explore",element:h.jsx(v.Suspense,{fallback:h.jsx("div",{children:"Loading Explore..."}),children:h.jsx(o4,{})})},{path:"/help",element:h.jsx(RP,{})},{path:"/demo",element:h.jsx(t4,{})},{path:"/admin",element:h.jsx(v.Suspense,{fallback:h.jsx("div",{children:"Loading Admin..."}),children:h.jsx(a4,{})})},{path:"/map/:mapId",element:h.jsx(v.Suspense,{fallback:h.jsx("div",{children:"Loading Map Details..."}),children:h.jsx(s4,{})})}]}],{basename:"/"}),[]),[n,i]=v.useState([]);v.useEffect(()=>{u4()},[]);const o=v.useCallback(g=>{i(y=>Qx([...y,g],x=>x.name)??y)},[i]),s=v.useCallback(g=>{i(y=>{const x=y.findIndex(m=>m.name===g);if(x===-1)return y;const b=[...y];return b.splice(x,1),b})},[i]),u=v.useCallback((g,y)=>{i(x=>{const b=x.findIndex(w=>w.name===g);if(b===-1)return x;const m=[...x];return m[b]={...m[b],...y},m})},[i]),d=v.useMemo(()=>({alerts:n,addAlert:o,removeAlert:s,updateAlert:u}),[n,o,s,u]),f=v.useMemo(()=>({languageNamespaceStatus:{},setLanguageNamespaceStatus:()=>{},currentLanguage:"en",setCurrentLanguage:()=>{},strings:{},setStrings:()=>{},registerNamespace:()=>{}}),[]);return h.jsx(l4,{children:h.jsx(Wx.Provider,{value:d,children:h.jsx(y0.Provider,{value:f,children:h.jsx(r4,{children:h.jsx(uP,{children:h.jsx(Ox,{router:e})})})})})})}function d4(){return h.jsx(c4,{})}console.log("React version at runtime:",v.version,"createContext exists?",!!v.createContext);X1.createRoot(document.getElementById("root")).render(h.jsx(v.StrictMode,{children:h.jsx(d4,{})}));export{Mb as A,ua as B,p4 as C,cP as D,v4 as E,_f as F,Kn as G,kn as H,q as I,io as J,h4 as K,su as L,xP as M,Iu as N,jt as O,qg as P,w4 as Q,E0 as R,wd as S,n4 as T,y4 as U,f4 as V,e0 as W,Xo as _,ze as a,Ot as b,C4 as c,S4 as d,m4 as e,Pb as f,S0 as g,b4 as h,x4 as i,h as j,gr as k,Jx as l,tN as m,Ue as n,Me as o,nb as p,cs as q,v as r,_0 as s,y0 as t,Bx as u,Ab as v,$b as w,ks as x,g4 as y,on as z}; diff --git a/py_backend/static/assets/index-BzZTDKPD.js b/py_backend/static/assets/index-Dz4vX1uX.js similarity index 99% rename from py_backend/static/assets/index-BzZTDKPD.js rename to py_backend/static/assets/index-Dz4vX1uX.js index ad0922a2..c7653c52 100644 --- a/py_backend/static/assets/index-BzZTDKPD.js +++ b/py_backend/static/assets/index-Dz4vX1uX.js @@ -1 +1 @@ -import{r as n,y as nt,t as ht,a as q,c as gt,j as e,o as N,b as re,R as st,z,g as rt,d as ft,m as vt,e as pt,n as Z,A as xt,f as _t,h as Ct,i as yt,k as he,l as bt,p as ye,q as jt,s as Nt,E as wt,C as St,U as Mt,Q as It,u as Dt,N as je,_ as Et,L as Tt}from"./index-Rlfiitbv.js";const kt=({title:m,titleId:a,...h})=>n.createElement("svg",Object.assign({xmlns:"http://www.w3.org/2000/svg","aria-hidden":"true",viewBox:"0 0 24 24",fill:"currentColor",width:"1em",height:"1em","aria-labelledby":a},h),m?n.createElement("title",{id:a},m):null,n.createElement("g",{clipPath:"url(#arrow-drop-down-line_svg__a)"},n.createElement("path",{d:"m12 15-4.243-4.243 1.415-1.414L12 12.172l2.828-2.83 1.415 1.415L12 15Z"})),n.createElement("defs",null,n.createElement("clipPath",{id:"arrow-drop-down-line_svg__a"},n.createElement("path",{d:"M0 0h24v24H0z"})))),Lt=({title:m,titleId:a,...h})=>n.createElement("svg",Object.assign({xmlns:"http://www.w3.org/2000/svg","aria-hidden":"true",viewBox:"0 0 24 24",fill:"currentColor",width:"1em",height:"1em","aria-labelledby":a},h),m?n.createElement("title",{id:a},m):null,n.createElement("g",{clipPath:"url(#arrow-drop-up-line_svg__a)"},n.createElement("path",{d:"m12 11.828-2.828 2.829-1.415-1.414L12 9l4.243 4.243-1.415 1.414L12 11.828Z"})),n.createElement("defs",null,n.createElement("clipPath",{id:"arrow-drop-up-line_svg__a"},n.createElement("path",{d:"M0 0h24v24H0z"})))),Pt=({title:m,titleId:a,...h})=>n.createElement("svg",Object.assign({xmlns:"http://www.w3.org/2000/svg","aria-hidden":"true",viewBox:"0 0 24 24",fill:"currentColor",width:"1em",height:"1em","aria-labelledby":a},h),m?n.createElement("title",{id:a},m):null,n.createElement("g",{clipPath:"url(#information-line_svg__a)"},n.createElement("path",{d:"M12 22C6.477 22 2 17.523 2 12S6.477 2 12 2s10 4.477 10 10-4.477 10-10 10Zm0-2a8 8 0 1 0 0-16.001A8 8 0 0 0 12 20ZM11 7h2v2h-2V7Zm0 4h2v6h-2v-6Z"})),n.createElement("defs",null,n.createElement("clipPath",{id:"information-line_svg__a"},n.createElement("path",{d:"M0 0h24v24H0z"})))),Rt=({title:m,titleId:a,...h})=>n.createElement("svg",Object.assign({xmlns:"http://www.w3.org/2000/svg","aria-hidden":"true",viewBox:"0 0 24 24",fill:"currentColor",width:"1em",height:"1em","aria-labelledby":a},h),m?n.createElement("title",{id:a},m):null,n.createElement("path",{fillRule:"evenodd",d:"m15.063 12 .937.938-4 4-4-4L8.938 12 12 15.063 15.063 12Z",clipRule:"evenodd"}),n.createElement("mask",{id:"table-sorting-line_svg__a",width:8,height:5,x:8,y:12,maskUnits:"userSpaceOnUse",style:{maskType:"luminance"}},n.createElement("path",{fillRule:"evenodd",d:"m15.063 12 .937.938-4 4-4-4L8.938 12 12 15.063 15.063 12Z",clipRule:"evenodd"})),n.createElement("g",{mask:"url(#table-sorting-line_svg__a)"},n.createElement("path",{d:"M-24-22h72v72h-72z"})),n.createElement("path",{fillRule:"evenodd",d:"M8.938 11 8 10.062l4-4 4 4-.938.938L12 7.937 8.937 11Z",clipRule:"evenodd"}),n.createElement("mask",{id:"table-sorting-line_svg__b",width:8,height:5,x:8,y:6,maskUnits:"userSpaceOnUse",style:{maskType:"luminance"}},n.createElement("path",{fillRule:"evenodd",d:"M8.938 11 8 10.062l4-4 4 4-.938.938L12 7.937 8.937 11Z",clipRule:"evenodd"})),n.createElement("g",{mask:"url(#table-sorting-line_svg__b)"},n.createElement("path",{d:"M48 45h-72v-72h72z"}))),$t="_number-output_1blvi_1",Bt={numberOutput:$t};function we(m){const{className:a,invalidText:h=nt,separatorHidden:o,compact:f,currency:g,value:b,tooltip:_,unit:y,prefix:x,suffix:w,maximumFractionDigits:C=1}=m,{currentLanguage:j}=n.useContext(ht),v=n.useMemo(()=>{if(q(b))return h;const S=gt(b,{currency:g,compact:f,separatorHidden:o,maximumFractionDigits:C,unit:y,language:j});return e.jsxs(e.Fragment,{children:[x,S,w]})},[h,b,f,o,g,y,C,x,j,w]);return e.jsx("div",{className:N(Bt.numberOutput,a),title:re(_)?String(_):void 0,children:v})}const At="_tooltip-dummy_rbf3f_1",Ft="_tooltip-content_rbf3f_7",Ot="_pointer_rbf3f_14",Ne={tooltipDummy:At,tooltipContent:Ft,pointer:Ot};function Ht(m){const{className:a,title:h,description:o,preferredWidth:f}=m,[g,b]=n.useState(!1),[_,y]=n.useState(!1),x=n.useRef(),w=n.useRef(null);return n.useEffect(()=>{const C=()=>{y(!0)},j=()=>{y(!1)};if(q(w.current))return;const{current:{parentNode:v}}=w;if(!q(v))return x.current=v,v.addEventListener("mouseover",C),v.addEventListener("mouseout",j),b(!0),()=>{v.removeEventListener("mouseover",C),v.removeEventListener("mouseout",j)}},[]),e.jsxs(e.Fragment,{children:[!g&&e.jsx("div",{className:Ne.tooltipDummy,ref:w}),_&&e.jsx(st,{className:N(Ne.tooltipContent,a),parentRef:x,pointerClassName:Ne.pointer,preferredWidth:f,children:e.jsx(z,{heading:h,withInternalPadding:!0,contentViewType:"vertical",children:o})})]})}function B(m){return m.id}const Vt="common",zt={booleanYesLabel:"Yes",booleanNoLabel:"No"},Ut={namespace:Vt,strings:zt},Wt="_boolean-output_kg1uq_1",Qt={booleanOutput:Wt};function Zt(m){const{className:a,invalidText:h,value:o}=m,f=rt(Ut);let g;return o===!0?g=f.booleanYesLabel:o===!1?g=f.booleanNoLabel:g=h,e.jsx("div",{className:N(Qt.booleanOutput,a),children:g})}const qt="_date-output_4jzjo_1",Gt={dateOutput:qt};function Yt(m){const{value:a,format:h,className:o,invalidText:f}=m,g=n.useMemo(()=>ft(a,h),[a,h]);return e.jsx("div",{className:N(Gt.dateOutput,o),children:g??f})}const Kt="_dropdown-menu_16hml_1",Xt="_icons_16hml_4",Jt="_content_16hml_5",ea="_actions_16hml_6",ta="_dropdown-icon_16hml_10",aa="_dropdown-content_16hml_16",le={dropdownMenu:Kt,icons:Xt,content:Jt,actions:ea,dropdownIcon:ta,dropdownContent:aa};function na(m){const a=n.useRef(null),{className:h,popupClassName:o,children:f,label:g,activeClassName:b,icons:_,variant:y="secondary",actions:x,withoutDropdownIcon:w,componentRef:C,elementRef:j=a,persistent:v,preferredPopupWidth:S}=m,p=n.useRef(null),[L,I]=n.useState(!1);n.useEffect(()=>{C&&(C.current={setShowDropdown:I})},[C,I]);const R=n.useCallback(()=>{I(ie=>!ie)},[I]),k=n.useCallback((ie,ae)=>{ae||ie&&v||I(!1)},[I,v]);vt(L,k,p,j);const G=n.useMemo(()=>({setShowDropdown:I}),[I]),U=!!x||!w;return e.jsxs(pt.Provider,{value:G,children:[e.jsx(Z,{name:void 0,className:N(le.dropdownMenu,L&&b,h),elementRef:j,onClick:R,variant:y,actionsContainerClassName:le.actions,iconsContainerClassName:le.icons,childrenContainerClassName:le.content,actions:U?e.jsxs(e.Fragment,{children:[x,!w&&(L?e.jsx(xt,{className:le.dropdownIcon}):e.jsx(_t,{className:le.dropdownIcon}))]}):void 0,icons:_,children:g}),L&&e.jsx(st,{elementRef:p,className:N(le.dropdownContent,o),parentRef:j,preferredWidth:S,children:f})]})}const sa="_info-popup_i3rna_1",ra="_label_i3rna_2",ia="_icon_i3rna_7",oa="_dropdown-container_i3rna_15",la="_content_i3rna_20",ge={infoPopup:sa,label:ra,icon:ia,dropdownContainer:oa,content:la};function ca(m){const{className:a,icon:h=e.jsx(Pt,{}),infoLabel:o,title:f,description:g,withoutIcon:b,popupClassName:_,descriptionClassName:y}=m;return e.jsx(na,{label:e.jsxs("div",{className:ge.label,children:[o,!b&&h&&e.jsx("div",{className:ge.icon,children:h})]}),popupClassName:N(ge.dropdownContainer,_),className:N(ge.infoPopup,a),variant:"tertiary",withoutDropdownIcon:!0,children:e.jsx(z,{heading:f,childrenContainerClassName:N(y,ge.content),withInternalPadding:!0,children:g})})}const da="_progress-wrapper_x340w_1",ua="_title_x340w_7",ma="_total_x340w_11",ha="_progress_x340w_1",fe={progressWrapper:da,title:ua,total:ma,progress:ha};function Ye(m){const{className:a,title:h,description:o,totalValue:f,value:g,showPercentageInTitle:b,children:_,color:y="var(--go-ui-color-primary-red)"}=m,x=re(g)?g:0,w=re(f)?f:0;let C;return w===0?C=0:C=x/w*100,e.jsxs("div",{className:N(fe.progressWrapper,a),children:[(h||b)&&e.jsxs("div",{className:fe.title,children:[h,b&&e.jsx(we,{value:C,suffix:"%"})]}),e.jsx("div",{className:fe.total,children:e.jsx("div",{className:fe.progress,style:{width:`${C}%`,backgroundColor:y}})}),o&&e.jsx("div",{className:fe.description,children:o}),_]})}const ga="_legend-element_1a9ic_1",fa="_color_1a9ic_7",va="_icon-container_1a9ic_14",pa="_icon_1a9ic_14",xa="_label_1a9ic_31",ve={legendElement:ga,color:fa,iconContainer:va,icon:pa,label:xa};function _a(m){const{className:a,colorClassName:h,iconClassName:o,color:f,label:g,iconSrc:b}=m;return e.jsxs("div",{className:N(ve.legendElement,a),children:[b?e.jsx("div",{style:{backgroundColor:f},className:ve.iconContainer,children:e.jsx("img",{className:N(ve.icon,o),src:b,alt:""})}):e.jsx("div",{style:{backgroundColor:f},className:N(ve.color,h)}),e.jsx("div",{className:ve.label,children:g})]})}const Ca="_text-output_10oza_1",ya="_with-background_10oza_6",ba="_label_10oza_11",ja="_with-colon_10oza_12",Na="_value_10oza_17",wa="_text-type_10oza_18",Sa="_strong_10oza_24",ee={textOutput:Ca,withBackground:ya,label:ba,withColon:ja,value:Na,textType:wa,strong:Sa};function Ke(m){const{className:a,label:h,icon:o,description:f,labelClassName:g,descriptionClassName:b,valueClassName:_,strongLabel:y,strongValue:x,strongDescription:w,withoutLabelColon:C,withBackground:j,invalidText:v=nt,...S}=m,{value:p}=m;let L=v;return S.valueType==="number"?L=e.jsx(we,{...S,invalidText:v}):S.valueType==="date"?L=e.jsx(Yt,{...S,invalidText:v}):S.valueType==="boolean"?L=e.jsx(Zt,{...S,invalidText:v}):p instanceof Date||(L=p||v),e.jsxs("div",{className:N(ee.textOutput,j&&ee.withBackground,a),children:[o,h&&e.jsx("div",{className:N(ee.label,y&&ee.strong,g,!C&&ee.withColon),children:h}),e.jsx("div",{className:N(ee.value,x&&ee.strong,S.valueType==="text"&&ee.textType,_),children:L}),f&&e.jsx("div",{className:N(ee.description,w&&ee.strong,b),children:f})]})}const Ma="_pie-chart_pyr7m_1",Ia="_legend_pyr7m_7",Da="_legend-item_pyr7m_13",pe={pieChart:Ma,legend:Ia,legendItem:Da},Ea=70,Ta=40;function Xe(m,a=1){return Math.round(m*10**a)/10**a}function Je(m,a){const h=(a-90)*Math.PI/180;return{x:Xe(m+m*Math.cos(h)),y:Xe(m+m*Math.sin(h))}}function ka(m,a,h){let o=h;const f=o-a===360;f&&(o-=1);const g=Je(m,a),b=Je(m,o),_=o-a<=180?0:1,y=["M",g.x,g.y,"A",m,m,0,_,1,b.x,b.y];return f?y.push("Z"):y.push("L",m,m,"L",g.x,g.y,"Z"),y.join(" ")}function xe(m){const{className:a,data:h,valueSelector:o,labelSelector:f,keySelector:g,colorSelector:b,colors:_,pieRadius:y=Ea,chartPadding:x=Ta,legendClassName:w,showPercentageInLegend:C}=m,j=Ct(h?.map(p=>o(p))),v=q(j)||j===0?1:j,S=n.useMemo(()=>{let p=0;const L=h?.map(I=>{const R=o(I);if(q(R))return;const k=360*(R/v);return p+=k,{key:g(I),value:R,label:f(I),startAngle:p-k,percentage:yt(R,v),endAngle:p,datum:I}}).filter(re)??[];return b?L.map(({datum:I,...R})=>({...R,color:b(I)})):L.map(({datum:I,...R},k)=>({...R,color:_[k%_.length]}))},[h,g,o,f,v,b,_]);return e.jsxs("div",{className:N(pe.pieChart,a),children:[e.jsx("svg",{className:pe.svg,style:{width:`${x+y*2}px`,height:`${x+y*2}px`},children:e.jsx("g",{style:{transform:`translate(${x/2}px, ${x/2}px)`},children:S.map(p=>e.jsx("path",{className:pe.path,d:ka(y,p.startAngle,p.endAngle),fill:p.color,children:e.jsx(Ht,{description:e.jsx(Ke,{label:p.label,value:p.value})})},p.key))})}),e.jsx("div",{className:N(pe.legend,w),children:S.map(p=>e.jsx(_a,{className:pe.legendItem,label:C?e.jsx(Ke,{label:p.label,value:p.percentage,valueType:"number",prefix:"(",suffix:"%)",withoutLabelColon:!0}):p.label,color:p.color},p.key))})]})}const La="_td_1k4cn_1",Pa={td:La};function Ra(m){const{className:a,children:h,...o}=m;return e.jsx("td",{className:N(a,Pa.td),...o,children:h})}function it(m){const{className:a,children:h,...o}=m;return e.jsx("tr",{className:a,...o,children:h})}const $a="_row_1829z_1",Ba="_cell_1829z_2",et={row:$a,cell:Ba};function Aa(m){const{data:a,keySelector:h,columns:o,rowClassName:f,cellClassName:g,rowModifier:b}=m;return e.jsx(e.Fragment,{children:a?.map((_,y)=>{const x=h(_,y),w=o.map(v=>{const{id:S,cellRenderer:p,cellRendererClassName:L,cellRendererParams:I,cellContainerClassName:R}=v,k=I(x,_,y,a),G=e.jsx(p,{className:L,...k,name:S});return e.jsx(Ra,{className:N(et.cell,R,typeof g=="function"?g(x,_,S):g),children:G},S)}),C=e.jsx(it,{className:N(et.row,typeof f=="function"?f(x,_):f),children:w});let j=C;return b&&(j=b({rowKey:x,row:C,cells:w,columns:o,datum:_})),e.jsx(n.Fragment,{children:j},x)})})}const Fa="_th_cdv41_1",Oa="_resize-handle_cdv41_8",tt={th:Fa,resizeHandle:Oa};function Ha(m){const{className:a,children:h,onResize:o,onResizeComplete:f,name:g,...b}=m,_=n.useRef(null),y=n.useRef(),x=n.useRef(),w=n.useRef(),C=n.useCallback(v=>{var S;if(re(y.current)&&_.current&&o){v.preventDefault(),v.stopPropagation();const p=v.clientX-y.current;if(re(x.current)){const L=x.current+p;w.current=L,o(L,g)}else x.current=(S=_.current)==null?void 0:S.offsetWidth}},[o,g]),j=n.useCallback(v=>{var S;v.preventDefault(),y.current=v.clientX,x.current=(S=_.current)==null?void 0:S.offsetWidth,window.addEventListener("mousemove",C,!0)},[C]);return n.useEffect(()=>{const v=()=>{y.current=void 0,x.current=void 0,f&&re(w.current)&&f(w.current,g),window.removeEventListener("mousemove",C,!0)};return window.addEventListener("mouseup",v,!0),()=>{window.removeEventListener("mouseup",v,!0),window.removeEventListener("mousemove",C,!0)}},[C,g,f]),e.jsxs("th",{ref:_,className:N(a,tt.th),...b,children:[o&&e.jsx("div",{role:"presentation",className:tt.resizeHandle,onMouseDown:j}),h]})}const Va="_table_nilhy_1",za="_table-overflow-wrapper_nilhy_8",Ua="_table-element_nilhy_13",Wa="_header-row_nilhy_23",Qa="_header-element_nilhy_24",Za="_header-component_nilhy_29",ce={table:Va,tableOverflowWrapper:za,tableElement:Ua,headerRow:Wa,headerElement:Qa,headerComponent:Za};function qa(m,a){return a??m.columnWidth??wt}function A(m){const{data:a,keySelector:h,columns:o,caption:f,className:g,captionClassName:b,headerRowClassName:_,headerCellClassName:y,rowClassName:x,cellClassName:w,rowModifier:C,fixedColumnWidth:j,resizableColumn:v,headersHidden:S,pending:p,filtered:L,errored:I=!1}=m,R=n.useRef(null),[k]=he.useState(()=>bt()),[G,U]=he.useState({});n.useEffect(()=>{U(W=>{if(q(R.current))return W;const T=R.current.getBoundingClientRect(),{width:O}=T;let F=o.map(M=>({id:M.id,stretch:!!M.columnStretch,width:qa(M,W[M.id])}));const X=ye(F.filter(M=>M.stretch).map(M=>M.width)),ne=ye(F.filter(M=>!M.stretch).map(M=>M.width)),Y=(O-ne)/X;return Y>1&&(F=F.map(M=>({...M,width:M.stretch?M.width*Y:M.width}))),jt(F,M=>M.id,M=>M.width)})},[o]);const ie=he.useCallback((W,T)=>{const O=document.getElementById(`${k}-${T}`),F=Math.max(W,80);if(q(O)||(O.style.width=`${F}px`,!j))return;const X=document.getElementById(k);if(q(X))return;const ne=ye(o.map(Y=>Y.id===T?F:G[Y.id]));X.style.width=`${ne}px`},[k,G,o,j]),ae=he.useCallback((W,T)=>{re(T)&&U(O=>({...O,[T]:Math.max(W,80)}))},[U]),be=he.useMemo(()=>ye(o.map(W=>G[W.id])),[G,o]),K=q(a)||a.length===0||Object.keys(G).length===0;return e.jsxs("div",{ref:R,className:N(ce.table,g),children:[!K&&e.jsx("div",{className:ce.tableOverflowWrapper,children:e.jsxs("table",{className:ce.tableElement,style:j?{width:`${be}px`}:void 0,id:k,children:[f&&e.jsx("caption",{className:b,children:f}),e.jsx("colgroup",{children:o.map(W=>{const{id:T,columnClassName:O}=W,F=G[T],X=j?{width:`${F}px`}:void 0;return e.jsx("col",{id:`${k}-${T}`,style:X,className:N(ce.column,O)},T)})}),!S&&e.jsx("thead",{children:e.jsx(it,{className:N(ce.headerRow,_),children:o.map((W,T)=>{const{id:O,title:F,headerCellRenderer:X,headerCellRendererClassName:ne,headerCellRendererParams:Y,headerContainerClassName:M}=W,se=e.jsx(X,{...Y,name:O,title:F,index:T,className:N(ne,ce.headerComponent)});return e.jsx(Ha,{scope:"col",name:O,onResize:v?ie:void 0,onResizeComplete:v?ae:void 0,className:N(ce.headerElement,typeof y=="function"?y(O):y,M),children:se},O)})})}),e.jsx("tbody",{children:e.jsx(Aa,{data:a,keySelector:h,columns:o,rowClassName:x,cellClassName:w,rowModifier:C})})]})}),e.jsx(Nt,{filtered:L,empty:K,errored:I,pending:p,overlayPending:!0})]})}function Ga(m){const{className:a,value:h}=m;return q(h)?null:e.jsx("div",{className:a,children:h})}const Ya="common",Ka={sortTableButtonTitle:"Sort Table"},Xa={namespace:Ya,strings:Ka},Ja="_header-cell_vn24d_1",en="_sort-button_vn24d_8",tn="_icon_vn24d_12",an="_info-popup-icon_vn24d_17",de={headerCell:Ja,sortButton:en,icon:tn,infoPopupIcon:an};function ot(m){const{className:a,titleClassName:h,title:o,name:f,sortable:g,defaultSortDirection:b="asc",infoTitle:_,infoDescription:y}=m,{sorting:x,setSorting:w}=n.useContext(St),C=rt(Xa),j=x?.name===f?x.direction:void 0,v=n.useRef(null),S=n.useCallback(()=>{if(q(w))return;let p;q(j)?p=b:j==="asc"?p="dsc":j==="dsc"&&(p="asc"),w(p?{name:f,direction:p}:void 0)},[f,w,j,b]);return e.jsxs("div",{ref:v,className:N(a,de.headerCell),children:[g&&e.jsxs(Z,{name:void 0,variant:"tertiary",onClick:S,title:C.sortTableButtonTitle,className:de.sortButton,children:[q(j)&&e.jsx(Rt,{className:de.icon}),j==="asc"&&e.jsx(Lt,{className:de.icon}),j==="dsc"&&e.jsx(kt,{className:de.icon})]}),e.jsx("div",{className:N(h,de.title),children:o}),_&&y&&e.jsx(ca,{className:de.infoPopupIcon,title:_,description:y})]})}const at={};function Q(m,a,h,o){return{id:m,title:a,columnClassName:o?.columnClassName,headerCellRenderer:ot,headerCellRendererClassName:o?.headerCellRendererClassName,headerContainerClassName:o?.headerContainerClassName,headerCellRendererParams:{sortable:o?.sortable,infoTitle:o?.headerInfoTitle,infoDescription:o?.headerInfoDescription},cellRendererClassName:o?.cellRendererClassName,cellContainerClassName:o?.cellContainerClassName,cellRenderer:Ga,cellRendererParams:(f,g)=>({value:h(g)||"--"}),valueSelector:h,valueComparator:(f,g)=>Mt(h(f),h(g)),columnWidth:o?.columnWidth,columnStretch:o?.columnStretch,columnStyle:o?.columnStyle}}function E(m,a,h,o){return{id:m,title:a,columnClassName:o?.columnClassName,headerCellRenderer:ot,headerCellRendererClassName:N(at.numberCellHeader,o?.headerCellRendererClassName),headerContainerClassName:o?.headerContainerClassName,headerCellRendererParams:{sortable:o?.sortable,infoTitle:o?.headerInfoTitle,infoDescription:o?.headerInfoDescription},cellRendererClassName:N(at.numberCell,o?.cellRendererClassName),cellContainerClassName:o?.cellContainerClassName,cellRenderer:we,cellRendererParams:(f,g)=>({value:h(g),suffix:o?.suffix,maximumFractionDigits:o?.maximumFractionDigits,invalidText:"--"}),valueSelector:h,valueComparator:(f,g)=>It(h(f),h(g)),columnWidth:o?.columnWidth,columnStretch:o?.columnStretch,columnStyle:o?.columnStyle}}const nn="_tabSelector_vlxoe_1",sn="_progressSection_vlxoe_14",rn="_progressLabel_vlxoe_20",on="_chartGrid_vlxoe_28",ln="_chartContainer_vlxoe_40",cn="_tableContainer_vlxoe_51",dn="_modelPerformance_vlxoe_59",un="_loadingContainer_vlxoe_67",mn="_errorContainer_vlxoe_77",hn="_userInteractionCards_vlxoe_96",gn="_userInteractionCard_vlxoe_96",fn="_userInteractionCardValue_vlxoe_116",vn="_userInteractionCardLabel_vlxoe_123",pn="_userInteractionCardButton_vlxoe_130",xn="_summaryStatsCards_vlxoe_148",_n="_summaryStatsCard_vlxoe_148",Cn="_summaryStatsCardValue_vlxoe_169",yn="_summaryStatsCardLabel_vlxoe_176",l={tabSelector:nn,progressSection:sn,progressLabel:rn,chartGrid:on,chartContainer:ln,tableContainer:cn,modelPerformance:dn,loadingContainer:un,errorContainer:mn,userInteractionCards:hn,userInteractionCard:gn,userInteractionCardValue:fn,userInteractionCardLabel:vn,userInteractionCardButton:pn,summaryStatsCards:xn,summaryStatsCard:_n,summaryStatsCardValue:Cn,summaryStatsCardLabel:yn};function jn(){const[m]=Dt(),[a,h]=n.useState(null),[o,f]=n.useState(!0),[g,b]=n.useState("crisis_maps"),[_,y]=n.useState([]),[x,w]=n.useState([]),[C,j]=n.useState([]),[v,S]=n.useState([]),[p,L]=n.useState(!1),[I,R]=n.useState(!1),[k,G]=n.useState(!1),[U,ie]=n.useState(!1),[ae,be]=n.useState(!1),[K,W]=n.useState(!1),T=t=>{L(t==="editTime"),R(t==="percentage"),G(t==="delete"),ie(t==="regions"),be(t==="sources"),W(t==="types")},O=[{key:"crisis_maps",label:"Crisis Maps"},{key:"drone_images",label:"Drone Images"}],F=n.useCallback((t,c)=>{if(!t||!c)return 0;const d=t.toLowerCase().replace(/[^\w\s]/g,"").split(/\s+/).filter(u=>u.length>0),r=c.toLowerCase().replace(/[^\w\s]/g,"").split(/\s+/).filter(u=>u.length>0);if(d.length===0&&r.length===0)return 1;if(d.length===0||r.length===0)return 0;const s=new Set(d),i=new Set(r),D=new Set([...s].filter(u=>i.has(u))),$=new Set([...s,...i]);return D.size/$.size},[]),X=n.useCallback(async()=>{f(!0);try{const c=await(await fetch("/api/images")).json(),d={},r=c.filter(u=>u.image_type==="crisis_map"),s=c.filter(u=>u.image_type==="drone_image"),i={totalCaptions:c.length,sources:{},types:{},regions:{},models:{},modelEditTimes:d,percentageModified:0,modelPercentageData:{},totalDeleteCount:0,deleteRate:0,crisisMaps:r,droneImages:s};c.forEach(u=>{if(u.source&&(i.sources[u.source]=(i.sources[u.source]||0)+1),u.event_type&&(i.types[u.event_type]=(i.types[u.event_type]||0)+1),u.countries&&u.countries.forEach(P=>{P.r_code&&(i.regions[P.r_code]=(i.regions[P.r_code]||0)+1)}),u.model){const P=u.model,V=i.models[P]||={count:0,avgAccuracy:0,avgContext:0,avgUsability:0,totalScore:0,deleteCount:0};if(V.count++,u.accuracy!=null&&(V.avgAccuracy+=u.accuracy),u.context!=null&&(V.avgContext+=u.context),u.usability!=null&&(V.avgUsability+=u.usability),u.created_at&&u.updated_at){const te=new Date(u.created_at).getTime(),Ce=new Date(u.updated_at).getTime()-te;Ce>0&&(d[P]||(d[P]=[]),d[P].push(Ce))}}}),_.forEach(u=>{u.s_code&&!i.sources[u.s_code]&&(i.sources[u.s_code]=0)}),x.forEach(u=>{u.t_code&&!i.types[u.t_code]&&(i.types[u.t_code]=0)}),C.forEach(u=>{u.r_code&&!i.regions[u.r_code]&&(i.regions[u.r_code]=0)}),["GPT-4","Claude","Gemini","Llama","Other"].forEach(u=>{i.models[u]||(i.models[u]={count:0,avgAccuracy:0,avgContext:0,avgUsability:0,totalScore:0,deleteCount:0})}),Object.values(i.models).forEach(u=>{u.count>0&&(u.avgAccuracy=Math.round(u.avgAccuracy/u.count),u.avgContext=Math.round(u.avgContext/u.count),u.avgUsability=Math.round(u.avgUsability/u.count),u.totalScore=Math.round((u.avgAccuracy+u.avgContext+u.avgUsability)/3))});const $=c.filter(u=>u.generated&&u.edited);if($.length>0){const P=[...$.map(oe=>F(oe.generated,oe.edited))].sort((oe,Ce)=>oe-Ce),V=Math.floor(P.length/2),te=P.length%2===0?(P[V-1]+P[V])/2:P[V];i.percentageModified=Math.round((1-te)*100)}const H={};c.forEach(u=>{if(u.model&&u.generated&&u.edited){const P=F(u.generated,u.edited),V=Math.round((1-P)*100);H[u.model]||(H[u.model]=[]),H[u.model].push(V)}}),i.modelPercentageData=H;try{const u=await fetch("/api/models");if(u.ok){const P=await u.json();if(P.models){P.models.forEach(te=>{i.models[te.m_code]&&(i.models[te.m_code].deleteCount=te.delete_count||0)});const V=P.models.reduce((te,oe)=>te+(oe.delete_count||0),0);i.totalDeleteCount=V,i.deleteRate=V>0?Math.round(V/(V+c.length)*100):0}}}catch(u){console.log("Could not fetch model delete counts:",u)}h(i)}catch{h(null)}finally{f(!1)}},[_,x,C,F]),ne=n.useCallback(async()=>{try{const[t,c,d,r]=await Promise.all([fetch("/api/sources"),fetch("/api/types"),fetch("/api/regions"),fetch("/api/models")]),s=await t.json(),i=await c.json(),D=await d.json(),$=await r.json();y(s),w(i),j(D),S($.models||[])}catch(t){console.log("Could not fetch lookup data:",t)}},[]);n.useEffect(()=>{const t=m.get("view");(t==="crisis_maps"||t==="drone_images")&&b(t)},[m]),n.useEffect(()=>{ne()},[ne]),n.useEffect(()=>{_.length>0&&x.length>0&&C.length>0&&v.length>0&&X()},[_,x,C,v,X]);const Y=n.useCallback(t=>{const c=_.find(d=>d.s_code===t);return c?c.label:t},[_]),M=n.useCallback(t=>{if(t.length===0)return 0;const c=[...t].sort((r,s)=>r-s),d=Math.floor(c.length/2);return c.length%2===0?Math.round((c[d-1]+c[d])/2):c[d]},[]),se=n.useCallback(t=>{const c=Math.floor(t/1e3),d=Math.floor(c/60),r=Math.floor(d/60);return r>0?`${r}h ${d%60}m`:d>0?`${d}m ${c%60}s`:`${c}s`},[]),_e=n.useCallback(t=>{const c=x.find(d=>d.t_code===t);return c?c.label:t},[x]),J=n.useCallback(t=>{const c=v.find(d=>d.m_code===t);return c?c.label:t},[v]),Se=n.useMemo(()=>a?Object.entries(a.modelEditTimes||{}).filter(([,t])=>t.length>0).sort(([,t],[,c])=>M(c)-M(t)).map(([t,c],d)=>({id:d+1,name:J(t),count:c.length,avgEditTime:M(c),minEditTime:Math.min(...c),maxEditTime:Math.max(...c)})):[],[a,M,J]),Me=n.useMemo(()=>a?Object.entries(a.modelPercentageData||{}).filter(([,t])=>t.length>0).sort(([,t],[,c])=>{const d=[...t].sort((H,u)=>H-u),r=[...c].sort((H,u)=>H-u),s=Math.floor(d.length/2),i=Math.floor(r.length/2),D=d.length%2===0?(d[s-1]+d[s])/2:d[s];return(r.length%2===0?(r[i-1]+r[i])/2:r[i])-D}).map(([t,c],d)=>{const r=[...c].sort((D,$)=>D-$),s=Math.floor(r.length/2),i=r.length%2===0?Math.round((r[s-1]+r[s])/2):r[s];return{id:d+1,name:J(t),count:c.length,avgPercentageModified:i,minPercentageModified:Math.min(...c),maxPercentageModified:Math.max(...c)}}):[],[a,J]),Ie=n.useMemo(()=>a?Object.entries(a.models).filter(([t,c])=>c.count>0&&t!=="manual").map(([t,c],d)=>{const r=[c.avgAccuracy,c.avgContext,c.avgUsability],s=r.reduce(($,H)=>$+H,0)/r.length,i=r.reduce(($,H)=>$+Math.pow(H-s,2),0)/r.length,D=Math.round(100-Math.sqrt(i));return{id:d+1,name:J(t),consistency:Math.max(0,D),avgScore:Math.round(s),count:c.count}}).sort((t,c)=>c.consistency-t.consistency):[],[a,J]),De=n.useMemo(()=>[Q("name","Region",t=>t.name),E("count","Count",t=>t.count),E("percentage","% of Total",t=>t.percentage,{suffix:"%",maximumFractionDigits:0})],[]),Ee=n.useMemo(()=>[Q("name","Type",t=>t.name),E("count","Count",t=>t.count),E("percentage","% of Total",t=>t.percentage,{suffix:"%",maximumFractionDigits:0})],[]),lt=n.useMemo(()=>[Q("name","Source",t=>t.name),E("count","Count",t=>t.count),E("percentage","% of Total",t=>t.percentage,{suffix:"%",maximumFractionDigits:0})],[]),Te=n.useMemo(()=>[Q("name","Model",t=>t.name),E("count","Count",t=>t.count),E("accuracy","Accuracy",t=>t.accuracy,{suffix:"%",maximumFractionDigits:0}),E("context","Context",t=>t.context,{suffix:"%",maximumFractionDigits:0}),E("usability","Usability",t=>t.usability,{suffix:"%",maximumFractionDigits:0}),E("totalScore","Total Score",t=>t.totalScore,{suffix:"%",maximumFractionDigits:0})],[]),ke=n.useMemo(()=>[Q("name","Model",t=>t.name),E("count","Count",t=>t.count),Q("avgEditTime","Median Edit Time",t=>se(t.avgEditTime)),Q("minEditTime","Min Edit Time",t=>se(t.minEditTime)),Q("maxEditTime","Max Edit Time",t=>se(t.maxEditTime))],[se]),Le=n.useMemo(()=>[Q("name","Model",t=>t.name),E("count","Count",t=>t.count),E("avgPercentageModified","Median % Modified",t=>t.avgPercentageModified,{suffix:"%",maximumFractionDigits:0}),E("minPercentageModified","Min % Modified",t=>t.minPercentageModified,{suffix:"%",maximumFractionDigits:0}),E("maxPercentageModified","Max % Modified",t=>t.maxPercentageModified,{suffix:"%",maximumFractionDigits:0})],[]),Pe=n.useMemo(()=>[Q("name","Model",t=>t.name),E("count","Total Count",t=>t.count),E("deleteCount","Delete Count",t=>t.deleteCount),E("deleteRate","Delete Rate",t=>t.deleteRate,{suffix:"%",maximumFractionDigits:1})],[]),ct=n.useMemo(()=>[Q("source","Source",t=>t.source),E("avgQuality","Average Quality",t=>t.avgQuality,{suffix:"%",maximumFractionDigits:0}),E("count","Count",t=>t.count)],[]),Re=n.useMemo(()=>[Q("eventType","Event Type",t=>t.eventType),E("avgQuality","Average Quality",t=>t.avgQuality,{suffix:"%",maximumFractionDigits:0}),E("count","Count",t=>t.count)],[]),$e=n.useMemo(()=>[Q("name","Model",t=>t.name),E("consistency","Consistency",t=>t.consistency,{suffix:"%",maximumFractionDigits:0}),E("avgScore","Average Score",t=>t.avgScore,{suffix:"%",maximumFractionDigits:0}),E("count","Count",t=>t.count)],[]),ue=n.useCallback(t=>a?t==="crisis_map"?a.crisisMaps.length:t==="drone_image"?a.droneImages.length:0:0,[a]),Be=n.useCallback(t=>{if(!a)return[];const c=t==="crisis_map"?a.crisisMaps:a.droneImages,d={};return c.forEach(r=>{r.countries&&r.countries.forEach(s=>{s.r_code&&(d[s.r_code]=(d[s.r_code]||0)+1)})}),Object.entries(d).filter(([,r])=>r>0).map(([r,s])=>({name:C.find(i=>i.r_code===r)?.label||r,value:s}))},[a,C]),Ae=n.useCallback(t=>{if(!a)return[];const c=t==="crisis_map"?a.crisisMaps:a.droneImages,d={};c.forEach(s=>{s.countries&&s.countries.forEach(i=>{i.r_code&&(d[i.r_code]=(d[i.r_code]||0)+1)})});const r=C.reduce((s,i)=>(i.r_code&&(s[i.r_code]={name:i.label,count:d[i.r_code]||0}),s),{});return Object.entries(r).sort(([,s],[,i])=>i.count-s.count).map(([,{name:s,count:i}],D)=>({id:D+1,name:s,count:i,percentage:c.length>0?Math.round(i/c.length*100):0}))},[a,C]),dt=n.useCallback(t=>{if(!a)return[];const c=t==="crisis_map"?a.crisisMaps:a.droneImages,d={};return c.forEach(r=>{r.source&&(d[r.source]=(d[r.source]||0)+1)}),Object.entries(d).filter(([,r])=>r>0).map(([r,s])=>({name:_.find(i=>i.s_code===r)?.label||r,value:s}))},[a,_]),ut=n.useCallback(t=>{if(!a)return[];const c=t==="crisis_map"?a.crisisMaps:a.droneImages,d={};return c.forEach(r=>{r.source&&(d[r.source]=(d[r.source]||0)+1)}),Object.entries(d).sort(([,r],[,s])=>s-r).map(([r,s],i)=>({id:i+1,name:Y(r),count:s,percentage:c.length>0?Math.round(s/c.length*100):0}))},[a,Y]),Fe=n.useCallback(t=>{if(!a)return[];const c=t==="crisis_map"?a.crisisMaps:a.droneImages,d={};return c.forEach(r=>{r.event_type&&(d[r.event_type]=(d[r.event_type]||0)+1)}),Object.entries(d).filter(([,r])=>r>0).map(([r,s])=>({name:x.find(i=>i.t_code===r)?.label||r,value:s}))},[a,x]),Oe=n.useCallback(t=>{if(!a)return[];const c=t==="crisis_map"?a.crisisMaps:a.droneImages,d={};return c.forEach(r=>{r.event_type&&(d[r.event_type]=(d[r.event_type]||0)+1)}),Object.entries(d).sort(([,r],[,s])=>s-r).map(([r,s],i)=>({id:i+1,name:_e(r),count:s,percentage:c.length>0?Math.round(s/c.length*100):0}))},[a,_e]),He=n.useCallback(t=>{if(!a)return"No data available";const c=t==="crisis_map"?a.crisisMaps:a.droneImages,d=new Set;c.forEach(i=>{i.model&&d.add(i.model)}),console.log(`Debug ${t}:`,{totalImages:c.length,usedModels:Array.from(d),availableEditTimes:Object.keys(a.modelEditTimes),modelEditTimesData:a.modelEditTimes});const s=Object.entries(a.modelEditTimes).filter(([i])=>d.has(i)).flatMap(([,i])=>i);return s.length===0?"No data available":se(M(s))},[a,se,M]),Ve=n.useCallback(()=>{if(!a)return"No data available";const t=a.totalCaptions||0,c=a.percentageModified||0;return t>0?Math.round(c/t*100):0},[a]),ze=n.useCallback(()=>a&&a.deleteRate>=0?`${a.deleteRate}%`:"No data available",[a]),Ue=n.useCallback(t=>{if(!a)return[];const c=t==="crisis_map"?a.crisisMaps:a.droneImages,d=new Set;return c.forEach(s=>{s.model&&d.add(s.model)}),Se.filter(s=>{const i=v.find(D=>D.label===s.name)?.m_code;return i&&d.has(i)})},[a,Se,v]),We=n.useCallback(t=>{if(!a)return[];const c=t==="crisis_map"?a.crisisMaps:a.droneImages,d=new Set;return c.forEach(s=>{s.model&&d.add(s.model)}),Me.filter(s=>{const i=v.find(D=>D.label===s.name)?.m_code;return i&&d.has(i)})},[a,Me,v]),Qe=n.useCallback(t=>{if(!a)return[];const c=t==="crisis_map"?a.crisisMaps:a.droneImages,d={};return c.forEach(r=>{r.model&&(d[r.model]||(d[r.model]={count:0,deleteCount:0}),d[r.model].count++)}),Object.entries(d).map(([r,s],i)=>{const $=a.models?.[r]?.deleteCount||0,H=s.count>0?Math.round($/s.count*100*10)/10:0;return{id:i+1,name:J(r),count:s.count,deleteCount:$,deleteRate:H}}).sort((r,s)=>s.count-r.count)},[a,J]),Ze=n.useCallback(t=>{if(!a)return[];const d=(t==="crisis_map"?a.crisisMaps:a.droneImages).filter(s=>s.model!=="manual"),r={};return d.forEach(s=>{s.model&&(r[s.model]||(r[s.model]={count:0,totalAccuracy:0,totalContext:0,totalUsability:0}),r[s.model].count++,s.accuracy!=null&&(r[s.model].totalAccuracy+=s.accuracy),s.context!=null&&(r[s.model].totalContext+=s.context),s.usability!=null&&(r[s.model].totalUsability+=s.usability))}),Object.entries(r).map(([s,i],D)=>({id:D+1,name:J(s),count:i.count,accuracy:i.count>0?Math.round(i.totalAccuracy/i.count):0,context:i.count>0?Math.round(i.totalContext/i.count):0,usability:i.count>0?Math.round(i.totalUsability/i.count):0,totalScore:i.count>0?Math.round((i.totalAccuracy+i.totalContext+i.totalUsability)/(3*i.count)):0})).sort((s,i)=>i.totalScore-s.totalScore)},[a,J]),mt=n.useCallback(t=>{if(!a)return[];const d=(t==="crisis_map"?a.crisisMaps:a.droneImages).filter(s=>s.model!=="manual"),r={};return d.forEach(s=>{s.source&&(r[s.source]||(r[s.source]={total:0,count:0,totalImages:0}),r[s.source].totalImages+=1,s.accuracy!=null&&(r[s.source].total+=s.accuracy,r[s.source].count+=1))}),Object.entries(r).map(([s,i],D)=>({id:D+1,source:Y(s),avgQuality:i.count>0?Math.round(i.total/i.count):0,count:i.totalImages}))},[a,Y]),qe=n.useCallback(t=>{if(!a)return[];const d=(t==="crisis_map"?a.crisisMaps:a.droneImages).filter(s=>s.model!=="manual"),r={};return d.forEach(s=>{s.event_type&&(r[s.event_type]||(r[s.event_type]={total:0,count:0,totalImages:0}),r[s.event_type].totalImages+=1,s.accuracy!=null&&(r[s.event_type].total+=s.accuracy,r[s.event_type].count+=1))}),Object.entries(r).map(([s,i],D)=>({id:D+1,eventType:_e(s),avgQuality:i.count>0?Math.round(i.total/i.count):0,count:i.totalImages}))},[a,_e]),Ge=n.useCallback(t=>{if(!a)return[];const d=(t==="crisis_map"?a.crisisMaps:a.droneImages).filter(i=>i.model!=="manual"),r=new Set;return d.forEach(i=>{i.model&&r.add(i.model)}),Ie.filter(i=>{const D=v.find($=>$.label===i.name)?.m_code;return D&&D!=="manual"&&r.has(D)})},[a,Ie,v]);if(o)return e.jsx(je,{children:e.jsx("div",{className:l.loadingContainer,children:e.jsx(Et,{})})});if(!a)return e.jsx(je,{children:e.jsx("div",{className:l.errorContainer,children:e.jsx("div",{className:"text-red-500",children:"Failed to load analytics data. Please try again."})})});const me=["#F5333F","#F64752","#F75C65","#F87079","#F9858C","#FA999F","#FBADB2","#FCC2C5"];return e.jsx(je,{children:e.jsxs("div",{className:"max-w-7xl mx-auto",children:[e.jsx("div",{className:l.tabSelector,children:e.jsx(Tt,{name:"analytics-view",value:g,onChange:t=>{(t==="crisis_maps"||t==="drone_images")&&b(t)},options:O,keySelector:t=>t.key,labelSelector:t=>t.label})}),g==="crisis_maps"?e.jsxs("div",{className:l.chartGrid,children:[e.jsxs(z,{heading:"Summary Statistics",headingLevel:3,withHeaderBorder:!0,withInternalPadding:!0,children:[e.jsxs("div",{className:l.summaryStatsCards,children:[e.jsxs("div",{className:l.summaryStatsCard,children:[e.jsx("div",{className:l.summaryStatsCardValue,children:ue("crisis_map")}),e.jsx("div",{className:l.summaryStatsCardLabel,children:"Total Crisis Maps"})]}),e.jsxs("div",{className:l.summaryStatsCard,children:[e.jsx("div",{className:l.summaryStatsCardValue,children:"2000"}),e.jsx("div",{className:l.summaryStatsCardLabel,children:"Target Amount"})]})]}),e.jsxs("div",{className:l.progressSection,children:[e.jsxs("div",{className:l.progressLabel,children:[e.jsx("span",{children:"Progress towards target"}),e.jsxs("span",{children:[Math.round(ue("crisis_map")/2e3*100),"%"]})]}),e.jsx(Ye,{value:ue("crisis_map"),totalValue:2e3})]})]}),e.jsxs(z,{heading:"Distribution Analysis",headingLevel:3,withHeaderBorder:!0,withInternalPadding:!0,children:[e.jsxs("div",{className:l.userInteractionCards,children:[e.jsxs("div",{className:l.userInteractionCard,children:[e.jsx("div",{className:l.userInteractionCardLabel,children:"Regions Distribution"}),e.jsx("div",{className:l.chartContainer,children:e.jsx(xe,{data:Be("crisis_map"),valueSelector:t=>t.value,labelSelector:t=>t.name,keySelector:t=>t.name,colors:me,showPercentageInLegend:!0})}),e.jsx(Z,{name:"view-regions-details",variant:U?"primary":"secondary",onClick:()=>T(U?"none":"regions"),className:l.userInteractionCardButton,children:U?"Hide Details":"View Details"})]}),e.jsxs("div",{className:l.userInteractionCard,children:[e.jsx("div",{className:l.userInteractionCardLabel,children:"Sources Distribution"}),e.jsx("div",{className:l.chartContainer,children:e.jsx(xe,{data:dt("crisis_map"),valueSelector:t=>t.value,labelSelector:t=>t.name,keySelector:t=>t.name,colors:me,showPercentageInLegend:!0})}),e.jsx(Z,{name:"view-sources-details",variant:ae?"primary":"secondary",onClick:()=>T(ae?"none":"sources"),className:l.userInteractionCardButton,children:ae?"Hide Details":"View Details"})]}),e.jsxs("div",{className:l.userInteractionCard,children:[e.jsx("div",{className:l.userInteractionCardLabel,children:"Types Distribution"}),e.jsx("div",{className:l.chartContainer,children:e.jsx(xe,{data:Fe("crisis_map"),valueSelector:t=>t.value,labelSelector:t=>t.name,keySelector:t=>t.name,colors:me,showPercentageInLegend:!0})}),e.jsx(Z,{name:"view-types-details",variant:K?"primary":"secondary",onClick:()=>T(K?"none":"types"),className:l.userInteractionCardButton,children:K?"Hide Details":"View Details"})]})]}),U&&e.jsx("div",{className:l.modelPerformance,children:e.jsx(A,{data:Ae("crisis_map"),columns:De,keySelector:B,filtered:!1,pending:!1})}),ae&&e.jsx("div",{className:l.modelPerformance,children:e.jsx(A,{data:ut("crisis_map"),columns:lt,keySelector:B,filtered:!1,pending:!1})}),K&&e.jsx("div",{className:l.modelPerformance,children:e.jsx(A,{data:Oe("crisis_map"),columns:Ee,keySelector:B,filtered:!1,pending:!1})})]}),e.jsxs(z,{heading:"User Interaction Statistics",headingLevel:3,withHeaderBorder:!0,withInternalPadding:!0,children:[e.jsxs("div",{className:l.userInteractionCards,children:[e.jsxs("div",{className:l.userInteractionCard,children:[e.jsx("div",{className:l.userInteractionCardValue,children:He("crisis_map")}),e.jsx("div",{className:l.userInteractionCardLabel,children:"Median Edit Time"}),e.jsx(Z,{name:"view-edit-time-details",variant:p?"primary":"secondary",onClick:()=>T(p?"none":"editTime"),className:l.userInteractionCardButton,children:p?"Hide Details":"View Details"})]}),e.jsxs("div",{className:l.userInteractionCard,children:[e.jsx("div",{className:l.userInteractionCardValue,children:Ve()}),e.jsx("div",{className:l.userInteractionCardLabel,children:"Median % Modified"}),e.jsx(Z,{name:"view-percentage-details",variant:I?"primary":"secondary",onClick:()=>T(I?"none":"percentage"),className:l.userInteractionCardButton,children:I?"Hide Details":"View Details"})]}),e.jsxs("div",{className:l.userInteractionCard,children:[e.jsx("div",{className:l.userInteractionCardValue,children:ze()}),e.jsx("div",{className:l.userInteractionCardLabel,children:"Delete Rate"}),e.jsx(Z,{name:"view-delete-details",variant:k?"primary":"secondary",onClick:()=>T(k?"none":"delete"),className:l.userInteractionCardButton,children:k?"Hide Details":"View Details"})]})]}),p&&e.jsx("div",{className:l.modelPerformance,children:e.jsx(A,{data:Ue("crisis_map"),columns:ke,keySelector:B,filtered:!1,pending:!1})}),I&&e.jsx("div",{className:l.modelPerformance,children:e.jsx(A,{data:We("crisis_map"),columns:Le,keySelector:B,filtered:!1,pending:!1})}),k&&e.jsx("div",{className:l.modelPerformance,children:e.jsx(A,{data:Qe("crisis_map"),columns:Pe,keySelector:B,filtered:!1,pending:!1})})]}),e.jsx(z,{heading:"Model Performance",headingLevel:3,withHeaderBorder:!0,withInternalPadding:!0,children:e.jsx("div",{className:l.modelPerformance,children:e.jsx(A,{data:Ze("crisis_map"),columns:Te,keySelector:B,filtered:!1,pending:!1})})}),e.jsx(z,{heading:"Quality-Source Correlation",headingLevel:3,withHeaderBorder:!0,withInternalPadding:!0,children:e.jsx("div",{className:l.tableContainer,children:e.jsx(A,{data:mt("crisis_map"),columns:ct,keySelector:B,filtered:!1,pending:!1})})}),e.jsx(z,{heading:"Quality-Event Type Correlation",headingLevel:3,withHeaderBorder:!0,withInternalPadding:!0,children:e.jsx("div",{className:l.tableContainer,children:e.jsx(A,{data:qe("crisis_map"),columns:Re,keySelector:B,filtered:!1,pending:!1})})}),e.jsx(z,{heading:"Model Consistency Analysis",headingLevel:3,withHeaderBorder:!0,withInternalPadding:!0,children:e.jsx("div",{className:l.tableContainer,children:e.jsx(A,{data:Ge("crisis_map"),columns:$e,keySelector:B,filtered:!1,pending:!1})})})]}):e.jsxs("div",{className:l.chartGrid,children:[e.jsxs(z,{heading:"Summary Statistics",headingLevel:3,withHeaderBorder:!0,withInternalPadding:!0,children:[e.jsxs("div",{className:l.summaryStatsCards,children:[e.jsxs("div",{className:l.summaryStatsCard,children:[e.jsx("div",{className:l.summaryStatsCardValue,children:ue("drone_image")}),e.jsx("div",{className:l.summaryStatsCardLabel,children:"Total Drone Images"})]}),e.jsxs("div",{className:l.summaryStatsCard,children:[e.jsx("div",{className:l.summaryStatsCardValue,children:"2000"}),e.jsx("div",{className:l.summaryStatsCardLabel,children:"Target Amount"})]})]}),e.jsxs("div",{className:l.progressSection,children:[e.jsxs("div",{className:l.progressLabel,children:[e.jsx("span",{children:"Progress towards target"}),e.jsxs("span",{children:[Math.round(ue("drone_image")/2e3*100),"%"]})]}),e.jsx(Ye,{value:ue("drone_image"),totalValue:2e3})]})]}),e.jsxs(z,{heading:"Distribution Analysis",headingLevel:3,withHeaderBorder:!0,withInternalPadding:!0,children:[e.jsxs("div",{className:l.userInteractionCards,children:[e.jsxs("div",{className:l.userInteractionCard,children:[e.jsx("div",{className:l.userInteractionCardLabel,children:"Regions Distribution"}),e.jsx("div",{className:l.chartContainer,children:e.jsx(xe,{data:Be("drone_image"),valueSelector:t=>t.value,labelSelector:t=>t.name,keySelector:t=>t.name,colors:me,showPercentageInLegend:!0})}),e.jsx(Z,{name:"view-regions-details",variant:U?"primary":"secondary",onClick:()=>T(U?"none":"regions"),className:l.userInteractionCardButton,children:U?"Hide Details":"View Details"})]}),e.jsxs("div",{className:l.userInteractionCard,children:[e.jsx("div",{className:l.userInteractionCardLabel,children:"Types Distribution"}),e.jsx("div",{className:l.chartContainer,children:e.jsx(xe,{data:Fe("drone_image"),valueSelector:t=>t.value,labelSelector:t=>t.name,keySelector:t=>t.name,colors:me,showPercentageInLegend:!0})}),e.jsx(Z,{name:"view-types-details",variant:K?"primary":"secondary",onClick:()=>T(K?"none":"types"),className:l.userInteractionCardButton,children:K?"Hide Details":"View Details"})]})]}),U&&e.jsx("div",{className:l.modelPerformance,children:e.jsx(A,{data:Ae("drone_image"),columns:De,keySelector:B,filtered:!1,pending:!1})}),K&&e.jsx("div",{className:l.modelPerformance,children:e.jsx(A,{data:Oe("drone_image"),columns:Ee,keySelector:B,filtered:!1,pending:!1})})]}),e.jsxs(z,{heading:"User Interaction Statistics",headingLevel:3,withHeaderBorder:!0,withInternalPadding:!0,children:[e.jsxs("div",{className:l.userInteractionCards,children:[e.jsxs("div",{className:l.userInteractionCard,children:[e.jsx("div",{className:l.userInteractionCardValue,children:He("drone_image")}),e.jsx("div",{className:l.userInteractionCardLabel,children:"Median Edit Time"}),e.jsx(Z,{name:"view-edit-time-details",variant:p?"primary":"secondary",onClick:()=>T(p?"none":"editTime"),className:l.userInteractionCardButton,children:p?"Hide Details":"View Details"})]}),e.jsxs("div",{className:l.userInteractionCard,children:[e.jsx("div",{className:l.userInteractionCardValue,children:Ve()}),e.jsx("div",{className:l.userInteractionCardLabel,children:"Median % Modified"}),e.jsx(Z,{name:"view-percentage-details",variant:I?"primary":"secondary",onClick:()=>T(I?"none":"percentage"),className:l.userInteractionCardButton,children:I?"Hide Details":"View Details"})]}),e.jsxs("div",{className:l.userInteractionCard,children:[e.jsx("div",{className:l.userInteractionCardValue,children:ze()}),e.jsx("div",{className:l.userInteractionCardLabel,children:"Delete Rate"}),e.jsx(Z,{name:"view-delete-details",variant:k?"primary":"secondary",onClick:()=>T(k?"none":"delete"),className:l.userInteractionCardButton,children:k?"Hide Details":"View Details"})]})]}),p&&e.jsx("div",{className:l.modelPerformance,children:e.jsx(A,{data:Ue("drone_image"),columns:ke,keySelector:B,filtered:!1,pending:!1})}),I&&e.jsx("div",{className:l.modelPerformance,children:e.jsx(A,{data:We("drone_image"),columns:Le,keySelector:B,filtered:!1,pending:!1})}),k&&e.jsx("div",{className:l.modelPerformance,children:e.jsx(A,{data:Qe("drone_image"),columns:Pe,keySelector:B,filtered:!1,pending:!1})})]}),e.jsx(z,{heading:"Model Performance",headingLevel:3,withHeaderBorder:!0,withInternalPadding:!0,children:e.jsx("div",{className:l.modelPerformance,children:e.jsx(A,{data:Ze("drone_image"),columns:Te,keySelector:B,filtered:!1,pending:!1})})}),e.jsx(z,{heading:"Quality-Event Type Correlation",headingLevel:3,withHeaderBorder:!0,withInternalPadding:!0,children:e.jsx("div",{className:l.tableContainer,children:e.jsx(A,{data:qe("drone_image"),columns:Re,keySelector:B,filtered:!1,pending:!1})})}),e.jsx(z,{heading:"Model Consistency Analysis",headingLevel:3,withHeaderBorder:!0,withInternalPadding:!0,children:e.jsx("div",{className:l.tableContainer,children:e.jsx(A,{data:Ge("drone_image"),columns:$e,keySelector:B,filtered:!1,pending:!1})})})]})]})})}export{jn as default}; +import{r as n,y as nt,t as ht,a as q,c as gt,j as e,o as N,b as re,R as st,z,g as rt,d as ft,m as vt,e as pt,n as Z,A as xt,f as _t,h as Ct,i as yt,k as he,l as bt,p as ye,q as jt,s as Nt,E as wt,C as St,U as Mt,Q as It,u as Dt,N as je,_ as Et,L as Tt}from"./index-CcfIBRoF.js";const kt=({title:m,titleId:a,...h})=>n.createElement("svg",Object.assign({xmlns:"http://www.w3.org/2000/svg","aria-hidden":"true",viewBox:"0 0 24 24",fill:"currentColor",width:"1em",height:"1em","aria-labelledby":a},h),m?n.createElement("title",{id:a},m):null,n.createElement("g",{clipPath:"url(#arrow-drop-down-line_svg__a)"},n.createElement("path",{d:"m12 15-4.243-4.243 1.415-1.414L12 12.172l2.828-2.83 1.415 1.415L12 15Z"})),n.createElement("defs",null,n.createElement("clipPath",{id:"arrow-drop-down-line_svg__a"},n.createElement("path",{d:"M0 0h24v24H0z"})))),Lt=({title:m,titleId:a,...h})=>n.createElement("svg",Object.assign({xmlns:"http://www.w3.org/2000/svg","aria-hidden":"true",viewBox:"0 0 24 24",fill:"currentColor",width:"1em",height:"1em","aria-labelledby":a},h),m?n.createElement("title",{id:a},m):null,n.createElement("g",{clipPath:"url(#arrow-drop-up-line_svg__a)"},n.createElement("path",{d:"m12 11.828-2.828 2.829-1.415-1.414L12 9l4.243 4.243-1.415 1.414L12 11.828Z"})),n.createElement("defs",null,n.createElement("clipPath",{id:"arrow-drop-up-line_svg__a"},n.createElement("path",{d:"M0 0h24v24H0z"})))),Pt=({title:m,titleId:a,...h})=>n.createElement("svg",Object.assign({xmlns:"http://www.w3.org/2000/svg","aria-hidden":"true",viewBox:"0 0 24 24",fill:"currentColor",width:"1em",height:"1em","aria-labelledby":a},h),m?n.createElement("title",{id:a},m):null,n.createElement("g",{clipPath:"url(#information-line_svg__a)"},n.createElement("path",{d:"M12 22C6.477 22 2 17.523 2 12S6.477 2 12 2s10 4.477 10 10-4.477 10-10 10Zm0-2a8 8 0 1 0 0-16.001A8 8 0 0 0 12 20ZM11 7h2v2h-2V7Zm0 4h2v6h-2v-6Z"})),n.createElement("defs",null,n.createElement("clipPath",{id:"information-line_svg__a"},n.createElement("path",{d:"M0 0h24v24H0z"})))),Rt=({title:m,titleId:a,...h})=>n.createElement("svg",Object.assign({xmlns:"http://www.w3.org/2000/svg","aria-hidden":"true",viewBox:"0 0 24 24",fill:"currentColor",width:"1em",height:"1em","aria-labelledby":a},h),m?n.createElement("title",{id:a},m):null,n.createElement("path",{fillRule:"evenodd",d:"m15.063 12 .937.938-4 4-4-4L8.938 12 12 15.063 15.063 12Z",clipRule:"evenodd"}),n.createElement("mask",{id:"table-sorting-line_svg__a",width:8,height:5,x:8,y:12,maskUnits:"userSpaceOnUse",style:{maskType:"luminance"}},n.createElement("path",{fillRule:"evenodd",d:"m15.063 12 .937.938-4 4-4-4L8.938 12 12 15.063 15.063 12Z",clipRule:"evenodd"})),n.createElement("g",{mask:"url(#table-sorting-line_svg__a)"},n.createElement("path",{d:"M-24-22h72v72h-72z"})),n.createElement("path",{fillRule:"evenodd",d:"M8.938 11 8 10.062l4-4 4 4-.938.938L12 7.937 8.937 11Z",clipRule:"evenodd"}),n.createElement("mask",{id:"table-sorting-line_svg__b",width:8,height:5,x:8,y:6,maskUnits:"userSpaceOnUse",style:{maskType:"luminance"}},n.createElement("path",{fillRule:"evenodd",d:"M8.938 11 8 10.062l4-4 4 4-.938.938L12 7.937 8.937 11Z",clipRule:"evenodd"})),n.createElement("g",{mask:"url(#table-sorting-line_svg__b)"},n.createElement("path",{d:"M48 45h-72v-72h72z"}))),$t="_number-output_1blvi_1",Bt={numberOutput:$t};function we(m){const{className:a,invalidText:h=nt,separatorHidden:o,compact:f,currency:g,value:b,tooltip:_,unit:y,prefix:x,suffix:w,maximumFractionDigits:C=1}=m,{currentLanguage:j}=n.useContext(ht),v=n.useMemo(()=>{if(q(b))return h;const S=gt(b,{currency:g,compact:f,separatorHidden:o,maximumFractionDigits:C,unit:y,language:j});return e.jsxs(e.Fragment,{children:[x,S,w]})},[h,b,f,o,g,y,C,x,j,w]);return e.jsx("div",{className:N(Bt.numberOutput,a),title:re(_)?String(_):void 0,children:v})}const At="_tooltip-dummy_rbf3f_1",Ft="_tooltip-content_rbf3f_7",Ot="_pointer_rbf3f_14",Ne={tooltipDummy:At,tooltipContent:Ft,pointer:Ot};function Ht(m){const{className:a,title:h,description:o,preferredWidth:f}=m,[g,b]=n.useState(!1),[_,y]=n.useState(!1),x=n.useRef(),w=n.useRef(null);return n.useEffect(()=>{const C=()=>{y(!0)},j=()=>{y(!1)};if(q(w.current))return;const{current:{parentNode:v}}=w;if(!q(v))return x.current=v,v.addEventListener("mouseover",C),v.addEventListener("mouseout",j),b(!0),()=>{v.removeEventListener("mouseover",C),v.removeEventListener("mouseout",j)}},[]),e.jsxs(e.Fragment,{children:[!g&&e.jsx("div",{className:Ne.tooltipDummy,ref:w}),_&&e.jsx(st,{className:N(Ne.tooltipContent,a),parentRef:x,pointerClassName:Ne.pointer,preferredWidth:f,children:e.jsx(z,{heading:h,withInternalPadding:!0,contentViewType:"vertical",children:o})})]})}function B(m){return m.id}const Vt="common",zt={booleanYesLabel:"Yes",booleanNoLabel:"No"},Ut={namespace:Vt,strings:zt},Wt="_boolean-output_kg1uq_1",Qt={booleanOutput:Wt};function Zt(m){const{className:a,invalidText:h,value:o}=m,f=rt(Ut);let g;return o===!0?g=f.booleanYesLabel:o===!1?g=f.booleanNoLabel:g=h,e.jsx("div",{className:N(Qt.booleanOutput,a),children:g})}const qt="_date-output_4jzjo_1",Gt={dateOutput:qt};function Yt(m){const{value:a,format:h,className:o,invalidText:f}=m,g=n.useMemo(()=>ft(a,h),[a,h]);return e.jsx("div",{className:N(Gt.dateOutput,o),children:g??f})}const Kt="_dropdown-menu_16hml_1",Xt="_icons_16hml_4",Jt="_content_16hml_5",ea="_actions_16hml_6",ta="_dropdown-icon_16hml_10",aa="_dropdown-content_16hml_16",le={dropdownMenu:Kt,icons:Xt,content:Jt,actions:ea,dropdownIcon:ta,dropdownContent:aa};function na(m){const a=n.useRef(null),{className:h,popupClassName:o,children:f,label:g,activeClassName:b,icons:_,variant:y="secondary",actions:x,withoutDropdownIcon:w,componentRef:C,elementRef:j=a,persistent:v,preferredPopupWidth:S}=m,p=n.useRef(null),[L,I]=n.useState(!1);n.useEffect(()=>{C&&(C.current={setShowDropdown:I})},[C,I]);const R=n.useCallback(()=>{I(ie=>!ie)},[I]),k=n.useCallback((ie,ae)=>{ae||ie&&v||I(!1)},[I,v]);vt(L,k,p,j);const G=n.useMemo(()=>({setShowDropdown:I}),[I]),U=!!x||!w;return e.jsxs(pt.Provider,{value:G,children:[e.jsx(Z,{name:void 0,className:N(le.dropdownMenu,L&&b,h),elementRef:j,onClick:R,variant:y,actionsContainerClassName:le.actions,iconsContainerClassName:le.icons,childrenContainerClassName:le.content,actions:U?e.jsxs(e.Fragment,{children:[x,!w&&(L?e.jsx(xt,{className:le.dropdownIcon}):e.jsx(_t,{className:le.dropdownIcon}))]}):void 0,icons:_,children:g}),L&&e.jsx(st,{elementRef:p,className:N(le.dropdownContent,o),parentRef:j,preferredWidth:S,children:f})]})}const sa="_info-popup_i3rna_1",ra="_label_i3rna_2",ia="_icon_i3rna_7",oa="_dropdown-container_i3rna_15",la="_content_i3rna_20",ge={infoPopup:sa,label:ra,icon:ia,dropdownContainer:oa,content:la};function ca(m){const{className:a,icon:h=e.jsx(Pt,{}),infoLabel:o,title:f,description:g,withoutIcon:b,popupClassName:_,descriptionClassName:y}=m;return e.jsx(na,{label:e.jsxs("div",{className:ge.label,children:[o,!b&&h&&e.jsx("div",{className:ge.icon,children:h})]}),popupClassName:N(ge.dropdownContainer,_),className:N(ge.infoPopup,a),variant:"tertiary",withoutDropdownIcon:!0,children:e.jsx(z,{heading:f,childrenContainerClassName:N(y,ge.content),withInternalPadding:!0,children:g})})}const da="_progress-wrapper_x340w_1",ua="_title_x340w_7",ma="_total_x340w_11",ha="_progress_x340w_1",fe={progressWrapper:da,title:ua,total:ma,progress:ha};function Ye(m){const{className:a,title:h,description:o,totalValue:f,value:g,showPercentageInTitle:b,children:_,color:y="var(--go-ui-color-primary-red)"}=m,x=re(g)?g:0,w=re(f)?f:0;let C;return w===0?C=0:C=x/w*100,e.jsxs("div",{className:N(fe.progressWrapper,a),children:[(h||b)&&e.jsxs("div",{className:fe.title,children:[h,b&&e.jsx(we,{value:C,suffix:"%"})]}),e.jsx("div",{className:fe.total,children:e.jsx("div",{className:fe.progress,style:{width:`${C}%`,backgroundColor:y}})}),o&&e.jsx("div",{className:fe.description,children:o}),_]})}const ga="_legend-element_1a9ic_1",fa="_color_1a9ic_7",va="_icon-container_1a9ic_14",pa="_icon_1a9ic_14",xa="_label_1a9ic_31",ve={legendElement:ga,color:fa,iconContainer:va,icon:pa,label:xa};function _a(m){const{className:a,colorClassName:h,iconClassName:o,color:f,label:g,iconSrc:b}=m;return e.jsxs("div",{className:N(ve.legendElement,a),children:[b?e.jsx("div",{style:{backgroundColor:f},className:ve.iconContainer,children:e.jsx("img",{className:N(ve.icon,o),src:b,alt:""})}):e.jsx("div",{style:{backgroundColor:f},className:N(ve.color,h)}),e.jsx("div",{className:ve.label,children:g})]})}const Ca="_text-output_10oza_1",ya="_with-background_10oza_6",ba="_label_10oza_11",ja="_with-colon_10oza_12",Na="_value_10oza_17",wa="_text-type_10oza_18",Sa="_strong_10oza_24",ee={textOutput:Ca,withBackground:ya,label:ba,withColon:ja,value:Na,textType:wa,strong:Sa};function Ke(m){const{className:a,label:h,icon:o,description:f,labelClassName:g,descriptionClassName:b,valueClassName:_,strongLabel:y,strongValue:x,strongDescription:w,withoutLabelColon:C,withBackground:j,invalidText:v=nt,...S}=m,{value:p}=m;let L=v;return S.valueType==="number"?L=e.jsx(we,{...S,invalidText:v}):S.valueType==="date"?L=e.jsx(Yt,{...S,invalidText:v}):S.valueType==="boolean"?L=e.jsx(Zt,{...S,invalidText:v}):p instanceof Date||(L=p||v),e.jsxs("div",{className:N(ee.textOutput,j&&ee.withBackground,a),children:[o,h&&e.jsx("div",{className:N(ee.label,y&&ee.strong,g,!C&&ee.withColon),children:h}),e.jsx("div",{className:N(ee.value,x&&ee.strong,S.valueType==="text"&&ee.textType,_),children:L}),f&&e.jsx("div",{className:N(ee.description,w&&ee.strong,b),children:f})]})}const Ma="_pie-chart_pyr7m_1",Ia="_legend_pyr7m_7",Da="_legend-item_pyr7m_13",pe={pieChart:Ma,legend:Ia,legendItem:Da},Ea=70,Ta=40;function Xe(m,a=1){return Math.round(m*10**a)/10**a}function Je(m,a){const h=(a-90)*Math.PI/180;return{x:Xe(m+m*Math.cos(h)),y:Xe(m+m*Math.sin(h))}}function ka(m,a,h){let o=h;const f=o-a===360;f&&(o-=1);const g=Je(m,a),b=Je(m,o),_=o-a<=180?0:1,y=["M",g.x,g.y,"A",m,m,0,_,1,b.x,b.y];return f?y.push("Z"):y.push("L",m,m,"L",g.x,g.y,"Z"),y.join(" ")}function xe(m){const{className:a,data:h,valueSelector:o,labelSelector:f,keySelector:g,colorSelector:b,colors:_,pieRadius:y=Ea,chartPadding:x=Ta,legendClassName:w,showPercentageInLegend:C}=m,j=Ct(h?.map(p=>o(p))),v=q(j)||j===0?1:j,S=n.useMemo(()=>{let p=0;const L=h?.map(I=>{const R=o(I);if(q(R))return;const k=360*(R/v);return p+=k,{key:g(I),value:R,label:f(I),startAngle:p-k,percentage:yt(R,v),endAngle:p,datum:I}}).filter(re)??[];return b?L.map(({datum:I,...R})=>({...R,color:b(I)})):L.map(({datum:I,...R},k)=>({...R,color:_[k%_.length]}))},[h,g,o,f,v,b,_]);return e.jsxs("div",{className:N(pe.pieChart,a),children:[e.jsx("svg",{className:pe.svg,style:{width:`${x+y*2}px`,height:`${x+y*2}px`},children:e.jsx("g",{style:{transform:`translate(${x/2}px, ${x/2}px)`},children:S.map(p=>e.jsx("path",{className:pe.path,d:ka(y,p.startAngle,p.endAngle),fill:p.color,children:e.jsx(Ht,{description:e.jsx(Ke,{label:p.label,value:p.value})})},p.key))})}),e.jsx("div",{className:N(pe.legend,w),children:S.map(p=>e.jsx(_a,{className:pe.legendItem,label:C?e.jsx(Ke,{label:p.label,value:p.percentage,valueType:"number",prefix:"(",suffix:"%)",withoutLabelColon:!0}):p.label,color:p.color},p.key))})]})}const La="_td_1k4cn_1",Pa={td:La};function Ra(m){const{className:a,children:h,...o}=m;return e.jsx("td",{className:N(a,Pa.td),...o,children:h})}function it(m){const{className:a,children:h,...o}=m;return e.jsx("tr",{className:a,...o,children:h})}const $a="_row_1829z_1",Ba="_cell_1829z_2",et={row:$a,cell:Ba};function Aa(m){const{data:a,keySelector:h,columns:o,rowClassName:f,cellClassName:g,rowModifier:b}=m;return e.jsx(e.Fragment,{children:a?.map((_,y)=>{const x=h(_,y),w=o.map(v=>{const{id:S,cellRenderer:p,cellRendererClassName:L,cellRendererParams:I,cellContainerClassName:R}=v,k=I(x,_,y,a),G=e.jsx(p,{className:L,...k,name:S});return e.jsx(Ra,{className:N(et.cell,R,typeof g=="function"?g(x,_,S):g),children:G},S)}),C=e.jsx(it,{className:N(et.row,typeof f=="function"?f(x,_):f),children:w});let j=C;return b&&(j=b({rowKey:x,row:C,cells:w,columns:o,datum:_})),e.jsx(n.Fragment,{children:j},x)})})}const Fa="_th_cdv41_1",Oa="_resize-handle_cdv41_8",tt={th:Fa,resizeHandle:Oa};function Ha(m){const{className:a,children:h,onResize:o,onResizeComplete:f,name:g,...b}=m,_=n.useRef(null),y=n.useRef(),x=n.useRef(),w=n.useRef(),C=n.useCallback(v=>{var S;if(re(y.current)&&_.current&&o){v.preventDefault(),v.stopPropagation();const p=v.clientX-y.current;if(re(x.current)){const L=x.current+p;w.current=L,o(L,g)}else x.current=(S=_.current)==null?void 0:S.offsetWidth}},[o,g]),j=n.useCallback(v=>{var S;v.preventDefault(),y.current=v.clientX,x.current=(S=_.current)==null?void 0:S.offsetWidth,window.addEventListener("mousemove",C,!0)},[C]);return n.useEffect(()=>{const v=()=>{y.current=void 0,x.current=void 0,f&&re(w.current)&&f(w.current,g),window.removeEventListener("mousemove",C,!0)};return window.addEventListener("mouseup",v,!0),()=>{window.removeEventListener("mouseup",v,!0),window.removeEventListener("mousemove",C,!0)}},[C,g,f]),e.jsxs("th",{ref:_,className:N(a,tt.th),...b,children:[o&&e.jsx("div",{role:"presentation",className:tt.resizeHandle,onMouseDown:j}),h]})}const Va="_table_nilhy_1",za="_table-overflow-wrapper_nilhy_8",Ua="_table-element_nilhy_13",Wa="_header-row_nilhy_23",Qa="_header-element_nilhy_24",Za="_header-component_nilhy_29",ce={table:Va,tableOverflowWrapper:za,tableElement:Ua,headerRow:Wa,headerElement:Qa,headerComponent:Za};function qa(m,a){return a??m.columnWidth??wt}function A(m){const{data:a,keySelector:h,columns:o,caption:f,className:g,captionClassName:b,headerRowClassName:_,headerCellClassName:y,rowClassName:x,cellClassName:w,rowModifier:C,fixedColumnWidth:j,resizableColumn:v,headersHidden:S,pending:p,filtered:L,errored:I=!1}=m,R=n.useRef(null),[k]=he.useState(()=>bt()),[G,U]=he.useState({});n.useEffect(()=>{U(W=>{if(q(R.current))return W;const T=R.current.getBoundingClientRect(),{width:O}=T;let F=o.map(M=>({id:M.id,stretch:!!M.columnStretch,width:qa(M,W[M.id])}));const X=ye(F.filter(M=>M.stretch).map(M=>M.width)),ne=ye(F.filter(M=>!M.stretch).map(M=>M.width)),Y=(O-ne)/X;return Y>1&&(F=F.map(M=>({...M,width:M.stretch?M.width*Y:M.width}))),jt(F,M=>M.id,M=>M.width)})},[o]);const ie=he.useCallback((W,T)=>{const O=document.getElementById(`${k}-${T}`),F=Math.max(W,80);if(q(O)||(O.style.width=`${F}px`,!j))return;const X=document.getElementById(k);if(q(X))return;const ne=ye(o.map(Y=>Y.id===T?F:G[Y.id]));X.style.width=`${ne}px`},[k,G,o,j]),ae=he.useCallback((W,T)=>{re(T)&&U(O=>({...O,[T]:Math.max(W,80)}))},[U]),be=he.useMemo(()=>ye(o.map(W=>G[W.id])),[G,o]),K=q(a)||a.length===0||Object.keys(G).length===0;return e.jsxs("div",{ref:R,className:N(ce.table,g),children:[!K&&e.jsx("div",{className:ce.tableOverflowWrapper,children:e.jsxs("table",{className:ce.tableElement,style:j?{width:`${be}px`}:void 0,id:k,children:[f&&e.jsx("caption",{className:b,children:f}),e.jsx("colgroup",{children:o.map(W=>{const{id:T,columnClassName:O}=W,F=G[T],X=j?{width:`${F}px`}:void 0;return e.jsx("col",{id:`${k}-${T}`,style:X,className:N(ce.column,O)},T)})}),!S&&e.jsx("thead",{children:e.jsx(it,{className:N(ce.headerRow,_),children:o.map((W,T)=>{const{id:O,title:F,headerCellRenderer:X,headerCellRendererClassName:ne,headerCellRendererParams:Y,headerContainerClassName:M}=W,se=e.jsx(X,{...Y,name:O,title:F,index:T,className:N(ne,ce.headerComponent)});return e.jsx(Ha,{scope:"col",name:O,onResize:v?ie:void 0,onResizeComplete:v?ae:void 0,className:N(ce.headerElement,typeof y=="function"?y(O):y,M),children:se},O)})})}),e.jsx("tbody",{children:e.jsx(Aa,{data:a,keySelector:h,columns:o,rowClassName:x,cellClassName:w,rowModifier:C})})]})}),e.jsx(Nt,{filtered:L,empty:K,errored:I,pending:p,overlayPending:!0})]})}function Ga(m){const{className:a,value:h}=m;return q(h)?null:e.jsx("div",{className:a,children:h})}const Ya="common",Ka={sortTableButtonTitle:"Sort Table"},Xa={namespace:Ya,strings:Ka},Ja="_header-cell_vn24d_1",en="_sort-button_vn24d_8",tn="_icon_vn24d_12",an="_info-popup-icon_vn24d_17",de={headerCell:Ja,sortButton:en,icon:tn,infoPopupIcon:an};function ot(m){const{className:a,titleClassName:h,title:o,name:f,sortable:g,defaultSortDirection:b="asc",infoTitle:_,infoDescription:y}=m,{sorting:x,setSorting:w}=n.useContext(St),C=rt(Xa),j=x?.name===f?x.direction:void 0,v=n.useRef(null),S=n.useCallback(()=>{if(q(w))return;let p;q(j)?p=b:j==="asc"?p="dsc":j==="dsc"&&(p="asc"),w(p?{name:f,direction:p}:void 0)},[f,w,j,b]);return e.jsxs("div",{ref:v,className:N(a,de.headerCell),children:[g&&e.jsxs(Z,{name:void 0,variant:"tertiary",onClick:S,title:C.sortTableButtonTitle,className:de.sortButton,children:[q(j)&&e.jsx(Rt,{className:de.icon}),j==="asc"&&e.jsx(Lt,{className:de.icon}),j==="dsc"&&e.jsx(kt,{className:de.icon})]}),e.jsx("div",{className:N(h,de.title),children:o}),_&&y&&e.jsx(ca,{className:de.infoPopupIcon,title:_,description:y})]})}const at={};function Q(m,a,h,o){return{id:m,title:a,columnClassName:o?.columnClassName,headerCellRenderer:ot,headerCellRendererClassName:o?.headerCellRendererClassName,headerContainerClassName:o?.headerContainerClassName,headerCellRendererParams:{sortable:o?.sortable,infoTitle:o?.headerInfoTitle,infoDescription:o?.headerInfoDescription},cellRendererClassName:o?.cellRendererClassName,cellContainerClassName:o?.cellContainerClassName,cellRenderer:Ga,cellRendererParams:(f,g)=>({value:h(g)||"--"}),valueSelector:h,valueComparator:(f,g)=>Mt(h(f),h(g)),columnWidth:o?.columnWidth,columnStretch:o?.columnStretch,columnStyle:o?.columnStyle}}function E(m,a,h,o){return{id:m,title:a,columnClassName:o?.columnClassName,headerCellRenderer:ot,headerCellRendererClassName:N(at.numberCellHeader,o?.headerCellRendererClassName),headerContainerClassName:o?.headerContainerClassName,headerCellRendererParams:{sortable:o?.sortable,infoTitle:o?.headerInfoTitle,infoDescription:o?.headerInfoDescription},cellRendererClassName:N(at.numberCell,o?.cellRendererClassName),cellContainerClassName:o?.cellContainerClassName,cellRenderer:we,cellRendererParams:(f,g)=>({value:h(g),suffix:o?.suffix,maximumFractionDigits:o?.maximumFractionDigits,invalidText:"--"}),valueSelector:h,valueComparator:(f,g)=>It(h(f),h(g)),columnWidth:o?.columnWidth,columnStretch:o?.columnStretch,columnStyle:o?.columnStyle}}const nn="_tabSelector_vlxoe_1",sn="_progressSection_vlxoe_14",rn="_progressLabel_vlxoe_20",on="_chartGrid_vlxoe_28",ln="_chartContainer_vlxoe_40",cn="_tableContainer_vlxoe_51",dn="_modelPerformance_vlxoe_59",un="_loadingContainer_vlxoe_67",mn="_errorContainer_vlxoe_77",hn="_userInteractionCards_vlxoe_96",gn="_userInteractionCard_vlxoe_96",fn="_userInteractionCardValue_vlxoe_116",vn="_userInteractionCardLabel_vlxoe_123",pn="_userInteractionCardButton_vlxoe_130",xn="_summaryStatsCards_vlxoe_148",_n="_summaryStatsCard_vlxoe_148",Cn="_summaryStatsCardValue_vlxoe_169",yn="_summaryStatsCardLabel_vlxoe_176",l={tabSelector:nn,progressSection:sn,progressLabel:rn,chartGrid:on,chartContainer:ln,tableContainer:cn,modelPerformance:dn,loadingContainer:un,errorContainer:mn,userInteractionCards:hn,userInteractionCard:gn,userInteractionCardValue:fn,userInteractionCardLabel:vn,userInteractionCardButton:pn,summaryStatsCards:xn,summaryStatsCard:_n,summaryStatsCardValue:Cn,summaryStatsCardLabel:yn};function jn(){const[m]=Dt(),[a,h]=n.useState(null),[o,f]=n.useState(!0),[g,b]=n.useState("crisis_maps"),[_,y]=n.useState([]),[x,w]=n.useState([]),[C,j]=n.useState([]),[v,S]=n.useState([]),[p,L]=n.useState(!1),[I,R]=n.useState(!1),[k,G]=n.useState(!1),[U,ie]=n.useState(!1),[ae,be]=n.useState(!1),[K,W]=n.useState(!1),T=t=>{L(t==="editTime"),R(t==="percentage"),G(t==="delete"),ie(t==="regions"),be(t==="sources"),W(t==="types")},O=[{key:"crisis_maps",label:"Crisis Maps"},{key:"drone_images",label:"Drone Images"}],F=n.useCallback((t,c)=>{if(!t||!c)return 0;const d=t.toLowerCase().replace(/[^\w\s]/g,"").split(/\s+/).filter(u=>u.length>0),r=c.toLowerCase().replace(/[^\w\s]/g,"").split(/\s+/).filter(u=>u.length>0);if(d.length===0&&r.length===0)return 1;if(d.length===0||r.length===0)return 0;const s=new Set(d),i=new Set(r),D=new Set([...s].filter(u=>i.has(u))),$=new Set([...s,...i]);return D.size/$.size},[]),X=n.useCallback(async()=>{f(!0);try{const c=await(await fetch("/api/images")).json(),d={},r=c.filter(u=>u.image_type==="crisis_map"),s=c.filter(u=>u.image_type==="drone_image"),i={totalCaptions:c.length,sources:{},types:{},regions:{},models:{},modelEditTimes:d,percentageModified:0,modelPercentageData:{},totalDeleteCount:0,deleteRate:0,crisisMaps:r,droneImages:s};c.forEach(u=>{if(u.source&&(i.sources[u.source]=(i.sources[u.source]||0)+1),u.event_type&&(i.types[u.event_type]=(i.types[u.event_type]||0)+1),u.countries&&u.countries.forEach(P=>{P.r_code&&(i.regions[P.r_code]=(i.regions[P.r_code]||0)+1)}),u.model){const P=u.model,V=i.models[P]||={count:0,avgAccuracy:0,avgContext:0,avgUsability:0,totalScore:0,deleteCount:0};if(V.count++,u.accuracy!=null&&(V.avgAccuracy+=u.accuracy),u.context!=null&&(V.avgContext+=u.context),u.usability!=null&&(V.avgUsability+=u.usability),u.created_at&&u.updated_at){const te=new Date(u.created_at).getTime(),Ce=new Date(u.updated_at).getTime()-te;Ce>0&&(d[P]||(d[P]=[]),d[P].push(Ce))}}}),_.forEach(u=>{u.s_code&&!i.sources[u.s_code]&&(i.sources[u.s_code]=0)}),x.forEach(u=>{u.t_code&&!i.types[u.t_code]&&(i.types[u.t_code]=0)}),C.forEach(u=>{u.r_code&&!i.regions[u.r_code]&&(i.regions[u.r_code]=0)}),["GPT-4","Claude","Gemini","Llama","Other"].forEach(u=>{i.models[u]||(i.models[u]={count:0,avgAccuracy:0,avgContext:0,avgUsability:0,totalScore:0,deleteCount:0})}),Object.values(i.models).forEach(u=>{u.count>0&&(u.avgAccuracy=Math.round(u.avgAccuracy/u.count),u.avgContext=Math.round(u.avgContext/u.count),u.avgUsability=Math.round(u.avgUsability/u.count),u.totalScore=Math.round((u.avgAccuracy+u.avgContext+u.avgUsability)/3))});const $=c.filter(u=>u.generated&&u.edited);if($.length>0){const P=[...$.map(oe=>F(oe.generated,oe.edited))].sort((oe,Ce)=>oe-Ce),V=Math.floor(P.length/2),te=P.length%2===0?(P[V-1]+P[V])/2:P[V];i.percentageModified=Math.round((1-te)*100)}const H={};c.forEach(u=>{if(u.model&&u.generated&&u.edited){const P=F(u.generated,u.edited),V=Math.round((1-P)*100);H[u.model]||(H[u.model]=[]),H[u.model].push(V)}}),i.modelPercentageData=H;try{const u=await fetch("/api/models");if(u.ok){const P=await u.json();if(P.models){P.models.forEach(te=>{i.models[te.m_code]&&(i.models[te.m_code].deleteCount=te.delete_count||0)});const V=P.models.reduce((te,oe)=>te+(oe.delete_count||0),0);i.totalDeleteCount=V,i.deleteRate=V>0?Math.round(V/(V+c.length)*100):0}}}catch(u){console.log("Could not fetch model delete counts:",u)}h(i)}catch{h(null)}finally{f(!1)}},[_,x,C,F]),ne=n.useCallback(async()=>{try{const[t,c,d,r]=await Promise.all([fetch("/api/sources"),fetch("/api/types"),fetch("/api/regions"),fetch("/api/models")]),s=await t.json(),i=await c.json(),D=await d.json(),$=await r.json();y(s),w(i),j(D),S($.models||[])}catch(t){console.log("Could not fetch lookup data:",t)}},[]);n.useEffect(()=>{const t=m.get("view");(t==="crisis_maps"||t==="drone_images")&&b(t)},[m]),n.useEffect(()=>{ne()},[ne]),n.useEffect(()=>{_.length>0&&x.length>0&&C.length>0&&v.length>0&&X()},[_,x,C,v,X]);const Y=n.useCallback(t=>{const c=_.find(d=>d.s_code===t);return c?c.label:t},[_]),M=n.useCallback(t=>{if(t.length===0)return 0;const c=[...t].sort((r,s)=>r-s),d=Math.floor(c.length/2);return c.length%2===0?Math.round((c[d-1]+c[d])/2):c[d]},[]),se=n.useCallback(t=>{const c=Math.floor(t/1e3),d=Math.floor(c/60),r=Math.floor(d/60);return r>0?`${r}h ${d%60}m`:d>0?`${d}m ${c%60}s`:`${c}s`},[]),_e=n.useCallback(t=>{const c=x.find(d=>d.t_code===t);return c?c.label:t},[x]),J=n.useCallback(t=>{const c=v.find(d=>d.m_code===t);return c?c.label:t},[v]),Se=n.useMemo(()=>a?Object.entries(a.modelEditTimes||{}).filter(([,t])=>t.length>0).sort(([,t],[,c])=>M(c)-M(t)).map(([t,c],d)=>({id:d+1,name:J(t),count:c.length,avgEditTime:M(c),minEditTime:Math.min(...c),maxEditTime:Math.max(...c)})):[],[a,M,J]),Me=n.useMemo(()=>a?Object.entries(a.modelPercentageData||{}).filter(([,t])=>t.length>0).sort(([,t],[,c])=>{const d=[...t].sort((H,u)=>H-u),r=[...c].sort((H,u)=>H-u),s=Math.floor(d.length/2),i=Math.floor(r.length/2),D=d.length%2===0?(d[s-1]+d[s])/2:d[s];return(r.length%2===0?(r[i-1]+r[i])/2:r[i])-D}).map(([t,c],d)=>{const r=[...c].sort((D,$)=>D-$),s=Math.floor(r.length/2),i=r.length%2===0?Math.round((r[s-1]+r[s])/2):r[s];return{id:d+1,name:J(t),count:c.length,avgPercentageModified:i,minPercentageModified:Math.min(...c),maxPercentageModified:Math.max(...c)}}):[],[a,J]),Ie=n.useMemo(()=>a?Object.entries(a.models).filter(([t,c])=>c.count>0&&t!=="manual").map(([t,c],d)=>{const r=[c.avgAccuracy,c.avgContext,c.avgUsability],s=r.reduce(($,H)=>$+H,0)/r.length,i=r.reduce(($,H)=>$+Math.pow(H-s,2),0)/r.length,D=Math.round(100-Math.sqrt(i));return{id:d+1,name:J(t),consistency:Math.max(0,D),avgScore:Math.round(s),count:c.count}}).sort((t,c)=>c.consistency-t.consistency):[],[a,J]),De=n.useMemo(()=>[Q("name","Region",t=>t.name),E("count","Count",t=>t.count),E("percentage","% of Total",t=>t.percentage,{suffix:"%",maximumFractionDigits:0})],[]),Ee=n.useMemo(()=>[Q("name","Type",t=>t.name),E("count","Count",t=>t.count),E("percentage","% of Total",t=>t.percentage,{suffix:"%",maximumFractionDigits:0})],[]),lt=n.useMemo(()=>[Q("name","Source",t=>t.name),E("count","Count",t=>t.count),E("percentage","% of Total",t=>t.percentage,{suffix:"%",maximumFractionDigits:0})],[]),Te=n.useMemo(()=>[Q("name","Model",t=>t.name),E("count","Count",t=>t.count),E("accuracy","Accuracy",t=>t.accuracy,{suffix:"%",maximumFractionDigits:0}),E("context","Context",t=>t.context,{suffix:"%",maximumFractionDigits:0}),E("usability","Usability",t=>t.usability,{suffix:"%",maximumFractionDigits:0}),E("totalScore","Total Score",t=>t.totalScore,{suffix:"%",maximumFractionDigits:0})],[]),ke=n.useMemo(()=>[Q("name","Model",t=>t.name),E("count","Count",t=>t.count),Q("avgEditTime","Median Edit Time",t=>se(t.avgEditTime)),Q("minEditTime","Min Edit Time",t=>se(t.minEditTime)),Q("maxEditTime","Max Edit Time",t=>se(t.maxEditTime))],[se]),Le=n.useMemo(()=>[Q("name","Model",t=>t.name),E("count","Count",t=>t.count),E("avgPercentageModified","Median % Modified",t=>t.avgPercentageModified,{suffix:"%",maximumFractionDigits:0}),E("minPercentageModified","Min % Modified",t=>t.minPercentageModified,{suffix:"%",maximumFractionDigits:0}),E("maxPercentageModified","Max % Modified",t=>t.maxPercentageModified,{suffix:"%",maximumFractionDigits:0})],[]),Pe=n.useMemo(()=>[Q("name","Model",t=>t.name),E("count","Total Count",t=>t.count),E("deleteCount","Delete Count",t=>t.deleteCount),E("deleteRate","Delete Rate",t=>t.deleteRate,{suffix:"%",maximumFractionDigits:1})],[]),ct=n.useMemo(()=>[Q("source","Source",t=>t.source),E("avgQuality","Average Quality",t=>t.avgQuality,{suffix:"%",maximumFractionDigits:0}),E("count","Count",t=>t.count)],[]),Re=n.useMemo(()=>[Q("eventType","Event Type",t=>t.eventType),E("avgQuality","Average Quality",t=>t.avgQuality,{suffix:"%",maximumFractionDigits:0}),E("count","Count",t=>t.count)],[]),$e=n.useMemo(()=>[Q("name","Model",t=>t.name),E("consistency","Consistency",t=>t.consistency,{suffix:"%",maximumFractionDigits:0}),E("avgScore","Average Score",t=>t.avgScore,{suffix:"%",maximumFractionDigits:0}),E("count","Count",t=>t.count)],[]),ue=n.useCallback(t=>a?t==="crisis_map"?a.crisisMaps.length:t==="drone_image"?a.droneImages.length:0:0,[a]),Be=n.useCallback(t=>{if(!a)return[];const c=t==="crisis_map"?a.crisisMaps:a.droneImages,d={};return c.forEach(r=>{r.countries&&r.countries.forEach(s=>{s.r_code&&(d[s.r_code]=(d[s.r_code]||0)+1)})}),Object.entries(d).filter(([,r])=>r>0).map(([r,s])=>({name:C.find(i=>i.r_code===r)?.label||r,value:s}))},[a,C]),Ae=n.useCallback(t=>{if(!a)return[];const c=t==="crisis_map"?a.crisisMaps:a.droneImages,d={};c.forEach(s=>{s.countries&&s.countries.forEach(i=>{i.r_code&&(d[i.r_code]=(d[i.r_code]||0)+1)})});const r=C.reduce((s,i)=>(i.r_code&&(s[i.r_code]={name:i.label,count:d[i.r_code]||0}),s),{});return Object.entries(r).sort(([,s],[,i])=>i.count-s.count).map(([,{name:s,count:i}],D)=>({id:D+1,name:s,count:i,percentage:c.length>0?Math.round(i/c.length*100):0}))},[a,C]),dt=n.useCallback(t=>{if(!a)return[];const c=t==="crisis_map"?a.crisisMaps:a.droneImages,d={};return c.forEach(r=>{r.source&&(d[r.source]=(d[r.source]||0)+1)}),Object.entries(d).filter(([,r])=>r>0).map(([r,s])=>({name:_.find(i=>i.s_code===r)?.label||r,value:s}))},[a,_]),ut=n.useCallback(t=>{if(!a)return[];const c=t==="crisis_map"?a.crisisMaps:a.droneImages,d={};return c.forEach(r=>{r.source&&(d[r.source]=(d[r.source]||0)+1)}),Object.entries(d).sort(([,r],[,s])=>s-r).map(([r,s],i)=>({id:i+1,name:Y(r),count:s,percentage:c.length>0?Math.round(s/c.length*100):0}))},[a,Y]),Fe=n.useCallback(t=>{if(!a)return[];const c=t==="crisis_map"?a.crisisMaps:a.droneImages,d={};return c.forEach(r=>{r.event_type&&(d[r.event_type]=(d[r.event_type]||0)+1)}),Object.entries(d).filter(([,r])=>r>0).map(([r,s])=>({name:x.find(i=>i.t_code===r)?.label||r,value:s}))},[a,x]),Oe=n.useCallback(t=>{if(!a)return[];const c=t==="crisis_map"?a.crisisMaps:a.droneImages,d={};return c.forEach(r=>{r.event_type&&(d[r.event_type]=(d[r.event_type]||0)+1)}),Object.entries(d).sort(([,r],[,s])=>s-r).map(([r,s],i)=>({id:i+1,name:_e(r),count:s,percentage:c.length>0?Math.round(s/c.length*100):0}))},[a,_e]),He=n.useCallback(t=>{if(!a)return"No data available";const c=t==="crisis_map"?a.crisisMaps:a.droneImages,d=new Set;c.forEach(i=>{i.model&&d.add(i.model)}),console.log(`Debug ${t}:`,{totalImages:c.length,usedModels:Array.from(d),availableEditTimes:Object.keys(a.modelEditTimes),modelEditTimesData:a.modelEditTimes});const s=Object.entries(a.modelEditTimes).filter(([i])=>d.has(i)).flatMap(([,i])=>i);return s.length===0?"No data available":se(M(s))},[a,se,M]),Ve=n.useCallback(()=>{if(!a)return"No data available";const t=a.totalCaptions||0,c=a.percentageModified||0;return t>0?Math.round(c/t*100):0},[a]),ze=n.useCallback(()=>a&&a.deleteRate>=0?`${a.deleteRate}%`:"No data available",[a]),Ue=n.useCallback(t=>{if(!a)return[];const c=t==="crisis_map"?a.crisisMaps:a.droneImages,d=new Set;return c.forEach(s=>{s.model&&d.add(s.model)}),Se.filter(s=>{const i=v.find(D=>D.label===s.name)?.m_code;return i&&d.has(i)})},[a,Se,v]),We=n.useCallback(t=>{if(!a)return[];const c=t==="crisis_map"?a.crisisMaps:a.droneImages,d=new Set;return c.forEach(s=>{s.model&&d.add(s.model)}),Me.filter(s=>{const i=v.find(D=>D.label===s.name)?.m_code;return i&&d.has(i)})},[a,Me,v]),Qe=n.useCallback(t=>{if(!a)return[];const c=t==="crisis_map"?a.crisisMaps:a.droneImages,d={};return c.forEach(r=>{r.model&&(d[r.model]||(d[r.model]={count:0,deleteCount:0}),d[r.model].count++)}),Object.entries(d).map(([r,s],i)=>{const $=a.models?.[r]?.deleteCount||0,H=s.count>0?Math.round($/s.count*100*10)/10:0;return{id:i+1,name:J(r),count:s.count,deleteCount:$,deleteRate:H}}).sort((r,s)=>s.count-r.count)},[a,J]),Ze=n.useCallback(t=>{if(!a)return[];const d=(t==="crisis_map"?a.crisisMaps:a.droneImages).filter(s=>s.model!=="manual"),r={};return d.forEach(s=>{s.model&&(r[s.model]||(r[s.model]={count:0,totalAccuracy:0,totalContext:0,totalUsability:0}),r[s.model].count++,s.accuracy!=null&&(r[s.model].totalAccuracy+=s.accuracy),s.context!=null&&(r[s.model].totalContext+=s.context),s.usability!=null&&(r[s.model].totalUsability+=s.usability))}),Object.entries(r).map(([s,i],D)=>({id:D+1,name:J(s),count:i.count,accuracy:i.count>0?Math.round(i.totalAccuracy/i.count):0,context:i.count>0?Math.round(i.totalContext/i.count):0,usability:i.count>0?Math.round(i.totalUsability/i.count):0,totalScore:i.count>0?Math.round((i.totalAccuracy+i.totalContext+i.totalUsability)/(3*i.count)):0})).sort((s,i)=>i.totalScore-s.totalScore)},[a,J]),mt=n.useCallback(t=>{if(!a)return[];const d=(t==="crisis_map"?a.crisisMaps:a.droneImages).filter(s=>s.model!=="manual"),r={};return d.forEach(s=>{s.source&&(r[s.source]||(r[s.source]={total:0,count:0,totalImages:0}),r[s.source].totalImages+=1,s.accuracy!=null&&(r[s.source].total+=s.accuracy,r[s.source].count+=1))}),Object.entries(r).map(([s,i],D)=>({id:D+1,source:Y(s),avgQuality:i.count>0?Math.round(i.total/i.count):0,count:i.totalImages}))},[a,Y]),qe=n.useCallback(t=>{if(!a)return[];const d=(t==="crisis_map"?a.crisisMaps:a.droneImages).filter(s=>s.model!=="manual"),r={};return d.forEach(s=>{s.event_type&&(r[s.event_type]||(r[s.event_type]={total:0,count:0,totalImages:0}),r[s.event_type].totalImages+=1,s.accuracy!=null&&(r[s.event_type].total+=s.accuracy,r[s.event_type].count+=1))}),Object.entries(r).map(([s,i],D)=>({id:D+1,eventType:_e(s),avgQuality:i.count>0?Math.round(i.total/i.count):0,count:i.totalImages}))},[a,_e]),Ge=n.useCallback(t=>{if(!a)return[];const d=(t==="crisis_map"?a.crisisMaps:a.droneImages).filter(i=>i.model!=="manual"),r=new Set;return d.forEach(i=>{i.model&&r.add(i.model)}),Ie.filter(i=>{const D=v.find($=>$.label===i.name)?.m_code;return D&&D!=="manual"&&r.has(D)})},[a,Ie,v]);if(o)return e.jsx(je,{children:e.jsx("div",{className:l.loadingContainer,children:e.jsx(Et,{})})});if(!a)return e.jsx(je,{children:e.jsx("div",{className:l.errorContainer,children:e.jsx("div",{className:"text-red-500",children:"Failed to load analytics data. Please try again."})})});const me=["#F5333F","#F64752","#F75C65","#F87079","#F9858C","#FA999F","#FBADB2","#FCC2C5"];return e.jsx(je,{children:e.jsxs("div",{className:"max-w-7xl mx-auto",children:[e.jsx("div",{className:l.tabSelector,children:e.jsx(Tt,{name:"analytics-view",value:g,onChange:t=>{(t==="crisis_maps"||t==="drone_images")&&b(t)},options:O,keySelector:t=>t.key,labelSelector:t=>t.label})}),g==="crisis_maps"?e.jsxs("div",{className:l.chartGrid,children:[e.jsxs(z,{heading:"Summary Statistics",headingLevel:3,withHeaderBorder:!0,withInternalPadding:!0,children:[e.jsxs("div",{className:l.summaryStatsCards,children:[e.jsxs("div",{className:l.summaryStatsCard,children:[e.jsx("div",{className:l.summaryStatsCardValue,children:ue("crisis_map")}),e.jsx("div",{className:l.summaryStatsCardLabel,children:"Total Crisis Maps"})]}),e.jsxs("div",{className:l.summaryStatsCard,children:[e.jsx("div",{className:l.summaryStatsCardValue,children:"2000"}),e.jsx("div",{className:l.summaryStatsCardLabel,children:"Target Amount"})]})]}),e.jsxs("div",{className:l.progressSection,children:[e.jsxs("div",{className:l.progressLabel,children:[e.jsx("span",{children:"Progress towards target"}),e.jsxs("span",{children:[Math.round(ue("crisis_map")/2e3*100),"%"]})]}),e.jsx(Ye,{value:ue("crisis_map"),totalValue:2e3})]})]}),e.jsxs(z,{heading:"Distribution Analysis",headingLevel:3,withHeaderBorder:!0,withInternalPadding:!0,children:[e.jsxs("div",{className:l.userInteractionCards,children:[e.jsxs("div",{className:l.userInteractionCard,children:[e.jsx("div",{className:l.userInteractionCardLabel,children:"Regions Distribution"}),e.jsx("div",{className:l.chartContainer,children:e.jsx(xe,{data:Be("crisis_map"),valueSelector:t=>t.value,labelSelector:t=>t.name,keySelector:t=>t.name,colors:me,showPercentageInLegend:!0})}),e.jsx(Z,{name:"view-regions-details",variant:U?"primary":"secondary",onClick:()=>T(U?"none":"regions"),className:l.userInteractionCardButton,children:U?"Hide Details":"View Details"})]}),e.jsxs("div",{className:l.userInteractionCard,children:[e.jsx("div",{className:l.userInteractionCardLabel,children:"Sources Distribution"}),e.jsx("div",{className:l.chartContainer,children:e.jsx(xe,{data:dt("crisis_map"),valueSelector:t=>t.value,labelSelector:t=>t.name,keySelector:t=>t.name,colors:me,showPercentageInLegend:!0})}),e.jsx(Z,{name:"view-sources-details",variant:ae?"primary":"secondary",onClick:()=>T(ae?"none":"sources"),className:l.userInteractionCardButton,children:ae?"Hide Details":"View Details"})]}),e.jsxs("div",{className:l.userInteractionCard,children:[e.jsx("div",{className:l.userInteractionCardLabel,children:"Types Distribution"}),e.jsx("div",{className:l.chartContainer,children:e.jsx(xe,{data:Fe("crisis_map"),valueSelector:t=>t.value,labelSelector:t=>t.name,keySelector:t=>t.name,colors:me,showPercentageInLegend:!0})}),e.jsx(Z,{name:"view-types-details",variant:K?"primary":"secondary",onClick:()=>T(K?"none":"types"),className:l.userInteractionCardButton,children:K?"Hide Details":"View Details"})]})]}),U&&e.jsx("div",{className:l.modelPerformance,children:e.jsx(A,{data:Ae("crisis_map"),columns:De,keySelector:B,filtered:!1,pending:!1})}),ae&&e.jsx("div",{className:l.modelPerformance,children:e.jsx(A,{data:ut("crisis_map"),columns:lt,keySelector:B,filtered:!1,pending:!1})}),K&&e.jsx("div",{className:l.modelPerformance,children:e.jsx(A,{data:Oe("crisis_map"),columns:Ee,keySelector:B,filtered:!1,pending:!1})})]}),e.jsxs(z,{heading:"User Interaction Statistics",headingLevel:3,withHeaderBorder:!0,withInternalPadding:!0,children:[e.jsxs("div",{className:l.userInteractionCards,children:[e.jsxs("div",{className:l.userInteractionCard,children:[e.jsx("div",{className:l.userInteractionCardValue,children:He("crisis_map")}),e.jsx("div",{className:l.userInteractionCardLabel,children:"Median Edit Time"}),e.jsx(Z,{name:"view-edit-time-details",variant:p?"primary":"secondary",onClick:()=>T(p?"none":"editTime"),className:l.userInteractionCardButton,children:p?"Hide Details":"View Details"})]}),e.jsxs("div",{className:l.userInteractionCard,children:[e.jsx("div",{className:l.userInteractionCardValue,children:Ve()}),e.jsx("div",{className:l.userInteractionCardLabel,children:"Median % Modified"}),e.jsx(Z,{name:"view-percentage-details",variant:I?"primary":"secondary",onClick:()=>T(I?"none":"percentage"),className:l.userInteractionCardButton,children:I?"Hide Details":"View Details"})]}),e.jsxs("div",{className:l.userInteractionCard,children:[e.jsx("div",{className:l.userInteractionCardValue,children:ze()}),e.jsx("div",{className:l.userInteractionCardLabel,children:"Delete Rate"}),e.jsx(Z,{name:"view-delete-details",variant:k?"primary":"secondary",onClick:()=>T(k?"none":"delete"),className:l.userInteractionCardButton,children:k?"Hide Details":"View Details"})]})]}),p&&e.jsx("div",{className:l.modelPerformance,children:e.jsx(A,{data:Ue("crisis_map"),columns:ke,keySelector:B,filtered:!1,pending:!1})}),I&&e.jsx("div",{className:l.modelPerformance,children:e.jsx(A,{data:We("crisis_map"),columns:Le,keySelector:B,filtered:!1,pending:!1})}),k&&e.jsx("div",{className:l.modelPerformance,children:e.jsx(A,{data:Qe("crisis_map"),columns:Pe,keySelector:B,filtered:!1,pending:!1})})]}),e.jsx(z,{heading:"Model Performance",headingLevel:3,withHeaderBorder:!0,withInternalPadding:!0,children:e.jsx("div",{className:l.modelPerformance,children:e.jsx(A,{data:Ze("crisis_map"),columns:Te,keySelector:B,filtered:!1,pending:!1})})}),e.jsx(z,{heading:"Quality-Source Correlation",headingLevel:3,withHeaderBorder:!0,withInternalPadding:!0,children:e.jsx("div",{className:l.tableContainer,children:e.jsx(A,{data:mt("crisis_map"),columns:ct,keySelector:B,filtered:!1,pending:!1})})}),e.jsx(z,{heading:"Quality-Event Type Correlation",headingLevel:3,withHeaderBorder:!0,withInternalPadding:!0,children:e.jsx("div",{className:l.tableContainer,children:e.jsx(A,{data:qe("crisis_map"),columns:Re,keySelector:B,filtered:!1,pending:!1})})}),e.jsx(z,{heading:"Model Consistency Analysis",headingLevel:3,withHeaderBorder:!0,withInternalPadding:!0,children:e.jsx("div",{className:l.tableContainer,children:e.jsx(A,{data:Ge("crisis_map"),columns:$e,keySelector:B,filtered:!1,pending:!1})})})]}):e.jsxs("div",{className:l.chartGrid,children:[e.jsxs(z,{heading:"Summary Statistics",headingLevel:3,withHeaderBorder:!0,withInternalPadding:!0,children:[e.jsxs("div",{className:l.summaryStatsCards,children:[e.jsxs("div",{className:l.summaryStatsCard,children:[e.jsx("div",{className:l.summaryStatsCardValue,children:ue("drone_image")}),e.jsx("div",{className:l.summaryStatsCardLabel,children:"Total Drone Images"})]}),e.jsxs("div",{className:l.summaryStatsCard,children:[e.jsx("div",{className:l.summaryStatsCardValue,children:"2000"}),e.jsx("div",{className:l.summaryStatsCardLabel,children:"Target Amount"})]})]}),e.jsxs("div",{className:l.progressSection,children:[e.jsxs("div",{className:l.progressLabel,children:[e.jsx("span",{children:"Progress towards target"}),e.jsxs("span",{children:[Math.round(ue("drone_image")/2e3*100),"%"]})]}),e.jsx(Ye,{value:ue("drone_image"),totalValue:2e3})]})]}),e.jsxs(z,{heading:"Distribution Analysis",headingLevel:3,withHeaderBorder:!0,withInternalPadding:!0,children:[e.jsxs("div",{className:l.userInteractionCards,children:[e.jsxs("div",{className:l.userInteractionCard,children:[e.jsx("div",{className:l.userInteractionCardLabel,children:"Regions Distribution"}),e.jsx("div",{className:l.chartContainer,children:e.jsx(xe,{data:Be("drone_image"),valueSelector:t=>t.value,labelSelector:t=>t.name,keySelector:t=>t.name,colors:me,showPercentageInLegend:!0})}),e.jsx(Z,{name:"view-regions-details",variant:U?"primary":"secondary",onClick:()=>T(U?"none":"regions"),className:l.userInteractionCardButton,children:U?"Hide Details":"View Details"})]}),e.jsxs("div",{className:l.userInteractionCard,children:[e.jsx("div",{className:l.userInteractionCardLabel,children:"Types Distribution"}),e.jsx("div",{className:l.chartContainer,children:e.jsx(xe,{data:Fe("drone_image"),valueSelector:t=>t.value,labelSelector:t=>t.name,keySelector:t=>t.name,colors:me,showPercentageInLegend:!0})}),e.jsx(Z,{name:"view-types-details",variant:K?"primary":"secondary",onClick:()=>T(K?"none":"types"),className:l.userInteractionCardButton,children:K?"Hide Details":"View Details"})]})]}),U&&e.jsx("div",{className:l.modelPerformance,children:e.jsx(A,{data:Ae("drone_image"),columns:De,keySelector:B,filtered:!1,pending:!1})}),K&&e.jsx("div",{className:l.modelPerformance,children:e.jsx(A,{data:Oe("drone_image"),columns:Ee,keySelector:B,filtered:!1,pending:!1})})]}),e.jsxs(z,{heading:"User Interaction Statistics",headingLevel:3,withHeaderBorder:!0,withInternalPadding:!0,children:[e.jsxs("div",{className:l.userInteractionCards,children:[e.jsxs("div",{className:l.userInteractionCard,children:[e.jsx("div",{className:l.userInteractionCardValue,children:He("drone_image")}),e.jsx("div",{className:l.userInteractionCardLabel,children:"Median Edit Time"}),e.jsx(Z,{name:"view-edit-time-details",variant:p?"primary":"secondary",onClick:()=>T(p?"none":"editTime"),className:l.userInteractionCardButton,children:p?"Hide Details":"View Details"})]}),e.jsxs("div",{className:l.userInteractionCard,children:[e.jsx("div",{className:l.userInteractionCardValue,children:Ve()}),e.jsx("div",{className:l.userInteractionCardLabel,children:"Median % Modified"}),e.jsx(Z,{name:"view-percentage-details",variant:I?"primary":"secondary",onClick:()=>T(I?"none":"percentage"),className:l.userInteractionCardButton,children:I?"Hide Details":"View Details"})]}),e.jsxs("div",{className:l.userInteractionCard,children:[e.jsx("div",{className:l.userInteractionCardValue,children:ze()}),e.jsx("div",{className:l.userInteractionCardLabel,children:"Delete Rate"}),e.jsx(Z,{name:"view-delete-details",variant:k?"primary":"secondary",onClick:()=>T(k?"none":"delete"),className:l.userInteractionCardButton,children:k?"Hide Details":"View Details"})]})]}),p&&e.jsx("div",{className:l.modelPerformance,children:e.jsx(A,{data:Ue("drone_image"),columns:ke,keySelector:B,filtered:!1,pending:!1})}),I&&e.jsx("div",{className:l.modelPerformance,children:e.jsx(A,{data:We("drone_image"),columns:Le,keySelector:B,filtered:!1,pending:!1})}),k&&e.jsx("div",{className:l.modelPerformance,children:e.jsx(A,{data:Qe("drone_image"),columns:Pe,keySelector:B,filtered:!1,pending:!1})})]}),e.jsx(z,{heading:"Model Performance",headingLevel:3,withHeaderBorder:!0,withInternalPadding:!0,children:e.jsx("div",{className:l.modelPerformance,children:e.jsx(A,{data:Ze("drone_image"),columns:Te,keySelector:B,filtered:!1,pending:!1})})}),e.jsx(z,{heading:"Quality-Event Type Correlation",headingLevel:3,withHeaderBorder:!0,withInternalPadding:!0,children:e.jsx("div",{className:l.tableContainer,children:e.jsx(A,{data:qe("drone_image"),columns:Re,keySelector:B,filtered:!1,pending:!1})})}),e.jsx(z,{heading:"Model Consistency Analysis",headingLevel:3,withHeaderBorder:!0,withInternalPadding:!0,children:e.jsx("div",{className:l.tableContainer,children:e.jsx(A,{data:Ge("drone_image"),columns:$e,keySelector:B,filtered:!1,pending:!1})})})]})]})})}export{jn as default}; diff --git a/py_backend/static/assets/jszip.min-D6OY4_4u.js b/py_backend/static/assets/jszip.min-Csqqcm8m.js similarity index 99% rename from py_backend/static/assets/jszip.min-D6OY4_4u.js rename to py_backend/static/assets/jszip.min-Csqqcm8m.js index 7a87db7c..bb316195 100644 --- a/py_backend/static/assets/jszip.min-D6OY4_4u.js +++ b/py_backend/static/assets/jszip.min-Csqqcm8m.js @@ -1,4 +1,4 @@ -import{V as bt,W as It}from"./index-Rlfiitbv.js";function vt(yt){throw new Error('Could not dynamically require "'+yt+'". Please configure the dynamicRequireTargets or/and ignoreDynamicRequires option of @rollup/plugin-commonjs appropriately for this require call to work.')}var kt={exports:{}};/*! +import{V as bt,W as It}from"./index-CcfIBRoF.js";function vt(yt){throw new Error('Could not dynamically require "'+yt+'". Please configure the dynamicRequireTargets or/and ignoreDynamicRequires option of @rollup/plugin-commonjs appropriately for this require call to work.')}var kt={exports:{}};/*! JSZip v3.10.1 - A JavaScript class for generating and reading zip files diff --git a/py_backend/static/assets/useAdmin-CnId_VLW.js b/py_backend/static/assets/useAdmin-CrA3XozJ.js similarity index 65% rename from py_backend/static/assets/useAdmin-CnId_VLW.js rename to py_backend/static/assets/useAdmin-CrA3XozJ.js index 291899c3..1615aa25 100644 --- a/py_backend/static/assets/useAdmin-CnId_VLW.js +++ b/py_backend/static/assets/useAdmin-CrA3XozJ.js @@ -1 +1 @@ -import{r,T as e}from"./index-Rlfiitbv.js";const o=()=>{const t=r.useContext(e);if(t===void 0)throw new Error("useAdmin must be used within an AdminProvider");return t};export{o as u}; +import{r,T as e}from"./index-CcfIBRoF.js";const o=()=>{const t=r.useContext(e);if(t===void 0)throw new Error("useAdmin must be used within an AdminProvider");return t};export{o as u}; diff --git a/py_backend/static/index.html b/py_backend/static/index.html index e62522a3..52f99b2a 100644 --- a/py_backend/static/index.html +++ b/py_backend/static/index.html @@ -42,7 +42,7 @@ }); } - +