SCGR's picture
fix
6f3f084
const __vite__mapDeps=(i,m=__vite__mapDeps,d=(m.f||(m.f=["assets/jszip.min-B2-9j7XO.js","assets/index-C_hAuRbb.js","assets/index-FBu17hMI.css"])))=>i.map(i=>d[i]);
import{J as ea,x as aa,j as a,N as Y,n as F,r as m,D as ta,_ as we,L as sa,z as P,v as ie,w as oe,F as ia,K as oa,G as na}from"./index-C_hAuRbb.js";import{u as ra}from"./useAdmin-B_kWg5HW.js";import{F as la,E as ca}from"./ExportModal-DJ-UV1s7.js";const da="_tabSelector_usssr_1",ga="_imageContainer_usssr_12",ma="_imagePlaceholder_usssr_33",ua="_metadataTags_usssr_45",fa="_metadataTag_usssr_45",pa="_captionContainer_usssr_67",ha="_captionText_usssr_74",_a="_gridLayout_usssr_131",xa="_detailsSection_usssr_155",ya="_loadingContainer_usssr_161",va="_errorContainer_usssr_171",wa="_fullSizeModalOverlay_usssr_205",Ca="_fullSizeModalContent_usssr_219",ja="_ratingWarningContent_usssr_230",Ia="_ratingWarningTitle_usssr_236",Na="_ratingWarningText_usssr_243",ba="_ratingWarningButtons_usssr_250",Sa="_carouselContainer_usssr_365",La="_carouselImageWrapper_usssr_370",Da="_carouselImage_usssr_370",ka="_carouselNavigation_usssr_393",Ma="_carouselButton_usssr_405",Ta="_carouselIndicators_usssr_429",Fa="_carouselIndicator_usssr_429",Ea="_carouselIndicatorActive_usssr_458",Pa="_singleImageContainer_usssr_488",Ra="_viewImageButtonContainer_usssr_494",p={tabSelector:da,imageContainer:ga,imagePlaceholder:ma,metadataTags:ua,metadataTag:fa,captionContainer:pa,captionText:ha,gridLayout:_a,detailsSection:xa,loadingContainer:ya,errorContainer:va,fullSizeModalOverlay:wa,fullSizeModalContent:Ca,ratingWarningContent:ja,ratingWarningTitle:Ia,ratingWarningText:Na,ratingWarningButtons:ba,carouselContainer:Sa,carouselImageWrapper:La,carouselImage:Da,carouselNavigation:ka,carouselButton:Ma,carouselIndicators:Ta,carouselIndicator:Fa,carouselIndicatorActive:Ea,singleImageContainer:Pa,viewImageButtonContainer:Ra};function st(){const{mapId:h}=ea(),v=aa(),{isAuthenticated:ne}=ra();console.log("MapDetailsPage: Current URL:",window.location.href),console.log("MapDetailsPage: Hash:",window.location.hash),console.log("MapDetailsPage: mapId from useParams:",h),console.log("MapDetailsPage: mapId type:",typeof h),console.log("MapDetailsPage: mapId length:",h?.length),console.log("MapDetailsPage: mapId value:",JSON.stringify(h));const Ce=/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i;if(!h||h==="undefined"||h==="null"||h.trim()===""||!Ce.test(h))return a.jsx(Y,{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 = "',h,'" (type: ',typeof h,")"]}),a.jsx(F,{name:"back-to-explore",variant:"secondary",onClick:()=>v("/explore"),children:"Return to Explore"})]})});const[re,je]=m.useState("mapDetails"),[e,ee]=m.useState(null),[W,z]=m.useState(!0),[le,O]=m.useState(null),[ce,Ie]=m.useState([]),[de,Ne]=m.useState([]),[ge,be]=m.useState([]),[me,Se]=m.useState([]),[Le,De]=m.useState([]),[ke,Me]=m.useState(!1),[Te,Fe]=m.useState(!1),[B,q]=m.useState(!1),[Ee,K]=m.useState(!1),[ue,Z]=m.useState(!1),[Pe,ae]=m.useState(!1),[Re,te]=m.useState(!1),[$a,za]=m.useState("standard"),[R,Aa]=m.useState(80),[J,Oa]=m.useState(10),[Ua,Wa]=m.useState(10),[Ba,Ja]=m.useState(!0),[Ha,Va]=m.useState(!0),[Q,X]=m.useState(!1),[$e,fe]=m.useState(!1),[ze,pe]=m.useState(null),[Ae,H]=m.useState(!1),[x,V]=m.useState([]),[M,A]=m.useState(0),[G,he]=m.useState(!1),{search:d,setSearch:Ga,srcFilter:w,setSrcFilter:qa,catFilter:C,setCatFilter:Ka,regionFilter:j,setRegionFilter:Za,countryFilter:I,setCountryFilter:Qa,imageTypeFilter:N,setImageTypeFilter:Xa,uploadTypeFilter:b,setUploadTypeFilter:Ya,showReferenceExamples:k,setShowReferenceExamples:Oe,clearAllFilters:Ue}=ta(),We=[{key:"explore",label:"List"},{key:"mapDetails",label:"Carousel"}],_e=m.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),O("Invalid Map ID"),z(!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),O("Invalid Map ID format"),z(!1);return}console.log("fetchMapData: Making API call for id:",t),q(!0),z(!0);try{const u=await fetch(`/api/images/${t}`);if(!u.ok)throw new Error("Map not found");const s=await u.json();if(ee(s),s.all_image_ids&&s.all_image_ids.length>1)await xe(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 l=await fetch("/api/images/grouped");if(l.ok){const r=(await l.json()).find(c=>c.all_image_ids&&c.all_image_ids.includes(s.image_id));r&&r.all_image_ids?await xe(r.all_image_ids):(V([s]),A(0))}else V([s]),A(0)}catch(l){console.error("Failed to fetch from grouped endpoint:",l),V([s]),A(0)}}else V([s]),A(0);await se(t)}catch(u){O(u instanceof Error?u.message:"Unknown error occurred")}finally{z(!1),q(!1)}},[]),xe=m.useCallback(async t=>{console.log("fetchAllImages called with imageIds:",t),he(!0);try{const i=t.map(async s=>{const l=await fetch(`/api/images/${s}`);if(!l.ok)throw new Error(`Failed to fetch image ${s}`);return l.json()}),u=await Promise.all(i);V(u),A(0),console.log("fetchAllImages: Loaded",u.length,"images")}catch(i){console.error("fetchAllImages error:",i),O(i instanceof Error?i.message:"Failed to load all images")}finally{he(!1)}},[]),Be=m.useCallback(()=>{x.length>1&&A(t=>t>0?t-1:x.length-1)},[x.length]),Je=m.useCallback(()=>{x.length>1&&A(t=>t<x.length-1?t+1:0)},[x.length]),He=m.useCallback(t=>{t>=0&&t<x.length&&A(t)},[x.length]),ye=m.useCallback(async t=>{const i=t||(x.length>0?x[M]:e);if(i){H(!0),pe(i),fe(!0);try{const u=new Image;u.onload=()=>{H(!1)},u.onerror=()=>{H(!1)},u.src=i.image_url}catch(u){console.error("Error preloading full-size image:",u),H(!1)}}},[x,M,e]),Ve=m.useCallback(()=>{fe(!1),pe(null),H(!1)},[]);m.useEffect(()=>{if(console.log("MapDetailsPage: mapId from useParams:",h),console.log("MapDetailsPage: mapId type:",typeof h),console.log("MapDetailsPage: mapId value:",h),!h||h==="undefined"||h==="null"||h.trim()===""||h===void 0||h===null){console.log("MapDetailsPage: Invalid mapId, setting error"),O("Map ID is required"),z(!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(h)){console.log("MapDetailsPage: Invalid UUID format:",h),O("Invalid Map ID format"),z(!1);return}console.log("MapDetailsPage: Fetching data for mapId:",h),_e(h)},[h,_e]),m.useEffect(()=>{if(!e||W||Q)return;if(!h||h==="undefined"||h==="null"||h.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(h)){console.log("Auto-navigation skipped: Invalid mapId format");return}(()=>{const u=!d||e.title?.toLowerCase().includes(d.toLowerCase())||e.generated?.toLowerCase().includes(d.toLowerCase())||e.source?.toLowerCase().includes(d.toLowerCase())||e.event_type?.toLowerCase().includes(d.toLowerCase()),s=!w||e.source===w,l=!C||e.event_type===C,o=!j||e.countries.some(T=>T.r_code===j),r=!I||e.countries.some(T=>T.c_code===I),c=!N||e.image_type===N,n=!k||e.starred===!0,y=u&&s&&l&&o&&r&&c&&n;return console.log("Auto-navigation check:",{mapId:h,search:d,srcFilter:w,catFilter:C,regionFilter:j,countryFilter:I,imageTypeFilter:N,showReferenceExamples:k,matchesSearch:u,matchesSource:s,matchesCategory:l,matchesRegion:o,matchesCountry:r,matchesImageType:c,matchesReferenceExamples:n,matches:y}),y})()||(console.log("Current map does not match filters, looking for first matching item"),fetch("/api/images").then(u=>u.json()).then(u=>{console.log("Auto-navigation: Received images from API:",u.length),console.log("Auto-navigation: First few images:",u.slice(0,3).map(l=>({image_id:l.image_id,title:l.title})));const s=u.find(l=>{const o=!d||l.title?.toLowerCase().includes(d.toLowerCase())||l.generated?.toLowerCase().includes(d.toLowerCase())||l.source?.toLowerCase().includes(d.toLowerCase())||l.event_type?.toLowerCase().includes(d.toLowerCase()),r=!w||l.source===w,c=!C||l.event_type===C,n=!j||l.countries?.some(f=>f.r_code===j),y=!I||l.countries?.some(f=>f.c_code===I),T=!N||l.image_type===N,L=!k||l.starred===!0;return o&&r&&c&&n&&y&&T&&L});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!==h&&(/^[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),v(`/map/${s.image_id}`)):console.error("Auto-navigation blocked: Invalid image_id format:",s.image_id))}).catch(console.error))},[e,d,w,C,j,I,N,k,h,v,W,Q]);const se=async t=>{if(!(!t||t==="undefined"||t==="null"||t.trim()===""))try{const i=await fetch("/api/images/grouped");if(i.ok){const s=(await i.json()).filter(o=>{const r=!d||o.title?.toLowerCase().includes(d.toLowerCase())||o.generated?.toLowerCase().includes(d.toLowerCase())||o.source?.toLowerCase().includes(d.toLowerCase())||o.event_type?.toLowerCase().includes(d.toLowerCase()),c=!w||o.source===w,n=!C||o.event_type===C,y=!j||o.countries?.some(_=>_.r_code===j),T=!I||o.countries?.some(_=>_.c_code===I),L=!N||o.image_type===N,f=!b||b==="single"&&(!o.image_count||o.image_count<=1)||b==="multiple"&&o.image_count&&o.image_count>1,S=!k||o.starred===!0;return r&&c&&n&&y&&T&&L&&f&&S}),l=s.findIndex(o=>o.image_id===t);Me(s.length>1&&l>0),Fe(s.length>1&&l<s.length-1)}}catch(i){console.error("Failed to check navigation availability:",i)}},ve=async t=>{if(!B){q(!0);try{const i=await fetch("/api/images/grouped");if(i.ok){const u=await i.json(),s=u.filter(n=>{const y=!d||n.title?.toLowerCase().includes(d.toLowerCase())||n.generated?.toLowerCase().includes(d.toLowerCase())||n.source?.toLowerCase().includes(d.toLowerCase())||n.event_type?.toLowerCase().includes(d.toLowerCase()),T=!w||n.source===w,L=!C||n.event_type===C,f=!j||n.countries?.some($=>$.r_code===j),S=!I||n.countries?.some($=>$.c_code===I),_=!N||n.image_type===N,D=!b||b==="single"&&(!n.image_count||n.image_count<=1)||b==="multiple"&&n.image_count&&n.image_count>1,U=!k||n.starred===!0;return y&&T&&L&&f&&S&&_&&D&&U});if(s.findIndex(n=>n.image_id===h)===-1){const n=u.find(y=>y.image_id===h);n&&s.push(n)}const o=s.findIndex(n=>n.image_id===h);if(o===-1){console.error("Current image not found in filtered list");return}let r;t==="previous"?r=o>0?o-1:s.length-1:r=o<s.length-1?o+1:0;const c=s[r];c&&c.image_id&&c.image_id!=="undefined"&&c.image_id!=="null"&&c.image_id.trim()!==""&&(/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i.test(c.image_id)?(console.log("Carousel navigating to:",c.image_id),v(`/map/${c.image_id}`)):console.error("Carousel navigation blocked: Invalid image_id format:",c.image_id))}}catch(i){console.error("Failed to navigate to item:",i)}finally{q(!1)}}};m.useEffect(()=>{e&&h&&!W&&!Q&&se(h)},[e,h,d,w,C,j,I,N,b,k,W,Q,se]),m.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,u,s,l])=>{Ie(t),Ne(i),be(u),Se(s),De(l)}).catch(console.error)},[]);const Ge=async()=>{e&&K(!0)},qe=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?ee(i=>i?{...i,starred:!i.starred}:null):console.error("Failed to toggle starred status")}catch(t){console.error("Error toggling starred status:",t)}},Ke=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){ee(i=>i?{...i,starred:!i.starred}:null),K(!1);try{const i=await fetch("/api/images/grouped");if(i.ok){const s=(await i.json()).filter(o=>{const r=!d||o.title?.toLowerCase().includes(d.toLowerCase())||o.generated?.toLowerCase().includes(d.toLowerCase())||o.source?.toLowerCase().includes(d.toLowerCase())||o.event_type?.toLowerCase().includes(d.toLowerCase()),c=!w||o.source===w,n=!C||o.event_type===C,y=!j||o.countries?.some(_=>_.r_code===j),T=!I||o.countries?.some(_=>_.c_code===I),L=!N||o.image_type===N,f=!b||b==="single"&&(!o.image_count||o.image_count<=1)||b==="multiple"&&o.image_count&&o.image_count>1,S=!k||o.starred===!0;return r&&c&&n&&y&&T&&L&&f&&S}),l=s.filter(o=>o.image_id!==e.image_id);if(l.length>0){const o=s.findIndex(c=>c.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:l[r]?.image_id}),r>=0&&r<l.length){const c=l[r];c&&c.image_id&&c.image_id!=="undefined"&&c.image_id!=="null"&&c.image_id.trim()!==""?/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i.test(c.image_id)?(console.log("Navigating to:",c.image_id),v(`/map/${c.image_id}`)):(console.error("Navigation blocked: Invalid image_id format:",c.image_id),v("/explore")):(console.error("Navigation blocked: Invalid image_id:",c?.image_id),v("/explore"))}else l[0]&&l[0].image_id&&l[0].image_id!=="undefined"&&l[0].image_id!=="null"&&l[0].image_id.trim()!==""?/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i.test(l[0].image_id)?(console.log("Fallback navigation to first item:",l[0].image_id),v(`/map/${l[0].image_id}`)):(console.error("Fallback navigation blocked: Invalid image_id format:",l[0].image_id),v("/explore")):(console.log("No valid remaining items, going to explore page"),v("/explore"))}else console.log("No remaining items, going to explore page"),v("/explore")}else v("/explore")}catch(i){console.error("Failed to navigate to next item:",i),v("/explore")}finally{X(!1)}}else console.error("Delete failed"),X(!1)}catch(t){console.error("Delete failed:",t),X(!1)}}},g=m.useMemo(()=>{if(!e)return null;if(!d&&!w&&!C&&!j&&!I&&!N&&!b&&!k)return e;const t=!d||e.title?.toLowerCase().includes(d.toLowerCase())||e.generated?.toLowerCase().includes(d.toLowerCase())||e.source?.toLowerCase().includes(d.toLowerCase())||e.event_type?.toLowerCase().includes(d.toLowerCase()),i=!w||e.source===w,u=!C||e.event_type===C,s=!j||e.countries.some(y=>y.r_code===j),l=!I||e.countries.some(y=>y.c_code===I),o=!N||e.image_type===N,r=!b||b==="single"&&(!e.image_count||e.image_count<=1)||b==="multiple"&&e.image_count&&e.image_count>1,c=!k||e.starred===!0,n=t&&i&&u&&s&&l&&o&&r&&c;return!n&&(d||w||C||j||I||N||b||k)?(setTimeout(()=>{Ze()},100),e):n?e:null},[e,d,w,C,j,I,N,b,k]),Ze=m.useCallback(async()=>{z(!0);try{const t=await fetch("/api/images/grouped");if(t.ok){const u=(await t.json()).filter(s=>{const l=!d||s.title?.toLowerCase().includes(d.toLowerCase())||s.generated?.toLowerCase().includes(d.toLowerCase())||s.source?.toLowerCase().includes(d.toLowerCase())||s.event_type?.toLowerCase().includes(d.toLowerCase()),o=!w||s.source===w,r=!C||s.event_type===C,c=!j||s.countries?.some(f=>f.r_code===j),n=!I||s.countries?.some(f=>f.c_code===I),y=!N||s.image_type===N,T=!b||b==="single"&&(!s.image_count||s.image_count<=1)||b==="multiple"&&s.image_count&&s.image_count>1,L=!k||s.starred===!0;return l&&o&&r&&c&&n&&y&&T&&L});if(u.length>0){const s=u[0];s&&s.image_id&&v(`/map/${s.image_id}`)}else v("/explore")}}catch(t){console.error("Failed to navigate to matching image:",t),v("/explore")}finally{z(!1)}},[d,w,C,j,I,N,b,k,v]),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(",")}`;v(s);return}const i=`/upload?step=1&contribute=true&imageIds=${e.all_image_ids.join(",")}`;v(i)},E=(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){ae(!0),te(!1);try{const i=(await na(async()=>{const{default:r}=await import("./jszip.min-B2-9j7XO.js").then(c=>c.j);return{default:r}},__vite__mapDeps([0,1,2]))).default,u=new i;if(e.image_type==="crisis_map"){const r=u.folder("crisis_maps_dataset"),c=r?.folder("images");if(c)try{const n=e.image_count&&e.image_count>1?e.all_image_ids||[e.image_id]:[e.image_id],y=n.map(async(f,S)=>{try{const _=await fetch(`/api/images/${f}/file`);if(!_.ok)throw new Error(`Failed to fetch image ${f}`);const D=await _.blob(),U=e.file_key.split(".").pop()||"jpg",$=`0001_${String(S+1).padStart(2,"0")}.${U}`;return c.file($,D),{success:!0,fileName:$,imageId:f}}catch(_){return console.error(`Failed to process image ${f}:`,_),{success:!1,fileName:"",imageId:f}}}),L=(await Promise.all(y)).filter(f=>f.success);if(L.length===0)throw new Error("No images could be processed");if(t==="fine-tuning"){const f=[],S=[],_=[],D=L.map(Ye=>`images/${Ye.fileName}`),U=Math.random(),$={image:D.length===1?D[0]:D,caption:e.edited||e.generated||"",metadata:{image_id:n,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}};U<R/100?f.push($):U<(R+J)/100?S.push($):_.push($),r&&(r.file("train.jsonl",JSON.stringify(f,null,2)),r.file("test.jsonl",JSON.stringify(S,null,2)),r.file("val.jsonl",JSON.stringify(_,null,2)))}else{const f=L.map(_=>`images/${_.fileName}`),S={image:f.length===1?f[0]:f,caption:e.edited||e.generated||"",metadata:{image_id:n,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(n){throw console.error(`Failed to process image ${e.image_id}:`,n),n}}else if(e.image_type==="drone_image"){const r=u.folder("drone_images_dataset"),c=r?.folder("images");if(c)try{const n=await fetch(`/api/images/${e.image_id}/file`);if(!n.ok)throw new Error(`Failed to fetch image ${e.image_id}`);const y=await n.blob(),L=`0001.${e.file_key.split(".").pop()||"jpg"}`;if(c.file(L,y),t==="fine-tuning"){const f=[],S=[],_=[];if(String(e?.image_type)==="crisis_map"){const D=Math.random();D<R/100?f.push(E(e,"0001")):D<(R+J)/100?S.push(E(e,"0001")):_.push(E(e,"0001"))}else if(String(e?.image_type)==="drone_image"){const D=Math.random();D<R/100?f.push(E(e,"0001")):D<(R+J)/100?S.push(E(e,"0001")):_.push(E(e,"0001"))}r&&(r.file("train.jsonl",JSON.stringify(f,null,2)),r.file("test.jsonl",JSON.stringify(S,null,2)),r.file("val.jsonl",JSON.stringify(_,null,2)))}else{const f={image:`images/${L}`,caption:e.edited||e.generated||"",metadata:{image_id:e.image_count&&e.image_count>1?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(f,null,2))}}catch(n){throw console.error(`Failed to process image ${e.image_id}:`,n),n}}else{const r=u.folder("generic_dataset"),c=r?.folder("images");if(c)try{const n=await fetch(`/api/images/${e.image_id}/file`);if(!n.ok)throw new Error(`Failed to fetch image ${e.image_id}`);const y=await n.blob(),L=`0001.${e.file_key.split(".").pop()||"jpg"}`;if(c.file(L,y),t==="fine-tuning"){const f=[],S=[],_=[];if(String(e?.image_type)==="crisis_map"){const D=Math.random();D<R/100?f.push(E(e,"0001")):D<(R+J)/100?S.push(E(e,"0001")):_.push(E(e,"0001"))}else if(String(e?.image_type)==="drone_image"){const D=Math.random();D<R/100?f.push(E(e,"0001")):D<(R+J)/100?S.push(E(e,"0001")):_.push(E(e,"0001"))}r&&(r.file("train.jsonl",JSON.stringify(f,null,2)),r.file("test.jsonl",JSON.stringify(S,null,2)),r.file("val.jsonl",JSON.stringify(_,null,2)))}else{const f={image:`images/${L}`,caption:e.edited||e.generated||"",metadata:{image_id:e.image_count&&e.image_count>1?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(f,null,2))}}catch(n){throw console.error(`Failed to process image ${e.image_id}:`,n),n}}const s=await u.generateAsync({type:"blob"}),l=URL.createObjectURL(s),o=document.createElement("a");o.href=l,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(l),console.log(`Exported ${e.image_type} dataset with 1 image in ${t} mode`),te(!0)}catch(i){console.error("Export failed:",i),alert("Failed to export dataset. Please try again.")}finally{ae(!1)}}};return W?a.jsx(Y,{children:a.jsx("div",{className:p.loadingContainer,children:a.jsxs("div",{className:"flex flex-col items-center gap-4",children:[a.jsx(we,{className:"text-ifrcRed"}),a.jsx("div",{children:"Loading map details..."})]})})}):le||!e?a.jsx(Y,{children:a.jsx("div",{className:p.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:le||"Map not found"}),a.jsx(F,{name:"back-to-explore",variant:"secondary",onClick:()=>v("/explore"),children:"Return to Explore"})]})})}):a.jsxs(Y,{children:[a.jsxs("div",{className:"max-w-7xl mx-auto",children:[a.jsxs("div",{className:p.tabSelector,children:[a.jsx(sa,{name:"map-details-view",value:re,onChange:t=>{(t==="mapDetails"||t==="explore")&&(je(t),t==="explore"&&v("/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:()=>Oe(!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:()=>Z(!0),children:"Export"})]})]}),a.jsx(la,{sources:ce,types:de,regions:me,countries:Le,imageTypes:ge,isLoadingFilters:!1}),re==="mapDetails"?a.jsx("div",{className:"relative",children:g?a.jsxs(a.Fragment,{children:[a.jsxs("div",{className:p.gridLayout,children:[a.jsxs(P,{heading:a.jsxs("div",{className:"flex items-center gap-2",children:[a.jsx("span",{children:g.title||"Map Image"}),g.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:p.imageContainer,children:e?.image_count&&e.image_count>1||x.length>1?a.jsxs("div",{className:p.carouselContainer,children:[a.jsx("div",{className:p.carouselImageWrapper,children:G?a.jsxs("div",{className:p.imagePlaceholder,children:[a.jsx(we,{className:"text-ifrcRed"}),a.jsx("div",{children:"Loading images..."})]}):x[M]?.detail_url?a.jsx("img",{src:x[M].detail_url,alt:x[M].file_key,className:p.carouselImage,onError:t=>{console.log("MapDetailsPage: Detail image failed to load, falling back to original:",x[M].detail_url);const i=t.target;x[M].image_url&&(i.src=x[M].image_url)},onLoad:()=>console.log("MapDetailsPage: Detail image loaded successfully:",x[M].detail_url)}):x[M]?.image_url?a.jsx("img",{src:x[M].image_url,alt:x[M].file_key,className:p.carouselImage,onLoad:()=>console.log("MapDetailsPage: Original image loaded successfully:",x[M].image_url)}):a.jsx("div",{className:p.imagePlaceholder,children:"No image available"})}),a.jsxs("div",{className:p.carouselNavigation,children:[a.jsx(F,{name:"previous-image",variant:"tertiary",size:1,onClick:Be,disabled:G,className:p.carouselButton,children:a.jsx(ie,{className:"w-4 h-4"})}),a.jsx("div",{className:p.carouselIndicators,children:x.map((t,i)=>a.jsx("button",{onClick:()=>He(i),className:`${p.carouselIndicator} ${i===M?p.carouselIndicatorActive:""}`,disabled:G,children:i+1},i))}),a.jsx(F,{name:"next-image",variant:"tertiary",size:1,onClick:Je,disabled:G,className:p.carouselButton,children:a.jsx(oe,{className:"w-4 h-4"})})]}),a.jsx("div",{className:p.viewImageButtonContainer,children:a.jsx(F,{name:"view-full-size-carousel",variant:"secondary",size:1,onClick:()=>ye(x[M]),disabled:G||!x[M]?.image_url,children:"View Image"})})]}):a.jsxs("div",{className:p.singleImageContainer,children:[g.detail_url?a.jsx("img",{src:g.detail_url,alt:g.file_key,onError:t=>{console.log("MapDetailsPage: Detail image failed to load, falling back to original:",g.detail_url);const i=t.target;g.image_url&&(i.src=g.image_url)},onLoad:()=>console.log("MapDetailsPage: Detail image loaded successfully:",g.detail_url)}):g.image_url?a.jsx("img",{src:g.image_url,alt:g.file_key,onLoad:()=>console.log("MapDetailsPage: Original image loaded successfully:",g.image_url)}):a.jsx("div",{className:p.imagePlaceholder,children:"No image available"}),a.jsx("div",{className:p.viewImageButtonContainer,children:a.jsx(F,{name:"view-full-size-single",variant:"secondary",size:1,onClick:()=>ye(g),disabled:!g.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:p.metadataTags,children:[g.image_type!=="drone_image"&&a.jsx("span",{className:p.metadataTag,children:ce.find(t=>t.s_code===g.source)?.label||g.source}),a.jsx("span",{className:p.metadataTag,children:de.find(t=>t.t_code===g.event_type)?.label||g.event_type}),a.jsx("span",{className:p.metadataTag,children:ge.find(t=>t.image_type===g.image_type)?.label||g.image_type}),g.countries&&g.countries.length>0&&a.jsxs(a.Fragment,{children:[a.jsx("span",{className:p.metadataTag,children:me.find(t=>t.r_code===g.countries[0].r_code)?.label||"Unknown Region"}),a.jsx("span",{className:p.metadataTag,children:g.countries.map(t=>t.label).join(", ")})]}),g.image_count&&g.image_count>1&&a.jsxs("span",{className:p.metadataTag,title:`Multi-upload with ${g.image_count} images`,children:["πŸ“· ",g.image_count]}),(!g.image_count||g.image_count<=1)&&a.jsx("span",{className:p.metadataTag,title:"Single Upload",children:"Single"})]})})]}),a.jsx("div",{className:p.detailsSection,children:g.edited&&g.edited.includes("Description:")||g.generated&&g.generated.includes("Description:")?a.jsx(P,{heading:"AI Generated Content",headingLevel:3,withHeaderBorder:!0,withInternalPadding:!0,spacing:"comfortable",children:a.jsx("div",{className:p.captionContainer,children:a.jsx("div",{className:p.captionText,children:(g.edited||g.generated||"").split(`
`).map((t,i)=>a.jsx("div",{children:t.startsWith("Description:")||t.startsWith("Analysis:")||t.startsWith("Recommended Actions:")?a.jsx("h4",{className:"font-semibold text-gray-800 mt-4 mb-2",children:t}):t.trim()===""?a.jsx("br",{}):a.jsx("p",{className:"mb-2",children:t})},i))})})}):a.jsx(P,{heading:"Description",headingLevel:3,withHeaderBorder:!0,withInternalPadding:!0,spacing:"comfortable",children:a.jsx("div",{className:p.captionContainer,children:g.generated?a.jsx("div",{className:p.captionText,children:a.jsx("p",{children:g.edited||g.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:[ke&&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 ${B?"opacity-50 cursor-not-allowed":"hover:scale-110"}`,onClick:()=>ve("previous"),disabled:B,children:a.jsxs("div",{className:"flex items-center gap-1",children:[a.jsxs("div",{className:"flex -space-x-1",children:[a.jsx(ie,{className:"w-4 h-4"}),a.jsx(ie,{className:"w-4 h-4"})]}),a.jsx("span",{className:"font-semibold",children:"Previous"})]})})}),ne&&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:Ge,title:"Delete","aria-label":"Delete saved image",children:a.jsx(ia,{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"})}),ne&&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:qe,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 ${B?"opacity-50 cursor-not-allowed":"hover:scale-110"}`,onClick:()=>ve("next"),disabled:B,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(oe,{className:"w-4 h-4"}),a.jsx(oe,{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:Ue,children:"Clear Filters"})})]})}):null]}),Ee&&a.jsx("div",{className:p.fullSizeModalOverlay,onClick:()=>K(!1),children:a.jsx("div",{className:p.fullSizeModalContent,onClick:t=>t.stopPropagation(),children:a.jsxs("div",{className:p.ratingWarningContent,children:[a.jsx("h3",{className:p.ratingWarningTitle,children:"Delete Image?"}),a.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?"}),a.jsxs("div",{className:p.ratingWarningButtons,children:[a.jsx(F,{name:"confirm-delete",variant:"secondary",onClick:Ke,children:"Delete"}),a.jsx(F,{name:"cancel-delete",variant:"tertiary",onClick:()=>K(!1),children:"Cancel"})]})]})})}),ue&&a.jsx(ca,{isOpen:ue,onClose:()=>{Z(!1),te(!1),ae(!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:()=>{Z(!1),v("/explore")},onNavigateAndExport:()=>{Z(!1),v("/explore?export=true")}}),a.jsx(oa,{isOpen:$e,imageUrl:ze?.image_url||null,preview:null,selectedImageData:null,onClose:Ve,isLoading:Ae})]})}export{st as default};