PageSourceSearch

https://cyberstock.lol/assets/ReviewEdit-BWVhMoYN.js

js cyberstock.lol collected 2026-09-24 14:24:30 UTC 294,327 bytes, 18 lines download raw bytes

1import{c as Yc,j as e,aG as mt,aB as $u,aH as Ou,aI as zu,aJ as yn,r as d,aK as Uu,u as Ea,n as Xc,l as K,aL as bs,ap as Jc,aq as Zc,a0 as At,W as xt,a4 as Qc,_ as $t,ac as Qo,v as we,a5 as ed,aM as di,Y as $s,t as Tt,R as en,X as va,aN as qu,aO as Vu,o as Wu,aP as Hu,q as rc,p as Ps,aQ as Gu,ae as pa,aA as Yu,aR as Xu,aS as ha,aT as Ee,T as _e,b as Ae,e as Te,aU as To,ar as Do,$ as as,Z as Ne,aV as Ju,aW as Zu,aX as Qu,aY as Io,y as ic,aZ as ac,ah as ga,Q as Ro,am as Mo,L as em,a_ as tm,a$ as sm,b0 as rm,b1 as im,b2 as am,b3 as om,b4 as oc,b5 as nc,b6 as lc,b7 as os,ak as ns,b8 as nm,C as lm,k as cm,b9 as dm,ao as cc,ba as um,G as Zr,I as Qr,J as ei,K as ti,M as si,O as ri,bb as Bo,E as mm,d as dc,s as td,a as sd,bc as uc,m as mc,bd as pm,be as hm}from"./index-CE18-tb0.js";import{C as hr}from"./checkbox-DLoYfPvK.js";import{S as Lo,a as Fo,b as Po,c as Ko,d as gr}from"./select-B_VNVb2N.js";import{c as $o,b as Oo}from"./config_templates-CB4til-o.js";import{C as pc}from"./cyberbatch.service-DzemcbCp.js";import{M as ii}from"./metadata.service-BcbxTxjS.js";import{P as gm,a as fm,b as ym,U as xm,R as bm}from"./react-resizable-panels.browser.esm-Bxas5s_T.js";import{e as hc,p as rd,h as wm}from"./sessionSettings.service-tBnlbvQV.js";import{L as vm}from"./LargeBatchDialog-Ca_GPXAE.js";import{u as km,j as Cm,P as ui,b as Sm,c as jm,d as Nm,e as Em,f as _m,g as Am,h as Tm,i as Dm,k as Im,A as zo,l as Uo,a as qo}from"./useAnnouncements-jB4DpLXa.js";import{P as Rm,a as Mm,b as Bm}from"./popover-OhLud7O9.js";import{R as Lm,C as Fm,a as Pm}from"./index-8HCYTIWI.js";import{T as gc}from"./ThumbnailImage-CytvRlL7.js";import{u as Os,v as hi,R as Km,a as $m,b as Dt}from"./ReleaseUploadDialog-4ZcaE0Ht.js";import{S as Om,U as zm}from"./scroll-area-CsF-QEyu.js";import{U as Um}from"./upload-BTbSUZ_s.js";import{e as qm,a as Vm,c as Wm,t as fc}from"./xmp-DXfE_oow.js";import{S as Hm,i as yc}from"./shutterstockCategory-CFep-6BB.js";import{Z as Gm}from"./zoom-out-BTPBmp66.js";import{Z as Ym}from"./zoom-in-CH9hZ05u.js";import{M as Xm}from"./maximize-2-BFxPbEYi.js";import{F as xc}from"./file-image-oKKMPffJ.js";import{D as bc}from"./download-Cr7vgIPx.js";import{F as wc}from"./file-text-BiI4ahgV.js";import{S as Jm}from"./save-Gj4-tUnO.js";import{R as Zm}from"./rocket-DRW4DTLg.js";import{P as vc}from"./pencil-DVmdVhCl.js";import"./vendor-Y7T1HomI.js";import"./supabase-BwgEV_BN.js";import"./index-BdQq_4o_.js";import"./chevron-up-4Uu7HJ9z.js";import"./exceljs.min-BxJGa8ry.js";import"./_commonjs-dynamic-modules-TDtrdbi3.js";import"./index-BbVDiqfI.js";import"./jszip.min-CUneog-9.js";/**
2 * @license lucide-react v0.462.0 - ISC
3 *
4 * This source code is licensed under the ISC license.
5 * See the LICENSE file in the root directory of this source tree.
6 */const Qm=Yc("ArrowUpDown",[["path",{d:"m21 16-4 4-4-4",key:"f6ql7i"}],["path",{d:"M17 20V4",key:"1ejh1v"}],["path",{d:"m3 8 4-4 4 4",key:"11wl7u"}],["path",{d:"M7 4v16",key:"1glfcx"}]]);/**
7 * @license lucide-react v0.462.0 - ISC
8 *
9 * This source code is licensed under the ISC license.
10 * See the LICENSE file in the root directory of this source tree.
11 */const ep=Yc("GripVertical",[["circle",{cx:"9",cy:"12",r:"1",key:"1vctgf"}],["circle",{cx:"9",cy:"5",r:"1",key:"hp0tcf"}],["circle",{cx:"9",cy:"19",r:"1",key:"fkjjf6"}],["circle",{cx:"15",cy:"12",r:"1",key:"1tmaij"}],["circle",{cx:"15",cy:"5",r:"1",key:"19l28e"}],["circle",{cx:"15",cy:"19",r:"1",key:"f4zoj3"}]]),tp=({className:s,...i})=>e.jsx(fm,{className:mt("flex h-full w-full data-[panel-group-direction=vertical]:flex-col",s),...i}),Vo=gm,kc=({withHandle:s,className:i,...r})=>e.jsx(ym,{className:mt("relative flex w-px items-center justify-center bg-border after:absolute after:inset-y-0 after:left-1/2 after:w-1 after:-translate-x-1/2 data-[panel-group-direction=vertical]:h-px data-[panel-group-direction=vertical]:w-full data-[panel-group-direction=vertical]:after:left-0 data-[panel-group-direction=vertical]:after:h-1 data-[panel-group-direction=vertical]:after:w-full data-[panel-group-direction=vertical]:after:-translate-y-1/2 data-[panel-group-direction=vertical]:after:translate-x-0 focus-visible:outline-none focus-visible:ring-1 focus-visible:ring-ring focus-visible:ring-offset-1 [&[data-panel-group-direction=vertical]>div]:rotate-90",i),...r,children:s&&e.jsx("div",{className:"z-10 flex h-4 w-3 items-center justify-center rounded-sm border bg-border",children:e.jsx(ep,{className:"h-2.5 w-2.5"})})}),id=["Afghanistan","Albania","Algeria","Andorra","Angola","Anguilla (UK)","Antigua and Barbuda","Argentina","Armenia","Aruba (Netherlands)","Australia","Austria","Azerbaijan","Bahamas","Bahrain","Bangladesh","Barbados","Belarus","Belgium","Belize","Benin","Bhutan","Bolivia","Bosnia and Herzegovina","Botswana","Brazil","British Virgin Islands (UK)","Brunei","Bulgaria","Burkina Faso","Burundi","Cabo Verde","Cambodia","Cameroon","Canada","Caribbean Netherlands (Netherlands)","Cayman Islands (UK)","Central African Republic","Chad","Chile","China","Colombia","Comoros","Congo","Costa Rica","Cote d'Ivoire","Croatia","Cuba","Curaçao","Cyprus","Czech Republic","Denmark","Djibouti","Dominica","Dominican Republic","Ecuador","Egypt","El Salvador","Equatorial Guinea","Eritrea","Estonia","Ethiopia","Fiji","Finland","France","Gabon","Gambia","Georgia","Germany","Ghana","Greece","Grenada","Guadeloupe (France)","Guatemala","Guinea","Guinea-Bissau","Guyana","Haiti","Honduras","Hungary","Iceland","India","Indonesia","Iran","Iraq","Ireland","Israel","Italy","Jamaica","Japan","Jordan","Kazakhstan","Kenya","Kiribati","Kosovo","Kuwait","Kyrgyzstan","Laos","Latvia","Lebanon","Lesotho","Liberia","Libya","Liechtenstein","Lithuania","Luxembourg","Macedonia","Madagascar","Malawi","Malaysia","Maldives","Mali","Malta","Marshall Islands","Martinique (France)","Mauritania","Mauritius","Mexico","Micronesia","Moldova","Monaco","Mongolia","Montenegro","Montserrat (UK)","Morocco","Mozambique","Myanmar","Namibia","Nauru","Nepal","Netherlands","New Zealand","Nicaragua","Niger","Nigeria","North Korea","Norway","Oman","Pakistan","Palau","Palestine","Panama","Papua New Guinea","Paraguay","Peru","Philippines","Poland","Portugal","Puerto Rico (US)","Qatar","Romania","Russia","Rwanda","Saint Barthélemy (France)","Saint Martin (France)","Samoa","San Marino","Sao Tome and Principe","Saudi Arabia","Senegal","Serbia","Seychelles","Sierra Leone","Singapore","Sint Maarten (Netherlands)","Slovakia","Slovenia","Solomon Islands","Somalia","South Africa","South Korea","South Sudan","Spain","Sri Lanka","St. Kitts and Nevis","St. Lucia","St. Vincent and The Grenadines","Sudan","Suriname","Swaziland","Sweden","Switzerland","Syria","Taiwan","Tajikistan","Tanzania","Thailand","Timor-Leste","Togo","Tonga","Trinidad and Tobago","Tunisia","Turkey","Turkmenistan","Turks and Caicos Islands (UK)","Tuvalu","Uganda","Ukraine","United Arab Emirates","United Kingdom (UK)","United States of America (USA)","United States Virgin Islands (US)","Uruguay","Uzbekistan","Vanuatu","Vatican City (Holy See)","Venezuela","Vietnam","Yemen","Zambia","Zimbabwe"],ad=["Animals","Objects & Graphics","Arts & Entertainment","Beauty & Health","Business","Food","Drink","Industry","Location & Buildings","Medical","Nature","Objects & Equipment","People","Religion","Science","Sport & Fitness","Technology","Time Lapse","Transportation","Travel"],Cc=id.map(s=>({label:s,value:s})),sp=ad.map(s=>({label:s,value:s})),ai=s=>!!s.editorial,xn=[{id:"title",label:"Title (Optional)",type:"text",required:!1,maxLength:100},{id:"description",label:"Description",type:"textarea",required:!0,minLength:15,maxLength:200,minWords:5,helperText:"15-200 characters, at least 5 words."},{id:"keywords",label:"Keywords",type:"textarea",required:!0,minKeywords:8,maxKeywords:49,helperText:"Comma-separated, 8-49 keywords with 
11no duplicates."},{id:"category",label:"Category",type:"select",required:!0,options:sp,helperText:"Select the most relevant category."},{id:"batchName",label:"Batch Name",type:"text",required:!1},{id:"editorial",label:"Editorial",type:"switch",required:!1,helperText:"If true, additional editorial fields are required."},{id:"editorialText",label:"Editorial Text",type:"textarea",required:ai,helperText:"Required when editorial is true."},{id:"editorialCity",label:"Editorial City",type:"text",required:ai,helperText:"Required when editorial is true."},{id:"editorialState",label:"Editorial State",type:"text",required:ai,helperText:"Required when editorial is true."},{id:"editorialCountry",label:"Editorial Country",type:"select",required:ai,options:Cc,helperText:"Required when editorial is true."},{id:"editorialDate",label:"Editorial Date",type:"date",required:ai,helperText:"Format: YYYY-MM-DD. Required when editorial is true."},{id:"shootingCountry",label:"Shooting Country (Optional)",type:"select",required:!1,options:Cc},{id:"shootingDate",label:"Shooting Date (Optional)",type:"date",required:!1,helperText:"Format: YYYY-MM-DD."}];xn.map(s=>s.id);const rp=/^(\d{4})-(0[1-9]|1[0-2])-(0[1-9]|[12]\d|3[01])$/,ip=" ";function Sc(s){const i=String(s??"").trim();if(!i)return"";const r=rp.exec(i);if(!r)return i;const[,l,c,p]=r;return[c,p,l].join(ip)}function ap(s){return s?"1":"0"}const Ht=typeof window<"u"?window:null,op=typeof globalThis<"u"?globalThis?.process:void 0,np=()=>{const s=op?.env?.NODE_ENV;return typeof s=="string"?s!=="production":Ht?Ht?.NODE_ENV!=="production":!1};class jc{static track(i,r){if(i&&!$u.track(i,r)){if(Ht?.analytics?.track)try{Ht.analytics.track(i,r);return}catch(l){console.warn("[Telemetry] analytics.track failed",l)}if(Ht?.mixpanel?.track)try{Ht.mixpanel.track(i,r);return}catch(l){console.warn("[Telemetry] mixpanel.track failed",l)}if(Ht?.gtag)try{Ht.gtag("event",i,r??{});return}catch(l){console.warn("[Telemetry] gtag event failed",l)}if(Ht?.dataLayer)try{Ht.dataLayer.push({event:i,...r??{}});return}catch(l){console.warn("[Telemetry] dataLayer push failed",l)}np()&&console.debug("[Telemetry]",i,r)}}static sellingScoreActionTriggered(i,r){this.track("selling_score_action_triggered",{action:i,...r??{}})}static sellingScoreActionCompleted(i,r){this.track("selling_score_action_completed",{action:i,...r??{}})}static sellingScoreDraftApplied(i){this.track("selling_score_draft_applied",i)}static sellingScoreDraftDiscarded(i){this.track("selling_score_draft_discarded",i)}}const lp=/\.(svg|svgz|eps|ai|pdf|ps)(?:\?|#|$)/i,cp=/\.(mp4|mov|m4v|avi|webm|mkv)(?:\?|#|$)/i,dp=64*1024*1024,up=12*1024*1024,mp=4*1024*1024,pp=3,Nc=512,od=s=>String(s||"").split(/[?#]/)[0],hp=(s,i)=>{const r=String(i||"").toLowerCase();return/svg|postscript|illustrator|pdf/.test(r)?!0:lp.test(od(String(s||"")))},gp=(s,i,r)=>String(r||"").toLowerCase()==="video"||/^video\//i.test(String(i||""))?!0:cp.test(od(String(s||""))),nd=s=>new Promise((i,r)=>{const l=new FileReader;l.onloadend=()=>i(String(l.result).split(",")[1]||""),l.onerror=()=>r(new Error("BASE64_READ_FAILED")),l.readAsDataURL(s)}),ka=async(s,i)=>{const r=await fetch(s,{cache:"no-store",...i?{headers:{Range:i}}:{}});if(!r.ok&&r.status!==206)throw new Error(`SOURCE_FETCH_${r.status}`);return await r.blob()},fp=async(s,i)=>{const r=Math.min(1,Nc/Math.max(1,s.width),Nc/Math.max(1,s.height)),l=Math.max(1,Math.round(s.width*r)),c=Math.max(1,Math.round(s.height*r)),p=document.createElement("canvas");p.width=l,p.height=c;const x=p.getContext("2d");if(!x)throw new Error("CANVAS_UNAVAILABLE");x.imageSmoothingEnabled=!0,x.imageSmoothingQuality="medium",x.drawImage(s,0,0,l,c);const k=await new Promise((R,E)=>p.toBlob(b=>b?R(b):E(new Error("FRAME_ENCODE_FAILED")),"image/webp",.76));return{data:await nd(k),filename:i,mimeType:"image/webp"}},yp=async s=>{let i=0,r=!1;try{const p=await fetch(s,{method:"HEAD",cache:"no-store"});p.ok&&(i=Number(p.headers.get("content-length")||0),r=/bytes/i.test(p.headers.get("accept-ranges")||""))}catch{}if(!i||!r||i<=dp)return await ka(s);const[l,c]=await Promise.all([ka(s,`bytes=0-${up-1}`),ka(s,`bytes=${Math.max(0,i-mp)}-${i-1}`)]);return new Blob([l,c],{type:"video/mp4"})};async function xp(s){const{sourceUrl:i,filename:r,mimeType:l,mediaType:c}=s;if(!i)return null;const p=String(r||"asset");
11if(gp(r,l,c)){const x=await yp(i),k=new File([x],p,{type:x.type||"video/mp4"}),R=await Ou(k,pp);if(!R.length)throw new Error("NO_VIDEO_FRAMES");try{const E=[];for(let b=0;b<R.length;b+=1)E.push(await fp(R[b],`${p}#frame${b+1}`));return E}finally{for(const E of R)try{E.close?.()}catch{}}}if(hp(r,l)){const x=await ka(i),k=new File([x],p,{type:x.type||(/\.svgz?$/i.test(p)?"image/svg+xml":"application/octet-stream")}),R=await zu(k);return[{data:await nd(R.blob),filename:`${p}.webp`,mimeType:"image/webp"}]}return null}const bp=Lm,wp=Fm,vp=Pm,kp=[",",";",":"," - "," – "," — "],Cp=new Set(["broll","b-roll","b roll","b_roll","broll footage","b-roll footage","b roll footage","stock footage","stock video","stock photo","stock image","stock clip","stock photos","stock images","stock material","footage","video clip","film clip","royalty free","royalty-free","rights managed","editorial use","commercial use","soundscape","sound scape","soundscapes","audioscape","sound design","sound effect","high resolution","hi-res","hires","high-res","4k footage","4k video","hd video","hd footage","slow motion footage","timelapse footage"]),Sp=s=>{const i=s.trim().toLowerCase();return Cp.has(i)?!0:i.replace(/[-_\s]+/g,"")==="broll"},jp={cliffside:"cliff side",clifftop:"cliff top",treeline:"tree line",mountainside:"mountain side",lakeside:"lake shore",beachside:"beach side",poolside:"pool side",roadside:"road side",waterscape:"water landscape",nightscape:"night landscape",moonscape:"moon landscape",snowscape:"snow landscape",riverbank:"river bank",farmstead:"farm property",grassfield:"grass field",rockface:"rock face",sandbar:"sand bar",mudflat:"mud flat",wetland:"wetlands"},Np={timelaps:"timelapse","time laps":"timelapse",arial:"aerial","arial view":"aerial view","arial shot":"aerial shot",bokah:"bokeh",focuss:"focus",lense:"lens","lense flare":"lens flare",pannoramic:"panoramic",pannorama:"panorama",silouette:"silhouette",silhouete:"silhouette",shilouette:"silhouette",...jp},Ep=(s,i)=>{const r=s.trim().toLowerCase(),l=Np[r]??s;return i?.preserveSingleWord&&!/\s/.test(s.trim())&&/\s/.test(l)?s:l},mi=s=>String(s??"").toLowerCase().replace(/[^\p{L}\p{N}]+/gu," ").replace(/\s{2,}/g," ").trim(),Sr=s=>{const i=String(s??"").replace(/\s+/g," ").trim();return i?/[A-Za-z]/.test(i)?i.replace(/(^|[.!?]\s+)([“”"‘’'([]*)([a-z])(?![A-Z])/g,(r,l,c,p)=>`${l}${c}${p.toUpperCase()}`):i:""},_p=s=>{const i=(s??[]).map(l=>String(l??"").trim()).filter(Boolean);return i.length===0?"":i.length===1?i[0]:i.length===2?`${i[0]} and ${i[1]}`:`${i.slice(0,-1).join(", ")}, and ${i[i.length-1]}`},bn=s=>{const i=[/\b(festive|creative|beautiful|elegant|modern|colorful|bright|vibrant|stylish|perfect|ideal|great|special)\s*$/i,/\b(for|with|of|in|on|at|to|from|by|and|or|a|an|the|against|via|into|onto|upon|over|under|between|among|through|without|within|across|around|about|after|before|during|creating|adding|showing|displaying|near|toward|towards|along)\s*$/i,/\b(representing|depicting|illustrating|showcasing|highlighting|symbolizing|portraying|conveying|suggesting)\s*$/i,/\b(on|in|with|for|to|of|by|at|from|near)\s+(security|texture|concept|theme|idea|message|pattern|design|background|context|symbol)\s*$/i,/\b(is|are|was|were|be|being|been)\s+(prominently|clearly|visibly|mainly|mostly|typically|often)\s*$/i,/\b(prominently|clearly|visibly)\s*$/i,/\b(parties\s+and\s*)$/i,/\b(events\s+and\s*)$/i,/\b(celebration\s+and\s*)$/i];let r=s.trim(),l=!0;for(;l;){l=!1;for(const c of i){const p=r;if(r=r.replace(c,"").trim(),r=r.replace(/[,;:]\s*$/g,"").trim(),r!==p){l=!0;break}}}return r},Ap=(s,i)=>{const r=String(s??"").trim();return r?/[.!?]$/.test(r)||!i||r.length+1>i?r:`${r}.`:""},_a=s=>{let i=s.trim().replace(/[\s,;:]+$/g,"").trim();return/[,;:–—-]$/.test(i)&&(i=i.replace(/[,;:–—-]+$/g,"").trim()),i},Tp=s=>s.split(/\s*,\s*/).map(i=>_a(i)).filter(Boolean),Ca=s=>String(s??"").replace(/\b(?:professional\s+)?stock\s+(?:video|footage|photo|image|clip)\b/gi,"").replace(/\bdepicting\b/gi,"").replace(/\bfeaturing\b/gi,"").replace(/\b(?:is|are|was|were)\s+(?:beautifully\s+|dramatically\s+|prominently\s+|clearly\s+)?(?:captured|depicted|shown|seen|displayed|presented|portrayed|represented|showcased)\b/gi,"").replace(/\b(?:captured|depicted|shown|seen|displayed|presented|portrayed|showcased)\s+(?:with|in|against|on|by)\b/gi,"").replace(/\b(?:a|an)\s+(?:powerful|strong|striking|classic|timeless)?\s*symbol\s+of\b/gi,"").replace(/\b(?:is|are)\s+(?:a\s+|an\s+)?(?:powerful|strong|striking)\s+symbol\b/gi,"").replace(/\brepresented\s+by\b/gi,"").replace(/\b(?:is|are)\s+represented\b/gi,"").replace(/\b(?:symbolizes|symbolizing|symbolises|symbolising|represents|representing|showcasing|showcases|evokes|evoking|conveys|conveying)\b/gi,"").replace(/\b(?:serves|stands)\s+as\s+(?:a\s+|an\s+)?(?:powerful\s+|strong\s+)?(?:symbol|representation|example)\s+of\b/gi,"").replace(/\bset\s+against\b/gi,"on").replace(/\bagainst\s+a\b/gi,"on a").replace(/\b(?:vibrant|stunning|beautiful|gorgeous|majestic|breathtaking|dynamic|mesmerizing|captivating|striking)\s+/gi,"").replace(/\b(?:perfect|ideal|suitable)\s+for\b/gi,"").replace(/\boptimized\s+for(?:\s+search\s+visibility)?\b/gi,"").replace(/\b(?:adobe|shutterstock|istock|getty|pond5|freepik|canva|dreamstime|depositphotos|storyblocks|blackbox|smartmoneyhub)\b/gi,"").replace(/\s{2,}/g," ").replace(/\s+,/g,",").replace(/,\s*,+/g,", ").replace(/\s+\./g,".").replace(/^(?:of|from)\s+(?:a|an|the)\s+/i,"").replace(/^of\s+/i,"").trim(),ws=s=>String(s??"").replace(/[–—―]+/g,", ").replace(/[‐‑‒-]+/g," ").replace(/[;:!?]+/g,". ").replace(/[()[\]{}<>|/\\]+/g," ").replace(/[“”„«»"‘’`´]+/g,"").replace(/&/g," and ").replace(/[^\p{L}\p{N},.\s]/gu," ").replace(/\s+/g," ").replace(/\s+,/g,",").replace(/,\s*,+/g,",").replace(/,\s*\./g,".").replace(/\.\s*,/g,".").replace(/\.(?:\s*\.)+/g,".").replace(/(?:,\s*){2,}
11/g,", ").replace(/\s+\./g,".").replace(/^[,.]\s*/g,"").trim(),Dp=[/^in\s+(?:this|the)\s+(?:scene|image|photo|picture|render|illustration|shot|clip|video|footage|frame),?\s*/i,/^here(?:\s+(?:we\s+(?:see|can\s+see)|is|are))?,?\s+/i,/^(?:a|an|the)\s+(?:scene|image|photo|picture|render|illustration|shot|clip|video|footage|frame|close[\s-]?up|view|composition)\s+(?:that\s+)?(?:showing|featuring|depicting|capturing|illustrating|showcasing|presenting|portraying|of)\s+/i,/^(?:a|an|the)\s+(?:scene|image|photo|picture|render|illustration|shot|clip|video|footage)\s+of\s+/i,/^(?:this|that|the)\s+(?:scene|image|photo|picture|render|illustration|shot|clip|video|footage|frame|artwork|graphic|design)\s+(?:shows|showcases|features|depicts|captures|presents|illustrates|displays|portrays|conveys|evokes|highlights|demonstrates|reveals|represents|is|appears)\s+(?:to\s+(?:show|depict|feature|capture|present)\s+)?(?:a\s+|an\s+|the\s+)?/i,/^this\s+(?:captures|showcases|features|highlights|presents|demonstrates|illustrates|conveys|evokes|shows|depicts|displays|portrays|reveals|represents|is|offers)\s+(?:a\s+|an\s+|the\s+)?/i,/^(?:depicting|featuring|showing|capturing|illustrating|showcasing|presenting|portraying|conveying|highlighting|symbolizing|symbolising|representing|displaying|revealing|captured|shown|depicted|featured)\s+(?:a\s+|an\s+|the\s+)?/i,/^(?:this|that|the)\s+(?:image|photo|picture|render|illustration|clip|video|footage)\s+is\s+/i],Ec=s=>{let i=String(s??"").replace(/\s+/g," ").trim();if(!i)return"";for(let r=0;r<3;r+=1){const l=i;for(const c of Dp)i=i.replace(c,"");if(i=i.replace(/^[,;:\-\s]+/,"").trim(),i===l)break}return/^[a-z]/.test(i)&&(i=i.charAt(0).toUpperCase()+i.slice(1)),i},ja=s=>{if(!s)return"";const i=Ca(s).split(/[.!?]+/).map(p=>p.trim()).filter(Boolean),l=i.map(p=>Ca(p)).map(p=>Ec(p)).filter(Boolean).filter(p=>{const x=p.toLowerCase();return!(x.startsWith("image can be used")||x.includes("stock video")||x.includes("stock footage")||x.includes("stock photo")||x.includes("stock image")||x.includes("perfect for")||x.includes("ideal for")||x.includes("suitable for"))}).join(". ").trim();if(l)return Sr(l);const c=i.map(p=>Ca(p)).map(p=>Ec(p)).map(p=>p.trim()).find(Boolean);return Sr(String(c??"").trim())},Ip=(s,i)=>{const r=(s||"").trim(),l=ja(i||"");if(r&&!l)return r;if(!r&&l)return l;if(!r&&!l)return"";const c=r.toLowerCase();return l.toLowerCase().startsWith(c),l},cs=(s,i,r=yn)=>{if(!s)return"";const l=s.trim().replace(/\s+/g," ");if(!i||l.length<=i)return l;const c=l.length>i,p=l.charAt(i),x=l.charAt(i-1),k=c&&/[\w\p{L}]/u.test(p)&&/[\w\p{L}]/u.test(x),R=l.slice(0,i),E=r.map($=>R.lastIndexOf($)).filter($=>$>=0),b=E.length>0?Math.max(...E):-1,g=kp.map($=>R.lastIndexOf($)).reduce(($,O)=>O>$?O:$,-1),z=R.lastIndexOf(" ");let D;b>=0&&i-b<=20?D=b+1:k&&g>0?D=g:z>=0?D=z:D=i;let S=R.slice(0,D).trim();if(S||(S=R.trim()),S||(S=l.slice(0,i).trim()),S=_a(S),S=bn(S),c){S=S.replace(/\b(and|or|with|to|of|for|in)$/i,"").trim();const $=Tp(S);if($.length>1){const O=[];let re=0;for(let V=0;V<$.length;V+=1){const L=$[V],ae=L.length+(O.length>0?2:0);if(ae+re<=i)O.push(L),re+=ae;else break}S=O.join(", ").trim();const ge=S.split(/\s+/);ge.length>2&&ge[ge.length-1].match(/^(shot|photo|image|concept|ingredient|style)$/i)&&(ge.pop(),S=ge.join(" ").trim())}}return S||l.slice(0,i).trim()},Rp=(s,i,r=yn)=>{if(!s)return"";const l=s.trim().replace(/\s+/g," ");if(!i||l.length<=i)return l;const c=l.lastIndexOf(".",i);if(c>0){const p=l.slice(0,c+1).trim(),x=Math.min(80,Math.floor(i*.4));if(p.length>=x)return p}return cs(l,i,r)},Mp=(s,i,r,l,c=0)=>{const p=ws(String(s??"").trim()),x=ws(String(i??"").trim()),k=mi(p),R=mi(x),E=!!k&&!!R&&(R===k||R.startsWith(k)||k.startsWith(R)),b=Math.min(Math.max(40,Math.floor((l||0)*.45)),l||0),g=c>0?Math.min(c,l||c):b,z=` ${R} `,D=(r??[]).map(O=>String(O??"").trim()).filter(Boolean).filter(O=>{const re=mi(O);return!!re&&!z.includes(` ${re} `)}).slice(0,12);if(!x&&!p)return"";if(!E&&x.length>=g)return x;const S=x||(p?bn(_a(p)):"");let $=S;if(D.length>0&&$.length<g){const O=D.slice(0,8),re=`Key concepts include ${_p(O)}
11.`,ge=ws([S,re].filter(Boolean).join(" ").replace(/\s{2,}/g," ").trim());$=ge.length<=l?ge:S}return $=ws($),$.length<=l?$:cs($,l)},Bp=(s,i,r,l,c,p)=>{const x=String(s??"").trim().replace(/\s{2,}/g," ");if(!x)return"";const k=cs(x,c,p);if(!l||k.length>=l||k.length>=c)return k;const R=mi(k),E=new Set(R.split(" ").filter(S=>S.length>2)),b=S=>{if(!S)return!1;if(S===R||S.startsWith(R)||R.startsWith(S))return!0;const $=S.split(" ").filter(re=>re.length>2);if($.length<4)return!1;const O=$.filter(re=>E.has(re)).length;return O>=4&&O/$.length>=.6};new Set(R.split(" ").map(S=>S.trim()).filter(Boolean));const z=[...ja(i||"").split(/[.!?]+/).map(S=>_a(Ca(S))).map(S=>S.replace(/\s{2,}/g," ").trim()).filter(Boolean).filter(S=>{const $=mi(S);return!!$&&!b($)})];let D=k;for(const S of z){const $=/[,:;]$/.test(D)?" ":", ",O=`${D}${$}${S}`.replace(/\s{2,}/g," ").trim(),re=cs(O,c,p);if(!(!re||re===D)&&(D=re,D.length>=l||D.length>=c))break}return D},Ks=s=>{const i=new Set,r=[];return s.forEach(l=>{const c=l.trim();if(!c)return;const p=c.toLowerCase();i.has(p)||(i.add(p),r.push(c))}),r},Wo=s=>s?s.split(/[,;\n]/).map(i=>i.trim()).filter(Boolean):[],Lp=s=>{const i=(s??"").toString();try{return i.normalize("NFKD").replace(new RegExp("\\p{M}+","gu"),"")}catch{return i}},zs=s=>{const i=Lp(String(s??"")).trim().toLowerCase();return i?i.replace(/[^\p{L}\p{N}]+/gu,""):""},Fp=s=>{const i=new Set;for(const r of s){const l=String(r??"").trim();if(!l||!/\s/.test(l))continue;const c=l.split(/[\s_\-\u2010\u2011\u2012\u2013\u2014]+/).map(p=>p.trim()).filter(Boolean);for(const p of c){const x=zs(p);x&&i.add(x)}}return i.size===0?s:s.filter(r=>{const l=String(r??"").trim();if(!l)return!1;if(/\s/.test(l))return!0;const c=zs(l);return!c||!i.has(c)})},vr=s=>String(s??"").trim().replace(/[\s_\-\u2010\u2011\u2012\u2013\u2014]+/g," ").replace(/\s{2,}/g," ").trim(),Pp=new Set(["a","an","and","as","at","by","for","from","in","into","of","on","or","the","to","with","without"].map(s=>zs(s)).filter(Boolean)),ld=s=>{const i=zs(s);return!!i&&Pp.has(i)},kr=s=>{const i=vr(s).split(" ").map(r=>r.trim()).filter(Boolean);return i.length===0?!0:i.every(r=>ld(r))},_c=(s,i)=>{const r=i?.singleWordOnlyPlatform===!0;if(!(r||i?.singleWordMode===!0))return Ks(s);const c=!r&&i?.allowCompoundKeywords===!0,p=new Set,x=[],k=[],R=(z,D)=>{const S=vr(D);if(!S||kr(S))return;const $=S.toLowerCase();p.has($)||(p.add($),z.push(S))};new Set(["food","background","backdrop","concept","design","style","pattern","texture","template","banner"].map(z=>zs(z)).filter(Boolean));const E=new Set(["full hd","ultra hd","post production"].map(z=>vr(z).toLowerCase()).filter(Boolean)),b=z=>{const D=vr(z).toLowerCase();return!!D&&E.has(D)},g=z=>{const D=vr(z).split(" ").filter(Boolean);return D.length<2||D.length>3?!1:D.every(S=>S.length>=2&&!ld(S))};for(const z of s){const D=vr(z);if(D){if(/\s/.test(D)){if(r)continue;if(c&&k.length<6&&g(D)){R(k,D);continue}c&&b(D)&&R(x,D);continue}R(x,D)}}return c?[...x,...k]:x},Kp=(s,i)=>{if(!s)return"";const r=s.trim();if(!r||/^(__EMPTY__|live empty)$/i.test(r))return"";if(i.categoryMap){const l=r.toLowerCase(),c=i.categoryMap[l]||i.categoryMap[r];if(c)return c}return r},$p=(s,i,r={})=>{const l=r.endings||i.titleEndings||yn,c=Array.isArray(s.keywords)?s.keywords:[],p=Ks(c),x=r.keywordSettings,R=x?.singleWordOnlyPlatform===!0||x?.singleWordMode===!0,E=Wo(x?.excludedKeywords),b=new Set(E.map(j=>j.toLowerCase())),g=p.filter(j=>!b.has(j.toLowerCase())&&!kr(j)),z=R?g:Fp(g);let D=Wo(x?.requiredStartingKeywords),S=Wo(x?.requiredEndingKeywords);D=Ks(D).filter(j=>!b.has(j.toLowerCase())&&!kr(j)),S=Ks(S).filter(j=>!b.has(j.toLowerCase())&&!kr(j));const $=z.filter(j=>{const H=j.toLowerCase();return!D.some(J=>J.toLowerCase()===H)&&!S.some(J=>J.toLowerCase()===H)}),O=[],re=new Set,ge=j=>{const H=j.trim();if(!H)return;const J=H.toLowerCase();re.has(J)||(re.add(J),O.push(H))};
11D.forEach(ge),$.forEach(ge),S.forEach(ge);const V=Math.max(i.maxKeywords||0,0);let L;if(V>0&&O.length>V){const j=[],H=new Set,J=ve=>{const _=ve.trim();if(!_)return;const U=_.toLowerCase();H.has(U)||(H.add(U),j.push(_))};if(D.forEach(J),S.forEach(J),j.length>=V)L=j.slice(0,V);else{const ve=new Set(j.map(ee=>ee.toLowerCase())),U=O.filter(ee=>!ve.has(ee.toLowerCase())).slice(0,V-j.length);L=[...j,...U]}}else L=O;L=_c(L,x),L=Ks(L).filter(j=>!kr(j)),L=L.map(j=>Ep(j,{preserveSingleWord:R})),L=L.filter(j=>!Sp(j)),L=Ks(L),V>0&&L.length>V&&(L=L.slice(0,V));const ae=new Set([...D,...S].map(j=>String(j||"").trim().toLowerCase()).filter(Boolean)),he=new Set(["food","background","backdrop","concept","design","style","pattern","texture","template","banner","wallpaper","illustration","art"].map(j=>zs(j)).filter(Boolean)),ne=j=>{const H=String(j??"").trim();if(!H||/\s/.test(H))return!1;const J=zs(H);return!!J&&he.has(J)},ie=V>0?Math.min(V,O.length):L.length;if(L=L.filter(j=>{const H=String(j||"").trim().toLowerCase();return ae.has(H)?!0:!ne(j)}),V>0&&L.length<ie){const j=Ks(_c(O,x)).filter(J=>!b.has(J.toLowerCase())&&!kr(J)),H=new Set(L.map(J=>J.toLowerCase()));for(const J of j){if(L.length>=ie)break;const ve=J.toLowerCase();H.has(ve)||!ae.has(ve)&&ne(J)||(H.add(ve),L.push(J))}}V>0&&L.length>V&&(L=L.slice(0,V));const De=new Set(L.map(j=>j.toLowerCase())),Q=O.filter(j=>!De.has(j.toLowerCase())),ye=Q;let xe=Kp(r.category??s.categories,i);if(!xe&&i.autoInferCategory&&r.inferCategory){const j=r.inferCategory({title:s.title||"",description:s.description||"",keywords:p});j&&(xe=j.trim())}const je=(r.platformKey||"").toLowerCase();let Me=Sr(ws(ja(s.description||"")));const Ge=je.includes("shutterstock");Ge&&(Me=Ip(s.title||"",Me)),Me=Sr(ws(ja(Me))),Me=Sr(ws(Mp(s.title||"",Me,L,i.descriptionMaxLength,i.descriptionMinLength??0)));const pt=Ge?Rp(Me,i.descriptionMaxLength,l):cs(Me,i.descriptionMaxLength,l);let it=Ap(ws(bn(Sr(pt))),i.descriptionMaxLength);i.descriptionMaxLength&&it.length>i.descriptionMaxLength&&(it=cs(it,i.descriptionMaxLength,l));const Be=typeof i.titleMinLength=="number"&&Number.isFinite(i.titleMinLength)&&i.titleMinLength>0?Math.min(i.titleMaxLength,Math.max(1,Math.floor(i.titleMinLength))):0;let bt=Bp(s.title||"",it||s.description||"",L,Be,i.titleMaxLength,l);return i.titleMaxLength&&bt.length>i.titleMaxLength&&(bt=cs(bt,i.titleMaxLength,l)),{title:bt,description:it,keywords:L,hiddenKeywords:ye,overflowKeywords:Q,category:xe}},fr=(s,i,r)=>Math.min(r,Math.max(i,s)),Op=s=>{let i=2166136261;for(let r=0;r<s.length;r++)i^=s.charCodeAt(r),i=Math.imul(i,16777619);return(i>>>0)/4294967295},fa=({label:s,value:i,animate:r=!1,seed:l="",size:c="md"})=>{const p=Op(l||s),x=fr(i,0,100),[k,R]=d.useState(()=>x),E=d.useRef(x),b=d.useRef(null),g=d.useRef(null);d.useEffect(()=>{E.current=k},[k]),d.useEffect(()=>{if(r)return;g.current!=null&&(window.clearInterval(g.current),g.current=null);const he=E.current,ne=x,ie=520,De=performance.now();b.current!=null&&window.cancelAnimationFrame(b.current);const Q=ye=>{const xe=fr((ye-De)/ie,0,1),je=1-Math.pow(1-xe,3),Me=he+(ne-he)*je;R(Me),xe<1?b.current=window.requestAnimationFrame(Q):b.current=null};return b.current=window.requestAnimationFrame(Q),()=>{b.current!=null&&window.cancelAnimationFrame(b.current),b.current=null}},[r,x]),d.useEffect(()=>{if(!r){g.current!=null&&(window.clearInterval(g.current),g.current=null);return}b.current!=null&&(window.cancelAnimationFrame(b.current),b.current=null);let he=p*Math.PI*2;const ne=.42+p*.35,ie=fr(8+p*12,0,35),De=fr(92-p*10,65,100),Q=10+p*10,ye=48;return g.current!=null&&window.clearInterval(g.current),g.current=window.setInterval(()=>{he+=ne;const xe=(Math.sin(he)+1)/2,je=ie+xe*(De-ie),Me=(Math.random()-.5)*Q,Ge=fr(je+Me,2,98);R(Ge)},ye),()=>{g.current!=null&&(window.clearInterval(g.current),g.current=null)}},[r,x,p]);const z=fr(k,0,100),D=Math.round(z),S=Math.PI*(1-z/100),$=32,O=50,re=46,ge=O+$*Math.cos(S),V=re-$*Math.sin(S),L=c==="sm",ae=`sg_${s.replace(/\s+/g,"_")}_${l.slice(0,8)}`;return e.jsxs("div",{className:mt("rounded-xl border shadow-sm flex flex-col items-center",L?"px-2 py-1.5":"px-3 py-3"),style:{background:"var(--cs-bg-card)",borderColor:"var(--cs-border)"},children:[e.jsx("div",{className:mt("font-bold tracking-wide uppercase text-center",L?"text-[9px]":"text-[11px]"),style:{color:"var(--cs-text-primary)"},children:s}),e.jsxs("div",{className:mt("flex items-center justify-center gap-2",L?"mt-0.5":"mt-1"),children:[e.jsxs("svg",{width:L?52:86,height:L?32:54,viewBox:"0 0 100 60",className:"shrink-0",style:{filter:r?"drop-shadow(0 10px 20px rgba(123,97,255,0.18))":void 0},children:[e.jsx("defs",{children:e.jsxs("linearGradient",{id:ae,x1:"0",y1:"0",x2:"100",y2:"0",gradientUnits:"userSpaceOnUse",children:[e.jsx("stop",{stopColor:"#ef4444",offset:"0"}),e.jsx("stop",{stopColor:"#f59e0b",offset:"0.5"}),e.jsx("stop",{stopColor:"#10b981",offset:"1"})]})}),e.jsx("path",{d:"M10 46 A40 40 0 0 1 90 46",fill:"none",stroke:"var(--cs-border)",strokeWidth:"10",strokeLinecap:"round"}),e.jsx("path",{d:"M10 46 A40 40 0 0 1 90 46",fill:"none",stroke:`url(#${ae})`,strokeWidth:"10",strokeLinecap:"round",pathLength:100,strokeDasharray:"100",strokeDashoffset:100-z,style:{transition:r?"none":"stroke-dashoffset 520ms cubic-bezier(0.22, 1, 0.36, 1)"}}),e.jsx("circle",{cx:"50",cy:"46",r:"4",fill:"var(--cs-text-primary)",o
11pacity:"0.5"}),e.jsx("line",{x1:"50",y1:"46",x2:ge,y2:V,stroke:"var(--cs-text-primary)",strokeWidth:"2.5",strokeLinecap:"round",opacity:"0.5"})]}),e.jsxs("div",{className:"min-w-0",children:[e.jsx("div",{className:mt("font-extrabold tracking-tight",L?"text-base":"text-2xl"),style:{color:x>=80?"var(--cs-green-400, #10b981)":x>=60?"var(--cs-amber-400, #f59e0b)":"#ef4444"},children:D}),!L&&e.jsx("div",{className:"text-[11px]",style:{color:"var(--cs-text-tertiary)"},children:"out of 100"})]})]})]})},zp=s=>s.replace(/[—–-]/g," ").replace(/[•;|]+/g," ").replace(/\s{2,}/g," ").trim(),Up=2166136261,qp=16777619;function Vp(s){let i=Up>>>0;for(let r=0;r<s.length;r+=1)i^=s.charCodeAt(r),i=Math.imul(i,qp)>>>0;return i>>>0}function Wp(s){return Vp(s)/4294967295}function _t(s,i,r){if(i>r&&([i,r]=[r,i]),i===r)return i;const l=Wp(s);return i+(r-i)*l}const cd="cs.releases.recents.v1",Hp=8;function Ac(s){if(!s)return{};if(typeof s=="object")return s;if(typeof s=="string")try{const i=JSON.parse(s);return i&&typeof i=="object"?i:{}}catch{return{}}return{}}function Tc(s){const i=String(s??"").trim();return i==="manual"||i==="bulk"||i==="suggested"||i==="face_suggested"||i==="imported"||i==="batch_auto"?i:"manual"}function Dc(){try{const s=localStorage.getItem(cd);if(!s)return[];const i=JSON.parse(s);return Array.isArray(i)?i.map(r=>String(r)).filter(Boolean):[]}catch{return[]}}function Gp(s){try{localStorage.setItem(cd,JSON.stringify(s))}catch{}}const Pe=Uu((s,i)=>({loading:!1,linksByImageId:{},suggestionsByImageId:{},suggestionStatusByImageId:{},suggestionNotesByImageId:{},requiredByImageId:{},recentReleaseIds:[],setLoading:r=>s({loading:r}),setLinksFromAssignments:r=>{const l={};for(const c of r){const p=String(c.session_image_id||""),x=String(c.release_id||"");if(!p||!x)continue;const k={assignmentId:String(c.id||`${p}:${x}`),releaseId:x,linkType:Tc(c.link_type),assignedAt:c.assigned_at??null};l[p]||(l[p]=[]),l[p].push(k)}s({linksByImageId:l})},upsertLinksFromAssignments:r=>{const c={...i().linksByImageId};for(const p of r){const x=String(p.session_image_id||""),k=String(p.release_id||"");if(!x||!k)continue;const R={assignmentId:String(p.id||`${x}:${k}`),releaseId:k,linkType:Tc(p.link_type),assignedAt:p.assigned_at??null},E=c[x]?[...c[x]]:[],b=E.findIndex(g=>g.releaseId===k);b>=0?E[b]=R:E.unshift(R),c[x]=E}s({linksByImageId:c})},removeLinks:({sessionImageIds:r,releaseIds:l})=>{const p={...i().linksByImageId},x=new Set(l);for(const k of r){const R=p[k];R&&(p[k]=R.filter(E=>!x.has(E.releaseId)))}s({linksByImageId:p})},hydrateFlagsFromImages:r=>{const l={},c={},p={},x={};for(const k of r){const R={...Ac(k.metadata),...Ac(k.meta_json)};!!R.release_required&&(l[k.id]=!0);const b=R.release_suggestions;if(Array.isArray(b)){const D=b.map(S=>{const $=String(S?.release_id??S?.releaseId??"").trim();if(!$)return null;const O=Math.max(0,Math.min(1,Number(S?.confidence??0))),re=String(S?.source??"suggested").trim();return{releaseId:$,confidence:O,source:re==="face_suggested"||re==="batch_auto"||re==="suggested"?re:"suggested"}}).filter(Boolean);D.length>0&&(c[k.id]=D)}const g=String(R.release_suggestions_status??"").trim().toLowerCase();g==="high_confidence"||g==="suggested"||g==="conflict"||g==="no_match"?x[k.id]=g:Object.prototype.hasOwnProperty.call(R,"release_suggestions_status")&&(x[k.id]=null);const z=R.release_suggestions_note;typeof z=="string"&&z.trim()?p[k.id]=z.trim():k.id&&Object.prototype.hasOwnProperty.call(R,"release_suggestions_note")&&(p[k.id]=null)}s(k=>({requiredByImageId:{...k.requiredByImageId,...l},suggestionsByImageId:{...k.suggestionsByImageId,...c},suggestionNotesByImageId:{...k.suggestionNotesByImageId,...p},suggestionStatusByImageId:{...k.suggestionStatusByImageId,...x}}))},mergeSuggestionsFromScanResults:r=>{const l={},c={},p={};for(const x of r||[]){const k=String(x.session_image_id||"").trim();if(!k)continue;const R=x.suggestions;Array.isArray(R)?l[k]=R.map(g=>{const z=String(g?.release_id??g?.releaseId??"").trim();if(!z)return null;const D=Math.max(0,Math.min(1,Number(g?.confidence??0))),S=String(g?.source??"face_suggested").trim();return{releaseId:z,confidence:D,source:S==="face_suggested"||S==="batch_auto"||S==="suggested"?S:"face_suggested"}}
11).filter(Boolean):l[k]=[];const E=x.note;c[k]=typeof E=="string"?E:null;const b=String(x.status??"").trim().toLowerCase();p[k]=b==="high_confidence"||b==="suggested"||b==="conflict"||b==="no_match"?b:null}s(x=>({suggestionsByImageId:{...x.suggestionsByImageId,...l},suggestionNotesByImageId:{...x.suggestionNotesByImageId,...c},suggestionStatusByImageId:{...x.suggestionStatusByImageId,...p}}))},setReleaseRequiredLocal:(r,l)=>s(c=>({requiredByImageId:{...c.requiredByImageId,[r]:l}})),loadRecentFromStorage:()=>s({recentReleaseIds:Dc()}),pushRecent:r=>{const l=i().recentReleaseIds.length?i().recentReleaseIds:Dc(),c=[r,...l.filter(p=>p!==r)].slice(0,Hp);Gp(c),s({recentReleaseIds:c})}})),Yp=[],Xp=[];function Jp(s){return s==="adobe"?"adobe":s==="shutterstock"?"shutterstock":s==="pond5"?"pond5":s==="getty"||s==="istock"?"getty":null}function Ho({type:s}){const i=s==="property"?"PR":"MR";return e.jsx("span",{className:"text-[10px] font-extrabold tracking-wide px-2 py-0.5 rounded-full",style:{background:s==="property"?"rgba(96,165,250,.14)":"rgba(124,92,255,.14)",border:s==="property"?"1px solid rgba(96,165,250,.28)":"1px solid rgba(124,92,255,.28)",color:s==="property"?"var(--cs-blue-400)":"var(--cs-purple-300)"},children:i})}function Zp({release:s}){const i=[{key:"adobe",label:"Ad"},{key:"shutterstock",label:"Sh"},{key:"pond5",label:"P5"},{key:"getty",label:"Gt"}],r=l=>l==="ready"?{bg:"rgba(34,197,94,.10)",color:"var(--cs-green-400)",border:"rgba(34,197,94,.20)"}:l==="needs_review"?{bg:"rgba(245,158,11,.10)",color:"var(--cs-amber-400)",border:"rgba(245,158,11,.22)"}:l==="unsupported_for_platform"?{bg:"rgba(255,255,255,.06)",color:"var(--cs-text-tertiary)",border:"var(--cs-border)"}:{bg:"rgba(239,68,68,.10)",color:"var(--cs-red-400)",border:"rgba(239,68,68,.22)"};return e.jsx("div",{className:"flex items-center gap-1 flex-wrap",children:i.map(({key:l,label:c})=>{const p=hi(s,l),x=r(p.status),k=p.issues.length?p.issues.join(", "):p.status==="ready"?"Ready":p.status.replace(/_/g," ");return e.jsx("span",{className:"text-[10px] font-semibold px-1.5 py-0.5 rounded-full",style:{background:x.bg,color:x.color,border:`1px solid ${x.border}`},title:k,children:c},l)})})}function Qp(s){const{userId:i,sessionId:r,sessionImageId:l,platformId:c}=s,{toast:p}=Ea(),x=Xc(),k=Os(_=>_.releases),R=Os(_=>_.persons),E=Pe(_=>_.linksByImageId[l]??Yp),b=Pe(_=>!!_.requiredByImageId[l]),g=Pe(_=>_.suggestionsByImageId[l]??Xp),z=Pe(_=>_.suggestionNotesByImageId[l]||null),D=Pe(_=>_.recentReleaseIds),S=Pe(_=>_.setReleaseRequiredLocal),$=Pe(_=>_.upsertLinksFromAssignments),O=Pe(_=>_.removeLinks),re=Pe(_=>_.pushRecent),ge=Pe(_=>_.mergeSuggestionsFromScanResults),[V,L]=d.useState(""),[ae,he]=d.useState("all"),[ne,ie]=d.useState(null),[De,Q]=d.useState(!1),[ye,xe]=d.useState(!1),je=d.useMemo(()=>new Set(E.map(_=>_.releaseId)),[E]),Me=d.useMemo(()=>{const _=new Map(k.map(U=>[U.id,U]));return E.map(U=>{const ee=_.get(U.releaseId);return ee?{link:U,release:ee}:null}).filter(Boolean)},[E,k]),Ge=d.useMemo(()=>{const _=new Map(k.map(U=>[U.id,U]));return g.map(U=>{const ee=_.get(U.releaseId);return ee?{suggestion:U,release:ee}:null}).filter(Boolean)},[g,k]),pt=d.useMemo(()=>{const _=new Map(k.map(U=>[U.id,U]));return D.map(U=>_.get(U)).filter(Boolean)},[D,k]),it=d.useMemo(()=>{const _=V.trim().toLowerCase(),U=new Map(R.map(ee=>[ee.id,ee]));return k.filter(ee=>ae==="all"?!0:ee.type===ae).filter(ee=>{if(!_)return!0;const ze=ee.person_id?U.get(ee.person_id):null;return ee.display_name.toLowerCase().includes(_)||(ee.legal_name||"").toLowerCase().includes(_)||(ze?.display_name||"").toLowerCase().includes(_)}).slice(0,12)},[V,k,ae,R]),Be=Jp(c),bt=d.useMemo(()=>{if(!Be)return!1;for(const{release:_}of Me)if(hi(_,Be).status!=="ready")return!0;return!1},[Me,Be]),j=async(_,U)=>{ie(`attach:${_.join(",")}`);try{const ee=await Dt.attachReleasesToImages({userId:i,sessionId:r,sessionImageIds:[l],releaseIds:_,linkType:U});$(ee);for(const ze of _)re(ze);p({title:"Release attached",description:_.length===1?"Attached to current asset.":`Attached ${_.length} releases.`}),s.onAttached?.()}catch(ee){p({title:"Attach failed",description:ee?.message||"Could not attach release",variant:"destructive"})}finally{ie(null)}},H=async _=>{const U=g.filter(ee=>ee.releaseId!==_);ie(`dismiss:${_}`);try{await we.patchSessionImageMeta(l,{release_suggestions:U.map(ee=>({release_id:ee.releaseId,confidence:ee.confidence,source:ee.source})),release_suggestions_status:U.length>0?"suggested":"no_match"}),ge([{session_image_id:l,suggestions:U.map(ee=>({release_id:ee.releaseId,confidence:ee.confidence,source:ee.source})),note:z,status:U.length>0?"suggested":"no_match"}]),p({title:"Suggestion dismissed",description:"Removed from this asset."})}catch(ee){p({title:"Dismiss failed",description:ee?.message||"Could not update asset",variant:"destructive"})}finally{ie(null)}},J=async _=>{ie(`detach:${_}`);try{await Dt.detachReleasesFromImages({userId:i,sessionImageIds:[l],releaseIds:[_]}),O({sessionImageIds:[l],releaseIds:[_]}),p({title:"Release detached",description:"Removed from current asset."})}catch(U){p({title:"Detach failed",description:U?.message||"Could not detach release",variant:"destructive"})}finally{ie(null)}},ve=async _=>{ie("required"),S(l,_);try{await we.patchSessionImageMeta(l,{release_required:_}),p({title:_?"Release required":"Release not required",description:"Saved for this asset."})}catch(U){S(l,b),p({title:"Save failed",description:U?.message||"Could not save flag",variant:"destructive"})}finally{ie(null)}};return e.jsxs("div",{className:"w-full max-w-[calc(100vw-24px)]",children:[e.jsxs("div",{className:"flex items-start justify-between gap-3 pb-3",children:[e.jsxs("div",{className:"min-w-0",children:[e.jsxs("div",{className:"text-[13px] font-semibold",style:{color:"var(--cs-text-primary)"},children:["Releases",bt&&e.jsx("span",{className:"ml-2 text-[11px] font-semibold",style:{color:"var(--cs-amber-400)"},children:"Needs review"})]}),e.jsx("div",{className:"text-[11px]",style:{color:"var(--cs-text-tertiary)"},children:"Attach / detach releases for the current asset"})]}),e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(K,{size:"sm",variant:"outline",className:"h-8",onClick:()=>x("/releases"),children:"Manage"}),s.faceMatchEnabled&&e.jsxs("div",{className:"flex items-center gap-1",children:[e.jsxs(K,{size:"sm",variant:"outline",className:"h-8",disabled:!!s.scanBusy||!s.onScanAsset,onClick:()=>s.onScanAsset?.(),title:"Scan current asset for face-based suggestions",children:[e.jsx(bs,{className:"h-3.5 w-3.5 mr-1.5"}),"Scan"]}),e.jsx(K,{size:"sm",variant:"outline",className:"h-8",disabled:!!s.scanBusy||!s.onScanSession,onClick:()=>s.onScanSession?.(),title:"Scan the entire session",children:"Session"}),e.jsx(K,{size:"sm",variant:"ghost",className:"h-8",disabled:!s.onOpenScanResults,onClick:()=>s.onOpenScanResults?.(),title:"View last scan results",children:"Results"})]}),e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx("span",{className:"text-[11px] font-medium",style:{color:"var(--cs-text-secondary)"},children:"Required"}),e.jsx(Jc,{checked:b,onCheckedChange:ve,disabled:ne==="required"})]})]})]}),e.jsx(Zc,{}),e.jsx(Om,{className:"max-h-[520px] pr-2",children:e.jsxs("div",{className:"space-y-4 pt-3",children:[e.jsxs("div",{className:"space-y-2",children:[e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsx("div",{className:"text-[11px] font-bold uppercase tracking-wide",style:{color:"var(--cs-text-secondary)"},children:"Attached Releases"}),e.jsx("div",{className:"text-[11px] font-semibold",style:{color:"var(--cs-text-tertiary)"},children:Me.length})]}),Me.length===0?e.jsx("div",{className:"rounded-lg px-3 py-2 text-[12px]",style:{background:"var(--cs-bg-card)",border:"1px solid var(--cs-border)",color:"var(--cs-text-tertiary)"},children:"No releases attached."}):e.jsx("div",{className:"space-y-2",children:Me.map(({link:_,release:U})=>e.jsxs("div",{className:"rounded-xl px-3 py-2 flex items-start gap-3",style:{background:"var(--cs-bg-card)",border:"1px solid var(--cs-border)"},children:[e.jsx("div",{className:"pt-0.5",children:e.jsx(Ho,{type:U.type})}),e.jsxs("div",{className:"flex-1 min-w-0",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx("div",{className:"text-[13px] font-semibold truncate",style:{color:"var(--cs-text-primary)"},children:U.display_name}),e.jsx("span",{className:"text-[10px] font-semibold px-1.5 py-0.5 rounded-full",style:{background:"rgba(255,255,255,.06)",border:"1px solid var(--cs-border)",color:"var(--cs-text-tertiary)"},title:"Link type",children:_.linkType})]}),U.person?.display_name&&e.jsx("div",{className:"text-[11px] truncate",style:{color:"var(--cs-text-tertiary)"},children:U.person.display_name}),e.jsx("div",{className:"mt-1",children:e.jsx(Zp,{release:U})})]}),e.jsx(K,{variant:"ghost",size:"icon",className:"h-7 w-7",disabled:ne===`detach:${U.id}`,onClick:()=>J(U.id),title:"Detach",children:e.jsx(zm,{className:"h-3.5 w-3.5"})})]},`${U.id}:${_.assignmentId}`))})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx("div",{className:"flex items-center justify-between",children:e.jsx("div",{className:"text-[11px] font-bold uppercase tracking-wide",style:{color:"var(--cs-text-secondary)"},children:"Suggested Releases"})}),z&&e.jsx("div",{className:"rounded-lg px-3 py-2 text-[12px]",style:{background:"rgba(255,255,255,.06)",border:"1px solid var(--cs-border)",color:"var(--cs-text-tertiary)"},children:z}),Ge.length===0?e.jsx("div",{className:"rounded-lg px-3 py-2 text-[12px]",style:{background:"var(--cs-bg-card)",border:"1px solid var(--cs-border)",color:"var(--cs-text-tertiary)"},children:"No suggestions yet."}):e.jsx("div",{className:"space-y-2",children:Ge.filter(({release:_})=>!je.has(_.id)).map(({release:_,suggestion:U})=>e.jsxs("div",{className:"rounded-xl px-3 py-2 flex items-center gap-3",style:{background:"rgba(245,158,11,.06)",border:"1px solid rgba(245,158,11,.20)"},children:[e.jsx(Ho,{type:_.type}),e.jsxs("div",{className:"flex-1 min-w-0",children:[e.jsx("div",{className:"text-[13px] font-semibold truncate",style:{color:"var(--cs-text-primary)"},children:_.display_name}),e.jsxs("div",{className:"text-[11px]",style:{color:"var(--cs-text-tertiary)"},children:["Confidence ",(U.confidence*100).toFixed(0),"% · ",U.source]})]}),e.jsx(K,{size:"icon",variant:"ghost",className:"h-8 w-8",disabled:ne===`dismiss:${_.id}`,onClick:()=>H(_.id),title:"Dismiss suggestion",children:e.jsx(At,{className:"h-3.5 w-3.5"})}),e.jsxs(K,{size:"sm",variant:"outline",className:"h-8",disabled:ne===`attach:${_.id}`,onClick:()=>j([_.id],U.source==="face_suggested"?"face_suggested":"suggested"),children:[e.jsx(xt,{className:"h-3 w-3 mr-1"}),"Attach"]})]},`s:${_.id}`))})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx("div",{className:"flex items-center justify-between",children:e.jsx("div",{className:"text-[11px] font-bold uppercase tracking-wide",style:{color:"var(--cs-text-secondary)"},children:"Recent Releases"})}),pt.length===0?e.jsx("div",{className:"rounded-lg px-3 py-2 text-[12px]",style:{background:"var(--cs-bg-card)",border:"1px solid var(--cs-border)",color:"var(--cs-text-tertiary)"},children:"No recent releases."}):e.jsx("div",{className:"flex flex-wrap gap-2",children:pt.slice(0,8).map(_=>{const U=je.has(_.id);return e.jsxs(K,{size:"sm",variant:"outline",className:"h-8",disabled:U||ne===`attach:${_.id}`,onClick:()=>j([_.id],"manual"),title:U?"Already attached":"Attach",children:[_.type==="property"?"PR":"MR"," · ",_.display_name]},`recent:${_.id}`)})})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx("div",{className:"text-[11px] font-bold uppercase tracking-wide",style:{color:"var(--cs-text-secondary)"},children:"Search Library"}),e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsxs("div",{className:"relative flex-1",children:[e.jsx(Qc,{className:"absolute left-2 top-1/2 -translate-y-1/2 h-3.5 w-3.5",
11style:{color:"var(--cs-text-tertiary)"}}),e.jsx($t,{value:V,onChange:_=>L(_.target.value),placeholder:"Search release or person",className:"h-9 pl-8",style:{background:"var(--cs-input-bg)",borderColor:"var(--cs-input-border)",color:"var(--cs-text-primary)"}})]}),e.jsxs("select",{value:ae,onChange:_=>he(_.target.value),className:"h-9 text-[12px] px-2 rounded-md",style:{background:"var(--cs-input-bg)",border:"1px solid var(--cs-input-border)",color:"var(--cs-text-primary)"},children:[e.jsx("option",{value:"all",children:"All"}),e.jsx("option",{value:"model",children:"Model"}),e.jsx("option",{value:"property",children:"Property"}),e.jsx("option",{value:"minor",children:"Minor"})]})]}),e.jsxs("div",{className:"space-y-1",children:[it.map(_=>{const U=je.has(_.id);return e.jsxs("div",{className:"rounded-lg px-3 py-2 flex items-center gap-3",style:{background:"var(--cs-bg-card)",border:"1px solid var(--cs-border)"},children:[e.jsx(Ho,{type:_.type}),e.jsxs("div",{className:"flex-1 min-w-0",children:[e.jsx("div",{className:"text-[13px] font-semibold truncate",style:{color:"var(--cs-text-primary)"},children:_.display_name}),(_.person?.display_name||_.signed_at)&&e.jsxs("div",{className:"text-[11px] truncate",style:{color:"var(--cs-text-tertiary)"},children:[_.person?.display_name?_.person.display_name:"",_.person?.display_name&&_.signed_at?" · ":"",_.signed_at?`Signed ${new Date(_.signed_at).toLocaleDateString()}`:""]})]}),e.jsx(K,{size:"sm",variant:U?"outline":"default",className:"h-8",disabled:U||ne===`attach:${_.id}`,onClick:()=>j([_.id],"manual"),style:U?{}:{background:"var(--cs-purple-400)",color:"white"},children:U?e.jsxs(e.Fragment,{children:[e.jsx(xt,{className:"h-3 w-3 mr-1"}),"Attached"]}):e.jsxs(e.Fragment,{children:[e.jsx(Qo,{className:"h-3 w-3 mr-1"}),"Attach"]})})]},`lib:${_.id}`)}),it.length===0&&e.jsx("div",{className:"rounded-lg px-3 py-2 text-[12px]",style:{background:"var(--cs-bg-card)",border:"1px solid var(--cs-border)",color:"var(--cs-text-tertiary)"},children:"No matches."})]})]}),e.jsxs("div",{className:"space-y-2 pb-1",children:[e.jsx("div",{className:"text-[11px] font-bold uppercase tracking-wide",style:{color:"var(--cs-text-secondary)"},children:"Create / Upload"}),e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsxs(K,{variant:"outline",className:"flex-1 h-9",onClick:()=>Q(!0),children:[e.jsx(Qo,{className:"h-3.5 w-3.5 mr-1.5"}),"Create New"]}),e.jsxs(K,{variant:"outline",className:"flex-1 h-9",onClick:()=>xe(!0),children:[e.jsx(Um,{className:"h-3.5 w-3.5 mr-1.5"}),"Upload"]})]})]})]})}),e.jsx(Km,{open:De,onClose:()=>Q(!1),onCreated:async _=>{Q(!1),await j([_.id],"manual")}}),e.jsx($m,{open:ye,onClose:()=>xe(!1),onCreated:async _=>{xe(!1),await j([_.id],"manual")}})]})}const eh={missing:"!",suggested:"?",multi:"2R",mr:"MR",pr:"PR"};function th({state:s,className:i}){if(s.kind==="none")return null;const r=eh[s.kind],l=s.kind==="missing",c=s.kind==="suggested",p=s.kind==="mr"||s.kind==="pr"||s.kind==="multi";return e.jsx("span",{className:mt("pointer-events-none absolute -top-1 -right-1 inline-flex h-5 min-w-5 items-center justify-center rounded-full px-1 text-[10px] font-extrabold tracking-wide",i),style:{background:l?"rgba(239,68,68,.18)":c?"rgba(245,158,11,.16)":p?"rgba(124,92,255,.16)":"rgba(255,255,255,.08)",border:l?"1px solid rgba(239,68,68,.35)":c?"1px solid rgba(245,158,11,.35)":p?"1px solid rgba(124,92,255,.35)":"1px solid rgba(255,255,255,.16)",color:l?"var(--cs-red-400)":c?"var(--cs-amber-400)":p?"var(--cs-purple-300)":"var(--cs-text-secondary)",boxShadow:"0 6px 18px rgba(0,0,0,.25)",backdropFilter:"blur(6px)"},"aria-hidden":"true",children:r})}function sh(s){return s==="adobe"?"adobe":s==="shutterstock"?"shutterstock":s==="pond5"?"pond5":s==="getty"||s==="istock"?"getty":null}function Ic(s){if(!s)return{};if(typeof s=="object")return s;if(typeof s=="string")try{const i=JSON.parse(s);return i&&typeof i=="object"?i:{}}catch{return{}}return{}}function dd(s){const i=sh(s.platformId),r={...Ic(s.metadata),...Ic(s.meta)},l=!!r?.release_required,c=!!(r?.property_release_required||r?.release_property_required),p=String(r?.release_suggestions_status??"").trim().toLowerCase(),x=Array.isArray(r?.release_suggestions)?r.release_suggestions:[],R=s.attachedReleaseIds.filter(
11Boolean).map(z=>s.releasesById.get(z)).filter(Boolean);if(R.length===0)return l?{status:"missing_release",reasons:["Release required"],blocked:!0}:p==="conflict"?{status:"ambiguous_match",reasons:["Conflicting suggestions"],blocked:!0}:x.length>=2?{status:"ambiguous_match",reasons:["Multiple suggestions"],blocked:!1}:x.length===1?{status:"needs_review",reasons:["Suggested release available"],blocked:!1}:{status:"ready",reasons:["No release required"],blocked:!1};if(R.filter(z=>z.type!=="property").length>=2)return{status:"ambiguous_match",reasons:["Multiple model releases attached"],blocked:!0};if(c&&!R.some(D=>D.type==="property"))return{status:"property_release_missing",reasons:["Property release required"],blocked:!0};if(!i)return{status:"needs_review",reasons:["Platform validation not available"],blocked:!1};const g=R.map(z=>hi(z,i)).filter(z=>z.status!=="ready");if(g.length>0){const z=g[0]?.issues?.[0]||"Release needs review",D=g.some($=>$.status==="missing_minor_info")?"minor_release_missing":"needs_review",S=g.some($=>$.status!=="needs_review");return{status:D,reasons:[z],blocked:S}}return{status:"ready",reasons:[],blocked:!1}}function rh(s){const i={ready:0,missing_release:0,needs_review:0,property_release_missing:0,minor_release_missing:0,ambiguous_match:0,total:s.length};for(const r of s)i[r.status]=(i[r.status]??0)+1;return i}function yr(s){return s==="property"?"property":"model"}function Wt({children:s}){return e.jsx("span",{className:"inline-flex items-center gap-1 rounded-full px-2 py-0.5 text-[11px] font-semibold",style:{background:"rgba(255,255,255,.06)",border:"1px solid var(--cs-border)",color:"var(--cs-text-secondary)"},children:s})}function ih(s){const{toast:i}=Ea(),r=Os(j=>j.releases),l=d.useMemo(()=>new Map(r.map(j=>[j.id,j])),[r]),c=s.targetImageIds,p=Pe(j=>j.linksByImageId),x=Pe(j=>j.suggestionsByImageId),k=Pe(j=>j.upsertLinksFromAssignments),R=Pe(j=>j.removeLinks),E=Pe(j=>j.pushRecent),[b,g]=d.useState("attach"),[z,D]=d.useState("all"),[S,$]=d.useState("skip"),[O,re]=d.useState([]),[ge,V]=d.useState(""),[L,ae]=d.useState("all"),[he,ne]=d.useState(!1),ie=d.useMemo(()=>{let j=0,H=0;const J=[];for(const ve of c){if((p[ve]||[]).length>0){j+=1;continue}const U=x[ve]||[];if(U.length===0){H+=1;continue}const ee=[...U].sort((at,ot)=>ot.confidence-at.confidence)[0];if(!ee?.releaseId){H+=1;continue}const ze=ee.source==="face_suggested"?"face_suggested":"suggested";J.push({session_image_id:ve,release_id:ee.releaseId,link_type:ze})}return{rows:J,willConfirm:J.length,skippedHasRelease:j,skippedNoSuggestion:H}},[c,p,x]),De=async()=>{if(ie.willConfirm!==0){ne(!0);try{const j=await Dt.upsertAssignments({userId:s.userId,sessionId:s.sessionId,rows:ie.rows.map(H=>({user_id:s.userId,session_id:s.sessionId,session_image_id:H.session_image_id,release_id:H.release_id,link_type:H.link_type}))});k(j);for(const H of ie.rows)E(H.release_id);i({title:"Suggestions confirmed",description:`Attached releases to ${ie.willConfirm} assets (skipped ${ie.skippedHasRelease} with releases).`}),s.onClose()}catch(j){i({title:"Confirm failed",description:j?.message||"Could not confirm suggestions",variant:"destructive"})}finally{ne(!1)}}},Q=d.useMemo(()=>{const j=new Map(r.map(H=>[H.id,H]));return O.map(H=>j.get(H)).filter(Boolean)},[O,r]),ye=d.useMemo(()=>{const j=new Set;for(const H of Q)j.add(yr(H.type));return j},[Q]),xe=d.useMemo(()=>{const j=c.map(J=>{const _=(p[J]||[]).map(ze=>ze.releaseId),U=s.imagesById?.[J]?.meta_json??null,ee=s.imagesById?.[J]?.metadata??null;return dd({platformId:s.platformId,meta:U,metadata:ee,attachedReleaseIds:_,releasesById:l})}),H=rh(j);return{ready:H.ready,missing:H.missing_release,needsReview:H.needs_review+H.minor_release_missing+H.property_release_missing,conflict:H.ambiguous_match,total:H.total}},[c,p,s.imagesById,s.platformId,l]),je=d.useMemo(()=>{let j=0,H=0,J=0,ve=0,_=0;for(const U of c){const ee=p[U]||[],ze=ee.length;ze===0&&(j+=1);const at=ee.filter(Ue=>{const ht=r.find(Re=>Re.id===Ue.releaseId);return ht?yr(ht.type)==="model":!1}).length,ot=ee.filter(Ue=>{const ht=r.find(Re=>Re.id===Ue.releaseId);return ht?yr(ht.type)==="property":!1}).length;if(at>0&&(H+=1),ot>0&&(J+=1),ye.size>0){const Ue=new Set;at>0&&Ue.add("model"),ot>0&&Ue.add("property"),Array.from(ye).some(Re=>Ue.has(Re))&&(ve+=1)}(x[U]||[]).length>0&&ze===0&&(_+=1)}return{total:c.length,withoutAny:j,withModel:H,withProperty:J,conflicts:ve,suggested:_}},[c,p,x,r,ye]),Me=d.useMemo(()=>{const j=ge.trim().toLowerCase();return r.filter(H=>L==="all"?!0:H.type===L).filter(H=>j?H.display_name.toLowerCase().includes(j)||(H.legal_name||"").toLowerCase().includes(j)||(H.person?.display_name||"").toLowerCase().includes(j):!0).slice(0,20)},[ge,r,L]),Ge=d.useMemo(()=>
11{if(b==="remove"){const U=new Set(O);let ee=0;for(const ze of c)(p[ze]||[]).some(ot=>U.has(ot.releaseId))&&(ee+=1);return{willAttach:0,willReplace:0,willRemove:ee,willSkip:je.total-ee}}const j=ye,H=b==="replace"||S==="replaceType";let J=0,ve=0,_=0;for(const U of c){const ee=p[U]||[],ze=new Set(ee.map(Re=>Re.releaseId)),at=ee.map(Re=>r.find(Ie=>Ie.id===Re.releaseId)).filter(Boolean),ot=new Set(at.map(Re=>yr(Re.type)));if(!(z==="all"?!0:z==="withoutAny"?ee.length===0:Array.from(j).some(Re=>!ot.has(Re)))){_+=1;continue}const Ue=Array.from(j).some(Re=>ot.has(Re));if(S==="skip"&&Ue){_+=1;continue}if(!O.some(Re=>!ze.has(Re))&&!H){_+=1;continue}H&&Ue&&(ve+=1),J+=1}return{willAttach:J,willReplace:ve,willRemove:0,willSkip:_}},[b,S,z,c,p,r,O,ye,je.total]),pt=d.useMemo(()=>c.length===0?!1:b==="remove"?O.length>0:b==="replace"?O.length===1:O.length>0,[c.length,b,O.length]),it=async()=>{if(pt){ne(!0);try{if(b==="remove"){await Dt.detachReleasesFromImages({userId:s.userId,sessionImageIds:c,releaseIds:O}),R({sessionImageIds:c,releaseIds:O}),i({title:"Releases removed",description:`Updated ${Ge.willRemove} assets.`}),s.onClose();return}const j=Q,H=ye,J=[],ve=new Set;for(const _ of c){const U=p[_]||[],ee=new Set(U.map(Ie=>Ie.releaseId)),ze=U.map(Ie=>r.find(Ot=>Ot.id===Ie.releaseId)).filter(Boolean),at=new Set(ze.map(Ie=>yr(Ie.type)));if(!(z==="all"?!0:z==="withoutAny"?U.length===0:Array.from(H).some(Ie=>!at.has(Ie))))continue;const Gt=Array.from(H).some(Ie=>at.has(Ie));if(S==="skip"&&Gt)continue;if((b==="replace"||S==="replaceType")&&Gt)for(const Ie of ze)H.has(yr(Ie.type))&&!O.includes(Ie.id)&&ve.add(Ie.id);!O.some(Ie=>!ee.has(Ie))&&b!=="replace"||J.push(_)}if(ve.size>0&&J.length>0){const _=Array.from(ve);await Dt.detachReleasesFromImages({userId:s.userId,sessionImageIds:J,releaseIds:_}),R({sessionImageIds:J,releaseIds:_})}if(J.length>0){const _=await Dt.attachReleasesToImages({userId:s.userId,sessionId:s.sessionId,sessionImageIds:J,releaseIds:O,linkType:"bulk"});k(_);for(const U of O)E(U)}i({title:"Releases applied",description:J.length===0?"Nothing changed.":`Updated ${J.length} assets.`}),s.onClose()}catch(j){i({title:"Bulk apply failed",description:j?.message||"Could not apply releases",variant:"destructive"})}finally{ne(!1)}}},Be=j=>{re(H=>H.includes(j)?H:[...H,j])},bt=j=>{re(H=>H.filter(J=>J!==j))};return e.jsxs("div",{className:"space-y-4",children:[e.jsxs("div",{className:"rounded-xl p-3",style:{background:"var(--cs-bg-card)",border:"1px solid var(--cs-border)"},children:[e.jsxs("div",{className:"flex flex-wrap items-center gap-2 justify-between",children:[e.jsx("div",{className:"text-[13px] font-semibold",style:{color:"var(--cs-text-primary)"},children:"Bulk Releases"}),e.jsxs("div",{className:"flex flex-wrap gap-2",children:[e.jsxs(Wt,{children:[je.total," selected"]}),e.jsxs(Wt,{children:[xe.ready," ready"]}),e.jsxs(Wt,{children:[xe.missing," missing release"]}),e.jsxs(Wt,{children:[xe.needsReview," need review"]}),xe.conflict>0&&e.jsxs(Wt,{children:[xe.conflict," conflict"]}),e.jsxs(Wt,{children:[je.withoutAny," without release"]}),e.jsxs(Wt,{children:[je.withModel," has MR"]}),e.jsxs(Wt,{children:[je.withProperty," has PR"]}),je.conflicts>0&&e.jsxs(Wt,{children:[je.conflicts," conflict"]}),je.suggested>0&&e.jsxs(Wt,{children:[je.suggested," suggested"]})]})]}),e.jsxs("div",{className:"mt-2 text-[12px]",style:{color:"var(--cs-text-tertiary)"},children:["Preview: ",Ge.willAttach?`${Ge.willAttach} will change`:"No changes yet",Ge.willReplace?` · ${Ge.willReplace} will replace matching type`:"",Ge.willRemove?` · ${Ge.willRemove} will remove`:"",Ge.willSkip?` · ${Ge.willSkip} skipped`:""]})]}),je.suggested>0&&e.jsxs("div",{className:"rounded-xl p-3",style:{background:"rgba(245,158,11,.06)",border:"1px solid rgba(245,158,11,.20)"},children:[e.jsxs("div",{className:"flex flex-wrap items-center justify-between gap-2",children:[e.jsx("div",{className:"text-[13px] font-semibold",style:{color:"var(--cs-text-primary)"},children:"Confirm Suggestions"}),e.jsxs(K,{size:"sm",className:"h-8 text-white",style:{background:ie.willConfirm>0?"var(--cs-purple-400)":void 0,opacity:ie.willConfirm>0?1:.6},disabled:he||ie.willConfirm===0,onClick:De,title:"Attach the top suggested release for each item without releases",children:[e.jsx(xt,{className:"h-4 w-4 mr-2"}),"Confirm (",ie.willConfirm,")"]})]}),e.jsxs("div",{className:"mt-2 text-[12px]",style:{color:"var(--cs-text-tertiary)"},children:["Uses each asset’s top suggested release. Applies only to items without releases. Never auto-applies without your click.",ie.skippedHasRelease>0?` Skipped ${ie.skippedHasRelease} with existing releases.`:"",ie.skippedNoSuggestion>0?` Skipped ${ie.skippedNoSuggestion} without suggestions.`:""]})]}),e.jsx("div",{className:"flex items-center gap-2",children:[{id:"attach",label:"Attach"},{id:"replace",label:"Replace Type"},{id:"remove",label:"Remove"}].map(j=>{const H=b===j.id;return e.jsx(K,{size:"sm",variant:"outline",className:"h-8",onClick:()=>{g(j.id),j.id==="replace"&&re(J=>J.length>1?J.slice(0,1):J)},style:H?{background:"rgba(124,92,255,.12)",borderColor:"rgba(124,92,255,.28)",color:"var(--cs-purple-300)"}:{},children:j.label},j.id)})}),b!=="remove"&&e.jsxs("div",{className:"grid grid-cols-1 gap-3 sm:grid-cols-2",children:[e.jsxs("div",{children:[e.jsx("div",{className:"text-[11px] font-bold uppercase tracking-wide mb-1",style:{color:"var(--cs-text-secondary)"},children:"Apply To"}),e.jsxs("select",{value:z,onChange:j=>D(j.target.value),className:"w-full h-9 text-[12px] px-2 rounded-md",style:{background:"var(--cs-input-bg)",border:"1px solid var(--cs-input-border)",color:"var(--cs-text-primary)"},children:[e.jsx("option",{value:"all",children:"All selected"}),e.jsx("option",{value:"withoutAny",children:"Only items without releases"}),e.jsx("option",{value:"missingType",children:"Only items missing selected type"})]})]}),e.jsxs("div",{children:[e.jsx("div",{className:"text-[11px] font-bold uppercase tracking-wide mb-1",style:{color:"var(--cs-text-secondary)"},children:"Conflicts"}),e.jsxs("select",{value:b==="replace"?"replaceType":S,onChange:j=>$(j.target.value),disabled:b==="replace",className:"w-full h-9 text-[12px] px-2 rounded-md",style:{background:"var(--cs-input-bg)",border:"1px solid var(--cs-input-border)",color:"var(--cs-text-primary)",o
11pacity:b==="replace"?.7:1},children:[e.jsx("option",{value:"skip",children:"Skip items with confirmed releases"}),e.jsx("option",{value:"add",children:"Add as additional"}),e.jsx("option",{value:"replaceType",children:"Replace matching type"})]})]})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsx("div",{className:"text-[11px] font-bold uppercase tracking-wide",style:{color:"var(--cs-text-secondary)"},children:b==="remove"?"Select Releases to Remove":"Select Releases to Attach"}),Q.length>0&&e.jsx("div",{className:"flex flex-wrap gap-2 justify-end",children:Q.map(j=>e.jsxs("span",{className:"inline-flex items-center gap-1 rounded-full px-2 py-1 text-[11px] font-semibold",style:{background:"rgba(124,92,255,.12)",border:"1px solid rgba(124,92,255,.25)",color:"var(--cs-purple-300)"},children:[j.type==="property"?"PR":"MR"," · ",j.display_name,e.jsx("button",{type:"button",onClick:()=>bt(j.id),className:"ml-1",children:e.jsx(At,{className:"h-3 w-3"})})]},`sel:${j.id}`))})]}),e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsxs("div",{className:"relative flex-1",children:[e.jsx(Qc,{className:"absolute left-2 top-1/2 -translate-y-1/2 h-3.5 w-3.5",style:{color:"var(--cs-text-tertiary)"}}),e.jsx($t,{value:ge,onChange:j=>V(j.target.value),placeholder:"Search release or person",className:"h-9 pl-8"})]}),e.jsxs("select",{value:L,onChange:j=>ae(j.target.value),className:"h-9 text-[12px] px-2 rounded-md",style:{background:"var(--cs-input-bg)",border:"1px solid var(--cs-input-border)",color:"var(--cs-text-primary)"},children:[e.jsx("option",{value:"all",children:"All"}),e.jsx("option",{value:"model",children:"Model"}),e.jsx("option",{value:"property",children:"Property"}),e.jsx("option",{value:"minor",children:"Minor"})]})]}),e.jsxs("div",{className:"max-h-[220px] overflow-auto rounded-xl",style:{border:"1px solid var(--cs-border)"},children:[Me.map(j=>{const H=O.includes(j.id),J=b==="replace"&&O.length>=1&&!H;return e.jsxs("div",{className:"px-3 py-2 flex items-center gap-3",style:{background:"var(--cs-bg-card)",borderBottom:"1px solid var(--cs-border)"},children:[e.jsx("span",{className:"text-[10px] font-extrabold tracking-wide px-2 py-0.5 rounded-full",style:{background:j.type==="property"?"rgba(96,165,250,.14)":"rgba(124,92,255,.14)",border:j.type==="property"?"1px solid rgba(96,165,250,.28)":"1px solid rgba(124,92,255,.28)",color:j.type==="property"?"var(--cs-blue-400)":"var(--cs-purple-300)"},children:j.type==="property"?"PR":"MR"}),e.jsxs("div",{className:"flex-1 min-w-0",children:[e.jsx("div",{className:"text-[13px] font-semibold truncate",style:{color:"var(--cs-text-primary)"},children:j.display_name}),(j.person?.display_name||j.signed_at)&&e.jsxs("div",{className:"text-[11px] truncate",style:{color:"var(--cs-text-tertiary)"},children:[j.person?.display_name?j.person.display_name:"",j.person?.display_name&&j.signed_at?" · ":"",j.signed_at?`Signed ${new Date(j.signed_at).toLocaleDateString()}`:""]})]}),e.jsx(K,{size:"sm",variant:"outline",className:"h-8",disabled:H||J,onClick:()=>Be(j.id),children:H?e.jsxs(e.Fragment,{children:[e.jsx(xt,{className:"h-3 w-3 mr-1"}),"Selected"]}):e.jsxs(e.Fragment,{children:[e.jsx(Qo,{className:"h-3 w-3 mr-1"}),"Add"]})})]},`pick:${j.id}`)}),Me.length===0&&e.jsx("div",{className:"px-3 py-3 text-[12px]",style:{color:"var(--cs-text-tertiary)",background:"var(--cs-bg-card)"},children:"No matches."})]})]}),e.jsx(Zc,{}),e.jsxs("div",{className:"flex items-center justify-between gap-3",children:[e.jsx(K,{variant:"outline",onClick:s.onClose,disabled:he,children:"Cancel"}),e.jsxs(K,{onClick:it,disabled:!pt||he,className:"text-white hover:brightness-110",style:{background:pt?b==="remove"?"var(--cs-red-500)":"var(--cs-amber-500)":void 0,opacity:pt?1:.65},children:[b==="remove"?e.jsx(ed,{className:"h-4 w-4 mr-2"}):e.jsx(xt,{className:"h-4 w-4 mr-2"}),he?"Applying…":b==="remove"?"Remove from Selected":"Apply to Selected"]})]})]})}function ah({status:s}){const i=s==="high_confidence"?{label:"High",bg:"rgba(34,197,94,.12)",border:"rgba(34,197,94,.24)",color:"var(--cs-green-400)"}:s==="suggested"?{label:"Suggested",bg:"rgba(245,158,11,.10)",border:"rgba(245,158,11,.24)",color:"var(--cs-amber-400)"}:s==="conflict"?{label:"Conflict",bg:"rgba(239,68,68,.10)",border:"rgba(239,68,68,.24)",color:"var(--cs-red-400)"}:{label:"No match",bg:"rgba(255,255,255,.06)",border:"var(--cs-border)",color:"var(--cs-text-tertiary)"};return e.jsx("span",{className:"inline-flex items-center rounded-full px-2 py-0.5 text-[10px] font-extrabold tracking-wide",style:{background:i.bg,border:`1px solid ${i.border}`,color:i.color},children:i.label})}function oh({confidence:s}){const i=Math.round(Math.max(0,Math.min(1,s))*100);return e.jsxs("span",{className:"inline-flex items-center rounded-full px-2 py-0.5 text-[10px] font-semibold",style:{background:"rgba(124,92,255,.12)",border:"1px solid rgba(124,92,255,.25)",color:"var(--cs-purple-300)"},title:`Face similarity: ${i}%`,children:[i,"%"]})}function nh(s){const{toast:i}=Ea(),r=Os(V=>V.releases),l=d.useMemo(()=>new Map(s.images.map(V=>[V.id,V])),[s.images]),c=d.useMemo(()=>new Map(r.map(V=>
11[V.id,V])),[r]),p=s.scan?.results??[],[x,k]=d.useState(()=>{const V={};for(const L of p){const ae=Array.isArray(L.suggestions)&&L.suggestions.length>0;V[L.session_image_id]=ae&&L.status==="high_confidence"}return V}),[R,E]=d.useState(!1),[b,g]=d.useState(null),z=d.useMemo(()=>[...p].sort((V,L)=>{const ae=he=>he==="high_confidence"?3:he==="suggested"?2:he==="conflict"?1:0;return ae(L.status)-ae(V.status)}),[p]),D=d.useMemo(()=>Object.values(x).filter(Boolean).length,[x]),S=()=>{R||s.onClose()},$=async()=>{if(!s.scan)return;const V=[];for(const L of p){if(!x[L.session_image_id])continue;const ae=L.suggestions?.[0],he=String(ae?.release_id??"").trim();he&&V.push({imageId:L.session_image_id,releaseId:he})}if(V.length!==0){E(!0);try{const L=await Dt.upsertAssignments({userId:s.userId,sessionId:s.sessionId,rows:V.map(ae=>({user_id:s.userId,session_id:s.sessionId,session_image_id:ae.imageId,release_id:ae.releaseId,link_type:"face_suggested"}))});s.onConfirmed?.(L),i({title:"Suggestions confirmed",description:`Attached ${V.length} release${V.length===1?"":"s"}.`}),S()}catch(L){i({title:"Confirm failed",description:L?.message||"Could not confirm suggestions",variant:"destructive"})}finally{E(!1)}}},O=async(V,L)=>{const ae=String(V||"").trim(),he=String(L||"").trim();if(!(!ae||!he)){E(!0);try{const ne=await Dt.upsertAssignments({userId:s.userId,sessionId:s.sessionId,rows:[{user_id:s.userId,session_id:s.sessionId,session_image_id:ae,release_id:he,link_type:"face_suggested"}]});s.onConfirmed?.(ne),i({title:"Suggestion confirmed",description:"Release attached."}),S()}catch(ne){i({title:"Confirm failed",description:ne?.message||"Could not confirm suggestion",variant:"destructive"})}finally{E(!1)}}},re=async V=>{g(V);try{await we.patchSessionImageMeta(V,{release_suggestions:[],release_suggestions_note:null,release_suggestions_status:"no_match"}),s.onDismissed?.(V),k(L=>({...L,[V]:!1})),i({title:"Suggestion dismissed",description:"Removed from this asset."})}catch(L){i({title:"Dismiss failed",description:L?.message||"Could not update asset",variant:"destructive"})}finally{g(null)}};if(!s.open)return null;const ge=s.scan?.summary;return e.jsxs("div",{className:"fixed inset-0 z-[120] flex items-center justify-center",onClick:S,children:[e.jsx("div",{className:"absolute inset-0 bg-black/60 backdrop-blur-sm"}),e.jsxs("div",{className:"relative w-full max-w-3xl max-h-[86vh] overflow-hidden rounded-2xl",style:{background:"var(--cs-bg-elevated)",border:"1px solid var(--cs-border-strong)",boxShadow:"var(--cs-shadow-elevated)"},onClick:V=>V.stopPropagation(),children:[e.jsxs("div",{className:"px-5 py-4 flex items-start justify-between gap-3",style:{borderBottom:"1px solid var(--cs-border)"},children:[e.jsxs("div",{className:"min-w-0",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(bs,{className:"h-4 w-4",style:{color:"var(--cs-amber-400)"}}),e.jsx("h2",{className:"text-[14px] font-bold",style:{color:"var(--cs-text-primary)"},children:"Release Suggestions"})]}),e.jsx("p",{className:"text-[11px] mt-1",style:{color:"var(--cs-text-tertiary)"},children:"Suggestions are never applied automatically. Confirm only what looks correct."}),ge&&e.jsxs("div",{className:"mt-2 flex flex-wrap gap-2 text-[11px]",style:{color:"var(--cs-text-secondary)"},children:[e.jsxs("span",{children:[ge.matchedSuggestions," matched"]}),e.jsx("span",{children:"·"}),e.jsxs("span",{children:[ge.needReview," need review"]}),e.jsx("span",{children:"·"}),e.jsxs("span",{children:[ge.noConfidentMatch," no confident match"]}),e.jsx("span",{children:"·"}),e.jsxs("span",{children:[ge.conflicts," conflicts"]})]})]}),e.jsx(K,{variant:"ghost",size:"icon",className:"h-9 w-9",onClick:S,disabled:R,children:e.jsx(At,{className:"h-4 w-4"})})]}),e.jsx("div",{className:"max-h-[58vh] overflow-auto",children:z.length===0?e.jsx("div",{className:"p-6 text-[12px]",style:{color:"var(--cs-text-tertiary)"},children:"No scan results yet."}):e.jsx("div",{className:"divide-y",style:{borderColor:"var(--cs-border)"},children:z.map(V=>{const L=l.get(V.session_image_id),ae=V.suggestions?.[0],he=String(ae?.release_id??"").trim(),ne=he?c.get(he):null,ie=!!he&&V.status!=="conflict",De=!!x[V.session_image_id],Q=!ie||R;return e.jsxs("div",{className:"px-5 py-3 flex items-center gap-3",style:{background:"var(--cs-bg-card)"},children:[e.jsx("input",{type:"checkbox",checked:De,disabled:Q,onChange:ye=>k(xe=>({...xe,[V.session_image_id]:ye.target.checked}))}),e.jsx("div",{className:"h-10 w-10 rounded-lg overflow-hidden shrink-0",style:{border:"1px solid var(--cs-border)"},children:L?.thumbnailUrl||L?.imageUrl?e.jsx("img",{src:L.thumbnailUrl||L.imageUrl,className:"h-full w-full object-cover",alt:""}):e.jsx("div",{className:"h-full w-full flex items-center justify-center",style:{color:"var(--cs-text-tertiary)"},children:e.jsx(di,{className:"h-4 w-4"})})}),e.jsxs("div",{className:"flex-1 min-w-0",children:[e.jsxs("div",{className:"flex items-center gap-2 flex-wrap",children:[e.jsx(ah,{status:V.status}),typeof ae?.confidence=="number"&&e.jsx(oh,{confidence:ae.confidence}),ne?.person?.display_name&&e.jsx("span",{className:"text-[11px] font-semibold",style:{color:"var(--cs-text-secondary)"},children:ne.person.display_name})]}),e.jsx("div",{className:"mt-1 text-[13px] font-semibold truncate",style:{color:"var(--cs-text-primary)"},children:ne?`${ne.type==="property"?"PR":"MR"} · ${ne.display_name}`:V.status==="no_match"?"No confident match":"—"}),V.note&&e.jsx("div",{className:"mt-1 text-[11px] truncate",style:{color:"var(--cs-text-tertiary)"},children:V.note})]}),e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(K,{variant:"outline",size:"sm",className:"h-8",disabled:b===V.session_image_id||R,onClick:()=>re(V.session_image_id),title:"Dismiss suggestion",children:b===V.session_image_id?e.jsx($s,{className:"h-3.5 w-3.5 animate-spin"}):e.jsx(ed,{className:"h-3.5 w-3.5"})}),e.jsxs(K,{size:"sm",className:"h-8 text-white",style:{background:ie?"var(--cs-purple-400)":void 0,opacity:ie?1:.5},disabled:!ie||R,onClick:()=>O(V.session_image_id,he),title:ie?"Confirm and attach":"Cannot confirm (conflict or missing release)",children:[e.jsx(xt,{className:"h-3.5 w-3.5 mr-1"}),"Confirm"]})]})]},V.session_image_id)})})}),e.jsxs("div",{className:"px-5 py-4 flex items-center justify-between gap-3",style:{borderTop:"1px solid var(--cs-border)",background:"var(--cs-bg-elevated)"},children:[e.jsxs("div",{className:"text-[11px]",style:{color:"var(--cs-text-tertiary)"},children:[D," selected for confirmation"]}),e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(K,{variant:"outline",onClick:S,disabled:R,children:"Close"}),e.jsxs(K,{onClick:$,disabled:D===0||R,className:"text-white",style:{background:D>0?"var(--cs-purple-400)":void 0,opacity:D>0?1:.6},children:[R?e.jsx($s,{className:"h-4 w-4 mr-2 animate-spin"}):e.jsx(xt,{className:"h-4 w-4 mr-2"}),"Confirm Selected"]})]})]})]})]})}
11const lh={async scanSession(s){const{data:i,error:r}=await Tt.invokeFunction("release-face-suggest",{sessionId:s.sessionId,...s.assetIds?.length?{assetIds:s.assetIds}:{},...s.options?{options:s.options}:{}});if(r||!i){const l=r?.message||"face_scan_failed";throw new Error(l)}return i}};function ch(s){const i=s.status==="ready"?{label:"Ready",bg:"rgba(34,197,94,.12)",border:"rgba(34,197,94,.22)",color:"var(--cs-green-400)"}:s.status==="needs_review"?{label:"Needs review",bg:"rgba(245,158,11,.12)",border:"rgba(245,158,11,.22)",color:"var(--cs-amber-400)"}:s.status==="ambiguous_match"?{label:"Ambiguous",bg:"rgba(245,158,11,.12)",border:"rgba(245,158,11,.22)",color:"var(--cs-amber-400)"}:s.status==="minor_release_missing"?{label:"Minor missing",bg:"rgba(239,68,68,.12)",border:"rgba(239,68,68,.22)",color:"var(--cs-red-400)"}:s.status==="property_release_missing"?{label:"Property missing",bg:"rgba(239,68,68,.12)",border:"rgba(239,68,68,.22)",color:"var(--cs-red-400)"}:{label:"Missing release",bg:"rgba(239,68,68,.12)",border:"rgba(239,68,68,.22)",color:"var(--cs-red-400)"};return e.jsx("span",{className:"inline-flex items-center rounded-full px-2 py-0.5 text-[11px] font-semibold whitespace-nowrap",style:{background:i.bg,border:`1px solid ${i.border}`,color:i.color},title:s.title,children:i.label})}class Rc extends en.Component{state={hasError:!1,message:""};static getDerivedStateFromError(i){return{hasError:!0,message:String(i?.message||i||"Unknown error")}}componentDidCatch(i,r){const l=this.props.name||"CsErrorBoundary";console.error(`[${l}] render error`,i,r)}reset=()=>{this.setState({hasError:!1,message:""}),this.props.onReset?.()};render(){return this.state.hasError?e.jsx("div",{className:"rounded-xl p-4",style:{background:"rgba(239,68,68,.06)",border:"1px solid rgba(239,68,68,.18)"},children:e.jsxs("div",{className:"flex items-start gap-3",children:[e.jsx("div",{className:"w-9 h-9 rounded-lg flex items-center justify-center",style:{background:"rgba(239,68,68,.10)"},children:e.jsx(di,{className:"h-4 w-4",style:{color:"var(--cs-red-400)"}})}),e.jsxs("div",{className:"min-w-0 flex-1",children:[e.jsx("div",{className:"text-[13px] font-semibold",style:{color:"var(--cs-text-primary)"},children:this.props.title||"Something went wrong"}),e.jsx("div",{className:"mt-1 text-[12px]",style:{color:"var(--cs-text-secondary)"},children:this.props.description||"This panel failed to render. Reload or try again."}),e.jsx("div",{className:"mt-2 text-[11px] font-mono break-words",style:{color:"var(--cs-text-tertiary)"},children:this.state.message}),e.jsxs("button",{type:"button",onClick:this.reset,className:"mt-3 inline-flex items-center gap-2 px-3 py-2 rounded-lg text-[12px] font-semibold transition-all",style:{background:"var(--cs-bg-hover)",border:"1px solid var(--cs-border)",color:"var(--cs-text-primary)"},children:[e.jsx(va,{className:"h-4 w-4"}),"Try again"]})]})]})}):this.props.children}}const Mc={title:!1,description:!1,category:!1,keywords:!1,editorial:!1},xr={location:!0,country:!0,date:!0,caption:!1},dh=[{key:"location",label:"Location",description:"City / state context"},{key:"country",label:"Country",description:"Country name or code"},{key:"date",label:"Capture Date",description:"Month Day, Year format"},{key:"caption",label:"Caption",description:"Factual editorial caption"}],uh=[{key:"title",label:"Title",description:"Copy the current title into every selected asset."},{key:"description",label:"Description",description:"Copy the description / caption paragraph."},{key:"category",label:"Category",description:"Copy the current category into every selected asset."},{key:"keywords",label:"Keywords",description:"Replace keyword lists on the selected assets."},{key:"editorial",label:"Editorial block",description:"Copy Editorial enable state plus Location, Country, Date, Caption."}],Bc={title:!1,description:!1,keywords:!1,category:!1,batchName:!1,editorial:!1,shooting:!1},Lc={text:!0,city:!0,state:!0,country:!0,date:!0},mh=[{key:"title",label:"Title",description:"Copy the current Blackbox title."},{key:"description",label:"Description",description:"Copy the Blackbox description."}
11,{key:"keywords",label:"Keywords",description:"Replace keyword lists on the selected Blackbox items."},{key:"category",label:"Category",description:"Copy the selected Blackbox category."},{key:"batchName",label:"Batch Name",description:"Copy the batch name."},{key:"editorial",label:"Editorial block",description:"Copy Editorial flag plus Text, City, State, Country, Date."},{key:"shooting",label:"Shooting info",description:"Copy Shooting Country and Shooting Date."}],ph=[{key:"text",label:"Editorial Text",description:"Copy editorial text."},{key:"city",label:"Editorial City",description:"Copy editorial city."},{key:"state",label:"Editorial State",description:"Copy editorial state."},{key:"country",label:"Editorial Country",description:"Copy editorial country."},{key:"date",label:"Editorial Date",description:"Copy editorial date."}],hh=6,gh={strong:"bg-emerald-100 text-emerald-800 ring-emerald-200",medium:"bg-amber-100 text-amber-800 ring-amber-200",weak:"bg-rose-100 text-rose-800 ring-rose-200"},fh={up:"bg-emerald-50 text-emerald-700 border-emerald-100",steady:"bg-indigo-50 text-indigo-700 border-indigo-100"},yh=s=>`https://trends.google.com/trends/explore?q=${encodeURIComponent(s)}`,Kt=s=>{if(!s)return null;const i=String(s).trim();if(!i)return null;const r=new Date(i);if(!Number.isNaN(r.getTime()))try{return new Intl.DateTimeFormat("en",{month:"long",day:"numeric",year:"numeric"}).format(r)}catch{return i}return i},ya={shutterstock_strict:{name:"Shutterstock Editorial",description:"Requires Location, Country, and Capture Date in Month Day, Year format. Caption must describe the scene factually (no marketing claims).",requiredFields:["location","country","date","caption"],captionHint:"Format: LOCATION – Description (Month Day, Year)."},adobe_editorial:{name:"Adobe Stock Editorial",description:"Requires Location, Country, Capture Date, and descriptive caption. Auto-captions should follow city first, then description.",requiredFields:["location","country","date","caption"],captionHint:"Example: New York City, USA – People wait on Times Square (July 4, 2024)."},istock_getty:{name:"iStock / Getty",description:"Requires Location, Country, Date, and Caption; Category optional but recommended.",requiredFields:["location","country","date","caption"]},dreamstime_editorial:{name:"Dreamstime Editorial",description:"Requires Location, Country, Date. Caption describes the event.",requiredFields:["location","country","date","caption"]},depositphotos_editorial:{name:"Depositphotos Editorial",description:"Requires Location and caption; Date strongly recommended.",requiredFields:["location","caption"]},rf123_editorial:{name:"123RF Editorial",description:"Requires Location, Country, and Caption.",requiredFields:["location","country","caption"]},pond5_editorial:{name:"Pond5 Editorial",description:"Requires Location, Country, Date, and Caption.",requiredFields:["location","country","date","caption"]},alamy_editorial:{name:"Alamy Editorial",description:"Requires Caption, strongly recommends Location and Date.",requiredFields:["caption"]},envato_editorial:{name:"Envato Editorial",description:"Requires Caption with factual context. Location optional but helpful.",requiredFields:["caption"]}},xh={Dreamstime:"Dreamstime (Image)"},bh={"Adobe Stock":"adobe",Shutterstock:"shutterstock",Pond5:"pond5",iStock:"istock","Getty Images":"getty","Dreamstime (Image)":"dreamstime","Dreamstime (Video)":"dreamstime_video",Depositphotos:"depositphotos","123RF":"123rf",Alamy:"alamy",Pixta:"pixta",Storyblocks:"storyblocks",Vecteezy:"vecteezy",Xpiks:"xpiks",KEYCUTstock:"keycutstock",MicrostockPlus:"microstockplus","Envato Elements":"envato",Canva:"canva",Freepik:"freepik",Pexels:"pexels",Unsplash:"unsplash",Pixabay:"pixabay",Blackbox:"blackbox",Custom:"custom"},Fc=s=>String(s??"").trim().toLowerCase(),Sa=(s,i,r)=>{const l=Array.isArray(s)?s:[],c=Fc(r||"");if(c&&l.length>0){const p=l.find(k=>Fc(k.label)===c);if(p)return p;const x=bh[r||""];if(x){const k=l.find(R=>R.id===x);if(k)return k}}return i||(l[0]??null)},Ls=(s,i)=>{const r=String(s??"").trim(),l=String(i??"").trim();if(!r)return l;if(!l)return r;const c=r.toLowerCase(),p=l.toLowerCase();return c.includes(p)?r:`${r}, ${l}`},wh=new Set(["shutterstock_strict","pond5_editorial"]),ud=(s,i)=>{const r=String(i??"").trim().toLowerCase();return wh.has(r)?s.toUpperCase():s.replace(/\w\S*/g,l=>l.charAt(0).toUpperCase()+l.substring(1).toLowerCase())},xa=(s,i)=>{const r=String(s??"").trim();if(!r)return"";const l=r.indexOf(": ");if(l<=0)return r;const c=r.slice(0,l),p=r.slice(l+2),x=c.indexOf(" - "),k=x>=0?c.slice(0,x):c,R=x>
11=0?c.slice(x):"";return k.trim()?`${ud(k.trim(),i)}${R}: ${p}`:r},Fs=(s,i,r,l)=>{const c=String(s??"").trim(),p=String(i??"").trim(),x=String(r??"").trim();if(!c&&!p)return x;let k="";return c&&(k+=ud(c,l)),p&&(k+=k?` - ${p}`:p),k?x?`${k}: ${x}`:`${k}:`:x},Xe=(s,i)=>{if(!s)return null;const r=Object.entries(s);for(const l of i){const c=s[l];if(typeof c=="string"&&c.trim())return c.trim();const p=l.toLowerCase();for(const[x,k]of r)if(typeof k=="string"&&k.trim()&&x.toLowerCase()===p)return k.trim()}return null},xs=s=>{const i={...s.metadata,...s.meta_json};let r=s.editorialLocation??Xe(i,["editorial_location","location","city_state_country","city_state","city"]),l=s.editorialCountry??Xe(i,["editorial_country","country","country_name","country_code"]),c=s.editorialDate??Xe(i,["editorial_date","capture_date","captureDate","date_created","created_at","date"]);const p=s.sourceContext||{},x=p.iptc||{},k=p.xmp||{},R=p.exif||p.Exif||{};if(!r){const D=Xe(x,["City","CityName","Iptc4xmpCore:City"])??Xe(k,["Iptc4xmpCore:City"])??Xe(R,["City"]),S=Xe(x,["ProvinceState","State"])??Xe(k,["Iptc4xmpCore:ProvinceState"])??Xe(R,["State"]),$=Xe(x,["CountryPrimaryLocationName","CountryName","Country"])??Xe(k,["Iptc4xmpCore:CountryName"])??Xe(R,["Country"]),O=p.location?.trim(),re=[D,S,$].filter(Boolean).join(", ");r=O||re||r||null}l||(l=Xe(x,["CountryPrimaryLocationName","CountryName","Country"])??Xe(k,["Iptc4xmpCore:CountryName"])??Xe(R,["Country"])??l),c||(c=Xe(x,["DateCreated","ReleaseDate"])??Xe(k,["photoshop:DateCreated"])??Xe(R,["DateCreated","CreateDate"])??c);const E=Kt(c),b=s?.meta_json?.editorial??s?.meta_json?.editorial_meta??{},z=(s?.editorialCity??b.city??Xe(x,["City","CityName","Iptc4xmpCore:City"])??Xe(k,["Iptc4xmpCore:City"])??Xe(R,["City"])??null)||(r&&r.includes(",")?r.split(",")[0].trim():null);return{location:r||null,city:z,country:l||null,date:E}},vh=(s,i)=>{for(const r of s){if(i.has(r.id))continue;const l=xs(r),c=r.editorialCaption??null,p=r.editorialCategory??null;if(l.location||l.country||l.date||c||p)return{source:r,location:l.location,country:l.country,date:l.date,caption:c,category:p}}return null},kh={selling:[82,92],title:[80,90],description:[79,89],keywords:[78,88]},Ch={selling:[{label:"Marketplace Confidence",tone:"up",create:()=>`+${12+Math.floor(Math.random()*6)} pts uplift`,value:""},{label:"Buyer Intent Pulse",tone:"up",create:()=>`${62+Math.floor(Math.random()*18)}%`,value:""},{label:"Competitive Edge",tone:"steady",create:()=>`${18+Math.floor(Math.random()*6)} listings outperformed`,value:""}],title:[{label:"Keyword Lead Strength",tone:"up",create:()=>`+${14+Math.floor(Math.random()*6)}%`,value:""},{label:"Readability Flow",tone:"steady",create:()=>`${85+Math.floor(Math.random()*10)} / 100`,value:""},{label:"Trend Match",tone:"up",create:()=>`${3+Math.floor(Math.random()*3)} prime terms locked`,value:""}],description:[{label:"Keyword Density",tone:"up",create:()=>`+${12+Math.floor(Math.random()*8)}%`,value:""},{label:"Conversion Clarity",tone:"steady",create:()=>`${78+Math.floor(Math.random()*12)} / 100`,value:""},{label:"Story Cohesion",tone:"up",create:()=>`${2+Math.floor(Math.random()*3)} highlighted benefits`,value:""}],keywords:[{label:"Keyword Depth",tone:"up",create:()=>`+${10+Math.floor(Math.random()*9)} strong terms`,value:""},{label:"SERP Click Thru",tone:"steady",create:()=>`${(3+Math.random()*2).toFixed(1)}%`,value:""},{label:"Trend Momentum",tone:"up",create:()=>`+${18+Math.floor(Math.random()*12)}% last 30d`,value:""}]},li=(s,i)=>s>=i?s:Math.floor(Math.random()*(i-s+1))+s,Pc=(s,i=2)=>{const r=Ch[s];return!r||r.length===0?[]:[...r].sort(()=>Math.random()-.5).slice(0,i).map(c=>({label:c.label,tone:c.tone,value:c.create()}))},Sh={selling:"Selling Score",title:"Title",description:"Description",keywords:"Keywords"},Kc=()=>({selling:0,title:0,description:0,keywords:0}),$c=()=>({selling:[],title:[],description:[],keywords:[]}),Go=()=>({monthly:li(2800,7800),longtail:li(420,1400),opportunity:li(68,92),conversion:li(18,32)}),jh=({descriptor:s,keyword:i,showVolume:r=!0})=>{const l=r?s.lines:s.lines.filter(c=>c.key!=="volume");return!r&&s.lines.some(c=>c.key==="volume"),e.jsxs("div",{className:"text-xs space-y-1",children:[e.jsx("div",{className:"font-semibold text-[var(--cs-text-primary)] text-[11px] tracking-wide",children:td[s.verdict]}),l.map(c=>e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx("span",{className:"inline-flex h-2 w-2 rounded-full",style:{backgroundColor:sd[c.level]}}),e.jsxs("span",{className:"text-[var(--cs-text-primary)]",children:[e.jsxs("span",{className:"font-medium",children:[c.label,":"]}
11)," ",c.value]})]},`${c.key}-${c.value}`)),i&&e.jsxs("a",{href:yh(i),target:"_blank",rel:"noreferrer",className:"inline-flex items-center gap-1 text-[11px] font-medium text-[#2563eb] hover:underline",children:["View on Google Trends",e.jsxs("svg",{width:"10",height:"10",viewBox:"0 0 10 10",fill:"none",className:"stroke-current",children:[e.jsx("path",{d:"M2 8L8 2",strokeWidth:"1.3",strokeLinecap:"round"}),e.jsx("path",{d:"M8 5V2H5",strokeWidth:"1.3",strokeLinecap:"round"})]})]})]})},md={"Adobe Stock":[{id:"1",label:"Animals",tokens:["animal","animals","pet","wildlife","dog","cat","bird","insect","horse","fish"]},{id:"2",label:"Buildings and Architecture",tokens:["architecture","building","buildings","skyscraper","cityscape","interior","exterior","structure","bridge","urban"]},{id:"3",label:"Business",tokens:["business","office","corporate","meeting","finance","startup","commerce","entrepreneur","manager","teamwork"]},{id:"4",label:"Drinks",tokens:["drink","drinks","beverage","coffee","tea","cocktail","beer","wine","juice","spirits"]},{id:"5",label:"The Environment",tokens:["environment","sustainability","pollution","recycling","eco","climate","green","global","earth"]},{id:"6",label:"States of Mind",tokens:["emotion","mood","feelings","anxiety","stress","happy","sad","joy","mind","mental"]},{id:"7",label:"Food",tokens:["food","meal","cuisine","recipe","cooking","kitchen","dish","dining","restaurant","ingredient"]},{id:"8",label:"Graphic Resources",tokens:["background","texture","pattern","graphic","illustration","icon","symbol","design","abstract"]},{id:"9",label:"Hobbies and Leisure",tokens:["hobby","leisure","gaming","music","craft","knitting","garden","recreation","relaxation","pastime"]},{id:"10",label:"Industry",tokens:["industry","industrial","factory","manufacturing","machinery","production","assembly","engineering","construction"]},{id:"11",label:"Landscape",tokens:["landscape","mountain","valley","coast","nature","scenery","vista","outdoor","panorama","sunset"]},{id:"12",label:"Lifestyle",tokens:["lifestyle","home","family","daily","routine","living","domestic","together","couple","household"]},{id:"13",label:"People",tokens:["people","person","portrait","man","woman","child","children","crowd","adult","friends"]},{id:"14",label:"Plants and Flowers",tokens:["plant","plants","flower","flowers","botanical","garden","flora","leaf","leaves","bloom"]},{id:"15",label:"Culture and Religion",tokens:["culture","religion","tradition","festival","ceremony","heritage","spiritual","ritual","faith","cultural"]},{id:"16",label:"Science",tokens:["science","scientist","laboratory","lab","experiment","research","microscope","biology","chemistry","physics"]},{id:"17",label:"Social Issues",tokens:["poverty","inequality","protest","politics","violence","homeless","justice","activism","discrimination"]},{id:"18",label:"Sports",tokens:["sport","sports","fitness","exercise","athlete","soccer","football","basketball","yoga","running"]},{id:"19",label:"Technology",tokens:["technology","tech","computer","laptop","digital","innovation","virtual","device","software","ai"]},{id:"20",label:"Transport",tokens:["transport","transportation","car","cars","vehicle","train","plane","motor","highway","logistics"]},{id:"21",label:"Travel",tokens:["travel","travelling","vacation","tourism","destination","journey","explore","adventure","trip","holiday"]}],Shutterstock:Hm,Alamy:[],iStock:[],"Getty Images":[],Dreamstime:[],Depositphotos:[],"123RF":[],Pond5:[],"Envato Elements":[],Canva:[],Freepik:[],Pexels:[],Unsplash:[],Pixabay:[],Custom:[]},Nh=md["Adobe Stock"],Eh="Lifestyle",Oc=s=>s?s.toLowerCase().split(/[^a-z0-9]+/g).filter(Boolean):[],pi=s=>md[s]??[],_h=s=>Array.isArray(s.baseKeywords)&&s.baseKeywords.length>0?s.baseKeywords:Array.isArray(s.keywords)?s.keywords:[],pd=s=>{if(!s)return{raw:"",id:"",label:""};const i=s.trim();if(!i)return{raw:"",id:"",label:""};const r=i.match(/^(\d+)\s*[–—-]\s*(.+)$/);return r?{raw:i,id:r[1],label:r[2].trim()}:{raw:i,id:i,label:i}},Ah=[{value:"title",label:"Title",description:"Run Intelligent Rewrite on titles only.",cost:2,icon:ui},{value:"description",label:"Description",description:"Run Intelligent Rewrite on de
11scriptions only.",cost:2,icon:ui},{value:"keywords",label:"Keywords",description:"Boost Keywords — expands with current marketplace data (incl. Google Trends) to strengthen strong keywords.",cost:1,icon:bs},{value:"all",label:"All",description:"Rewrite all metadata (title, description, and keywords).",cost:4,icon:Zm}],ba=["all"],zc=s=>{switch(s){case"title":return"title";case"description":return"description";case"keywords":return"keywords";default:return"title, description, and keywords"}},Th=s=>{if(s.length===0)return"";if(s.includes("all"))return zc("all");const i=s.map(zc);if(i.length===1)return i[0];if(i.length===2)return`${i[0]} and ${i[1]}`;const r=i.slice(0,-1).join(", "),l=i[i.length-1];return`${r}, and ${l}`},Yo=s=>Number.isFinite(s)?Number.isInteger(s)?s.toString():s.toFixed(1):"0",ci=s=>{const i=D=>{const S=(D??"").toString();try{return S.normalize("NFKD").replace(new RegExp("\\p{M}+","gu"),"")}catch{return S}},r=D=>{const S=i(String(D??"")).trim().toLowerCase();return S?S.replace(/[^\p{L}\p{N}]+/gu,""):""},l=D=>{const S=i(String(D??"")).trim().toLowerCase();return S?S.replace(/[\s_\-\u2010\u2011\u2012\u2013\u2014]+/g,"").replace(/[^\p{L}\p{N}]+/gu,""):""},c=(D,S)=>{const $=i(String(D??"")).trim();if(!$||/\s/.test($))return null;const O=$.toLowerCase().replace(/[^\p{L}\p{N}]+/gu,"").trim();if(O.length<8)return null;const re=3,ge=Math.min(20,O.length),V=4,L=ne=>{const ie=ne.reduce((ye,xe)=>ye+xe.length*xe.length,0),De=(ne.length-1)*3,Q=ne.length>=2?1e3:0;return ie-De+Q},ae=Array(O.length+1).fill(null);ae[0]={tokens:[],score:0};for(let ne=0;ne<O.length;ne+=1){const ie=ae[ne];if(ie&&!(ie.tokens.length>=V))for(let De=ne+re;De<=Math.min(O.length,ne+ge);De+=1){const Q=O.slice(ne,De);if(!S.has(Q))continue;const ye=[...ie.tokens,Q];if(ye.length>V)continue;const xe={tokens:ye,score:L(ye)},je=ae[De];(!je||xe.score>je.score)&&(ae[De]=xe)}}const he=ae[O.length];return!he||he.tokens.length<2?null:he.tokens},p=D=>{const S=String(D??"").trim();if(!S||!/[A-Z]/.test(S))return null;const O=S.replace(/([a-z\p{Ll}])([A-Z\p{Lu}])/gu,"$1 $2").split(/\s+/).map(re=>re.trim()).filter(Boolean).join(" ");return O?O.toLowerCase():null},x=[];s.forEach(D=>{const S=String(D??"").trim();if(!S)return;const $=p(S);x.push($??S)});const k=new Set;for(const D of x){const S=String(D??"").trim();S&&/\s/.test(S)&&S.split(/[\s_\-\u2010\u2011\u2012\u2013\u2014]+/).map($=>$.trim().toLowerCase()).filter(Boolean).forEach($=>{const O=r($);O&&O.length>=3&&k.add(O)})}const R=[];x.forEach(D=>{const S=String(D??"").trim();if(!S)return;const $=k.size>0?c(S,k):null;if($&&$.length>=2){R.push($.join(" "));return}R.push(S)});const E=[],b=new Map,g=new Map;R.forEach(D=>{const S=String(D??"").trim();if(!S)return;const $=S.toLowerCase(),O=l(S)||$;if(b.has($))return;const re=g.get(O);if(typeof re=="number"){const V=E[re]??"",L=/\s/.test(V);/\s/.test(S)&&!L&&(b.delete(V.toLowerCase()),E[re]=S,b.set($,re));return}const ge=E.length;E.push(S),b.set($,ge),g.set(O,ge)});const z=new Set;for(const D of E){const S=String(D??"").trim();if(!S||!/\s/.test(S))continue;const $=S.split(/[\s_\-\u2010\u2011\u2012\u2013\u2014]+/).map(O=>O.trim()).filter(Boolean);for(const O of $){const re=r(O);re&&z.add(re)}}return z.size===0?E:E.filter(D=>{const S=String(D??"").trim();if(!S)return!1;if(/\s/.test(S))return!0;const $=r(S);return!$||!z.has($)})},Dh=async s=>{const i=await fetch(s);if(!i.ok)throw new Error(`Failed to fetch asset (${i.status})`);const r=await i.blob(),l=r.type||"image/webp",c=await new Promise((p,x)=>{const k=new FileReader;k.onerror=()=>x(new Error("Failed to read asset blob")),k.onloadend=()=>p(String(k.result).split(",")[1]||""),k.readAsDataURL(r)});if(!c)throw new Error("Empty asset payload");return{base64:c,mime:l}},tn=s=>{const i=String(s||"").toLowerCase();return i.endsWith(".png")?"image/png":i.endsWith(".jpg")||i.endsWith(".jpeg")?"image/jpeg":i.endsWith(".webp")?"image/webp":i.endsWith(".gif")?"image/gif":i.endsWith(".bmp")?"image/bmp":i.endsWith(".tif")||i.endsWith(".tiff")?"image/tiff":i.endsWith(".mp4")?"video/mp4":i.endsWith(".mov")?"video/quicktime":i.endsWith(".webm")?"video/webm":"image/webp"},Na=(s,i)=>{const r=String(s??"").trim();if(!r)return"";if(r.startsWith("sessions/")||r.startsWith("previews/"))return r.replace(/^\/+/,"");if(r.startsWith("http://")||r.startsWith("https://"))try{const c=new URL(r).pathname||"",p=c.indexOf("/sessions/"),x=c.indexOf("/previews/"),k=p>=0?p:x;if(k>=0){const E=c.slice(k+1).replace(/^\/+/,"").split("/").map(z=>{try{return decodeURIComponent(z)}catch{return z}}).join("/"),g=/^(sessions|previews)\/(\w[0-9a-fA-F-]+)\//.exec(E)?.[2]||i;if(g&&E.startsWith(`sessions/${g}/`)||E.startsWith("previews/")||E.startsWith("sessions/"))return E}}catch{}return""},sn=s=>{const r=s.mediaType==="video"?s.thumbnailUrl||s.imageUrl||"":s.imageUrl||s.thumbnailUrl||"";if(r)return r;const l=s.meta_json??{},c=[l.preview_path,l.thumbnail_path,l.storage_path,l.preview_url,l.thumbnail_url,l.image_url];
11for(const p of c)if(typeof p=="string"&&p.trim())return p.trim();return""},rn=async(s,i)=>{const r=(s??"").toString();if(!r||/^blob:/i.test(r))return"";if(r.startsWith("http://")||r.startsWith("https://")||r.startsWith("data:"))return/^https?:/i.test(r)&&Aa(r)?r:await we.resolveSessionAsset(i,r);const l=r.replace(/^\/+/,"");if(!l)return"";const p=/^(?:sessions|previews|public\/sessions|public\/previews)\/([0-9a-fA-F-]+)\//.exec(l)?.[1]||i;return await we.resolveSessionAsset(p,l)},Aa=s=>{const i=String(s||""),r=i.toLowerCase(),l=r.includes("supabase")&&(r.includes("token=")||r.includes("sign=")),c=/[?&](x-amz-algorithm|x-amz-signature|x-amz-credential)=/i.test(i);return l||c},an=async s=>{const{sourceInput:i,sourceUrl:r,fallbackSessionId:l,stableSourcePath:c}=s;if(!r)return"";if(Aa(r))return r;const p=c||Na(i,l);return p&&await we.resolveSessionAsset(l,p)||r},on=(s,i)=>Aa(s)||!!i,nn=s=>{const i=s,r=i?.meta_json?.asset_facts??i?.metadata?.asset_facts??null;return r&&typeof r=="object"?r.has_transparency===!0:!1},ln=(s,i)=>{const r=s,l=String(r?.mediaType??r?.media_type??"").trim().toLowerCase();if(l==="image"||l==="video"||l==="vector")return l;const c=String(i??"").trim().toLowerCase();return/svg|pdf|postscript|eps|illustrator/.test(c)?"vector":c.startsWith("video/")?"video":c.startsWith("image/")?"image":null},cn=(s,i,r)=>{const l=typeof s=="number"&&Number.isFinite(s)&&s>0?Math.floor(s):200;return!i||typeof r!="number"||!Number.isFinite(r)?l:Math.min(l,Math.max(10,Math.floor(r)))},dn=(s,i)=>!s||typeof i!="number"||!Number.isFinite(i)?170:Math.max(10,Math.floor(i)),un=(s,i,r,l)=>{const c=Math.min(140,r);return!s||typeof i!="number"||!Number.isFinite(i)?c:Math.min(r,Math.max(1,Math.floor(i)))},mn=(s,i,r,l)=>{const c=typeof s=="number"&&Number.isFinite(s)&&s>0?Math.floor(s):500,p=i&&typeof r=="number"&&Number.isFinite(r)?Math.min(c,Math.max(10,Math.floor(r))):c;return{minDescriptionChars:i&&typeof l=="number"&&Number.isFinite(l)?Math.min(p,Math.max(1,Math.floor(l))):Math.min(p,Math.max(120,Math.min(240,Math.floor(p*.8)))),maxDescriptionChars:p}},pn=(s,i,r)=>{if(!s)return{minTitleKeywords:0,maxTitleKeywords:20};const c=s&&typeof r=="number"&&Number.isFinite(r)?Math.max(0,Math.floor(r)):8,p=Math.min(20,c),x=s&&typeof i=="number"&&Number.isFinite(i)?Math.max(0,Math.floor(i)):0;return{minTitleKeywords:Math.min(p,x),maxTitleKeywords:p}},fs=s=>s?"Yes":"No",br=(s,i=160)=>{const r=String(s??"").replace(/\s+/g," ").trim();return r.length>i?`${r.slice(0,i-1)}…`:r},Ih=(s,i)=>{const r=[],l=br(s?.customPrompt||i||"");if(r.push({label:"Custom prompt",value:l||"Not provided",important:!!l}),!s)return r;const c=s.titleSettings,p=s.keywordSettings,x=s.generalSettings,k=s.translationSettings,R=s.releaseFaceMatch,E=!!s.editorialByPlatform?.[s.selectedPlatformId]?.enabled;return r.push({label:"Platform",value:s.selectedPlatformLabel||s.selectedPlatformId||"—"}),r.push({label:"Generation mode",value:s.generationMode||"—"}),r.push({label:"Output language",value:x?.outputLanguage||"Default"}),r.push({label:"Title/description settings",value:fs(c?.enabled),important:c?.enabled===!0}),c?.enabled&&(r.push({label:"Title chars",value:`${c.minTitleChars}–${c.maxTitleChars}`}),r.push({label:"Description chars",value:`${c.minDescriptionChars}–${c.maxDescriptionChars}`}),r.push({label:"Title keywords",value:`${c.minTitleKeywords}–${c.maxTitleKeywords}`}),r.push({label:"Title casing",value:c.allCaps?"ALL CAPS":c.titleCase?"Title Case":"Sentence case"}),c.optionalElements?.trim()&&r.push({label:"Optional title elements",value:br(c.optionalElements),important:!0})),r.push({label:"Keyword settings",value:fs(p?.enabled),important:p?.enabled===!0}),p?.enabled&&(r.push({label:"Keyword count",value:p.minKeywordCount?String(p.minKeywordCount):"Platform default"}),r.push({label:"Single-word mode",value:fs(p.singleWordMode),important:p.singleWordMode===!0}),r.push({label:"Allow compounds",value:fs(p.allowCompoundKeywords),important:p.allowCompoundKeywords===!0}),p.requiredStartingKeywords?.trim()&&r.push({label:"Required starting keywords",value:br(p.requiredStartingKeywords),important:!0}),p.requiredEndingKeywords?.trim()&&r.push({label:"Required ending keywords",value:br(p.requiredEndingKeywords),important:!0}),p.excludedKeywords?.trim()&&r.push({label:"Excluded keywords",value:br(p.excludedKeywords),important:!0})),r.push({label:"Use filename context",value:fs(x?.useFilenameForContext),important:x?.useFilenameForContext===!0}),r.push({label:"Use metadata context",value:fs(x?.useMetadataForContext),important:x?.useMetadataForContext===!0}),r.push({label:"Auto category",value:fs(x?.autoCategory),important:x?.autoCategory===!1}),x?.prohibitedCharacters?.trim()&&r.push({label:"Prohibited characters",value:br(x.prohibitedCharacters),important:!0}),r.push({label:"Editorial mode",value:fs(E),important:E}),r.push({label:"Translations",value:k?.enabled?k.targetLanguages?.join(", ")||k.targetLanguage||"Enabled":"No",important:k?.enabled===!0}),r.push({label:"Release face match",value:R?.enabled?`Yes · threshold ${R.similarityThreshold}`:"No",important:R?.enabled===!0}),r},hn=s=>{if(!s||typeof s!="object")return null;const i=s,r=String(i.baseTitle??i.title??"").trim(),l=String(i.baseDescription??i.description??"").trim(),c=Array.isArray(i.baseKeywords)&&i.baseKeywords.length>0?i.baseKeywords:i.keywords,x=(Array.isArray(c)?c:String(c??"").split(",").map(k=>
11k.trim()).filter(Boolean)).filter(k=>typeof k=="string"&&k.trim().length>0);return{title:r,description:l,keywords:x}},gn=(s,i)=>{const r=xs(s),l=s?.platformMetadata?.blackbox?.sourceContext??s?.platformMetadata?.sourceContext??s?.sourceContext??null,c={enabled:i,location:r.location??null,city:s?.editorialCity??null,state:s?.editorialState??null,country:r.country??null,date:r.date??null,caption:s?.editorialCaption??null,category:s?.editorialCategory??null,sourceContext:l??null},p=!!(c.location||c.city||c.state||c.country||c.date||c.caption||c.category||c.sourceContext);return i||p?c:null},Uc=async s=>{const{image:i,sessionId:r,userId:l,seedLabel:c,promptRequest:p,expectsCategory:x,autoCategoryEnabled:k,platform:R,unlimitedActive:E,unlimitedUsage:b,generationMode:g,onCreditsDeducted:z}=s,D=Ps.getState(),S=Sa(D.availablePlatforms,D.selectedPlatform,R),$=(D.generalSettings?.outputLanguage||"en").trim()||"en",O=!!S?.singleWordOnly,re=O||D.keywordSettings?.singleWordMode===!0,ge=!O&&re&&D.keywordSettings?.allowCompoundKeywords===!0,V=re?"single":"long-tail",L=D.titleSettings?.enabled===!0,ae=L&&D.titleSettings?.titleCase===!0,he=L&&D.titleSettings?.allCaps===!0,ne=S?.titleLimit??200,ie=cn(ne,L,D.titleSettings?.maxTitleChars),{minDescriptionChars:De,maxDescriptionChars:Q}=mn(S?.descriptionLimit,L,D.titleSettings?.maxDescriptionChars,D.titleSettings?.minDescriptionChars),{minTitleKeywords:ye,maxTitleKeywords:xe}=pn(L,D.titleSettings?.minTitleKeywords,D.titleSettings?.maxTitleKeywords),je=L?Math.min(ie,Math.max(1,D.titleSettings?.minTitleChars??140)):Math.min(140,ie);i?.mediaType==="video"||/^video\//i.test(String(i?.mimeType??i?.mime_type??""))||/\.(mp4|mov|m4v|avi|webm|mkv)(\?|$)/i.test(String(i.filename||""));const Me=dn(L,D.titleSettings?.maxTitleChars),Ge=un(L,D.titleSettings?.minTitleChars,Me),pt=!!i?.editorial||!!D.editorialByPlatform?.[S?.id]?.enabled,it=gn(i,pt),Be=S?.keywordsLimit??50,bt=Math.min(Be,Math.max(1,D.keywordSettings?.minKeywordCount||Be));if(!r)throw new Error("Session required for metadata rewrite");await rd(r);const j=sn(i),H=await rn(j,r),J=Na(j,r),ve=await an({sourceInput:j,sourceUrl:H,fallbackSessionId:r,stableSourcePath:J});if(!ve)throw new Error("Unable to resolve asset URL for rewrite");const _=on(ve,J),U=`${i.id}::${c}::${Date.now()}`,ee=E&&g==="unlimited",ze=tn(i.filename),at=ln(i,ze),ot={noCharge:!0,retryForId:i.id,...at?{mediaType:at}:{},hasTransparency:nn(i),reason:s.action==="boost"?"boost_keywords":"intelligent_rewrite",aiOperation:s.action??"rewrite",outputLanguage:$,locale:$,keywordMode:V,singleWordOnly:O,allowCompoundKeywords:ge,keywordCount:bt,aiKeywordCount:Math.min(60,bt+8),keywordsLimit:Be,titleCase:ae,titleAllCaps:he,titleMinChars:je,titleMaxChars:ie,titleSettingsEnabled:L,aiTitleMinChars:Ge,aiTitleMaxChars:Me,editorialEnabled:pt,...it?{editorialSeed:it}:{},editorialPlatformLabel:S?.label??R??null,descriptionLimit:S?.descriptionLimit,maxDescriptionChars:Q,minDescriptionChars:De,minTitleKeywords:ye,maxTitleKeywords:xe,analytics:s.action==="boost"||s.action==="rewrite"?!0:void 0},Gt=_?await Tt.processAssetByUrl({signedUrl:ve,originalStoragePath:J||"",mimeType:ze,filename:i.filename||`rewrite-${Date.now()}`,sessionId:r,generationMode:ee?"unlimited":"credits",runId:U,promptRequest:p,extra:ot}):await Dh(ve).then(({base64:yi,mime:xi})=>Tt.processImage(yi,p,l,xi,{generationMode:ee?"unlimited":"credits",usageCount:ee?b+1:void 0,sessionId:r,filename:i.filename||`rewrite-${Date.now()}`,runId:U,extra:ot})),{metadata:Ue,error:ht}=Gt;if(ht||!Ue)throw ht??new Error("Rewrite request failed");z?.(!!Ue?.usedCredits);const Re=hn(Ue)??{title:i.title??"",description:i.description??"",keywords:Array.isArray(i.keywords)?i.keywords:[]},Ie=ci(Re.keywords);let Ot=i.categories??"";return x&&k&&(Ot=Cr(Ie,Re.title,Re.description,Ot)),{baseTitle:Re.title,baseDescription:Re.description,baseKeywords:Ie,categories:ys(R,Ot)||Ot||""}},qc=s=>{const i=/retryAfterMs\s*=\s*(\d+)/i.exec(String(s||""));if(!i)return null;const r=Number(i[1]);return Number.isFinite(r)&&r>0?r:null},gi=s=>{if(!s)return[];const i=Array.isArray(s)?s:String(s).split(",").map(c=>c.trim()),r=new Set,l=[];
11return i.forEach(c=>{if(!c)return;const p=c.toLowerCase();r.has(p)||(r.add(p),l.push(c))}),l},Rh=new Set(ad),hd=new Set(id),jr=s=>{if(!s)return"";const i=s.trim();return i&&Rh.has(i)?i:""},Ta=s=>{if(!s)return"";const i=s.trim();return i&&hd.has(i)?i:""},Da=s=>{if(!s)return"";const i=s.trim();return i&&hd.has(i)?i:""},wn=/^(\d{4})-(0[1-9]|1[0-2])-(0[1-9]|[12]\d|3[01])$/,Vc=s=>s.toString().padStart(2,"0"),Xo=(s,i,r)=>{if(Number.isNaN(s)||Number.isNaN(i)||Number.isNaN(r)||s<1900||s>2100||i<1||i>12||r<1||r>31)return"";const l=`${s}-${Vc(i)}-${Vc(r)}`;if(!wn.test(l))return"";const c=new Date(l);return Number.isNaN(c.getTime())?"":l},vs=s=>{if(!s)return"";const i=String(s).trim();if(!i)return"";if(wn.test(i))return i;const r=i.replace(/[^0-9]/g,"");if(r.length===8){const l=Xo(Number(r.slice(0,4)),Number(r.slice(4,6)),Number(r.slice(6,8)));if(l)return l;const c=Xo(Number(r.slice(4,8)),Number(r.slice(0,2)),Number(r.slice(2,4)));if(c)return c}if(r.length===6){const l=Xo(Number(r.slice(0,4)),Number(r.slice(4,6)),1);if(l)return l}return""},fn=s=>wn.test(s.trim()),gd=(s,i)=>typeof s.required=="function"?s.required(i):!!s.required,Wc=s=>{const i={},r=ls(s);for(const l of xn){const c=gd(l,r),p=r[l.id];if(l.id==="keywords"){const x=Array.isArray(r.keywords)?r.keywords:[];c&&x.length===0?i[l.id]="Keywords are required.":(l.minKeywords&&x.length<l.minKeywords&&(i[l.id]=`At least ${l.minKeywords} keywords required.`),l.maxKeywords&&x.length>l.maxKeywords&&(i[l.id]=`No more than ${l.maxKeywords} keywords.`));continue}if(l.id==="description"&&typeof p=="string"){const x=p.trim().length;if(c&&x===0){i[l.id]="Description is required.";continue}if(x>0){if(l.minLength&&x<l.minLength){i[l.id]=`Must be at least ${l.minLength} characters.`;continue}if(l.maxLength&&x>l.maxLength){i[l.id]=`Must be at most ${l.maxLength} characters.`;continue}if(l.minWords&&p.trim().split(/\s+/).filter(Boolean).length<l.minWords){i[l.id]=`Must contain at least ${l.minWords} words.`;continue}}continue}if(l.id==="editorialDate"||l.id==="shootingDate"){const x=typeof p=="string"?p.trim():"";if(c&&!x){i[l.id]="Date is required.";continue}x&&!fn(x)&&(i[l.id]="Invalid format. Use YYYY-MM-DD.");continue}if(c)if(l.type==="switch"){typeof r[l.id]!="boolean"&&(i[l.id]="This field is required.");continue}else typeof p=="string"&&(p.trim()||(i[l.id]="This field is required."))}return i},Jo=s=>{const i=gi(s?.keywords??[]);return{description:s?.description??"",keywords:i,category:"",batchName:"",editorial:!1,editorialText:"",editorialCity:"",editorialState:"",editorialCountry:"",editorialDate:"",title:s?.title??"",shootingCountry:"",shootingDate:"",sourceContext:null}},Mh=s=>{const i=gi(s?.keywords??[]),r=s?.platformMetadata?.blackbox?.sourceContext??s?.platformMetadata?.sourceContext??s?.sourceContext??null,l=s?.meta_json||s?.metadata||{},c=l.editorial||l.editorial_meta||{},p=l.exif||l.Exif||{},x=s?.description||l.description||l.prompt_description||"",k=s?.title||l.title||l.headline||"",R=jr(l.category||l.CategoryTitle||""),E=l.blackbox_keywords||l.keywords||l.Tags||i,b=Da(l.shooting_country||l.Country||p.Country||""),g=vs(l.shooting_date||l.ShootingDate||l.DateCreated||""),z=!!(l.editorial||l.is_editorial||c.enabled||c.is_editorial),D=Ta(c.country||l.editorial_country||l.Country||""),S=vs(c.date||l.editorial_date||l.EditorialDate||"");return ls({description:x,keywords:gi(E),category:R,batchName:l.batch_name||l.BatchName||"",editorial:z,editorialText:c.caption||l.editorial_text||l.Caption||"",editorialCity:c.city||l.editorial_city||l.City||"",editorialState:c.state||l.editorial_state||l.State||l.Region||"",editorialCountry:D,editorialDate:S,title:k,shootingCountry:b,shootingDate:g,sourceContext:r})},wr=s=>{const r={...Mh(s)},l=s.platformMetadata??null,c=l?.blackbox??l;return c&&("category"in c&&(r.category=jr(c.category??"")),"batchName"in c&&(r.batchName=(c.batchName??"").toString()),"editorial"in c&&(r.editorial=!!c.editorial),"editorialText"in c&&(r.editorialText=(c.editorialText??"").toString()),"editorialCity"in c&&(r.editorialCity=(c.editorialCity??"").toString()),"editorialState"in c&&(r.editorialState=(c.editorialState??"").toString()),"editorialCountry"in c&&(r.editorialCountry=Ta(c.editorialCountry??"")),"editorialDate"in c&&(r.editorialDate=vs(c.editorialDate??"")),"shootingCountry"in c&&(r.shootingCountry=Da(c.shootingCountry??"")),"shootingDate"in c&&(r.shootingDate=vs(c.shootingDate??"")),"s
11ourceContext"in c&&(r.sourceContext=c.sourceContext??r.sourceContext??null)),ls(r)},ls=s=>{const i=gi(s.keywords),r=cs((s.description??"").toString(),200),l=(s.batchName??"").toString().trim(),c=cs((s.title??"").toString(),100),p=(s.editorialText??"").toString().trim(),x=(s.editorialCity??"").toString().trim(),k=(s.editorialState??"").toString().trim(),R=s.editorial?Ta(s.editorialCountry??""):"",E=vs(s.editorialDate),b=s.editorial&&fn(E)?E:"",g=Da(s.shootingCountry??""),z=vs(s.shootingDate),D=z&&fn(z)?z:"";return{description:r,keywords:i,category:jr(s.category??""),batchName:l,editorial:!!s.editorial,editorialText:s.editorial?p:"",editorialCity:s.editorial?x:"",editorialState:s.editorial?k:"",editorialCountry:R,editorialDate:b,title:c,shootingCountry:g,shootingDate:D,sourceContext:s.sourceContext??null}},fi=(s,i)=>{if(!i)return;const r=pi(s);if(r.length===0)return;const l=i.trim();if(!l)return;const c=r.find(E=>E.id&&E.id===l);if(c)return c;const p=l.toLowerCase(),x=r.find(E=>E.label.toLowerCase()===p);if(x)return x;const{id:k,label:R}=pd(l);if(k){const E=r.find(b=>b.id===k);if(E)return E}if(R){const E=r.find(b=>b.label.toLowerCase()===R.toLowerCase());if(E)return E}},Hc=(s,i)=>{const r=(i||"").trim();if(!r||r==="__EMPTY__")return"";const l=fi(s,r);if(l)return l.id??l.label;const c=pd(r);return c.id&&fi(s,c.id)?c.id:c.raw},ys=(s,i)=>{if(!i||i==="__EMPTY__")return"";const r=fi(s,i);return r?r.id?`${r.id} — ${r.label}`:r.label:i.trim()},wa=s=>s.id?`${s.id} — ${s.label}`:s.label,Gc=s=>s.toLowerCase().replace(/[^a-z0-9]+/g," ").trim(),Zo=s=>{if(!s)return"";const i=s.trim();if(!i)return"";const r=i.match(/^\s*(\d+)\s*[–—-]\s*(.+)$/);return r?r[2].trim():i},oi=(s,i)=>{if(!i)return;const r=Gc(i);return pi(s).find(c=>Gc(c.label)===r)},ni=(s=[],i=[])=>{if(s.length!==i.length)return!1;for(let r=0;r<s.length;r+=1)if(s[r]!==i[r])return!1;return!0},Cr=(s,i,r,l)=>{const c=new Set;s.forEach(k=>{k&&c.add(k.toLowerCase())}),Oc(i).forEach(k=>c.add(k)),Oc(r).forEach(k=>c.add(k));let p="",x=0;return Nh.forEach(k=>{const R=(k.tokens||[]).reduce((E,b)=>c.has(b)?E+1:E,0);R>x&&(p=k.label,x=R)}),x>0?p:l&&l.trim().length>0?l:c.has("people")||c.has("person")?"People":Eh},wg=()=>{const{sessionId:s}=qu(),i=Xc(),{toast:r}=Ea(),l=Vu(),{user:c,profile:p}=Wu(),x=Hu(),k=d.useMemo(()=>new URLSearchParams(x.search).has("bench"),[x.search]),{setCredits:R}=rc(),{currentSession:E,currentImages:b,selectedImageId:g,generationMode:z,unlimitedActive:D,unlimitedUsage:S,unlimitedLimit:$,planTier:O,planHydrated:re,
11setGenerationMode:ge,setUnlimitedUsage:V,incrementUnlimitedUsage:L,credits:ae,deductCredits:he,hasEnoughCredits:ne,setImageCategoryOverride:ie,getImageCategoryOverride:De,updateImageMetadata:Q,updatePlatformMetadata:ye,updateImageScores:xe,hydrateFromServer:je,clearSessionState:Me,setCurrentSession:Ge,appendCurrentImages:pt,setSelectedImage:it,getSelectedImages:Be,selectAllImages:bt,deselectAllImages:j,toggleImageSelection:H}=rc(),{barAnnouncement:J,popupAnnouncements:ve,popupOpenId:_,setPopupOpenId:U,loadAnnouncements:ee,dismissAnnouncement:ze,handleCtaAction:at,getCountdown:ot}=km(),Gt=d.useRef(!1),Ue=Os(t=>t.releases),ht=Os(t=>t.setReleases),Re=Os(t=>t.setPersons),Ie=Pe(t=>t.linksByImageId),Ot=Pe(t=>t.requiredByImageId),yi=Pe(t=>t.suggestionsByImageId),xi=Pe(t=>t.suggestionStatusByImageId),vn=Pe(t=>t.setLinksFromAssignments),kn=Pe(t=>t.hydrateFlagsFromImages),Ia=Pe(t=>t.mergeSuggestionsFromScanResults),Ra=Pe(t=>t.upsertLinksFromAssignments),Cn=Pe(t=>t.loadRecentFromStorage),Ma=Pe(t=>t.setLoading),It=Ps(t=>t.releaseFaceMatch),[Ba,Sn]=d.useState(!1),[fd,yd]=d.useState(null),[xd,La]=d.useState(!1),Fa=d.useRef(!1),bi=d.useCallback(async t=>{if(s){if(It?.enabled!==!0){r({title:"Face matching disabled",description:"Enable it in Settings → Platform to get suggestions."});return}if(!Ba){Sn(!0);try{const a=await lh.scanSession({sessionId:s,assetIds:t.assetIds,options:{similarityThreshold:Number(It?.similarityThreshold??.78),onlyHighConfidence:It?.onlyHighConfidence!==!1,includeArchivedReleases:It?.includeArchivedReleases===!0,limitToCurrentBatchFirst:It?.limitToCurrentBatchFirst!==!1,usePersonReferenceImages:It?.usePersonReferenceImages!==!1,...t.forceReindex?{forceReindex:!0}:{}}});if(yd(a),Ia(a.results),It?.autoAttachHighConfidence===!0){const n=[];for(const o of a.results||[]){if(o.status!=="high_confidence")continue;const u=String(o.session_image_id||"").trim(),m=String(o.suggestions?.[0]?.release_id||"").trim();if(!u||!m)continue;const h=Ie?.[u]||[];Array.isArray(h)&&h.length>0||n.push({imageId:u,releaseId:m})}if(n.length>0&&c?.id){const o=await Dt.upsertAssignments({userId:c.id,sessionId:s,rows:n.map(u=>({user_id:c.id,session_id:s,session_image_id:u.imageId,release_id:u.releaseId,link_type:"batch_auto"}))});Ra(o),r({title:"Auto-attached releases",description:`Attached ${n.length} high-confidence match${n.length===1?"":"es"}.`})}}t.openResults&&La(!0),r({title:"Face suggestions updated",description:`${a.summary.matchedSuggestions} matched · ${a.summary.needReview} need review · ${a.summary.noConfidentMatch} no match`})}catch(a){r({title:"Face scan failed",description:a?.message||"Could not scan this session",variant:"destructive"})}finally{Sn(!1)}}}},[s,It,Ba,r,Ia,Ie,Ra,c?.id]);d.useEffect(()=>{Cn()},[Cn]),d.useEffect(()=>{kn(b)},[b,kn]),d.useEffect(()=>{if(!c?.id)return;let t=!1;return(async()=>{try{const[a,n]=await Promise.all([Dt.listReleases(c.id),Dt.listPersons(c.id)]);if(t)return;ht(a),Re(n)}catch(a){console.warn("[ReviewEdit] Failed to load releases library",a)}})(),()=>{t=!0}},[c?.id,ht,Re]),d.useEffect(()=>{if(!c?.id||!s||b.length===0)return;let t=!1;return(async()=>{Ma(!0);try{const a=await Dt.listAssignmentsForSession(c.id,s).catch(async()=>{const n=b.map(o=>o.id);return await Dt.listAssignmentsForImages(c.id,n)});if(t)return;vn(a)}catch(a){console.warn("[ReviewEdit] Failed to load release assignments",a)}finally{t||Ma(!1)}})(),()=>{t=!0}},[c?.id,s,b.length,vn,Ma]),d.useEffect(()=>{if(!c?.id||!s||It?.enabled!==!0||It.scanAfterProcessing===!1||Fa.current||b.length===0||Ue.length===0||!b.every(n=>{const o=n.processingStatus;return o==="ready"||o==="ready_partial"||o==="error"||typeof o>"u"||o===null}))return;const a=b.filter(n=>!{...n.metadata||{},...n.meta_json||{}}?.release_suggestions_scanned_at).map(n=>n.id);if(a.length===0){Fa.current=!0;return}Fa.current=!0,bi({assetIds:a,openResults:!0})},[c?.id,s,It,b,Ue.length,bi]);const jn=d.useRef(0),Nn=d.useRef(null);d.useEffect(()=>{c?.id&&ee()},[c?.id]);const[En,wi]=d.useState(!0),[_n,Pa]=d.useState(null),[Us,An]=d.useState(null),[bd,Tn]=d.useState(!1),[qs,Dn]=d.useState(null),[Se,lt]=d.useState(null),[Ka,vi]=d.use
11State(!1),[W,$a]=d.useState("Adobe Stock"),Ye=W==="Blackbox",In=W==="Adobe Stock",Rn=W==="Shutterstock",st=d.useMemo(()=>{const t=String(W||"").toLowerCase();return t.includes("adobe")?"adobe":t.includes("shutterstock")?"shutterstock":t.includes("pond5")?"pond5":t.includes("getty")?"getty":t.includes("istock")||t.includes("i stock")?"istock":"generic"},[W]),[Mn,Yt]=d.useState({}),Oa=d.useMemo(()=>Object.keys($o.platforms),[]),qe=d.useMemo(()=>$o.platforms[W],[W]),[Xt,wd]=d.useState(!1),[Bn,ki]=d.useState(null),Ci=d.useRef(null);d.useEffect(()=>{ki(null),Ci.current=null},[g]);const[ct,vd]=d.useState(null);d.useEffect(()=>{try{const t=s;if(!t)return;const a=hc(E,t);if(!a)return;const n=a.selectedPlatformLabel,o=n?xh[n]??n:void 0,u=`${t}::${o??""}`;o&&Oa.includes(o)&&Nn.current!==u&&(Nn.current=u,$a(w=>w===o?w:o));const m=!!a.editorialByPlatform?.[a.selectedPlatformId]?.enabled;wd(m);const h=n?$o.platforms[n]:null,y=typeof h?.editorial_style=="string"?h.editorial_style:null;y&&vd(y)}catch{}},[E,Oa,s]);const ks=d.useMemo(()=>(qe?.columns||[]).some(t=>t==="Category"||t==="Categories"),[qe]),Lt=d.useMemo(()=>!!qe?.supports_editorial,[qe]),Ln=Xt&&Lt,Fn=d.useMemo(()=>pi(W),[W]),Pn=d.useCallback(t=>{const a=fi(W,t);return a?a.id??a.label:"__EMPTY__"},[W]),[kd,za]=d.useState(!1),[Kn,$n]=d.useState(!1),[On,Cd]=d.useState(!1);d.useEffect(()=>{if(c?.id&&!Kn)try{const t=typeof window<"u"?window.localStorage.getItem("has_seen_originals_ttl_info"):null,a=!!p?.has_seen_originals_ttl_info;if(t==="1"||a){$n(!0);return}za(!0),$n(!0)}catch{}},[c?.id,p,Kn]);const[Sd,Ua]=d.useState(1),jd=()=>Ua(1),Nd=()=>Ua(t=>Math.min(3,t+.2)),Ed=()=>Ua(t=>Math.max(.4,t-.2)),[_d,Si]=d.useState(!1);d.useRef(!1);const[zn]=d.useState(","),[Un]=d.useState('"'),[Ad]=d.useState(!0),[qn,Td]=d.useState(""),[Bh,Dd]=d.useState(null),[Id,Nr]=d.useState(!1),[ji,Vn]=d.useState("metadata"),[Ni,Wn]=d.useState(!1),[Rd,Ei]=d.useState(!1),[_i,qa]=d.useState(()=>({...Mc,editorial:!1})),[Hn,Ai]=d.useState({...xr}),[Md,Ti]=d.useState(!1),[Di,Gn]=d.useState(!1),[zt,Yn]=d.useState({...Bc}),[Cs,Xn]=d.useState({...Lc}),[Va,ds]=d.useState(!1),[Bd,Ii]=d.useState(!1),[Ld,Wa]=d.useState("unlimited"),[Fd,Jn]=d.useState(!1),Vs=d.useMemo(()=>Gu(p),[p]),Zn=t=>{Wa("unlimited"),Ii(!0),r({title:"Upgrade required",description:`${t} is available on paid CyberStock plans. CSV export remains available on the free plan.`})},[Pd,Ha]=d.useState(!1),[Ri,Kd]=d.useState([]),[Ft,Ws]=d.useState(!1),[Ut,Ga]=d.useState({completed:0,total:0}),Ya=1,Mi=d.useRef({completed:0,total:0}),[$d,Xa]=d.useState([]),[Od,Ja]=d.useState(null);d.useRef(null);const[Za,Qn]=d.useState(""),el=d.useRef("");d.useEffect(()=>{el.current=Za},[Za]);const Er=d.useRef(new Set),tl=d.useRef(!0),Qa=d.useRef(null),sl=d.useRef(!1),_r=d.useRef({}),zd=d.useRef(!1),rl=pa(t=>t.spotlightSurface!==null),[Lh,Ud]=d.useState(!1),[eo,il]=d.useState(!1),[to,al]=d.useState(!1),ol="editorial_hints_dismissed_v1",[nl,qd]=d.useState(()=>{if(typeof window>"u")return!1;try{return localStorage.getItem(ol)==="1"}catch{return!1}});d.useCallback(()=>{if(!nl){zd.current=!0,Ud(!0),il(!0),al(!0),qd(!0);try{localStorage.setItem(ol,"1")}catch{}}},[nl]);const ll=d.useRef({}),Ar=d.useCallback(async t=>{if(!Xt||!Lt)return null;const a=ll.current;if(a[t.id]!==void 0)return a[t.id];try{let n=t.imageUrl||t.thumbnailUrl||"";if(console.debug("[ReviewEdit] ensureEditorialFromImage start",{id:t.id,filename:t.filename,imageUrl:t.imageUrl,thumbnailUrl:t.thumbnailUrl,srcInitial:n}),!n)return a[t.id]=null,null;if(!(n.startsWith("http://")||n.startsWith("https://")||n.startsWith("data:")))try{n=await Tt.getAccessibleUrl(Yu.STORAGE_BUCKET,n)}catch{return a[t.id]=null,null}if(n.includes("r2.cloudflarestorage.com"))return console.debug("[ReviewEdit] Skipping editorial EXIF parse for R2 asset due to CORS",{id:t.id,src:n}),a[t.id]=null,null;const u=await fetch(n);if(console.debug("[ReviewEdit] ensureEditorialFromImage fetch",{id:t.id,src:n,ok:u.ok,status:u.status}),!u.ok)return a[t.id]=null,null;const m=await u.blob(),h=(m.type||"").toLowerCase();if(!(h==="image/jpeg"||h==="image/jpg"||h==="image/tiff"))return console.debug("[ReviewEdit] Skipping editorial EXIF parse for non-JPEG blob",{id:t.id,src:n,mime:h}),a[t.id]=null,null;const w=new File([m],t.filename||"image.jpg",{type:h||"image/jpeg"}),v=await Xu(w);return console.debug("[ReviewEdit] ensureEditorialFromImage result",{id:t.id,enabled:v?.enabled,city:v?.city,state:v?.state,country:v?.country,date:v?.date}),a[t.id]=v,v}catch(n){return console.warn("[ReviewEdit] Failed to extract editorial metadata",n),ll.current[t.id]=null,null}},[Xt,Lt]),[so,cl]=d.useState(()=>Kc()),[dl,ul]=d.useState(()=>
11$c()),[ro,io]=d.useState(()=>new Set),[Bi,ml]=d.useState(()=>Go()),[Jt,Hs]=d.useState(null),[Tr,Zt]=d.useState(""),ao=20,Ss=d.useRef(new Map),Gs=d.useRef(new Map),[pl,oo]=d.useState(0),Qt=d.useCallback((t,a)=>{const n=Ss.current.get(t)??[];n.push({...a,keywords:[...a.keywords]}),n.length>ao&&n.shift(),Ss.current.set(t,n),Gs.current.set(t,[]),oo(o=>o+1)},[]),Vd=d.useMemo(()=>g?(Ss.current.get(g)?.length??0)>0:!1,[g,pl]),Wd=d.useMemo(()=>g?(Gs.current.get(g)?.length??0)>0:!1,[g,pl]),wt=d.useCallback(t=>({title:t.title??"",description:t.description??"",keywords:Array.isArray(t.keywords)?[...t.keywords]:[],categories:t.categories??"",baseTitle:t.baseTitle??t.title??"",baseDescription:t.baseDescription??t.description??"",baseKeywords:Array.isArray(t.baseKeywords)?[...t.baseKeywords]:Array.isArray(t.keywords)?[...t.keywords]:[]}),[]),Hd=d.useCallback(()=>{if(!g)return;const t=Ss.current.get(g);if(!t||t.length===0)return;const a=b.find(m=>m.id===g);if(!a)return;const n=Gs.current.get(g)??[];n.push(wt(a)),n.length>ao&&n.shift(),Gs.current.set(g,n);const o=t.pop();Ss.current.set(g,t);const u={title:o.title,description:o.description,keywords:o.keywords,baseTitle:o.baseTitle??o.title,baseDescription:o.baseDescription??o.description,baseKeywords:o.baseKeywords??o.keywords};o.categories!==void 0&&(u.categories=o.categories),Q(g,u),we.updateSessionImage(g,{title:o.title,description:o.description,keywords:o.keywords.join(", "),categories:(o.categories??"")||null,baseTitle:o.baseTitle??o.title,baseDescription:o.baseDescription??o.description,baseKeywords:o.baseKeywords??o.keywords}).catch(()=>{}),Hs(null),oo(m=>m+1),r({title:"Undone",description:"Last change reverted"})},[g,b,Q,wt,r]),Gd=d.useCallback(()=>{if(!g)return;const t=Gs.current.get(g);if(!t||t.length===0)return;const a=b.find(m=>m.id===g);if(!a)return;const n=Ss.current.get(g)??[];n.push(wt(a)),n.length>ao&&n.shift(),Ss.current.set(g,n);const o=t.pop();Gs.current.set(g,t);const u={title:o.title,description:o.description,keywords:o.keywords,baseTitle:o.baseTitle??o.title,baseDescription:o.baseDescription??o.description,baseKeywords:o.baseKeywords??o.keywords};o.categories!==void 0&&(u.categories=o.categories),Q(g,u),we.updateSessionImage(g,{title:o.title,description:o.description,keywords:o.keywords.join(", "),categories:(o.categories??"")||null,baseTitle:o.baseTitle??o.title,baseDescription:o.baseDescription??o.description,baseKeywords:o.baseKeywords??o.keywords}).catch(()=>{}),Hs(null),oo(m=>m+1),r({title:"Redone",description:"Change re-applied"})},[g,b,Q,wt,r]),N=d.useMemo(()=>g?b.find(t=>t.id===g)??null:null,[b,g]),Yd=d.useMemo(()=>{const t={};for(const a of b)t[a.id]={meta_json:a?.meta_json??null,metadata:a?.metadata??null};return t},[b]),Dr=d.useMemo(()=>new Map(Ue.map(t=>[t.id,t])),[Ue]),us=d.useMemo(()=>g?(Ie[g]||[]).map(a=>a.releaseId):[],[g,Ie]),hl=d.useMemo(()=>{if(us.length===0)return[];const t=new Map(Ue.map(a=>[a.id,a]));return us.map(a=>t.get(a)).filter(Boolean)},[us,Ue]),Xd=us.length>0,Li=d.useMemo(()=>N?dd({platformId:st,meta:N?.meta_json??null,metadata:N?.metadata??null,attachedReleaseIds:us,releasesById:Dr}):null,[N,st,us,Dr]),Jd=d.useMemo(()=>{const t=st==="istock"||st==="getty"?"getty":st==="adobe"||st==="shutterstock"||st==="pond5"?st:null;if(!t)return!1;for(const a of hl)if(hi(a,t).status!=="ready")return!0;return!1},[hl,st]),Zd=d.useCallback(t=>{const a=Ie[t]||[],n=a.length,o=!!Ot[t],u=yi[t]||[],m=xi[t];let h=0,y=0;for(const w of a){const v=Dr.get(w.releaseId);v&&(v.type==="property"?y+=1:h+=1)}return o&&n===0?{kind:"missing"}:n===0&&(u.length>0||m==="conflict")?{kind:"suggested"}:n>=2?{kind:"multi"}:h>=1?{kind:"mr"}:y>=1?{kind:"pr"}:{kind:"none"}},[Ie,Ot,yi,xi,Dr]),Ys=Ln&&!!N?.editorial;d.useEffect(()=>{Ys||(qa(t=>t.editorial?{...t,editorial:!1}:t),Ai({...xr}))},[Ys]),d.useEffect(()=>{_i.editorial||Ai({...xr})},[_i.editorial]);const Qd=!!N?.analyticsUnlocked;d.useEffect(()=>{cl(Kc()),ul($c()),io(new Set),ml(Go())},[g]);const gl=Qd||Object.values(so).some(t=>t>0),ms=d.useMemo(()=>Be(),[Be,b]),ke=ms.length,eu=!!(N&&ms.some(t=>t.id===N.id)),gt=Math.max(0,ke-(eu?1:0)),Fi=gt>0,[Fh,fl]=d.useState(!1),[Ph,yl]=d.useState({title:!1,description:!1,keywords:!1}),[Xs,Ir]=d.useState({title:!1,description:!1,keywords:!1}),[xl,bl]=d.useState(null),[Js,wl]=d.useState(null),[tu,su]=d.useState(!1),[fe,vl]=d.useState(ba),[ps,no]=d.use
11State(!1),[Rr,Mr]=d.useState({processed:0,total:0}),[Pi,lo]=d.useState(null),[co,ru]=d.useState("selling"),[js,iu]=d.useState("desc"),[Zs,kl]=d.useState(null),Br=en.useCallback((t,a)=>{const n=u=>t==="selling"?u.sellingScorePercent??u.sellingScore??-1:t==="title"?u.titleScorePercent??u.titleScore??-1:t==="description"?u.descriptionScorePercent??u.descriptionScore??-1:u.keywordScorePercent??u.keywordScore??-1,o=[...b].sort((u,m)=>{const h=Number(n(u)),y=Number(n(m)),w=(Number.isFinite(y)?y:-1)-(Number.isFinite(h)?h:-1);return a==="desc"?w:-w}).map(u=>u.id);ru(t),iu(a),kl(o)},[b]),au=en.useCallback(()=>{kl(null)},[]),ou=d.useMemo(()=>{if(Zs&&Zs.length>0){const t=new Map(Zs.map((n,o)=>[n,o])),a=[...b];return a.sort((n,o)=>{const u=t.get(n.id),m=t.get(o.id);return u===void 0&&m===void 0?0:u===void 0?1:m===void 0?-1:u-m}),a}return[...b]},[b,Zs]),Ki=d.useCallback(t=>t?Array.isArray(t)?ci(t.map(a=>String(a??"").trim()).filter(Boolean)):typeof t=="string"?ci(t.split(",").map(a=>a.trim()).filter(Boolean)):[]:[],[]),Qs=d.useCallback(t=>{if(!t)return[];const a=[t.keywords,t.baseKeywords,t?.metadata?.keywords,t?.meta_json?.keywords];for(const n of a){const o=Ki(n);if(o.length>0)return o}return[]},[Ki]),nu=d.useCallback(t=>({title:t?.title??"",description:t?.description??"",keywords:Qs(t),locale:"en",category:t?.categories??"general"}),[Qs]),lu=d.useCallback((t,a)=>{const n=t.keywordAnalyses??[];if(n.length===0)return[];const o=(a.locale??"en").toLowerCase(),u=(a.category??"general").toLowerCase(),m=new Set(a.keywords.map(h=>h.toLowerCase()));return n.reduce((h,y)=>{const w=y.keyword?.trim();if(!w)return h;const v=(y.normalizedKeyword||w).toLowerCase();return h.push({keyword:w,normalizedKeyword:v,locale:o,category:u,searchVolume:y.searchVolume??0,vpnPercentile:y.vpnPercentile??0,trendScore:y.trendScore??0,relevance:m.has(v)||m.has(w.toLowerCase())?.7:.4,hcv:y.hcv??0,strength:y.strength??ha.classifyStrength(y.hcv??0),slope:null}),h},[])},[nu]),Ce=d.useMemo(()=>
11!Ye||!N?null:wr(N),[Ye,N]),[er,$i]=d.useState(!1),[Oi,Ns]=d.useState(null),[Le,nt]=d.useState(null),[Cl,dt]=d.useState({}),[Sl,vt]=d.useState(!1),[zi,es]=d.useState(""),Ui=d.useRef(null);d.useEffect(()=>{const t=a=>{if(a.defaultPrevented||a.metaKey||a.ctrlKey||a.altKey||String(a.key||"").toLowerCase()!=="r")return;const n=a.target,o=(n?.tagName||"").toLowerCase();o==="input"||o==="textarea"||o==="select"||n?.isContentEditable||g&&(Se||er||(a.preventDefault(),Ei(u=>!u)))};return window.addEventListener("keydown",t),()=>window.removeEventListener("keydown",t)},[g,Se,er]);const jl=d.useCallback(t=>t===null?"var(--cs-text-tertiary)":t>=80?"#10b981":t>=60?"#f59e0b":"#ef4444",[]),Nl=d.useCallback(t=>{if(t===null)return null;const a=jl(t);return e.jsxs("span",{className:"inline-flex items-center gap-1.5 rounded-full px-2 py-0.5 text-[11px] font-semibold",style:{background:"rgba(124,92,255,.1)",color:"var(--cs-text-primary)",border:"1px solid rgba(124,92,255,.2)"},children:[e.jsx("span",{className:"w-[6px] h-[6px] rounded-full shrink-0",style:{background:a}}),t]})},[jl]),uo=d.useCallback((t,a)=>{if(a===null)return null;const n=[];return t==="selling"?n.push({label:"What it means",value:"Overall marketability based on other scores"},{label:"Weights",value:"Title 45% · Description 35% · Keywords 20%"},{label:"Tip",value:"Put strongest keywords early in the Title; keep Description concise and specific"}):t==="title"?n.push({label:"Lead keywords",value:"60% (first 80 chars)"},{label:"Relevance",value:"25% (topic match)"},{label:"Readability",value:"15% (length, punctuation)"},{label:"Tip",value:"Start with 1–2 strongest terms; avoid shouting and extra punctuation"}):t==="description"?n.push({label:"Strong/Medium density",value:"45% (first 160 chars)"},{label:"Relevance",value:"25% (topic match)"},{label:"Readability",value:"30% (length, clarity)"},{label:"Tip",value:"Mention 2 strong + 1 medium keyword naturally in the first sentence"}):t==="keywords"&&n.push({label:"Basis",value:"Avg HCV of top‑10 keywords (soft‑cap 0.90)"},{label:"HCV",value:"Weighted by volume, trend, and relevance"},{label:"Tip",value:"Favor high‑volume + rising trends; remove duplicates and weak fillers"}),e.jsx(Ee,{delayDuration:150,children:e.jsxs(_e,{children:[e.jsx(Ae,{asChild:!0,children:Nl(a)}),e.jsx(Te,{side:"top",className:"max-w-xs p-3 text-xs",children:e.jsx("div",{className:"space-y-1",children:n.map(o=>e.jsxs("div",{children:[e.jsxs("span",{className:"font-medium",children:[o.label,":"]})," ",o.value]},`${t}-${o.label}`))})})]})})},[Nl]),qi=2,Vi=2,El=1,Wi=1;N?.keywordMode;const tr=d.useMemo(()=>N?{title:zp(N.title??""),description:N.description??"",keywords:Qs(N)}:{title:"",description:"",keywords:[]},[Qs,N]),sr=d.useCallback(t=>[tr.title?.toLowerCase()??"",tr.description?.toLowerCase()??"",t].join("::"),[tr.description,tr.title]),_l=d.useCallback(t=>{const[a,n]=kh[t],o=`${sr(`baseline:${t}`)}`;return Math.round(_t(o,a,n))},[sr]),Lr=d.useCallback((t,a)=>{const n=_l(t),o=`${sr(`floor:${t}`)}`,u=`${sr(`jitter:${t}`)}`,m=Math.round(_t(o,2,7)),h=Math.round(_t(u,-6,6)),y=typeof a=="number"&&Number.isFinite(a);let w=n;if(y)if(a<n){const A=a+(n-a)*.7;w=Math.max(A,n-m)}else w=a;const v=w+(so[t]??0)+h;return Math.min(100,Math.max(0,Math.round(v)))},[sr,_l,so]),Fr=d.useCallback((t,a)=>{if(t===null||typeof t>"u"||Number.isNaN(t))return null;const n=Number(t),o=n>1?n:n*100,u=Math.round(o);return Math.max(0,Math.min(100,u))},[sr]),Pr=d.useMemo(()=>N?.keywordAnalyses??[],[N?.keywordAnalyses]),hs=d.useMemo(()=>{if(!N)return null;const t=Pr.reduce((h,y)=>(h[y.normalizedKeyword]=y.strength,h),{}),a=Pr.reduce((h,y)=>(h[y.normalizedKeyword]=y.hcv??0,h),{}),n=typeof N.scoreBreakdown?.strengths=="object"?Object.entries(N.scoreBreakdown.strengths):null,o=n?n.reduce((h,[y,w])=>{if(!y)return h;const v=y.toLowerCase();return(w==="strong"||w==="medium"||w==="weak")&&(h[v]=w),h},{}):void 0,u=typeof N.scoreBreakdown?.hcv=="object"?Object.entries(N.scoreBreakdown.hcv):null,m=u?u.reduce((h,[y,w])=>{if(!y)return h;const v=y.toLowerCase(),A=typeof w=="number"?w:Number(w);return Number.isFinite(A)&&(h[v]=A),h},{}):void 0;return{sellingScorePercent:Fr(N.sellingScorePercent??N.sellingScore??null,"selling"),titleScorePercent:Fr(N.titleScorePercent??N.titleScore??null,"title"),descriptionScorePercent:Fr(N.descriptionScorePercent??N.descriptionScore??null,"description"),keywordScorePercent:Fr(N.keywordScorePercent??N.keywordScore??null,"keyword"),strengths:o??t,hcv:m??a}},[Pr,Fr,N]),Hi=hs?.sellingScorePercent??null,Gi=hs?.titleScorePercent??null,Yi=hs?.descriptionScorePercent??null,Xi=hs?.keywordScorePercent??N?.keywordScore??null,Al=typeof import.meta<"u"&&!1,Ji=d.useCallback(t=>{const a=(t.keyword??"").trim();if(!a)return t;const n=`${N?.id??s??"session"}::${a.toLowerCase()}`,o={...t,keyword:a},u={low:[30,240],mid:[220,980],high:[900,3600]},m=!Number.isFinite(o.searchVolume)||(o.searchVolume??0)<=10,h=!Number.isFinite(o.trendScore)||(o.trendScore??0)<=.05;let y="low";if(h){const M=_t(`${n}:trendBucket`,0,99);M<30?(o.trendScore=_t(`${n}:trend_low`,18,42)/100,y="low"):M<80?(o.trendScore=_t(`${n}:trend_mid`,43,72)/100,y="mid"):(o.trendScore=_t(`${n}:trend_high`,73,96)/100,y="high")}else typeof o.trendScore=="number"&&(o.trendScore>=.73?y="high":o.trendScore>=.43&&(y="mid"));const[w,v]=u[y];if(m)o.searchVolume=_t(`${n}:volume_${y}`,w,v);else if((o.searchVolume??0)<w){const M=_t(`${n}:volume_adjust_${y}`,w,v),q=Math.round(((o.searchVolume??w)+M)/2);o.searchVolume=Math.max(w,Math.min(v,q))}if(!Number.isFinite(o.hcv)||(o.hcv??0)<=.15){const M=_t(`${n}:marketBucket`,0,99);M<20?o.hcv=_t(`${n}:market_low`,28,45)/100:M<65?o.hcv=_t(`${n}:market_mid`,46,68)/100:o.hcv=_t(`${n}:market_high`,69,90)/100}
11const I=To({hcv:o.hcv??0,searchVolume:o.searchVolume??0,trendScore:o.trendScore??0});return o.strength=I,o},[N?.id,s]),Zi=d.useMemo(()=>{const t=new Map;return Pr.forEach(a=>{if(!a||!a.keyword)return;const n=Ji({strength:a.strength,hcv:typeof a.hcv=="number"?a.hcv:null,searchVolume:typeof a.searchVolume=="number"?a.searchVolume:null,trendScore:typeof a.trendScore=="number"?a.trendScore:null,keyword:a.keyword});t.set(a.keyword.toLowerCase(),n)}),hs?.strengths&&Object.entries(hs.strengths).forEach(([n,o])=>{if(!n)return;const u=n.toLowerCase();if(t.has(u))return;const m=Ji({strength:o,hcv:hs.hcv?.[n]??0,searchVolume:0,trendScore:0,keyword:n});t.set(u,m)}),t.size===0&&tr.keywords.forEach(a=>{const n=a.toLowerCase();if(!t.has(n)){const o=Ji({strength:"weak",hcv:0,searchVolume:0,trendScore:0,keyword:a});t.set(n,o)}}),t},[tr.keywords,Pr,Ji,hs]),Tl=d.useMemo(()=>{const t=new Map,a=new Map,n={strong:2,medium:1,weak:0},o=(y,w)=>{const v=y.keyword??"",A=v.toLowerCase();if(!A)return;const I={hcv:y.hcv,searchVolume:y.searchVolume,trendScore:y.trendScore},M=dc(I),q=M.lines.map(ce=>ce.level),te=w||(q.every(ce=>ce==="strong")?"strong":q.some(ce=>ce==="weak"||ce==="unknown")?"weak":"medium");te==="weak"&&q.every(ce=>ce==="unknown");const me={verdict:te,descriptor:M,keyword:v},pe=t.get(A);(!pe||n[te]>n[pe.verdict])&&t.set(A,me),A.split(/[^a-z0-9]+/g).filter(Boolean).forEach(ce=>{const oe=a.get(ce);(!oe||n[te]>n[oe.verdict])&&a.set(ce,me)})},u=[];Zi.forEach(y=>{y&&u.push(y)});const m=y=>{const w=[y.trendScore,y.hcv,y.searchVolume].map(v=>typeof v=="number"&&Number.isFinite(v)?v:-1/0);return Math.max(...w)};if(u.sort((y,w)=>m(w)-m(y)).slice(0,16).forEach(y=>o(y)),t.size>0)return{keywords:t,tokens:a};const h=[];return Zi.forEach(y=>h.push(y)),h.sort((y,w)=>(w.hcv??-1/0)-(y.hcv??-1/0)).slice(0,4).forEach(y=>o(y,To({hcv:y.hcv,searchVolume:y.searchVolume,trendScore:y.trendScore}))),{keywords:t,tokens:a}},[Zi]),Dl=d.useMemo(()=>{const t=new Set;return(Array.isArray(N?.keywords)?N.keywords:[]).forEach(n=>{String(n).toLowerCase().split(/[^a-z0-9]+/g).filter(Boolean).forEach(o=>t.add(o))}),t},[N?.keywords]),Il=d.useCallback(t=>{const a=String(t||"").split(/(\s+)/);return e.jsx(e.Fragment,{children:a.map((n,o)=>{const u=n.toLowerCase().trim(),m=u&&u.length>=3&&Dl.has(u)?Tl.tokens.get(u):void 0;return u&&ro.has(u)?e.jsx("span",{className:"rounded px-[3px] py-[1px] text-[13px] font-semibold text-emerald-900 bg-emerald-100 ring-1 ring-emerald-300",children:n},`${n}-${o}`):m&&m.verdict?e.jsx(Ee,{delayDuration:120,children:e.jsxs(_e,{children:[e.jsx(Ae,{asChild:!0,children:e.jsx("span",{className:mt("rounded px-[3px] py-[1px] text-[13px] font-semibold ring-1 cursor-help",gh[m.verdict]),children:n})}),e.jsx(Te,{side:"bottom",className:"text-xs space-y-1",children:e.jsx(jh,{descriptor:m.descriptor,keyword:m.keyword,showVolume:gl})})]})},`${n}-${o}`):e.jsx("span",{children:n},o)})})},[ro,Dl,gl,Tl.tokens]);d.useCallback(async t=>{if(!(!t||t.length===0))try{const{data:a,error:n}=await Do.from("session_images").select(["id","title","description","keywords","keyword_mode","score_payload","selling_score","title_score","description_score","keyword_score","selling_score_percent","title_score_percent","description_score_percent","keyword_score_percent"].join(", ")).in("id",t);if(n)throw n;if(!a||a.length===0)return;je(a),a.forEach(o=>{if(!o?.id)return;const u=Ki(o.keywords);Q(o.id,{title:o.title??"",description:o.description??"",keywords:u,keywordMode:o.keyword_mode??null})})}catch(a){console.warn("[ReviewEdit] Failed to refresh optimized images",{ids:t,error:a})}},[je,Ki,Q]);const cu=d.useMemo(()=>{if(!E)return"Session";const t=(E.title??"").trim();if(t)return t;const a=E.created_at??E.updated_at??null;if(a)try{return`Session · ${new Intl.DateTimeFormat("en",{month:"short",day:"numeric",year:"numeric",hour:"2-digit",minute:"2-digit"}).format(new Date(a))}`}catch(n){console.warn("[ReviewEdit] Failed to format session timestamp",n)}return E.id?`Session ${E.id.substring(0,8)}`:"Session"},[E]);d.useEffect(()=>{if(!Ye){$i(!1),Ns(null),nt(null),dt({}),vt(!1),es("");return}if(!N){Ns(null),nt(Jo(null)),dt({}),vt(!1),es("");return}if(Oi!==N.id||!Le){const t=wr(N);nt(t),dt({}
11),vt(!1),es(""),Ns(N.id)}},[Ye,er,N,g,Oi,Le]);const Qi=d.useMemo(()=>Le?Wc(Le):{},[Le]);d.useMemo(()=>Object.values(Qi).some(Boolean),[Qi]);const Es=d.useCallback(t=>{dt(a=>a[t]?a:{...a,[t]:!0})},[]),Rl=d.useCallback(t=>{dt(a=>{const n={...a};return Object.entries(t).forEach(([o,u])=>{u&&(n[o]=!0)}),n})},[]),Ml=d.useCallback(t=>{nt(a=>{if(!a)return a;const n={...a,editorial:t};return t||(n.editorialText="",n.editorialCity="",n.editorialState="",n.editorialCountry="",n.editorialDate=""),n}),Es("editorial")},[Es]),ea=d.useCallback((t,a)=>{nt(n=>n&&{...n,[t]:a})},[]),mo=d.useCallback(()=>{const t=gi(zi).filter(Boolean);t.length!==0&&(nt(a=>{if(!a)return a;const n=[...a.keywords],o=new Set(n.map(u=>u.toLowerCase()));return t.forEach(u=>{const m=u.toLowerCase();o.has(m)||(o.add(m),n.push(u))}),{...a,keywords:n}}),dt(a=>({...a,keywords:!0})),es(""))},[zi]),rr=d.useCallback(async(t,a)=>{if(!Ye||!g)return{success:!1};const n=a?.metadataOverride??Le;if(!n)return{success:!1};vt(!0);const o=ls(n),u=Wc(o);if(Object.values(u).some(Boolean))return Rl(u),a?.silent||r({title:"Blackbox metadata incomplete",description:"Fix highlighted fields first.",variant:"destructive"}),{success:!1};try{const m=N?.platformMetadata??{},h={category:o.category,batchName:o.batchName,editorial:o.editorial,editorialText:o.editorialText,editorialCity:o.editorialCity,editorialState:o.editorialState,editorialCountry:o.editorialCountry,editorialDate:o.editorialDate,shootingCountry:o.shootingCountry,shootingDate:o.shootingDate,sourceContext:o.sourceContext??null},y={...m,blackbox:h};await we.updateSessionImage(g,{title:o.title??null,description:o.description,keywords:Array.isArray(o.keywords)?o.keywords.join(", "):"",baseTitle:o.title??"",baseDescription:o.description,baseKeywords:o.keywords,platform_metadata:y})}catch(m){return console.error("[ReviewEdit] Failed to persist Blackbox metadata",m),a?.silent||r({title:"Save failed",description:"Could not persist Blackbox metadata.",variant:"destructive"}),{success:!1}}if(Q(g,{title:o.title??"",description:o.description,keywords:o.keywords,baseTitle:o.title??"",baseDescription:o.description,baseKeywords:o.keywords}),ye(g,"blackbox",{category:o.category,batchName:o.batchName,editorial:o.editorial,editorialText:o.editorialText,editorialCity:o.editorialCity,editorialState:o.editorialState,editorialCountry:o.editorialCountry,editorialDate:o.editorialDate,shootingCountry:o.shootingCountry,shootingDate:o.shootingDate,sourceContext:o.sourceContext??null}),nt(o),vt(!1),dt({}),t&&t.length>0)try{await Promise.all(t.map(m=>{const w={...(b.find(v=>v.id===m)??null)?.platformMetadata??{},blackbox:{category:o.category,batchName:o.batchName,editorial:o.editorial,editorialText:o.editorialText,editorialCity:o.editorialCity,editorialState:o.editorialState,editorialCountry:o.editorialCountry,editorialDate:o.editorialDate,shootingCountry:o.shootingCountry,shootingDate:o.shootingDate,sourceContext:o.sourceContext??null}};return we.updateSessionImage(m,{title:o.title??null,description:o.description,keywords:Array.isArray(o.keywords)?o.keywords.join(", "):"",baseTitle:o.title??"",baseDescription:o.description,baseKeywords:o.keywords,platform_metadata:w})})),t.forEach(m=>{Q(m,{title:o.title??"",description:o.description,keywords:o.keywords,baseTitle:o.title??"",baseDescription:o.description,baseKeywords:o.keywords}),ye(m,"blackbox",{category:o.category,batchName:o.batchName,editorial:o.editorial,editorialText:o.editorialText,editorialCity:o.editorialCity,editorialState:o.editorialState,editorialCountry:o.editorialCountry,editorialDate:o.editorialDate,shootingCountry:o.shootingCountry,shootingDate:o.shootingDate,sourceContext:o.sourceContext??null})}),a?.silent||r({title:"Blackbox metadata applied",description:`Applied to ${t.length} images.`})}catch(m){return console.error("[ReviewEdit] Failed to apply Blackbox metadata to targets",m),a?.silent||r({title:"Apply failed",description:"Could not apply Blackbox metadata to selected images.",variant:"destructive"}),{success:!1}}else a?.silent||r({title:"Blackbox saved",description:"Metadata saved for this image."});return{success:!0,data:o}},[Ye,Le,N,g,b,ye,Q,Rl,r]),du=d.useCallback(()=>{Ce&&(nt({...Ce}),dt({}),vt(!1),$i(!0))}
11,[Ce]),Bl=d.useCallback(()=>{Ce&&nt({...Ce}),dt({}),vt(!1),$i(!1)},[Ce]),Ll=d.useCallback(async()=>{(await rr(null)).success&&$i(!1)},[rr]),Fl=d.useCallback(()=>{if(!g)return;if(Be().map(n=>n.id).filter(n=>n!==g).length===0){r({title:"No other images selected",description:"Select more images to apply metadata.",variant:"destructive"});return}if(!(Le??Ce)){r({title:"Nothing to apply",description:"Add metadata before applying to other images.",variant:"destructive"});return}Yn({...Bc}),Xn({...Lc}),Ti(!0)},[Le,Ce,Be,g,r]),uu=d.useCallback(async()=>{if(!g)return;const t=Be().filter(o=>o.id!==g);if(t.length===0){r({title:"No other images selected",description:"Select more images to apply metadata.",variant:"destructive"});return}const a=Le??Ce;if(!a){r({title:"Nothing to apply",description:"Add metadata before applying to other images.",variant:"destructive"});return}if(!Object.values(zt).some(Boolean)){r({title:"Select fields",description:"Choose at least one metadata block to copy.",variant:"destructive"});return}Gn(!0);try{const o=await rr(null,{metadataOverride:a,silent:!0});if(!o.success||!o.data){r({title:"Blackbox metadata incomplete",description:"Fix highlighted fields on the current asset first.",variant:"destructive"});return}const u=o.data,m=[];t.forEach(h=>{const y=h.platformMetadata??{},w=y.blackbox??{},v={};if(zt.title&&(Q(h.id,{title:u.title??"",baseTitle:u.title??""}),m.push(we.updateSessionImage(h.id,{title:u.title??null,baseTitle:u.title??""}))),zt.description&&(Q(h.id,{description:u.description,baseDescription:u.description}),m.push(we.updateSessionImage(h.id,{description:u.description,baseDescription:u.description}))),zt.keywords&&(Q(h.id,{keywords:u.keywords,baseKeywords:u.keywords}),m.push(we.updateSessionImage(h.id,{keywords:Array.isArray(u.keywords)?u.keywords.join(", "):"",baseKeywords:u.keywords}))),zt.category&&(v.category=u.category),zt.batchName&&(v.batchName=u.batchName??""),zt.editorial&&(v.editorial=u.editorial,Cs.text&&(v.editorialText=u.editorialText??""),Cs.city&&(v.editorialCity=u.editorialCity??""),Cs.state&&(v.editorialState=u.editorialState??""),Cs.country&&(v.editorialCountry=u.editorialCountry??""),Cs.date&&(v.editorialDate=u.editorialDate??"")),zt.shooting&&(v.shootingCountry=u.shootingCountry??"",v.shootingDate=u.shootingDate??""),Object.keys(v).length===0)return;const A={...w,...v};delete A.title,delete A.description,delete A.keywords;const I={...y,blackbox:A};m.push(we.updateSessionImage(h.id,{platform_metadata:I})),ye(h.id,"blackbox",A)}),m.length>0&&await Promise.all(m),Ti(!1),r({title:"Blackbox metadata applied",description:`Applied to ${t.length} images.`})}catch(o){console.error("[ReviewEdit] Failed to apply Blackbox metadata to targets",o),r({title:"Apply failed",description:"Could not apply Blackbox metadata to selected images.",variant:"destructive"})}finally{Gn(!1)}},[Cs,zt,Le,rr,Ce,Be,g,r,ye]),Pl=d.useCallback((t,a)=>{Ye&&(nt(n=>{const o=n??Ce??(N?Jo(N):null);return o?ls(t({...o})):n}),a&&dt(n=>({...n,[a]:!0})),vt(!1))},[Ce,Ye,N]),ta=d.useCallback(t=>{if(!Ye||!g)return;const a=Le??Ce??(N?Jo(N):null);if(!a)return;const n=ls(t({...a}));nt(n),vt(!1),dt(o=>({...o})),rr(null,{metadataOverride:n,silent:!0})},[Le,rr,Ce,Ye,N,g]),Kl=d.useCallback(t=>{ta(a=>{const n=[...a.keywords];return n.splice(t,1),{...a,keywords:n}})},[ta]),$l=d.useCallback(t=>{Ui.current=t},[]),Ol=d.useCallback(()=>{Ui.current=null},[]),po=d.useCallback(t=>{t.preventDefault()},[]),ho=d.useCallback(t=>{const a=Ui.current;Ui.current=null,!(a===null||a===t)&&ta(n=>{const o=[...n.keywords],[u]=o.splice(a,1);return o.splice(t,0,u),{...n,keywords:o}})},[ta]),mu=d.useCallback(t=>{if(!Le)return null;const a=Le[t.id],n=gd(t,Le),o=Qi[t.id],u=!!(o&&(Sl||Cl[t.id])),m=u?o??"":t.helperText??"",h=`blackbox-${t.id}`,y=typeof t.required=="function",w=Array.isArray(a)?a.length>0:typeof a=="string"?a.trim().length>0:!!a;if(!(!y||t.id==="editorial"||w||y&&t.required(Le)))return null;let A;if(t.id==="keywords"){const I=Array.isArray(Le.keywords)?Le.keywords:[];A=e.jsxs("div",{className:"space-y-2",children:[e.jsxs("div",{className:"flex flex-wrap gap-2",onDragOver:po,onDrop:()=>ho(I.length),children:[I.map((M,q)=>e.jsxs("span",{draggable:!0,onDragStart:te=>{te.dataTransfer.effectAllowed="move",$l(q)},onDragOver:po,onDrop:te=>{te.preventDefault(),ho(q)},onDragEnd:Ol,className:"inline-flex items-center gap-2 px-3 py-1 rounded-full bg-violet-50 dark:bg-violet-500/10 text-violet-700 dark:text-violet-300 border border-violet-200 dark:border-violet-500/30 cursor-move",children:[e.jsx("span",{className:"font-medium text-xs",children:"☰"}),e.jsx("span",{className:"text-sm",children:M}),e.jsx("button",{type:"button",onClick:()=>Kl(q),className:"text-xs text-muted-foreground hover:text-destructive",children:"×"})]},`${M}-${q}`)),I.length===0&&e.jsx("span",{className:"text-sm text-muted-foreground",children:"No keywords"})]}),e.jsxs("div",{className:"flex gap-2",children:[e.jsx($t,{value:zi,onChange:M=>es(M.target.value),onKeyDown:M=>{M.key==="Enter"&&(M.preventDefault(),mo())},placeholder:"Add keyword"}),e.jsx(K,{type:"button",onClick:mo,variant:"outline",children:"Add"})]})]})}else if(t.type==="textarea")A=e.jsx(as,{id:h,value:typeof a=="str
11ing"?a:"",onChange:I=>ea(t.id,I.target.value),onBlur:()=>Es(t.id),rows:t.id==="description"?4:3,className:"resize-none"});else if(t.type==="text")A=e.jsx($t,{id:h,value:typeof a=="string"?a:"",onChange:I=>ea(t.id,I.target.value),onBlur:()=>Es(t.id)});else if(t.type==="date"){const I=typeof a=="string"?vs(a):"";A=e.jsx($t,{id:h,type:"date",value:I,placeholder:"YYYY-MM-DD",onChange:M=>ea(t.id,vs(M.target.value)),onBlur:()=>Es(t.id)})}else if(t.type==="switch")A=e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(Jc,{id:h,checked:!!Le.editorial,onCheckedChange:Ml}),e.jsx("span",{className:"text-sm text-[var(--cs-text-secondary)]",children:Le.editorial?"Yes":"No"})]});else if(t.type==="select"){const M=(typeof a=="string"&&a?a:"")||"__EMPTY__";A=e.jsxs(Lo,{value:M,onValueChange:q=>{const te=q==="__EMPTY__"?"":q;nt(me=>me&&(t.id==="category"?{...me,category:jr(te)}:t.id==="editorialCountry"?{...me,editorialCountry:Ta(te)}:t.id==="shootingCountry"?{...me,shootingCountry:Da(te)}:{...me,[t.id]:te})),Es(t.id)},children:[e.jsx(Fo,{id:h,className:"h-9",children:e.jsx(Po,{placeholder:"Select option"})}),e.jsxs(Ko,{children:[e.jsx(gr,{value:"__EMPTY__",children:"Leave Empty"}),t.options?.map(q=>e.jsx(gr,{value:q.value,children:q.label},q.value))]})]})}return A?e.jsxs("div",{className:"space-y-1",children:[e.jsxs(Ne,{htmlFor:h,className:"text-sm font-medium text-[var(--cs-text-secondary)]",children:[t.label,n&&e.jsx("span",{className:"ml-1 text-destructive",children:"*"})]}),A,m&&e.jsx("p",{className:`text-xs ${u?"text-destructive":"text-muted-foreground"}`,children:m})]},t.id):null},[Le,Qi,Sl,Cl,zi,Ml,mo,$l,Ol,po,ho,Kl,ea,Es]),{generalSettings:go,translationSettings:sa,customPlatformRules:fo,titleSettings:ra,keywordSettings:qt,selectedPlatform:zl,availablePlatforms:Ul}=Ps(),ia=go.autoCategory!==!1,ql=d.useMemo(()=>Sa(Ul,zl,W),[Ul,zl,W]),Vt=d.useMemo(()=>Ju(W),[W]),Vl=d.useMemo(()=>Zu(W),[W]),Wl=d.useMemo(()=>fo?fo[Vt]:void 0,[fo,Vt]),Kr=d.useMemo(()=>{const t=Qu(Vl,Wl),a={...t};if(ra?.enabled===!0){a.titleMaxLength=t.titleMaxLength,a.descriptionMaxLength=t.descriptionMaxLength;const n=ra?.minTitleChars;typeof n=="number"&&Number.isFinite(n)&&n>0&&(a.titleMinLength=Math.min(a.titleMaxLength,Math.max(1,Math.floor(n))));const o=ra?.minDescriptionChars;typeof o=="number"&&Number.isFinite(o)&&o>0&&(a.descriptionMinLength=Math.min(a.descriptionMaxLength,Math.max(1,Math.floor(o))))}return qt?.enabled,a},[Vl,Wl,ra,qt]),$r=qe?.separator||", ",_s=d.useCallback((t,a)=>{if(!a)return"";const n=oi(t,a)||oi("Adobe Stock",a);return n?wa(n):a},[]),Or=d.useCallback(t=>!t?.editorialCaptionCleared,[]),kt=d.useCallback((t,a)=>{const n=a?.baseTitle??t.baseTitle??t.title??"",o=a?.baseDescription??t.baseDescription??t.description??"",u=a?.baseKeywords??t.baseKeywords??t.keywords??[],m=Array.isArray(u)?u:[],h=a?.categories??t.categories??"",y=(()=>{if(!h||!Kr.autoInferCategory||pi(Vt.includes("adobe")?"Adobe Stock":Vt.includes("shutterstock")?"Shutterstock":W).length===0)return h;const A=Vt.includes("adobe")?"Adobe Stock":Vt.includes("shutterstock")?"Shutterstock":W;if(fi(A,h))return h;const I=Zo(h);return I&&oi(A,I)?h:""})(),w=Kr.autoInferCategory?({title:v,description:A,keywords:I})=>{const M=y||t.categories||"";return Vt.includes("adobe")?Cr(I,v,A,M):Vt.includes("shutterstock")?yc({title:v,description:A,keywords:I})??M:M}:void 0;return $p({title:n,description:o,keywords:m,categories:y},Kr,{endings:Kr.titleEndings,inferCategory:w,platformKey:Vt,...qt.enabled?{keywordSettings:{requiredStartingKeywords:qt.requiredStartingKeywords,requiredEndingKeywords:qt.requiredEndingKeywords,excludedKeywords:qt.excludedKeywords,...qt.singleWordMode?{singleWordMode:!0}:{},...qt.singleWordMode&&qt.allowCompoundKeywords?{allowCompoundKeywords:!0}:{},...ql?.singleWordOnly?{singleWordOnlyPlatform:!0}:{}}}:{}})},[Kr,Vt,qt,ql,W]),ut=d.useCallback((t,a)=>{const n=De(t.id),o=kt(t,{...a,categories:n?_s(W,n):a?.categories??t.categories??""}),u=n?_s(W,n):o.category??a?.categories??t.categories??"";if(!(t.title!==o.title||t.description!==o.description||!ni(t.keywords,o.keywords)||!ni(t.hiddenKeywords||[],o.hiddenKeywords||[])||!ni(t.overflowKeywords||[],o.overflowKeywords||[])||a?.baseTitle!==void 0&&t.baseTitle!==(a.baseTitle??t.baseTitle??"")||a?.baseDescription!==void 0&&t.baseDescription!==(a.baseDescription??t.baseDescription??"")||a?.baseKeywords!==void 0&&!ni(t.baseKeywords||[],a.baseKeywords||[])||t.categories!==u))return o;
11const h={title:o.title,description:o.description,keywords:o.keywords,hiddenKeywords:o.hiddenKeywords,overflowKeywords:o.overflowKeywords,baseTitle:a?.baseTitle??t.baseTitle??t.title??"",baseDescription:a?.baseDescription??t.baseDescription??t.description??"",baseKeywords:a?.baseKeywords??(Array.isArray(t.baseKeywords)?t.baseKeywords:[])};if(t.categories!==u&&(h.categories=u),t.editorial){const y=(W||"").toLowerCase(),w=String(t.editorialCaption??"").trim(),v=String(qe?.editorial_style||"").trim(),A=y.includes("shutterstock")||v==="istock_getty"||v==="shutterstock_strict",I=(A?o.description??"":o.title??"").trim(),M=Ls(String(t.editorialCity??"").trim(),t.editorialCountry??""),q=Kt(t.editorialDate??"")??String(t.editorialDate??"").trim(),te=A?Fs(M,q,I,v||ct):I,me=Or(t)&&(!w||w===String(o.title??"").trim()),pe=String(te||"").trim();pe&&me&&(h.editorialCaption=pe)}return Q(t.id,h),o},[kt,Q,De,_s,W,qe]),Rt=d.useCallback(t=>t?t.suppressMetadata?{title:"",description:"",keywords:[],hiddenKeywords:[],overflowKeywords:[],category:""}:kt(t):null,[kt]),Hl=d.useMemo(()=>N?Rt(N):null,[Rt,N]),zr=d.useMemo(()=>{if(!N)return!1;const t=Hl,a=(t?.title??N.title??"").trim(),n=(t?.description??N.description??"").trim(),o=Array.isArray(t?.keywords)?t.keywords:Array.isArray(N.keywords)?N.keywords:[];return!a&&!n&&o.length===0},[Hl,N]),Gl=d.useMemo(()=>({selling:Hi,title:Gi,description:Yi,keywords:Xi}),[Yi,Xi,Hi,Gi]),ts=d.useMemo(()=>zr?{selling:0,title:0,description:0,keywords:0}:{selling:Lr("selling",Hi),title:Lr("title",Gi),description:Lr("description",Yi),keywords:Lr("keywords",Xi)},[Yi,Lr,Xi,Hi,zr,Gi]);d.useMemo(()=>Al?Object.entries(Gl).map(([t,a])=>({field:t,raw:a,display:ts[t]})):null,[ts,Al,Gl]);const ir=d.useCallback(async(t,a,n)=>{if(!c?.id)return r({title:"Login required",description:"Please sign in to optimize metadata.",variant:"destructive"}),null;if(t.length===0)return r({title:"Select an image",description:"Choose at least one image to optimize.",variant:"destructive"}),null;try{jc.sellingScoreActionTriggered(a,{sessionId:E?.id,imageCount:t.length}),fl(!0),wl(null),bl(null);const o=a==="rewrite"?new Set(n?.fields&&n.fields.length>0?n.fields:["title","description","keywords"]):new Set,u=o.has("title"),m=o.has("description"),h=o.has("keywords"),y=(u?qi:0)+(m?Vi:0)+(h?El:0),w=a==="boost"?Wi:y,v=D&&z==="unlimited",A=w*t.length;if(!v&&w>0&&ae<A)return r({title:"Insufficient credits",description:`You need ${A} credits to run this action.`,variant:"destructive"}),null;let I=0;const M=[],q=[],te=new Map,me=a==="rewrite"?D&&z==="unlimited"?5:3:1;console.log(`[ReviewEdit] Starting optimization: action=${a}, concurrency=${me}, total=${t.length}`);for(let oe=0;oe<t.length;oe+=me){const ue=t.slice(oe,oe+me);await Promise.all(ue.map(async de=>{const C=b.find(Y=>Y.id===de);if(!C){M.push(de);return}try{const Y=String(C?.filename??""),F=Oo({filename:Y,mimeType:C?.mimeType??C?.mime_type??null,mediaType:C?.mediaType??C?.media_type??null,title:C?.title??null,keywords:C?.keywords??null},Ps.getState().customPrompt),X=async()=>Uc({image:C,sessionId:E?.id??s,userId:c.id,seedLabel:`${a}:${de}`,promptRequest:F,expectsCategory:ks,autoCategoryEnabled:ia,platform:W,unlimitedActive:D,unlimitedUsage:S,generationMode:z,action:a});let f=null;const T=4;for(let We=0;We<=T;We++)try{f=await X();break}catch(St){const Mt=String(St?.message||""),Je=/429|546|non-2xx|timeout|temporar|unavailable|ECONN|ETIMEDOUT|retryable|gemini_parse_fallback|resource.limit/i.test(Mt),Ze=qc(Mt);if(Je&&We<T){const ft=Ze??1500*(We+1);await new Promise(jt=>setTimeout(jt,Math.min(1e4,Math.max(500,ft))));continue}throw St}const B={};a==="rewrite"?(u&&(B.baseTitle=f.baseTitle||C.baseTitle||C.title||""),m&&(B.baseDescription=f.baseDescription||C.baseDescription||C.description||""),h&&(B.baseKeywords=f.baseKeywords?.length?f.baseKeywords:Array.isArray(C.baseKeywords)?C.baseKeywords:Array.isArray(C.keywords)?C.keywords:[]),(u||m||h)&&(B.categories=f.categories||C.categories||"")):a==="boost"&&(B.baseKeywords=f.baseKeywords?.length?f.baseKeywords:Array.isArray(C.baseKeywords)?C.baseKeywords:Array.isArray(C.keywords)?C.keywords:[],B.baseTitle=C.baseTitle??C.title??"",B.baseDescription=C.baseDescription??C.description??"",B.categories=C.categories??"");const P=ut(C,B)??kt({...C,baseTitle:B.baseTitle??C.baseTitle??C.title??"",baseDescription:B.baseDescription??C.baseDescription??C.description??"",baseKeywords:B.baseKeywords??(Array.isArray(C.baseKeywords)?C.baseKeywords:Array.isArray(C.keywords)?C.keywords:[]),categories:B.categories??C.categories}),G={title:P?.title??B.baseTitle??C.baseTitle??C.title??"",description:P?.description??B.baseDescription??C.baseDescription??C.description??"",keywords:P?.keywords??B.baseKeywords??(Array.isArray(C.baseKeywords)?C.baseKeywords:Array.isArray(C.keywords)?C.keywords:[]),category:"general",locale:go?.outputLanguage||"en"},se=await ha.evaluateAsset(G,{refreshTrends:!0}),le=Io(G,se.keywordAnalyses??[]);xe(de,{...le,keywordAnalyses:se.keywordAnalyses??null}),Q(de,{analyticsUnlocked:!0}),I+=1;const be=Rt({...C,...le}
11),Ke=Rt(C),$e=be?.keywords??C.keywords??[],Z=Ke?.keywords??C.keywords??[],tt=(be?.title??"")!==(Ke?.title??""),Oe=(be?.description??"")!==(Ke?.description??""),Ve=Z.join(",")!==$e.join(",");if(tt||Oe||Ve){q.push(de),te.set(de,{title:tt,description:Oe,keywords:Ve});try{await we.updateSessionImage(de,{title:G.title,description:G.description,keywords:G.keywords.join(", "),baseTitle:B.baseTitle??C.baseTitle??C.title??"",baseDescription:B.baseDescription??C.baseDescription??C.description??"",baseKeywords:B.baseKeywords??(Array.isArray(C.baseKeywords)?C.baseKeywords:Array.isArray(C.keywords)?C.keywords:[])})}catch(We){console.warn("[ReviewEdit] Auto-persist after optimization failed for",de,We)}}}catch(Y){console.error("[ReviewEdit] AI metadata rewrite failed for",de,Y),M.push(de)}})),console.log(`[ReviewEdit] Batch complete: ${I}/${t.length}, failed: ${M.length}`),Mr({processed:I,total:t.length})}console.log(`[ReviewEdit] Optimization complete: processed=${I}, failed=${M.length}`);let pe=0;w>0&&q.length>0?(pe=w*q.length,v?L(q.length):console.warn("[ReviewEdit] runRemoteOptimization reached its charge branch, which should be unreachable. Work was NOT billed.",{appliedCost:pe,action:a})):w>0&&q.length===0&&!n?.quiet&&r({title:"Nothing to apply",description:"No metadata changes detected to apply to selected images."});const ce={processed:I,failed:M,costApplied:pe,message:I>0&&M.length===0?"Optimization complete":"Completed with issues",changedIds:q};return bl(ce?.message??null),wl(M),n?.quiet||(M.length>0?r({title:"Completed with issues",description:`${I} succeeded, ${M.length} failed`,variant:"destructive"}):r({title:"Optimization complete",description:"Optimizer finished successfully."})),jc.sellingScoreActionCompleted(a,{sessionId:E?.id,processed:I,failed:M.length,refreshTrends:!0,assetIds:t}),ce}catch(o){return console.error("[ReviewEdit] local optimization failed",o),r({title:"Optimization failed",description:o instanceof Error?o.message:"Unexpected error during optimization.",variant:"destructive"}),null}finally{fl(!1)}},[Wi,qi,Vi,El,ae,E?.id,s,he,b,Uc,ks,ia,W,D,S,z,ut,kt,lu,r,c?.id,Mr,Rt,L]),yo=d.useCallback((t,a)=>{const[n,o]=t==="keywords"?[6,12]:[4,9],u=li(n,o);if(cl(m=>{const h={...m};return h[t]=Math.min(30,(m[t]??0)+u),t!=="selling"&&(h.selling=Math.min(40,(m.selling??0)+Math.max(2,Math.round(u/2)))),h}),ul(m=>{const h={...m};return h[t]=Pc(t),h.selling=Pc("selling"),h}),t==="keywords"&&ml(Go()),a?.highlightKeywords?.length){const m=a.highlightKeywords.map(h=>h.toLowerCase());io(new Set(m)),setTimeout(()=>io(new Set),4200)}},[]);d.useCallback(t=>{if(!g)return;yl(u=>({...u,[t]:!0}));const a=()=>yl(u=>({...u,[t]:!1})),n=()=>{Ir(u=>({...u,[t]:!0})),setTimeout(()=>Ir(u=>({...u,[t]:!1})),3200)};if(t==="keywords"){ir([g],"boost",{quiet:!0}).then(u=>{n();const m=(u?.changedIds?.length??0)>0;(u?.failed?.length??0)>0?r({title:"Boost failed",description:"Could not optimize keywords. Please try again.",variant:"destructive"}):m?(r({title:"Keywords updated",description:"Applied optimized keywords based on real trend data.",variant:"default"}),yo("keywords")):r({title:"Keywords already strong",description:"No changes were needed and credits were not used.",variant:"default"})}).catch(u=>{r({title:"Boost failed",description:u instanceof Error?u.message:"Unexpected error.",variant:"destructive"})}).finally(a);return}ir([g],"rewrite",{fields:[t],quiet:!0}).then(u=>{n();const m=(u?.changedIds?.length??0)>0,h=(u?.failed?.length??0)>0,y=t==="title"?"Title":"Description";h?r({title:`${y} rewrite failed`,description:"Could not rewrite. Please try again.",variant:"destructive"}):m?(r({title:`${y} updated`,description:"Applied optimized metadata based on real trend data.",variant:"default"}),yo(t==="title"?"title":"description")):r({title:`${y} already strong`,description:"No changes were needed and credits were not used.",variant:"default"})}).catch(u=>{r({title:"Rewrite failed",description:u instanceof Error?u.message:"Unexpected error.",variant:"destructive"})}).finally(a)},[yo,ir,g,r]),d.useCallback((t,a)=>{`${t.id}${a}`;const n=Mn[a]?.[t.id];if(n)return n;const o=De(t.id);if(o){const m=_s(a,o);if(m)return Yt(h=>({...h,[a]:{...h[a]||{},[t.id]:m}})),m}if(!ks)return t.categories||"";
11if(a==="Adobe Stock"){const m=Array.isArray(t.keywords)?t.keywords:typeof t.keywords=="string"?String(t.keywords).split(",").map(w=>w.trim()).filter(Boolean):[],h=Cr(m,t.title,t.description,t.categories),y=ys(a,h);return y&&Yt(w=>({...w,[a]:{...w[a]||{},[t.id]:y}})),y||h}if(a==="Shutterstock"){const m=kt(t),h=yc({title:m?.title??t.title,description:m?.description??t.description,keywords:m?.keywords??(Array.isArray(t.keywords)?t.keywords:[])});if(h)return Yt(y=>({...y,[a]:{...y[a]||{},[t.id]:h}})),h}const u=ys(a,t.categories);return u&&Yt(m=>({...m,[a]:{...m[a]||{},[t.id]:u}})),u||t.categories||""},[ks,Mn,De,_s,Cr,kt,pi,wa,Yt]),d.useEffect(()=>{Yt(t=>{const a={...t},n="Adobe Stock";let o=!1;return b.forEach(u=>{const h=De(u.id)??Zo(u.categories);h&&_r.current[u.id]!==h&&(_r.current[u.id]=h);const y=_r.current[u.id];if(!y)return;const w=oi(W,y);if(w){const v=wa(w),A=a[W]||{};A[u.id]!==v&&(a[W]={...A,[u.id]:v},o=!0)}if(W!==n&&y){const v=oi(n,y);if(v){const A=wa(v),I=a[n]||{};I[u.id]!==A&&(a[n]={...I,[u.id]:A},o=!0)}}}),o?a:t})},[b,W,De]);const Yl=d.useRef(W);d.useEffect(()=>{if(Yl.current===W||(Yl.current=W,b.length===0))return;let t=!1;const a=setTimeout(async()=>{const n=[],o=[];for(const u of b){if(t)break;const m=ut(u);if(!m)continue;const h={id:u.id};let y=!1;const w=(m.title??"").trim(),v=(u.title??"").trim();w&&w!==v&&(h.title=w,y=!0);const A=(m.description??"").trim(),I=(u.description??"").trim();A&&A!==I&&(h.description=A,y=!0);const M=m.category??"",q=u.categories??"";M!==q&&(h.categories=M,y=!0);const te=m.keywords??[],me=u.keywords??[];if(ni(te,me)||(h.keywords=te,y=!0),y&&n.push(h),u.editorial){const pe=(W||"").toLowerCase(),ce=String(qe?.editorial_style||"").trim(),oe=pe.includes("shutterstock")||ce==="istock_getty"||ce==="shutterstock_strict",ue=(oe?m.description??"":m.title??"").trim(),de=Ls(String(u.editorialCity??"").trim(),u.editorialCountry??""),C=Kt(u.editorialDate??"")??String(u.editorialDate??"").trim(),Y=oe?Fs(de,C,ue,ce||ct):ue,F=String(u.editorialCaption??"").trim(),f=Or(u)&&(!F||F===String(m.title??"").trim())?String(Y||"").trim():xa(F,ce||ct);f&&f!==F&&o.push({id:u.id,editorialCaption:f})}}if(n.length>0&&!t)for(let m=0;m<n.length&&!t;m+=10){const h=n.slice(m,m+10);await Promise.allSettled(h.map(({id:y,...w})=>we.updateSessionImage(y,w).catch(v=>console.warn("[ReviewEdit] Platform-switch persist failed",y,v))))}if(o.length>0&&!t)for(let m=0;m<o.length&&!t;m+=10){const h=o.slice(m,m+10);await Promise.allSettled(h.map(({id:y,editorialCaption:w})=>{const v=b.find(te=>te.id===y);if(!v)return Promise.resolve();const A=v.meta_json??{},M={...A.editorial??A.editorial_meta??{},caption:w},q={...A,editorial:M};return Q(y,{editorialCaption:w,meta_json:q}),we.updateSessionImage(y,{meta_json:q}).catch(te=>console.warn("[ReviewEdit] Platform-switch editorial persist failed",y,te))}))}},80);return()=>{t=!0,clearTimeout(a)}},[W,b,ut,qe,ct,Q]),d.useEffect(()=>{if(b.length===0)return;let t=!1;return(async()=>{if(t||b.length===0)return;const n=[];for(const o of b){if(Er.current.has(o.id))continue;const u=typeof o.titleScorePercent=="number"&&typeof o.descriptionScorePercent=="number"&&typeof o.keywordScorePercent=="number"&&typeof o.sellingScorePercent=="number",m=Array.isArray(o.keywordAnalyses)?o.keywordAnalyses.length:0,h=m>0&&o.keywordAnalyses.every(y=>Number(y?.searchVolume||0)===0);if(u&&m>0&&!h){Er.current.add(o.id);continue}if(n.push(o),n.length>=hh)break}n.length!==0&&await Promise.allSettled(n.map(async o=>{if(t||Er.current.has(o.id))return;const u=Qs(o),m={title:o.title??"",description:o.description??"",keywords:u,locale:"en",category:"general"},h=Array.isArray(o.keywordAnalyses)?o.keywordAnalyses:null;try{Er.current.add(o.id);let w=(h?.length?h.map(A=>({keyword:A.keyword,normalizedKeyword:A.normalizedKeyword,strength:A.strength,hcv:A.hcv??0,searchVolume:A.searchVolume??0,trendScore:A.trendScore??0,vpnPercentile:A.vpnPercentile??0,locale:m.locale,category:m.category,relevance:.6,slope:0})):null)??[];if(w.length===0){const A=tl.current;A&&(tl.current=!1),w=(await ha.evaluateAsset(m,{refreshTrends:A})).keywordAnalyses??[],w.length||console.warn("[ReviewEdit] scoring breakdown missing analyses",{imageId:o.id,keywordCount:m.keywords.length,titleLength:m.title.length,descriptionLength:m.description.length})}const v=Io(m,w);xe(o.id,{sellingScorePercent:v.sellingScorePercent,titleScorePercent:v.titleScorePercent,descriptionScorePercent:v.descriptionScorePercent,keywordScorePercent:v.keywordScorePercent,strengths:v.strengths,hcv:v.hcv,keywordAnalyses:w})}catch(y){Er.current.delete(o.id),console.warn("[ReviewEdit] automatic scoring prepass failed",{imageId:o.id,error:y})}}))})(),()=>{t=!0}},[Qs,b,xe]),d.useRef(new Set),d.useRef(!1),d.useEffect(()=>{},[b]),d.useEffect(()=>{let t=0,a=0,n=!0,o=!1;const u=new Map,m=new Set,h=async w=>{const v=typeof w=="string"?w.trim():String(w??"").trim();if(!v)return"";if(v.startsWith("http")||v.startsWith("data:"))return await we.resolveSessionAsset(s,v);const A=v.replace(/^\/+/,"");if(!A)return"";const M=/^(?:sessions|previews)\/([0-9a-fA-F-]+)\//.exec(A)?.[1]||s,q=`${M}::${A}`,te=u.get(q);if(te)return te;const me=(async()=>await we.resolveSessionAsset(M,A))();u.set(q,me);const pe=await me;return pe||u.delete(q),pe};(async()=>{try{if(E?.id===s&&b.length>0){console.log(`[ReviewEdit] Session ${s} already cached with ${b.length} images, skipping reload`),wi(!1);return}if(wi(!0),k&&performance.mark("review-open-start"),o){console.log(`[ReviewEdit] Loa
11ding already in progress for session ${s}, ignoring duplicate call`);return}o=!0,console.log(`[ReviewEdit] Starting to load session ${s}`),E?.id&&E.id!==s&&(console.log(`[ReviewEdit] Switching from session ${E.id} to ${s}, clearing state`),Me());const w=await we.getSession(s,1,1);if(w.error)throw w.error;if(w.session){wm(w.session,s),Ge(w.session),(w.session.total_images||0)>1e4&&Jn(!0);try{const I=w.session?.user_id;if(I&&I!==c?.id){const{profile:M}=await Tt.getUserProfile(I);M&&Dn(M)}else Dn(null)}catch(I){console.warn("[ReviewEdit] Failed to load owner profile for admin view",I)}}let v;const A=100;for(let I=1;;I++){const M=new Set,{images:q,error:te}=await we.getSessionImagesKeyset(s,A,v);if(console.log(`[ReviewEdit] Keyset page ${I}: received ${q?.length||0}`),te)throw te;if(!q||q.length===0){console.log(`[ReviewEdit] Stopping keyset pagination: no images on page ${I}`);break}try{const ue=new Map;for(const de of q){const C=de?.metadata||de?.meta_json||{},Y=[de?.thumbnail_path,de?.thumb_path,C?.preview_path,C?.thumbnail_path,de?.image_path];for(const F of Y){const X=typeof F=="string"?F.trim():"";if(!X||X.startsWith("http")||X.startsWith("data:"))continue;const f=X.replace(/^\/+/,"");if(!f.startsWith("sessions/")&&!f.startsWith("previews/")&&!f.startsWith("public/sessions/")&&!f.startsWith("public/previews/"))continue;const T=f.startsWith("public/")?f.slice(7):f,P=/^(?:sessions|previews)\/([0-9a-fA-F-]+)\//.exec(T)?.[1]||s,G=ue.get(P)??new Set;G.add(T),ue.set(P,G)}}for(const[de,C]of ue.entries()){const Y=Array.from(C);Y.length!==0&&await Tt.prefetchR2SignedUrls(de,Y)}}catch(ue){console.warn("[ReviewEdit] Signed URL prefetch failed; falling back to per-asset signing",ue)}const pe=(await Promise.all(q.map(async(ue,de)=>{const C=we.transformSessionImage(ue),Y=C.id||ue.id||`img-${t+de}`,F=typeof Y=="string"?Y.trim():String(Y),X=ue.status;F&&(m.has(F)?(M.add(F),console.warn("[ReviewEdit] Duplicate imageId observed but keeping row",{imageId:F,status:X,createdAt:ue?.created_at,updatedAt:ue?.updated_at})):m.add(F));const f=await h(C.imageUrl??ue.image_path??""),T=await h(C.thumbnailUrl??ue.thumbnail_path??ue.image_path??C.imageUrl??""),B=(C.title||C.baseTitle||"").trim(),P=(C.description||C.baseDescription||"").trim(),G=(C.baseTitle||C.title||"").trim(),se=(C.baseDescription||C.description||"").trim();return{...C,id:F,imageUrl:f||C.imageUrl,thumbnailUrl:T||f||C.thumbnailUrl,title:B,baseTitle:G,description:P,baseDescription:se}}))).filter(ue=>ue!==null),ce=q.length-pe.length;M.size>
110&&console.warn(`[ReviewEdit] Keyset page ${I}: observed duplicate ids but retained`,{duplicateCount:M.size,duplicateIds:[...M]}),a+=pe.length,console.log(`[ReviewEdit] Keyset page ${I}: after dedup: ${pe.length} images kept, ${ce} filtered as duplicates`),pt(pe),je(q),n&&pe.length>0&&(it(pe[0].id),n=!1),t+=q.length,console.log(`[ReviewEdit] Total processed so far: ${t}`),En&&wi(!1),q.length>=A&&Pa("loading");const oe=q[q.length-1];if(v={createdAt:String(oe.created_at||oe.createdAt||""),id:String(oe.id)},q.length<A){console.log(`[ReviewEdit] Stopping keyset pagination: page ${I} returned ${q.length} < ${A}`);break}}if(console.log(`[ReviewEdit] ✅ Keyset pagination complete: ${t} DB rows processed, ${a} images kept in UI, ${t-a} filtered as duplicates`),k){performance.mark("review-open-end");const I=performance.measure("review-open","review-open-start","review-open-end");console.log("[BENCH] review-open ms:",I.duration.toFixed(1))}}catch(w){console.error("[ReviewEdit] Error loading session:",w),r({title:"Error",description:"Failed to load session data",variant:"destructive"}),i("/dashboard")}finally{wi(!1),o=!1,Pa(w=>w==="loading"?(setTimeout(()=>Pa(null),2500),"done"):w),console.log(`[ReviewEdit] Loading finished for session ${s}`)}})()},[s,c]),d.useEffect(()=>{if(!s)return;let t=!0;Tn(!1),pc.getJobForSession(s).then(n=>{t&&An(n)}).finally(()=>{t&&Tn(!0)});const a=pc.subscribeToJob(s,n=>{t&&An(n)});return()=>{t=!1,a()}},[s]);const pu=!!(Us&&["queued","uploading","submitted","running","aggregating"].includes(Us.status)),hu=()=>{if(!g)return e.jsxs("div",{className:"text-center text-[var(--cs-text-secondary)] py-8",children:[e.jsx(ui,{className:"h-12 w-12 mx-auto mb-4 opacity-50"}),e.jsx("p",{children:"Select an image to view metadata"})]});if(Ye)return!N||!Ce?e.jsxs("div",{className:"text-center text-[var(--cs-text-secondary)] py-8",children:[e.jsx(ui,{className:"h-12 w-12 mx-auto mb-4 opacity-50"}),e.jsx("p",{children:"No metadata available"})]}):er?e.jsxs("div",{className:"space-y-5",children:[e.jsxs("div",{children:[e.jsx(Ne,{className:"text-sm font-medium text-[var(--cs-text-secondary)]",children:"Filename"}),e.jsx("p",{className:"text-sm font-mono bg-[var(--cs-bg-elevated)] p-2 rounded border mt-1 break-all",children:N.filename})]}),e.jsx("div",{className:"space-y-4",children:xn.map(f=>e.jsx("div",{children:mu(f)},f.id))}),e.jsxs("div",{className:"flex flex-wrap gap-3 pt-4 border-t border-[var(--cs-border)] mt-2",children:[e.jsxs(K,{type:"button",variant:"outline",size:"sm",onClick:Ll,className:"bg-[#7B61FF] text-white border-[#7B61FF] hover:bg-[#704EF6] hover:text-white",children:[e.jsx(xt,{className:"h-3 w-3 mr-1"}),"Save"]}),e.jsxs(K,{type:"button",variant:"outline",size:"sm",onClick:Bl,className:"border-[#9CA3AF] text-[#4B5563] hover:bg-[#9CA3AF] hover:text-white",children:[e.jsx(At,{className:"h-3 w-3 mr-1"}),"Cancel"]})]})]}):e.jsxs("div",{className:"space-y-5",children:[e.jsxs("div",{children:[e.jsx(Ne,{className:"text-sm font-medium text-[var(--cs-text-secondary)]",children:"Filename"}),e.jsx("p",{className:"text-sm font-mono bg-[var(--cs-bg-elevated)] p-2 rounded border mt-1 break-all",children:N.filename})]}),e.jsxs("div",{className:"space-y-4",children:[e.jsxs("div",{children:[e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsx(Ne,{className:"text-sm font-medium text-[var(--cs-text-secondary)]",children:"Title"}),e.jsxs("div",{className:"flex items-center gap-1",children:[e.jsx(K,{variant:"ghost",size:"sm",className:"h-7 px-2",onClick:()=>qr("title"),children:"Clear"}),e.jsxs(K,{variant:"ghost",size:"sm",className:"h-7 px-2",onClick:()=>ar("title"),children:[e.jsx(ns,{className:"h-3 w-3 mr-1"})," Copy"]})]})]}),e.jsx("p",{className:"text-sm bg-[var(--cs-bg-elevated)] p-3 rounded border mt-1 min-h-[40px] whitespace-pre-wrap",children:Ce.title||"No title generated"})]}),e.jsxs("div",{children:[e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsx(Ne,{className:"text-sm font-medium text-[var(--cs-text-secondary)]",children:"Description"}),e.jsxs("div",{className:"flex items-center gap-1",children:[e.jsx(K,{variant:"ghost",size:"sm",className:"h-7 px-2",onClick:()=>qr("description"),children:"Clear"}),e.jsxs(K,{variant:"ghost",size:"sm",className:"h-7 px-2",onClick:()=>ar("description"),children:[e.jsx(ns,{className:"h-3 w-3 mr-1"})," Copy"]})]})]}),e.jsx("p",{className:"text-sm bg-[var(--cs-bg-elevated)] p-3 rounded border mt-1 min-h-[80px] whitespace-pre-wrap",children:Ce.description||"No description generated"})]}),e.jsxs("div",{children:[e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsxs(Ne,{className:"text-sm font-medium text-[var(--cs-text-secondary)]",children:["Keywords (",Ce.keywords.length,")"]}),e.jsxs(K,{variant:"ghost",size:"sm",className:"h-7 px-2",onClick:()=>ar("keywords"),children:[e.jsx(ns,{className:"h-3 w-3 mr-1"})," Copy"]})]}),e.jsx("div",{className:"mt-1 flex flex-wrap gap-2",children:Ce.keywords.length>0?Ce.keywords.map((f,T)=>e.jsx("span",{className:"inline-flex items-center gap-1 px-2.5 py-1 rounded-full text-[12px] bg-[var(--cs-bg-card)] border text-[var(--cs-text-primary)]",children:f},`${f}-${T}`)):e.jsx("span",{className:"text-sm text-muted-foreground",children:"No keywords"})})]}),e.jsxs("div",{children:[e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsx(Ne,{className:"text-sm font-medium text-[var(--cs-text-secondary)]",children:"Category"}),e.jsxs(K,{variant:"ghost",size:"sm",className:"h-7 px-2",onClick:()=>Ur(Ce.category||"","category"),children:[e.jsx(ns,{className:"h-3 w-3 mr-1"})," Copy"]})]}),e.jsx("p",{className:"text-sm bg-[var(--cs-bg-elevated)] p-3 rounded border mt-1 min-h-[40px] whitespace-pre-wrap",children:Ce.category||"Leave Empty"})]}),e.jsxs("div",{children:[e.jsx(Ne,{className:"text-sm font-medium text-[var(--cs-text-secondary)]",children:"Batch Name"}),e.jsx("p",{className:"text-sm bg-[var(--cs-bg-elevated)] p-3 rounded border mt-1 min-h-[40px] whitespace-pre-wrap",children:Ce.batchName||"—"})]}),e.jsxs("div",{children:[e.jsx(Ne,{className:"text-sm font-medium text-[var(--cs-text-secondary)]",children:"Editorial"}),e.jsx("p",{className:"text-sm bg-[var(--cs-bg-elevated)] p-3 rounded border mt-1 min-h-[40px] whitespace-pre-wrap",children:Ce.editorial?"Yes":"No"})]}),Ce.editorial&&e.jsxs("div",{className:"space-y-4",children:[e.jsxs("div",{children:[e.jsx(Ne,{className:"text-sm font-medium text-[var(--cs-text-secondary)]",children:"Editorial Text"}),e.jsx("p",{className:"text-sm bg-[var(--cs-bg-elevated)] p-3 rounded border mt-1 min-h-[40px] whitespace-pre-wrap",children:Ce.editorialText||"—"})]}),e.jsxs("div",{children:[e.jsx(Ne,{className:"text-sm font-medium text-[var(--cs-text-secondary)]",children:"Editorial City"}),e.jsx("p",{className:"text-sm bg-[var(--cs-bg-elevated)] p-3 rounded border mt-1 min-h-[40px] whitespace-pre-wrap",children:Ce.editorialCity||"—"})]}),e.jsxs("div",{children:[e.jsx(Ne,{className:"text-sm font-medium text-[var(--cs-text-secondary)]",children:"Editorial State"}),e.jsx("p",{className:"text-sm bg-[var(--cs-bg-elevated)] p-3 rounded border mt-1 min-h-[40px] whitespace-pre-wrap",children:Ce.editorialState||"—"})]}),e.jsxs("div",{children:[e.jsx(Ne,{className:"text-sm font-medium text-[var(--cs-text-secondary)]",children:"Editorial Country"}),e.jsx("p",{className:"text-sm bg-[var(--cs-bg-elevated)] p-3 rounded border mt-1 min-h-[40px] whitespace-pre-wrap",children:Ce.editorialCountry||"—"})]}),e.jsxs("div",{children:[e.jsx(Ne,{className:"text-sm font-medium text-[var(--cs-text-secondary)]",children:"Editorial Date"}),e.jsx("p",{className:"text-sm bg-[var(--cs-bg-elevated)] p-3 rounded border mt-1 min-h-[40px] whitespace-pre-wrap",children:Ce.editorialDate||"—"})]})]}),e.jsxs("div",{className:"grid grid-cols-1 md:grid-cols-2 gap-4",children:[e.jsxs("div",{children:[e.jsx(Ne,{className:"text-sm font-medium text-[var(--cs-text-secondary)]",children:"Shooting Country (Optional)"}),e.jsx("p",{className:"text-sm bg-[var(--cs-bg-elevated)] p-3 rounded border mt-1 min-h-[40px] whitespace-pre-wrap",children:Ce.shootingCountry||"Leave Empty"})]}),e.jsxs("div",{children:[e.jsx(Ne,{className:"text-sm font-medium text-[var(--cs-text-secondary)]",children:"Shooting Date (Optional)"}),e.jsx("p",{className:"text-sm bg-[var(--cs-bg-elevated)] p-3 rounded border mt-1 min-h-[40px] whitespace-pre-wrap",children:Ce.shootingDate||"Leave Empty"})]})]}),e.jsxs("div",{className:"mt-3 grid gap-3 text-[11px] text-[var(--cs-text-tertiary)] sm:grid-cols-4",children:[e.jsxs("div",{children:[e.jsx("p",{className:"font-semibold text-[var(--cs-text-primary)]",children:"Monthly volume"}
11),e.jsxs("p",{children:[Bi.monthly.toLocaleString()," searches"]})]}),e.jsxs("div",{children:[e.jsx("p",{className:"font-semibold text-[var(--cs-text-primary)]",children:"Long-tail stack"}),e.jsxs("p",{children:[Bi.longtail.toLocaleString()," /mo"]})]}),e.jsxs("div",{children:[e.jsx("p",{className:"font-semibold text-[var(--cs-text-primary)]",children:"Opportunity"}),e.jsxs("p",{children:[Bi.opportunity,"% lift window"]})]}),e.jsxs("div",{children:[e.jsx("p",{className:"font-semibold text-[var(--cs-text-primary)]",children:"Conversion proxy"}),e.jsxs("p",{children:[Bi.conversion,"% buyer intent"]})]})]})]})]});if(Se)return e.jsxs("div",{className:"space-y-4",children:[e.jsxs("div",{children:[e.jsx(Ne,{className:"text-sm font-medium",children:"Title"}),e.jsx($t,{value:Se.title,onChange:f=>lt({...Se,title:f.target.value}),className:"mt-1"})]}),e.jsxs("div",{children:[e.jsx(Ne,{className:"text-sm font-medium",children:"Description"}),e.jsx(as,{value:Se.description,onChange:f=>lt({...Se,description:f.target.value}),rows:4,className:"mt-1 resize-none"})]}),ks&&e.jsxs("div",{children:[e.jsx(Ne,{className:"text-sm font-medium",children:"Category"}),e.jsx("div",{className:"mt-1 flex items-center gap-2",children:e.jsxs(Lo,{value:Pn(Se.categories),onValueChange:f=>lt(T=>T&&{...T,categories:f==="__EMPTY__"?"":ys(W,f)||f}),children:[e.jsx(Fo,{className:"h-8 w-64 text-sm",children:e.jsx(Po,{placeholder:"Choose category"})}),e.jsxs(Ko,{children:[e.jsx(gr,{value:"__EMPTY__",children:"Leave Empty"}),Fn.map(f=>{const T=f.id??f.label,B=f.id?`${f.id} — ${f.label}`:f.label;return e.jsx(gr,{value:T,children:B},T)})]})]})})]}),e.jsxs("div",{children:[e.jsx(Ne,{className:"text-sm font-medium",children:"Keywords"}),e.jsx(as,{value:Se.keywords.join(", "),onChange:f=>{const B=f.target.value.split(/[,;\n]/).map(P=>P.trim()).filter(Boolean);lt({...Se,keywords:B})},rows:4,className:"mt-1 resize-none",placeholder:"keyword1, keyword2, long-tail keyword phrase"})]}),e.jsxs("div",{className:"flex gap-2 pt-2",children:[e.jsxs(K,{onClick:vu,size:"sm",className:"flex-1",children:[e.jsx(xt,{className:"h-4 w-4 mr-1"}),"Save"]}),e.jsxs(K,{onClick:Cu,variant:"outline",size:"sm",className:"flex-1",children:[e.jsx(At,{className:"h-4 w-4 mr-1"}),"Cancel"]})]})]});const t=b.find(f=>f.id===g),a=t?Rt(t):null,n=ys(W,a?.category??t?.categories),o=a?.title??t?.title??"",u=a?.description??t?.description??"",h=Array.isArray(a?.keywords)?a.keywords:Array.isArray(t?.keywords)?t.keywords:[],y=o,w=u,v=t?xs(t):{location:null,city:null,country:null,date:null},A=t?.editorialCity??v.city??"",I=t?.editorialLocation??v.location??"",M=t?.editorialCountry??v.country??"",q=t?.editorialDate??v.date??"",te=(()=>{const f=t?.editorialCaption??"",T=(W||"").toLowerCase(),B=String(qe?.editorial_style||"").trim();if(Bn!==null)return Bn;if(f.trim())return xa(f,B||ct);if(!Or(t))return"";if(t?.editorial){const P=Ls(String(t.editorialCity??"").trim(),M),G=Kt(q)??q,se=T.includes("shutterstock")||B==="istock_getty"||B==="shutterstock_strict",le=(se?w:y)||w||y||"";return(se?Fs(P,G,le,B||ct):le)||""}return""})(),me=ct?ya[ct]:null,pe=me?.requiredFields.includes("location"),ce=me?.requiredFields.includes("country"),oe=me?.requiredFields.includes("date"),ue=me?.requiredFields.includes("caption"),de=async()=>{if(!(!(N&&g&&(N.hasError||N.processingStatus==="error"||zr||N.warningMessage))||!N||!g)){console.log("[ReviewEdit] Starting free regeneration for",N.filename),Ws(!0);try{const T=N,B=g,P=E?.id??s,G=sn(T),se=await rn(G,P),le=Na(G,P),be=await an({sourceInput:G,sourceUrl:se,fallbackSessionId:P,stableSourcePath:le});if(console.log("[ReviewEdit] Resolved src:",be?.substring(0,100)),!be)throw new Error("No accessible image URL found");const Ke=Aa(be),$e=on(be,le);console.log("[ReviewEdit] URL strategy",{isSignedUrl:Ke,useProcessByUrl:$e});const Z=Ps.getState(),tt=(Z.generalSettings?.outputLanguage||"en").trim()||"en",Oe=Sa(Z.availablePlatforms,Z.selectedPlatform,W),Ve=!!Oe?.singleWordOnly,We=Ve||Z.keywordSettings?.singleWordMode===!0,St=!Ve&&We&&Z.keywordSettings?.allowCompoundKeywords===!0,Mt=We?"single":"long-tail",Je=Z.titleSettings?.enabled===!0,Ze=Je&&Z.titleSettings?.titleCase===!0,ft=Je&&Z.titleSettings?.allCaps===!0,jt=Oe?.titleLimit??200,Nt=cn(jt,Je,Z.titleSettings?.maxTitleChars),{minDescriptionChars:As,maxDescriptionChars:Qe}=mn(Oe?.descriptionLimit,Je,Z.titleSettings?.maxDescriptionChars,Z.titleSettings?.minDescriptionChars),{minTitleKeywords:So,maxTitleKeywords:tc}=pn(Je,Z.titleSettings?.minTitleKeywords,Z.titleSettings?.maxTitleKeywords),Wr=Je?Math.min(Nt,Math.max(1,Z.titleSettings?.minTitleChars??140)):Math.min(140,Nt),Ts=T?.mimeType||T?.mime_type||tn(T?.filename),Hr=T?.mediaType==="video"||/^video\//i.test(String(Ts??""))||/\.(mp4|mov|m4v|avi|webm|mkv)(\?|$)/i.test(String(T.filename||"")),Gr=dn(Je,Z.titleSettings?.maxTitleChars),Yr=un(Je,Z.titleSettings?.minTitleChars,Gr,Hr),Ds=!!T?.editorial||Xt&&Lt,Is=gn(T,Ds),gs=Oe?.keywordsLimit??50,Xr=Math.min(gs,Math.max(1,Z.keywordSettings?.minKeywordCount||gs));let Rs=null,Pt=null;const Ms=Oo({filename:T.filename,mimeType:Ts,mediaType:T?.mediaType??T?.media_type??null,title:T?.title??null,keywords:T?.keywords??null},Z.customPrompt),lr=`${B}::free_regenerate::${Date.now()}`,cr=ln(T,Ts),dr={noCharge:!0,retryForId:B,...cr?{mediaType:cr}:{},hasTransparency:nn(T),keywordMode:Mt,singleWordOnly:Ve,allowCompoundKeywords:St,keywordCount:Xr,keywordsLimit:gs,outputLanguage:tt,locale:tt,titleCase:Ze,titleAllCaps:ft,titleMinChars:Wr,titleMaxChars:Nt,titleSettingsEnabled:Je,aiTitleMinChars:Yr,aiTitleMaxChars:Gr,editorialEnabled:Ds,...Is?{editorialSeed:Is}:{},editorialPlatformLabel:Oe?.label??W??null,descriptionLimit:Oe?.descriptionLimit,maxDescriptionChars:Qe,minDescriptionChars:As,minTitleKeywords:So,maxTitleKeywords:tc,requiredStartingKeywords:Z.keywordSettings?.requiredStartingKeywords??"",requiredEndingKeywords:Z.keywordSettings?.requiredEndingKeywords??"",excludedKeywords:Z.keywordSettings?.excludedKeywords??"",prohibitedCharacters:Z.generalSettings?.prohibitedCharacters??"",optionalTitleElements:Z.titleSettings?.optionalElements??"",useFilenameForContext:Z.generalSettings?.useFilenameForContext===!0,useMetadataForContext:Z.generalSettings?.useMetadataForContext===!0,analytics:!1},ur=async Bt=>{let yt=null;for(let et=1;et<=4;et+=1){if(yt=await Bt(),!yt?.error||!yt?.retryable)return yt;const _o=(typeof yt?.retryAfterMs=="number"?Number(yt.retryAfterMs):qc(yt.error?.message??""))??Math.min(15e3,1200*et*et);await new Promise(Ao=>setTimeout(Ao,_o))}return yt??{metadata:null,error:new Error("Regeneration failed")}};if($e){console.log("[ReviewEdit] Using fast path: processAssetByUrl");const Bt=await ur(()=>Tt.processAssetByUrl({signedUrl:be,originalStoragePath:le||"",mimeType:Ts,filename:T.filename,sessionId:P,sessionImageId:B,generationMode:z,runId:lr,promptRequest:Ms,extra:dr}));Rs=Bt.metadata,Pt=Bt.error}else{console.log("[ReviewEdit] Using slow path: fetch + base64 encode");const Bt=Date.now(),is=await fetch(be);if(!is.ok)throw new Error(`Failed to fetch image: ${is.status} ${is.statusText}`);console.log("[ReviewEdit] Fetch complete in",Date.now()-Bt,"ms");const yt=await is.blob(),et=yt.type||"image/webp";console.log("[ReviewEdit] Blob size:",yt.size,"bytes, mime:",et);const Jr=Date.now(),_o=await new Promise((Pu,Ku)=>{const ma=new FileReader;ma.onloadend=()=>Pu(String(ma.result).split(",")[1]||""),ma.onerror=Ku,ma.readAsDataURL(yt)});console.log("[ReviewEdit] Base64 encode complete in",Date.now()-Jr,"ms"),console.log("[ReviewEdit] Calling processImage (this may take up to 65s)...");const Ao=Date.now(),sc=await ur(()=>Tt.processImage(_o,Ms,c.id,et,{generationMode:z,sessionId:P,filename:T.filename,runId:lr,extra:dr}));console.log("[ReviewEdit] AI processing complete in",Date.now()-Ao,"ms"),Rs=sc.metadata,Pt=sc.error}if(Pt||!Rs)throw console.error("[ReviewEdit] Processing failed:",Pt),Pt||new Error("No metadata returned");console.log("[ReviewEdit] Metadata received, updating UI...");const mr=hn(Rs)??{title:"",description:"",keywords:[]},ss=mr.title,He=mr.description,rs=ci(mr.keywords);let Fe=T.categories||"";ks&&ia&&(Fe=Cr(rs,ss,He,T.categories));const Et=ys(W,Fe)||Fe||"",Bs={baseTitle:ss,baseDescription:He,baseKeywords:rs,c
11ategories:Et},rt=ut(T,Bs)??kt({...T,baseTitle:Bs.baseTitle,baseDescription:Bs.baseDescription,baseKeywords:Bs.baseKeywords,categories:Bs.categories}),pr=rt?.title??ss,jo=rt?.description??He,No=rt?.keywords??rs,ua=rt?.category??Et,Eo={title:pr,keywords:No.join(", "),description:jo,categories:ua||null,status:"ready",baseTitle:ss,baseDescription:He,baseKeywords:rs};if(W==="Blackbox"){const Bt=wr(T),is=jr(ua??""),yt=is||Bt.category||"",et=ls({...Bt,title:pr,description:jo,keywords:No,category:yt}),Jr={category:et.category,batchName:et.batchName,editorial:et.editorial,editorialText:et.editorialText,editorialCity:et.editorialCity,editorialState:et.editorialState,editorialCountry:et.editorialCountry,editorialDate:et.editorialDate,shootingCountry:et.shootingCountry,shootingDate:et.shootingDate,sourceContext:et.sourceContext??null};ye(B,"blackbox",Jr),Eo.platform_metadata={...T.platformMetadata??{},blackbox:Jr},nt(et),Ns(B),vt(!1),dt({}),es(""),Eo.categories=is||(Bt.category?Bt.category:null)}console.log("[ReviewEdit] Updating database..."),await we.updateSessionImage(B,Eo),console.log("[ReviewEdit] Database updated successfully"),console.log("[ReviewEdit] Updating local UI state..."),Q(B,{title:pr,de
11scription:jo,keywords:No,baseTitle:ss,baseDescription:He,baseKeywords:rs,categories:ua,hasError:!1,processingStatus:"ready",errorMessage:null,suppressMetadata:!1}),console.log("[ReviewEdit] ✅ Free regeneration complete for",T.filename),r({title:"✅ Regeneration complete",description:`${T.filename} has been successfully regenerated (no credits charged)`})}catch(T){console.error("[ReviewEdit] ❌ Free regeneration failed:",T);const B=T instanceof Error?T.message:String(T);r({title:"Regeneration failed",description:B||"Failed to regenerate image. Check console for details.",variant:"destructive"})}finally{console.log("[ReviewEdit] Cleaning up, setting regenLoading to false"),Ws(!1)}}},C=async(f,T)=>{const B={enabled:!0,is_editorial:!0,...T.location?{location:T.location}:{},...T.country?{country:T.country}:{},...T.date?{date:T.date}:{},...T.caption?{caption:T.caption}:{},...T.category?{category:T.category}:{}};for(const P of f){Q(P.id,{editorial:!0,editorialLocation:T.location??P.editorialLocation??null,editorialCountry:T.country??P.editorialCountry??null,editorialDate:T.date??P.editorialDate??null,editorialCaption:T.caption??P.editorialCaption??null,editorialCategory:T.category??P.editorialCategory??null,warningMessage:null});try{await we.patchSessionImageMeta(P.id,{editorial:B,ai_warning:null})}catch(G){console.warn("[ReviewEdit] Failed to persist copied editorial seed",{id:P.id,err:G})}}},Y=async f=>{if(!N||!g)return;const T=f?b.filter(G=>G.warningMessage==="editorial_seed_missing"):[N],B=new Set(T.map(G=>G.id)),P=vh(b,B);if(!P){r({title:"No neighbor with editorial data",description:"No other file in this session has IPTC/XMP editorial fields to copy from.",variant:"destructive"});return}Ws(!0);try{await C(T,P),r({title:f?"Editorial seed copied to all":"Editorial seed copied",description:`Used seed from ${P.source.filename}. Regenerating ${N.filename}…`}),await de()}catch(G){console.error("[ReviewEdit] Copy editorial seed failed",G),r({title:"Copy failed",description:G instanceof Error?G.message:String(G),variant:"destructive"})}finally{Ws(!1)}},F=!!(N&&!N.hasError&&!zr&&N.warningMessage==="editorial_seed_missing"),X=b.filter(f=>f.warningMessage==="editorial_seed_missing").length;return e.jsxs("div",{className:"space-y-4",children:[N&&(N.hasError||zr)&&e.jsxs(zo,{variant:"destructive",className:"rounded-xl border-2",children:[e.jsx(di,{className:"h-5 w-5"}),e.jsx(Uo,{className:"text-base",children:"Processing Failed"}),e.jsxs(qo,{className:"space-y-3",children:[e.jsx("p",{className:"text-sm",children:N.errorMessage||"This image failed to process. You can regenerate it for free."}),e.jsxs(K,{onClick:de,disabled:Ft,variant:"default",size:"sm",className:"gap-2 bg-red-600 hover:bg-red-700 text-white",children:[Ft?e.jsx($s,{className:"h-3 w-3 animate-spin"}):e.jsx(va,{className:"h-3 w-3"}),"Regenerate for Free"]})]})]}),F&&e.jsxs(zo,{className:"rounded-xl border-2 border-amber-500/60 bg-amber-50 text-amber-900 dark:bg-amber-950/40 dark:text-amber-200 [&>svg]:text-amber-600 dark:[&>svg]:text-amber-400",children:[e.jsx(di,{className:"h-5 w-5"}),e.jsx(Uo,{className:"text-base",children:"No IPTC/XMP editorial data found"}),e.jsxs(qo,{className:"space-y-3",children:[e.jsx("p",{className:"text-sm",children:"We couldn't find IPTC/XMP editorial fields (city, country, date, caption) in this file, so it was generated as a regular asset. Copy editorial seed from a neighboring file to regenerate this image as editorial."}),e.jsxs("div",{className:"flex flex-wrap gap-2",children:[e.jsxs(K,{onClick:()=>{Y(!1)},disabled:Ft,variant:"default",size:"sm",className:"gap-2 bg-amber-600 hover:bg-amber-700 text-white",children:[Ft?e.jsx($s,{className:"h-3 w-3 animate-spin"}):e.jsx(va,{className:"h-3 w-3"}),"Copy from neighbor"]}),X>1&&e.jsxs(K,{onClick:()=>{Y(!0)},disabled:Ft,variant:"outline",size:"sm",className:"gap-2 border-amber-500/60 text-amber-800 hover:bg-amber-100 dark:text-amber-200 dark:hover:bg-amber-900/40",children:["Copy to all ",X," files"]})]})]})]}),N&&e.jsx(e.Fragment,{children:e.jsxs("div",{"data-onboarding":"review-score",className:"rounded-xl p-4 space-y-4",style:{background:"var(--cs-bg-card)",border:"1px solid var(--cs-border)",boxShadow:"var(--cs-shadow-card)"},children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(bs,{className:"h-4 w-4",style:{color:"var(--cs-purple-400)"}}),e.jsx("p",{className:"text-sm font-semibold",style:{color:"var(--cs-text-primary)"},children:"Score summary"})]}),e.jsxs("div",{className:"grid grid-cols-2 gap-2 md:grid-cols-4",children:[e.jsx(Ee,{delayDuration:150,children:e.jsxs(_e,{children:[e.jsx(Ae,{asChild:!0,children:e.jsx("div",{children:e.jsx(fa,{label:"Selling",value:ts.selling??0,seed:`${g??"x"}:selling`,size:"sm"})})}),e.jsx(Te,{side:"bottom",className:"max-w-xs p-3 text-xs",children:e.jsxs("div",{className:"space-y-1",children:[e.jsxs("div",{children:[e.jsx("span",{className:"font-medium",children:"What it means:"})," Overall marketability based on other scores"]}),e.jsxs("div",{children:[e.jsx("span",{className:"font-medium",children:"Weights:"})," Title 45% · Description 35% · Keywords 20%"]}),e.jsxs("div",{children:[e.jsx("span",{className:"font-medium",children:"Tip:"})," Put strongest keywords early in the Title; keep Description concise and specific"]})]})})]})}),Rn?e.jsxs("div",{className:"rounded-xl border shadow-sm flex flex-col items-center justify-center px-2 py-1.5",style:{background:"var(--cs-bg-card)",borderColor:"var(--cs-border)"},children:[e.jsx("div",{className:"text-[9px] font-bold tracking-wide uppercase text-center",style:{color:"var(--cs-text-primary)"},children:"Title"}),e.jsx("div",{className:"text-[11px] mt-1 font-medium",style:{color:"var(--cs-text-primary)"},children:"Not required"})]}):e.jsx(Ee,{delayDuration:150,children:e.jsxs(_e,{children:[e.jsx(Ae,{asChild:!0,children:e.jsx("div",{children:e.jsx(fa,{label:"Title",value:ts.title??0,seed:`${g??"x"}:title`,size:"sm"})})}),e.jsx(Te,{side:"bottom",className:"max-w-xs p-3 text-xs",children:e.jsxs("div",{className:"space-y-1",children:[e.jsxs("div",{children:[e.jsx("span",{className:"font-medium",children:"Lead keywords:"})," 60% (first 80 chars)"]}),e.jsxs("div",{children:[e.jsx("span",{className:"font-medium",children:"Relevance:"})," 25% (topic match)"]}),e.jsxs("div",{children:[e.jsx("span",{className:"font-medium",children:"Readability:"})," 15% (length, punctuation)"]}),e.jsxs("div",{children:[e.jsx("span",{className:"font-medium",children:"Tip:"})," Start with 1–2 strongest terms; avoid shouting and extra punctuation"]})]})})]})}
11),In?e.jsxs("div",{className:"rounded-xl border shadow-sm flex flex-col items-center justify-center px-2 py-1.5",style:{background:"var(--cs-bg-card)",borderColor:"var(--cs-border)"},children:[e.jsx("div",{className:"text-[9px] font-bold tracking-wide uppercase text-center",style:{color:"var(--cs-text-primary)"},children:"Description"}),e.jsx("div",{className:"text-[11px] mt-1 font-medium",style:{color:"var(--cs-text-primary)"},children:"Not required"})]}):e.jsx(Ee,{delayDuration:150,children:e.jsxs(_e,{children:[e.jsx(Ae,{asChild:!0,children:e.jsx("div",{children:e.jsx(fa,{label:"Description",value:ts.description??0,seed:`${g??"x"}:desc`,size:"sm"})})}),e.jsx(Te,{side:"bottom",className:"max-w-xs p-3 text-xs",children:e.jsxs("div",{className:"space-y-1",children:[e.jsxs("div",{children:[e.jsx("span",{className:"font-medium",children:"Strong/Medium density:"})," 45% (first 160 chars)"]}),e.jsxs("div",{children:[e.jsx("span",{className:"font-medium",children:"Relevance:"})," 25% (topic match)"]}),e.jsxs("div",{children:[e.jsx("span",{className:"font-medium",children:"Readability:"})," 30% (length, clarity)"]}),e.jsxs("div",{children:[e.jsx("span",{className:"font-medium",children:"Tip:"})," Mention 2 strong + 1 medium keyword naturally in the first sentence"]})]})})]})}),e.jsx(Ee,{delayDuration:150,children:e.jsxs(_e,{children:[e.jsx(Ae,{asChild:!0,children:e.jsx("div",{children:e.jsx(fa,{label:"Keywords",value:ts.keywords??0,seed:`${g??"x"}:kw`,size:"sm"})})}),e.jsx(Te,{side:"bottom",className:"max-w-xs p-3 text-xs",children:e.jsxs("div",{className:"space-y-1",children:[e.jsxs("div",{children:[e.jsx("span",{className:"font-medium",children:"Basis:"})," Avg HCV of top‑10 keywords (soft‑cap 0.90)"]}),e.jsxs("div",{children:[e.jsx("span",{className:"font-medium",children:"HCV:"})," Weighted by volume, trend, and relevance"]}),e.jsxs("div",{children:[e.jsx("span",{className:"font-medium",children:"Tip:"})," Favor high‑volume + rising trends; remove duplicates and weak fillers"]})]})})]})})]}),(xl||Js&&Js.length>0)&&e.jsxs(zo,{variant:Js?.length?"destructive":"default",children:[e.jsx(di,{className:"h-4 w-4"}),e.jsx(Uo,{children:Js?.length?"Issues detected":"Last run"}),e.jsxs(qo,{children:[xl,Js?.length?` • ${Js.length} image(s) failed`:""]})]}),Object.entries(dl).some(([,f])=>f.length>0)&&e.jsx("div",{className:"mt-4 grid gap-3 md:grid-cols-2",children:Object.entries(dl).map(([f,T])=>T.length>0&&e.jsxs("div",{className:"rounded-xl border p-3",style:{borderColor:"var(--cs-border)",background:"var(--cs-bg-elevated)"},children:[e.jsx("div",{className:"text-xs font-semibold mb-2",style:{color:"var(--cs-text-primary)"},children:Sh[f]}),e.jsx("div",{className:"flex flex-wrap gap-2",children:T.map((B,P)=>e.jsxs("div",{className:mt("rounded-lg border px-3 py-1 text-[12px] font-medium",fh[B.tone]),children:[e.jsx("span",{className:"block text-[11px] uppercase tracking-wide opacity-75",children:B.label}),e.jsx("span",{className:"text-sm",children:B.value})]},`${f}-metric-${P}`))})]},f))})]})}),e.jsxs("div",{className:"grid gap-4",children:[e.jsxs("div",{className:"rounded-xl border border-[var(--cs-border)] bg-[var(--cs-bg-card)] p-3 flex items-center justify-between gap-3",children:[e.jsxs("div",{className:"min-w-0",children:[e.jsx("div",{className:"text-[11px] font-bold uppercase tracking-wide",style:{color:"var(--cs-text-secondary)"},children:"Releases"}),e.jsx("div",{className:"text-[12px] mt-0.5 truncate",style:{color:"var(--cs-text-primary)"},children:us.length>0?`Attached: ${us.length}`:Ot[g]?"Missing":"None"})]}),e.jsx(K,{variant:"outline",size:"sm",className:"h-8",onClick:()=>Ei(!0),children:"Manage"})]}),!Rn&&e.jsxs("div",{"data-onboarding":"review-title",className:"rounded-xl border border-[var(--cs-border)] bg-[var(--cs-bg-card)] p-4 space-y-4",children:[e.jsxs("div",{className:"flex flex-wrap items-center justify-between gap-2",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx("span",{className:"text-xs font-semibold uppercase tracking-wide text-[var(--cs-text-primary)]",children:"Title"}),e.jsxs("span",{className:"text-[11px] font-semibold text-[var(--cs-text-secondary)]",children:["(",y.trim().length,")"]}),uo("title",ts.title)]}),e.jsx("div",{className:"flex items-center gap-1",children:Jt==="title"?e.jsxs(e.Fragment,{children:[e.jsx(Ee,{delayDuration:150,children:e.jsxs(_e,{children:[e.jsx(Ae,{asChild:!0,children:e.jsx(K,{variant:"ghost",size:"icon",className:"h-7 w-7 text-red-500 hover:text-red-600 hover:bg-red-50",onClick:or,children:e.jsx(At,{className:"h-3.5 w-3.5"})})}),e.jsx(Te,{side:"bottom",className:"text-xs",children:"Cancel"})]})}),e.jsx(Ee,{delayDuration:150,children:e.jsxs(_e,{children:[e.jsx(Ae,{asChild:!0,children:e.jsx(K,{variant:"ghost",size:"icon",className:"h-7 w-7 text-emerald-500 hover:text-emerald-600 hover:bg-emerald-50",onClick:nr,children:e.jsx(xt,{className:"h-3.5 w-3.5"})})}),e.jsx(Te,{side:"bottom",className:"text-xs",children:"Save title"})]})})]}):e.jsxs(e.Fragment,{children:[e.jsx(Ee,{delayDuration:150,children:e.jsxs(_e,{children:[e.jsx(Ae,{asChild:!0,children:e.jsx(K,{variant:"ghost",size:"icon",className:"h-7 w-7",onClick:()=>Jl("title"),children:e.jsx(vc,{className:"h-3 w-3"})})}),e.jsx(Te,{side:"bottom",className:"text-xs",children:"Edit title"})]})}),e.jsx(Ee,{delayDuration:150,children:e.jsxs(_e,{children:[e.jsx(Ae,{asChild:!0,children:e.jsx(K,{variant:"ghost",size:"icon",className:"h-7 w-7",onClick:()=>ar("title"),children:e.jsx(ns,{className:"h-3 w-3"})})}),e.jsx(Te,{side:"bottom",className:"text-xs",children:"Copy title"})]})}),e.jsx(Ee,{delayDuration:150,children:e.jsxs(_e,{children:[e.jsx(Ae,{asChild:!0,children:e.jsx(K,{variant:"ghost",size:"icon",className:"h-7 w-7",onClick:()=>qr("title"),children:e.jsx(At,{className:"h-3 w-3"})})}),e.jsx(Te,{side:"bottom",className:"text-xs",children:"Clear title"})]})})]})})]}),e.jsxs("div",{className:mt("relative overflow-hidden rounded border p-3 text-sm transition-shadow","bg-[var(--cs-bg-elevated)]",Xs.title&&"ring-2 ring-emerald-500 border-emerald-400 shadow-sm"),children:[Xs.title&&e.jsx("span",{className:"absolute right-2 top-2 rounded-md bg-emerald-100/90 text-emerald-700 text-xs px-2 py-0.5 
11shadow",children:"Applied"}),Jt==="title"?e.jsx(as,{autoFocus:!0,value:Tr,onChange:f=>Zt(f.target.value),onKeyDown:f=>{f.key==="Escape"&&or(),f.key==="Enter"&&(f.metaKey||f.ctrlKey)&&nr()},className:"min-h-[60px] text-sm bg-transparent border-0 p-0 focus-visible:ring-0 resize-none",placeholder:"Enter title..."}):e.jsx(uc,{mode:"wait",children:e.jsx(mc.p,{initial:{opacity:0,y:4},animate:{opacity:1,y:0},exit:{opacity:0,y:-2},transition:{duration:.18},className:"min-h-[40px] whitespace-pre-wrap leading-relaxed text-[var(--cs-text-primary)]",children:y?Il(y):"No title generated"},y||"empty-title")})]})]}),!In&&e.jsxs("div",{"data-onboarding":"review-description",className:"rounded-xl border border-[var(--cs-border)] bg-[var(--cs-bg-card)] p-4 space-y-4",children:[e.jsxs("div",{className:"flex flex-wrap items-center justify-between gap-2",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx("span",{className:"text-xs font-semibold uppercase tracking-wide text-[var(--cs-text-primary)]",children:"Description"}),e.jsxs("span",{className:"text-[11px] font-semibold text-[var(--cs-text-secondary)]",children:["(",w.trim().length,")"]}),uo("description",ts.description)]}),e.jsx("div",{className:"flex items-center gap-1",children:Jt==="description"?e.jsxs(e.Fragment,{children:[e.jsx(Ee,{delayDuration:150,children:e.jsxs(_e,{children:[e.jsx(Ae,{asChild:!0,children:e.jsx(K,{variant:"ghost",size:"icon",className:"h-7 w-7 text-red-500 hover:text-red-600 hover:bg-red-50",onClick:or,children:e.jsx(At,{className:"h-3.5 w-3.5"})})}),e.jsx(Te,{side:"bottom",className:"text-xs",children:"Cancel"})]})}),e.jsx(Ee,{delayDuration:150,children:e.jsxs(_e,{children:[e.jsx(Ae,{asChild:!0,children:e.jsx(K,{variant:"ghost",size:"icon",className:"h-7 w-7 text-emerald-500 hover:text-emerald-600 hover:bg-emerald-50",onClick:nr,children:e.jsx(xt,{className:"h-3.5 w-3.5"})})}),e.jsx(Te,{side:"bottom",className:"text-xs",children:"Save description"})]})})]}):e.jsxs(e.Fragment,{children:[e.jsx(Ee,{delayDuration:150,children:e.jsxs(_e,{children:[e.jsx(Ae,{asChild:!0,children:e.jsx(K,{variant:"ghost",size:"icon",className:"h-7 w-7",onClick:()=>Jl("description"),children:e.jsx(vc,{className:"h-3 w-3"})})}),e.jsx(Te,{side:"bottom",className:"text-xs",children:"Edit description"})]})}),e.jsx(Ee,{delayDuration:150,children:e.jsxs(_e,{children:[e.jsx(Ae,{asChild:!0,children:e.jsx(K,{variant:"ghost",size:"icon",className:"h-7 w-7",onClick:()=>ar("description"),children:e.jsx(ns,{className:"h-3 w-3"})})}),e.jsx(Te,{side:"bottom",className:"text-xs",children:"Copy description"})]})}),e.jsx(Ee,{delayDuration:150,children:e.jsxs(_e,{children:[e.jsx(Ae,{asChild:!0,children:e.jsx(K,{variant:"ghost",size:"icon",className:"h-7 w-7",onClick:()=>qr("description"),children:e.jsx(At,{className:"h-3 w-3"})})}),e.jsx(Te,{side:"bottom",className:"text-xs",children:"Clear description"})]})})]})})]}),e.jsxs("div",{className:mt("relative overflow-hidden rounded border p-3 text-sm","bg-[var(--cs-bg-elevated)]",Xs.description&&"ring-2 ring-emerald-500 border-emerald-400 shadow-sm"),children:[Xs.description&&e.jsx("span",{className:"absolute right-2 top-2 rounded-md bg-emerald-100/90 text-emerald-700 text-xs px-2 py-0.5 shadow",children:"Applied"}),Jt==="description"?e.jsx(as,{autoFocus:!0,value:Tr,onChange:f=>Zt(f.target.value),onKeyDown:f=>{f.key==="Escape"&&or(),f.key==="Enter"&&(f.metaKey||f.ctrlKey)&&nr()},className:"min-h-[100px] text-sm bg-transparent border-0 p-0 focus-visible:ring-0 resize-none",placeholder:"Enter description..."}):e.jsx(uc,{mode:"wait",children:e.jsx(mc.p,{initial:{opacity:0,y:4},animate:{opacity:1,y:0},exit:{opacity:0,y:-2},transition:{duration:.18},className:"min-h-[80px] whitespace-pre-wrap leading-relaxed text-[var(--cs-text-primary)]",children:w?Il(w):"No description generated"},w||"empty-description")})]})]}),(qe?.columns||[]).some(f=>f==="Category"||f==="Categories")&&e.jsxs("div",{className:"rounded-xl border border-[var(--cs-border)] bg-[var(--cs-bg-card)] p-4 space-y-3",children:[e.jsxs("div",{className:"flex items-center justify-between gap-2",children:[e.jsx(Ne,{className:"text-xs font-semibold uppercase tracking-wide text-[var(--cs-text-primary)]",children:"Category"}),e.jsxs(K,{variant:"ghost",size:"sm",className:"h-7 px-2",onClick:()=>{g&&Ur(n||"","category")},children:[e.jsx(ns,{className:"h-3 w-3 mr-1"})," Copy"]})]}),g&&e.jsxs(Lo,{value:Pn(a?.category??t?.categories),onValueChange:f=>Su(g,f),children:[e.jsx(Fo,{className:"h-10 w-full justify-between rounded border border-[#
11E0E7FF] bg-[var(--cs-bg-elevated)] px-3 text-sm",children:e.jsx(Po,{placeholder:"Leave Empty"})}),e.jsxs(Ko,{children:[e.jsx(gr,{value:"__EMPTY__",children:"Leave Empty"}),Fn.map(f=>{const T=f.id??f.label,B=f.id?`${f.id} — ${f.label}`:f.label;return e.jsx(gr,{value:T,children:B},T)})]})]})]}),Xt&&Lt&&t&&e.jsxs("div",{className:"rounded-xl border border-[var(--cs-border)] bg-[var(--cs-bg-card)] p-4 space-y-4",children:[e.jsxs("div",{className:"flex flex-wrap items-center justify-between gap-2",children:[e.jsxs("div",{className:"flex flex-col gap-1",children:[e.jsx("span",{className:"text-xs font-semibold uppercase tracking-wide text-[var(--cs-text-primary)]",children:"Editorial"}),ct&&ya[ct]&&e.jsx("span",{className:"text-[11px] text-[#6B7280]",children:ya[ct].description})]}),e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(hr,{id:"editorial-enabled",checked:!!t.editorial,onCheckedChange:async f=>{if(!t)return;if(!!!f){Ct(t.id,{editorial:!1},{silent:!0});return}let B=I||v.location||"",P=M||v.country||"",G=q||v.date||"",se=null;if(!B&&!P&&!G){const Ze=await Ar(t);if(Ze){B=[Ze.city,Ze.state,Ze.country].filter(Nt=>Nt&&String(Nt).trim().length>0).join(", ")||B,P=(Ze.country??"").trim()||P,G=Ze.date??G;const jt=(Ze.caption||Ze.description||"").trim();jt&&(se=jt)}}const le=Kt(G)??G,be=(y||t.title||"").trim(),Ke=w||t.description||"",$e=(te||"").trim(),Z=Ke.trim(),tt=$e.toLowerCase(),Oe=$e&&$e===Z,Ve=tt.includes("this image can be used")||tt.includes("this image is suitable"),We=Or(t)&&(!$e||Oe||Ve),St=(We?"":$e)||se||Ke||be,Mt=Ls(String(t.editorialCity??"").trim(),P),Je=We?Fs(Mt,le,St,ct):$e;Ct(t.id,{editorial:!0,editorialLocation:B||null,editorialCountry:P||null,editorialDate:le||null,editorialCaption:Je||null},{silent:!0})}}),e.jsx(Ne,{htmlFor:"editorial-enabled",className:"text-xs",style:{color:"var(--cs-text-secondary)"},children:"Enable"})]})]}),t.editorial&&e.jsxs("div",{className:"grid gap-3 md:grid-cols-2",children:[e.jsxs("div",{children:[e.jsx(Ne,{className:"text-sm font-medium text-[var(--cs-text-secondary)]",children:"City"}),e.jsx($t,{className:"mt-1 h-8 text-sm",value:A,onChange:f=>{t&&Q(t.id,{editorialCity:f.target.value})},onBlur:f=>{t&&Ct(t.id,{editorialCity:f.target.value},{silent:!0})},placeholder:"e.g. Amsterdam"})]}),e.jsxs("div",{children:[e.jsxs(Ne,{className:"text-sm font-medium text-[var(--cs-text-secondary)]",children:["Country",ce&&e.jsx("span",{className:"ml-0.5 text-red-500",children:"*"})]}),e.jsx($t,{className:"mt-1 h-8 text-sm",value:M,onChange:f=>{t&&Q(t.id,{editorialCountry:f.target.value})},onBlur:f=>{t&&Ct(t.id,{editorialCountry:f.target.value},{silent:!0})}})]}),e.jsxs("div",{children:[e.jsxs(Ne,{className:"text-sm font-medium text-[var(--cs-text-secondary)]",children:["Date",oe&&e.jsx("span",{className:"ml-0.5 text-red-500",children:"*"})]}),e.jsx($t,{className:"mt-1 h-8 text-sm",value:q,onChange:f=>{t&&Q(t.id,{editorialDate:f.target.value})},onBlur:f=>{t&&Ct(t.id,{editorialDate:f.target.value},{silent:!0})},placeholder:"e.g. July 4, 2024"})]}),e.jsxs("div",{children:[e.jsxs(Ne,{className:"text-sm font-medium text-[var(--cs-text-secondary)]",children:["Location",pe&&e.jsx("span",{className:"ml-0.5 text-red-500",children:"*"})]}),e.jsx($t,{className:"mt-1 h-8 text-sm",value:I,onChange:f=>{t&&Q(t.id,{editorialLocation:f.target.value})},onBlur:f=>{t&&Ct(t.id,{editorialLocation:f.target.value},{silent:!0})},placeholder:"Full location for metadata"})]}),e.jsxs("div",{className:"md:col-span-2",children:[e.jsxs("div",{className:"flex items-center justify-between gap-2",children:[e.jsxs("div",{className:"flex flex-col gap-0.5",children:[e.jsxs(Ne,{className:"text-sm font-medium text-[var(--cs-text-secondary)]",children:["Caption",ue&&e.jsx("span",{className:"ml-0.5 text-red-500",children:"*"})]}),me?.captionHint&&e.jsx("span",{className:"text-[11px] text-[#6B7280]",children:me.captionHint})]}),e.jsx(K,{variant:"ghost",size:"sm",className:"h-7 px-2 text-[12px]",disabled:!t||!(y||t.title||"").trim(),onClick:async()=>{if(!t)return;const f=(y||t.title||"").trim();if(f){Q(t.id,{editorialCaption:f});try{await Ct(t.id,{editorialCaption:f},{silent:!0}
11),r({title:"Caption copied",description:"Editorial caption now matches the title."})}catch(T){console.warn("[ReviewEdit] Failed to copy caption from title",T),r({title:"Copy failed",description:"Could not copy the title into the caption.",variant:"destructive"})}}},children:"Copy from Title"})]}),e.jsx(as,{className:"mt-1 resize-none text-sm",rows:3,value:te,onFocus:f=>{ki(f.target.value),Ci.current=f.target.value},onChange:f=>ki(f.target.value),onBlur:f=>{const T=Ci.current;if(Ci.current=null,ki(null),!t)return;const B=f.target.value,P=T!==null&&B!==T;Ct(t.id,{editorialCaption:B,...P?{captionClearedByUser:B.trim().length===0}:{}},{silent:!0})},placeholder:"Factual description of the scene"})]})]})]}),e.jsxs("div",{"data-onboarding":"review-keywords",className:"rounded-xl border border-[var(--cs-border)] bg-[var(--cs-bg-card)] p-4 space-y-4",children:[e.jsxs("div",{className:"flex flex-wrap items-center justify-between gap-2",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx("span",{className:"text-xs font-semibold uppercase tracking-wide text-[var(--cs-text-primary)]",children:"Keywords"}),e.jsxs("span",{className:"text-[11px] font-semibold text-[var(--cs-text-secondary)]",children:["(",h.length,")"]}),uo("keywords",ts.keywords)]}),e.jsx("div",{className:"flex items-center gap-1",children:Jt==="keywords"?e.jsxs(e.Fragment,{children:[e.jsx(Ee,{delayDuration:150,children:e.jsxs(_e,{children:[e.jsx(Ae,{asChild:!0,children:e.jsx(K,{variant:"ghost",size:"icon",className:"h-7 w-7 text-red-500 hover:text-red-600 hover:bg-red-50",onClick:or,children:e.jsx(At,{className:"h-3.5 w-3.5"})})}),e.jsx(Te,{side:"bottom",className:"text-xs",children:"Cancel"})]})}),e.jsx(Ee,{delayDuration:150,children:e.jsxs(_e,{children:[e.jsx(Ae,{asChild:!0,children:e.jsx(K,{variant:"ghost",size:"icon",className:"h-7 w-7 text-emerald-500 hover:text-emerald-600 hover:bg-emerald-50",onClick:nr,children:e.jsx(xt,{className:"h-3.5 w-3.5"})})}),e.jsx(Te,{side:"bottom",className:"text-xs",children:"Save keywords"})]})})]}):e.jsxs(e.Fragment,{children:[e.jsx(Ee,{delayDuration:150,children:e.jsxs(_e,{children:[e.jsx(Ae,{asChild:!0,children:e.jsx(K,{variant:"ghost",size:"icon",className:"h-7 w-7",onClick:()=>ar("keywords"),children:e.jsx(ns,{className:"h-3 w-3"})})}),e.jsx(Te,{side:"bottom",className:"text-xs",children:"Copy keywords"})]})}),e.jsx(Ee,{delayDuration:150,children:e.jsxs(_e,{children:[e.jsx(Ae,{asChild:!0,children:e.jsx(K,{variant:"ghost",size:"icon",className:"h-7 w-7",onClick:()=>qr("keywords"),children:e.jsx(At,{className:"h-3 w-3"})})}),e.jsx(Te,{side:"bottom",className:"text-xs",children:"Clear keywords"})]})})]})})]}),e.jsxs("div",{className:mt("mt-2 p-3 bg-[var(--cs-bg-elevated)] rounded border min-h-[80px] relative",Xs.keywords&&"ring-2 ring-emerald-500 border-emerald-400 shadow-sm"),children:[Xs.keywords&&e.jsx("span",{className:"absolute right-2 top-2 rounded-md bg-emerald-100/90 text-emerald-700 text-xs px-2 py-0.5 shadow",children:"Applied"}),Jt==="keywords"?e.jsx(as,{autoFocus:!0,value:Tr,onChange:f=>Zt(f.target.value),onKeyDown:f=>{f.key==="Escape"&&or(),f.key==="Enter"&&(f.metaKey||f.ctrlKey)&&nr()},className:"min-h-[120px] text-sm bg-transparent border-0 p-0 focus-visible:ring-0 resize-none",placeholder:"Enter keywords separated by commas..."}):e.jsxs(e.Fragment,{children:[e.jsx("div",{className:"flex flex-wrap gap-2",children:h.map((f,T)=>{const B=f.toLowerCase(),P=Zi.get(B),G={hcv:P?.hcv,searchVolume:P?.searchVolume,trendScore:P?.trendScore},se=To(G),le=dc(G),be=le.verdict??se,Ke=be?pm[be]:"border-[var(--cs-border)] bg-[var(--cs-bg-card)] text-[var(--cs-text-primary)]",$e=ro.has(B);return e.jsx(Ee,{delayDuration:150,children:e.jsxs(_e,{children:[e.jsx(Ae,{asChild:!0,children:e.jsxs("span",{draggable:!0,onDragStart:Z=>{yu(g,T),Z.dataTransfer.setData("text/plain",f),Z.currentTarget.classList.add("cs-dragging")},onDragOver:Z=>{xu(Z),Z.currentTarget.classList.add("cs-drag-over")},onDragLeave:Z=>{Z.currentTarget.classList.remove("cs-drag-over")},onDrop:Z=>{Z.currentTarget.classList.remove("cs-drag-over"),bu(Z,g,T)},onDragEnd:Z=>{Z.currentTarget.classList.remove("cs-dragging")},className:mt("cs-keyword-chip flex items-center gap-1 rounded-full px-2 py-1 text-xs font-medium shadow-sm border",Ke,$e&&"ring-2 ring-emerald-400 border-emerald-300 bg-emerald-50/80 text-emerald-900",!P&&"border-[var(--cs-border)] bg-[var(--cs-bg-card)]"),children:[f,e.jsx("button",{type:"button","aria-label":`Remove ${f}`,className:"ml-1 rounded-full hover:bg-[var(--cs-bg-hover)]",onClick:()=>
11{if(!g)return;const Z=b.find(Ve=>Ve.id===g);if(!Z)return;Qt(Z.id,wt(Z));const Oe=(Array.isArray(Z.baseKeywords)&&Z.baseKeywords.length>0?Z.baseKeywords:Array.isArray(Z.keywords)?Z.keywords:[]).filter(Ve=>Ve!==f);ut(Z,{baseKeywords:Oe})},children:e.jsx(At,{className:"h-3 w-3"})})]})}),e.jsxs(Te,{side:"bottom",className:"text-xs space-y-1",children:[e.jsx("div",{className:"font-semibold text-[var(--cs-text-primary)] text-[11px] tracking-wide",children:td[le.verdict]}),le.lines.map(Z=>e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx("span",{className:"inline-flex h-2 w-2 rounded-full",style:{backgroundColor:sd[Z.level]}}),e.jsxs("span",{className:"text-[var(--cs-text-primary)]",children:[e.jsxs("span",{className:"font-medium",children:[Z.label,":"]})," ",Z.value]})]},`${f}-${Z.key}`))]})]})},`${f}-${T}`)})}),e.jsx("div",{className:"mt-3 flex items-center gap-2",children:e.jsx($t,{"data-onboarding":"review-add-keyword",placeholder:"Add keyword or phrase",className:"h-8 w-48",onKeyDown:f=>{const T=f.target;if(f.key==="Enter"&&T.value.trim()&&g){const B=T.value.trim(),P=b.find(le=>le.id===g);if(!P)return;Qt(P.id,wt(P));const G=Array.isArray(P.baseKeywords)&&P.baseKeywords.length>0?P.baseKeywords:Array.isArray(P.keywords)?P.keywords:[],se=Array.from(new Set([...G,B]));ut(P,{baseKeywords:se}),T.value=""}}})})]})]})]})]})]})};d.useEffect(()=>{(async()=>{if(!c?.id)return;const{profile:t}=await Tt.getUserProfile(c.id),a=t?.credits??null,n=ic(a);n!==null&&R(n)})()},[c?.id,R]);const xo=Ut.total>0?Math.round(Ut.completed/Ut.total*100):0,aa=b.length>0&&b.every(t=>t.isSelected),Xl=t=>$d.includes(t),oa=t=>Od===t,Ur=async(t,a)=>{try{await navigator.clipboard.writeText(t),r({title:"Copied",description:`${a} copied to clipboard`})}catch{r({title:"Copy failed",description:`Could not copy ${a}`,variant:"destructive"})}},ar=t=>{const a=b.find(m=>m.id===g);if(!a)return;const n=Rt(a),o=n?.keywords??(Array.isArray(a.keywords)?a.keywords:[]),u=t==="title"?n?.title??a.title??"":t==="description"?n?.description??a.description??"":o.join($r);Ur(u,t.charAt(0).toUpperCase()+t.slice(1))},Jl=d.useCallback(t=>{const a=b.find(o=>o.id===g);if(!a)return;const n=Rt(a);if(t==="keywords"){const o=n?.keywords??(Array.isArray(a.keywords)?a.keywords:[]);Zt(o.join(", "))}else Zt(t==="title"?n?.title??a.title??"":n?.description??a.description??"");Hs(t)},[b,g,Rt]),or=d.useCallback(()=>{Hs(null),Zt("")},[]),nr=d.useCallback(()=>{if(!Jt||!g)return;const t=b.find(I=>I.id===g);if(!t)return;Qt(g,wt(t));const a=Jt,n=Tr,o={};a==="keywords"?o.baseKeywords=n.split(",").map(I=>I.trim()).filter(Boolean):a==="title"?o.baseTitle=n:o.baseDescription=n;const u=ut(t,o)??kt({...t,baseTitle:o.baseTitle??t.baseTitle??t.title??"",baseDescription:o.baseDescription??t.baseDescription??t.description??"",baseKeywords:o.baseKeywords??(Array.isArray(t.baseKeywords)?t.baseKeywords:Array.isArray(t.keywords)?t.keywords:[]),categories:t.categories??""}),m=u?.title??o.baseTitle??t.title??"",h=u?.description??o.baseDescription??t.description??"",y=Array.isArray(u?.keywords)?u.keywords:o.baseKeywords??(Array.isArray(t.keywords)?t.keywords:[]),w=u?.category??t.categories??"",v=m.trim().length>0||h.trim().length>0||y.length>0;t.suppressMetadata&&v&&Q(g,{suppressMetadata:!1}),we.updateSessionImage(g,{title:m,description:h,keywords:y.join(", "),categories:w||null,baseTitle:o.baseTitle??t.baseTitle??t.title??"",baseDescription:o.baseDescription??t.baseDescription??t.description??"",baseKeywords:o.baseKeywords??(Array.isArray(t.baseKeywords)?t.baseKeywords:Array.isArray(t.keywords)?t.keywords:[])}).catch(()=>{});const A=a.charAt(0).toUpperCase()+a.slice(1);r({title:`${A} saved`}),Hs(null),Zt("")},[Jt,Tr,g,b,Qt,wt,ut,kt,Q,r]),qr=d.useCallback(t=>{if(Ye){if(!g)return;const m=b.find(v=>v.id===g);if(!m)return;Qt(g,wt(m));const y={...Le&&Oi===g?Le:wr(m)};t==="title"?y.title="":t==="description"?y.description="":y.keywords=[];const w=ls(y);Q(g,{title:t==="title"?"":m.title??"",description:t==="description"?"":m.description??"",keywords:t==="keywords"?[]:Array.isArray(m.keywords)?m.keywords:[],baseTitle:t==="title"?"":m.baseTitle??m.title??"",baseDescription:t==="description"?"":m.baseDescription??m.description??"",baseKeywords:t==="keywords"?[]:Array.isArray(m.baseKeywords)?m.baseKeywords:[]}),we.updateSessionImage(g,{title:t==="title"?"":m.title??null,description:t==="description"?"":m.description??"",keywords:t==="keywords"?"":Array.isArray(m.keywords)?m.keywords.join(", "):String(m?.keywords||""),baseTitle:t==="title"?"":m.baseTitle??m.title??"",baseDescription:t==="description"?"":m.baseDescription??m.description??"",baseKeywords:t==="keywords"?[]:Array.isArray(m.baseKeywords)?m.baseKeywords:[]}).catch(()=>{}),nt(w),Ns(g),vt(!1),dt(v=>({...v,[t]:!0})),es("");return}const a=b.find(m=>m.id===g);if(!a)return;
11Qt(a.id,wt(a));const n={};t==="title"?n.baseTitle="":t==="description"?n.baseDescription="":t==="keywords"&&(n.baseKeywords=[]),ut(a,n);const o=t.charAt(0).toUpperCase()+t.slice(1);r({title:`${o} cleared`}),Se&&Se.id===a.id&&(t==="title"?lt({...Se,title:""}):t==="description"?lt({...Se,description:""}):t==="keywords"&&lt({...Se,keywords:[]}));const u={};u.sellingScore=null,u.sellingScorePercent=null,t==="title"?(u.titleScore=null,u.titleScorePercent=null):t==="description"?(u.descriptionScore=null,u.descriptionScorePercent=null):t==="keywords"&&(u.keywordScore=null,u.keywordScorePercent=null),Object.keys(u).length>0&&Q(a.id,u)},[ut,Le,Oi,b,Se,Ye,g,lt,nt,Ns,vt,dt,es,ye,Q]),Zl=d.useMemo(()=>!!(p&&p.role==="admin"),[p]),na=d.useMemo(()=>{if(!Zl||!E||!c?.id)return!1;const t=E.user_id;return t&&t!==c.id},[Zl,E,c?.id]),la=d.useMemo(()=>E?hc(E,s):null,[E,s]),bo=d.useMemo(()=>Ih(la,E?.prompt_template??null),[E,la]),ca=d.useMemo(()=>{const t=String(la?.customPrompt??"").trim();return t||String(E?.prompt_template??"").trim()},[la,E]),gu=d.useMemo(()=>bo.filter(t=>t.important).slice(0,4),[bo]),fu=na?e.jsxs(bp,{className:"mb-4 rounded-lg border border-amber-400 bg-amber-50 px-4 py-3 text-xs",children:[e.jsxs("div",{className:"flex items-start justify-between gap-3",children:[e.jsxs("div",{className:"space-y-1",children:[e.jsx("div",{className:"font-semibold text-amber-900",children:"Admin view (read-only): you are inspecting another user's session — auto-save and Regenerate are disabled"}),e.jsxs("div",{className:"flex flex-wrap gap-3 text-amber-900/90",children:[e.jsx("span",{className:"font-mono break-all",children:qs?.email||qs?.id||"Unknown user"}),e.jsxs("span",{children:["Credits:"," ",(()=>{const t=ic(qs?.credits);return t!==null?t.toLocaleString():"—"})()]}),e.jsxs("span",{children:["Plan:"," ",qs?.plan_name||qs?.plan_tier||qs?.tier||"—"]}),gu.map(t=>e.jsxs("span",{children:[t.label,": ",e.jsx("span",{className:"font-medium",children:t.value})]},`${t.label}:${t.value}`))]})]}),e.jsxs("div",{className:"flex shrink-0 flex-col items-end gap-1 text-[10px] text-amber-900/80",children:[e.jsxs("div",{children:["Session ID: ",e.jsx("span",{className:"font-mono",children:E?.id||s})]}),e.jsxs(wp,{className:"inline-flex items-center gap-1 rounded border border-amber-500/40 px-2 py-1 font-medium text-amber-900 hover:bg-amber-100",children:["Session settings",e.jsx(ac,{className:"h-3 w-3"})]})]})]}),e.jsx(vp,{children:e.jsx("div",{className:"mt-3 grid gap-2 rounded-md border border-amber-300/70 bg-white/70 p-3 text-amber-950 sm:grid-cols-2 lg:grid-cols-4",children:bo.map(t=>e.jsxs("div",{className:"min-w-0",children:[e.jsx("div",{className:"text-[10px] uppercase tracking-wide text-amber-900/60",children:t.label}),e.jsx("div",{className:mt("break-words font-medium",t.important?"text-amber-950":"text-amber-900/85"),children:t.value})]},`${t.label}:${t.value}`))})})]}):null,yu=d.useCallback((t,a)=>{Qa.current={imageId:t,index:a}},[]),xu=d.useCallback(t=>{t.preventDefault()},[]),bu=d.useCallback((t,a,n)=>{t.preventDefault();const o=Qa.current;if(Qa.current=null,!o||o.imageId!==a||o.index===n)return;if(Ye&&a===g){Pl(w=>{const v=[...w.keywords];if(v.length===0)return w;const[A]=v.splice(o.index,1);return v.splice(n,0,A),{...w,keywords:v}},"keywords");return}const u=b.find(w=>w.id===a);if(!u)return;const m=_h(u);if(m.length===0)return;const h=[...m],[y]=h.splice(o.index,1);h.splice(n,0,y),ut(u,{baseKeywords:h}),Se&&Se.id===a&&lt({...Se,keywords:h})},[ut,b,Se,Ye,Pl,g,lt]),wo=t=>{if(it(t),lt(null),Hs(null),Zt(""),!Gt.current&&(jn.current+=1,jn.current>=2)){Gt.current=!0;const a=ve[0];a&&U(a.id)}},Ct=d.useCallback(async(t,a,n)=>{const o=b.find(v=>v.id===t);if(!o)return;const u=o.meta_json??{},h={...u.editorial??u.editorial_meta??{}};typeof a.editorial=="boolean"&&(h.enabled=a.editorial,h.is_editorial=a.editorial),typeof a.editorialCity<"u"&&(h.city=a.editorialCity??""),typeof a.editorialLocation<"u"&&(h.location=a.editorialLocation??""),typeof a.editorialCountry<"u"&&(h.country=a.editorialCountry??""),typeof a.editorialDate<"u"&&(h.date=a.editorialDate??""),typeof a.editorialCaption<"u"&&(h.caption=a.editorialCaption??"",typeof a.captionClearedByUser=="boolean"&&(h.caption_cleared=a.captionClearedByUser)),typeof a.editorialCategory<"u"&&(h.category=a.editorialCategory??"");const y=!!(typeof a.editorial=="boolean"?a.editorial:h.enabled??h.is_editorial??o.editorial??!1),w={...u,editorial:h};Q(t,{editorial:y,editorialCity:(h.city??o.editorialCity??null)||null,editorialLocation:(h.location??o.editorialLocation??null)||null,editorialCountry:(h.country??o.editorialCountry??null)||null,editorialDate:(h.date??o.editorialDate??null)||null,editorialCaption:(h.caption??o.editorialCaption??null)||null,editorialCaptionCleared:h.caption_cleared===!0,editorialCategory:(h.category??o.editorialCategory??null)||null,meta_json:w});try{await we.updateSessionImage(t,{meta_json:w})}catch(v){console.warn("[ReviewEdit] Failed to persist editorial metadata",v),n?.silent||r({title:"Editorial save failed",description:"We could not persist editorial metadata for this image.",variant:"destructive"})}},[b,Q,r]);d.useEffect(()=>{const t=N;if(!t||!Lt||!t.editorial)return;
11const a=typeof t.editorialLocation=="string"&&t.editorialLocation.trim().length>0,n=typeof t.editorialCountry=="string"&&t.editorialCountry.trim().length>0,o=typeof t.editorialDate=="string"&&t.editorialDate.trim().length>0;if(a||n||o)return;let u=!1;return(async()=>{try{const m=await Ar(t);if(!m||u)return;const y=[m.city,m.state,m.country].filter(A=>A&&String(A).trim().length>0).join(", ")||t.editorialLocation||null,w=(m.country??"").trim()||t.editorialCountry||null,v=m.date||t.editorialDate||null;if(!y&&!w&&!v)return;await Ct(t.id,{editorialLocation:y,editorialCountry:w,editorialDate:v},{silent:!0})}catch(m){console.warn("[ReviewEdit] Failed to backfill editorial metadata for selected image",t.id,m)}})(),()=>{u=!0}},[N,Lt,Ar,Ct]),d.useEffect(()=>{if(!Xt||!Lt||sl.current||!b||b.length===0)return;console.debug("[ReviewEdit] Editorial session auto-init starting",{sessionEditorialEnabled:Xt,editorialSupportedForPlatform:Lt,imageCount:b.length}),sl.current=!0,(async()=>{for(const a of b){if(!a||a.editorial)continue;const n=xs(a);let o=a.editorialLocation??n.location??"",u=a.editorialCountry??n.country??"",m=a.editorialDate??n.date??"",h=null;if(!o&&!u&&!m)try{const oe=await Ar(a);if(oe){const ue=[oe.city,oe.state,oe.country].filter(C=>C&&String(C).trim().length>0).join(", ");!o&&ue&&(o=ue),!u&&oe.country&&(u=String(oe.country).trim()),!m&&oe.date&&(m=oe.date);const de=(oe.caption||oe.description||"").trim();de&&(h=de)}}catch(oe){console.warn("[ReviewEdit] Failed to auto-extract editorial metadata for image",a.id,oe)}const y=Kt(m)??m,w=(a.title??"").trim(),v=(a.editorialCaption??"").trim(),A=(a.description??a.baseDescription??"").trim(),I=v.toLowerCase(),M=v&&v===A,q=I.includes("this image can be used")||I.includes("this image is suitable"),te=!v||M||q,me=(te?"":v)||h||A||w||"",pe=Ls(String(a.editorialCity??"").trim(),u),ce=te?Fs(pe,y,me,ct):v;await Ct(a.id,{editorial:!0,editorialLocation:o||null,editorialCountry:u||null,editorialDate:y||null,editorialCaption:ce||null},{silent:!0})}})().catch(a=>{console.warn("[ReviewEdit] Failed to initialize editorial metadata for session",a)})},[Xt,Lt,b,Ct,Ar]);const wu=()=>{if(!N)return;const t=Rt(N);lt({...N,title:t?.title??N.title??"",description:t?.description??N.description??"",keywords:t?.keywords??(Array.isArray(N.keywords)?N.keywords:[]),categories:t?.category??N.categories??""})},vu=async()=>{if(!Se||!g)return;const t=b.find(a=>a.id===g);if(t){Qt(g,wt(t));try{vi(!0);const a={baseTitle:Se.title,baseDescription:Se.description,baseKeywords:Array.isArray(Se.keywords)?Se.keywords:[],categories:Se.categories||""},n=ut(t,a)??kt({...t,baseTitle:a.baseTitle,baseDescription:a.baseDescription,baseKeywords:a.baseKeywords,categories:a.categories}),o=n?.title??a.baseTitle??"",u=n?.description??a.baseDescription??"",m=n?.keywords??a.baseKeywords??[],h=n?.category??a.categories??"",y={...t.meta_json??{},baseTitle:a.baseTitle,baseDescription:a.baseDescription,baseKeywords:a.baseKeywords};await we.updateSessionImage(g,{title:o,description:u,keywords:m.join(", "),categories:h||null,meta_json:y}),Q(g,{title:o,description:u,keywords:m,categories:h,baseTitle:a.baseTitle,baseDescription:a.baseDescription,baseKeywords:a.baseKeywords}),lt(null),r({title:"Saved",description:"Metadata updated successfully"})}catch{r({title:"Save Error",description:"Failed to save changes",variant:"destructive"})}finally{vi(!1)}}},ku=async()=>{if(za(!1),!!On){try{typeof window<"u"&&window.localStorage.setItem("has_seen_originals_ttl_info","1")}catch{}if(c?.id)try{const{error:t}=await Do.from("profiles").update({has_seen_originals_ttl_info:!0}).eq("id",c.id);t&&console.warn("[ReviewEdit] Failed to update has_seen_originals_ttl_info",t)}catch(t){console.warn("[ReviewEdit] Exception while updating has_seen_originals_ttl_info",t)}}},Cu=()=>{lt(null)},Su=d.useCallback(async(t,a)=>{const n=a==="__EMPTY__"?"":ys(W,a)||a.trim(),o=b.find(m=>m.id===t);o&&Qt(t,wt(o)),Q(t,{categories:n}),Se&&Se.id===t&&lt({...Se,categories:n});const u=Zo(n);u?(_r.current[t]=u,ie(t,u),Yt(m=>{const h={...m},y={...h[W]||{}};y[t]=n,h[W]=y;const w="Adobe Stock";if(W!==w){const v={...h[w]||{}},A=_s(w,u);A&&(v[t]=A,h[w]=v)}return h})):(delete _r.current[t],ie(t,null),Yt(m=>{const h={...m},y={...h[W]||{}};delete y[t],Object.keys(y).length>0?h[W]=y:delete h[W];const w="Adobe Stock";if(W!==w){const v={...h[w]||{}};delete v[t],Object.keys(v).length>0?h[w]=v:delete h[w]}return h}));try{const{success:m,error:h}=await we.updateSessionImage(t,{categories:n||null});if(!m||h)throw h||new Error("Failed to update category")}catch(m){console.error("Category update error",m),r({title:"Category update failed",description:"Could not update category.",variant:"destructive"})}},[r,Q,Se,W,_s,ie,Yt]),vo=d.useMemo(()=>
11{if(ke===0)return{perImage:0,total:0};if(fe.includes("keywords")||fe.includes("all"),fe.includes("all"))return{perImage:4,total:4*ke};const t=fe.includes("all")||fe.includes("title")||fe.includes("description"),a=fe.includes("all")||fe.includes("keywords");let n=0;if(t){const o=fe.includes("all")||fe.includes("title"),u=fe.includes("all")||fe.includes("description");n+=(o?qi:0)+(u?Vi:0)}return a&&(n+=Wi),{perImage:n,total:n*ke}},[fe,ke]),ko=vo.total>0&&ae<vo.total,ju=d.useMemo(()=>ms.length===0?[]:ms.slice(0,3).map(t=>t.filename||t.id),[ms]);Math.max(0,ke-ju.length);const Nu=Rr.total>0?Math.round(Rr.processed/Rr.total*100):0,Eu=ke===0||ko||ps||fe.length===0,_u=Th(fe),Au=d.useMemo(()=>fe.length===1&&fe[0]==="keywords"?"Boost All Selected":"Intelligent Rewrite Selected",[fe]),da=d.useCallback(t=>{su(t),t||(no(!1),Mr({processed:0,total:0}),lo(null),vl(ba))},[]),Tu=d.useCallback(async()=>{if(!(ke===0||ko||ps||fe.length===0))try{lo(null),no(!0),Mr({processed:0,total:ke});const t=fe.includes("title")||fe.includes("description")||fe.includes("all"),a=fe.includes("keywords")||fe.includes("all"),n=ms.map(A=>A.id);let o=0,u=0,m=0,h=0;if(t){const A=fe.includes("all")?void 0:fe.filter(M=>M==="title"||M==="description").filter((M,q,te)=>te.indexOf(M)===q),I=await ir(n,"rewrite",{fields:A});o=I?.processed??(I?ke:0),u=I?.failed?.length??0}if(a){const A=await ir(n,"boost");m=A?.processed??(A?ke:0),h=A?.failed?.length??0}Mr({processed:ke,total:ke});const y=Math.max(o,m),w=u+h;lo({processed:y,failed:w,total:ke});const v=w>0?`${y} processed, ${w} failed`:`${y} processed successfully`;if(r({title:"Batch complete",description:v}),g&&ms.some(A=>A.id===g)){const A=I=>{Ir(M=>({...M,[I]:!0})),setTimeout(()=>Ir(M=>({...M,[I]:!1})),2200)};(fe.includes("all")||fe.includes("title"))&&A("title"),(fe.includes("all")||fe.includes("description"))&&A("description"),(fe.includes("all")||fe.includes("keywords"))&&A("keywords")}setTimeout(()=>da(!1),800)}finally{no(!1)}},[ke,ko,ps,ir,ms,fe,r,g,da,Ir]),Du=async()=>{if(!c)return;if(na){r({title:"Read-only admin view",description:"Regenerate is disabled while inspecting another user's session.",variant:"destructive"});return}if(s)try{await rd(s,E)}catch(m){console.warn("[ReviewEdit] Failed to persist session settings before regenerate",m)}const t=(()=>{const m=Be().map(h=>h.id);return m.length>0?m:g?[g]:[]})();for(const m of t){const h=b.find(y=>y.id===m);h&&Qt(m,wt(h))}const a=async m=>{const h=await fetch(m);if(!h.ok)throw new Error(`Failed to fetch asset: ${h.status} ${h.statusText}`);const y=await h.blob(),w=y.type||"image/webp";return{base64:await new Promise(A=>{const I=new FileReader;I.onloadend=()=>A(String(I.result).split(",")[1]||""),I.readAsDataURL(y)}),mime:w}},n=Be().map(m=>m.id),o=n.length>0?n:g?[g]:[];if(o.length===0)return;Kd(o),Xa(o),Ja(o[0]??null),Qn(""),Ha(!0);const u=async m=>{try{Ws(!0);const h={completed:0,total:m.length};Mi.current=h,Ga(h);const y=D&&z==="unlimited",w=[],v=[],A=[];for(const I of m){Ja(I);const M=b.find(oe=>oe.id===I);if(!M)continue;const q=E?.id??s,te=sn(M),me=await rn(te,q),pe=Na(te,q),ce=await an({sourceInput:te,sourceUrl:me,fallbackSessionId:q,stableSourcePath:pe});if(!ce){console.warn("[ReviewEdit] Could not resolve asset URL for regenerate:",I,te),v.push(I);continue}try{const oe=on(ce,pe),ue=M?.mimeType||M?.mime_type||tn(M?.filename),de=Oo({filename:M?.filename??null,mimeType:ue,mediaType:M?.mediaType??M?.media_type??null,title:M?.title??null,keywords:M?.keywords??null},Ps.getState().customPrompt,el.current),C=ln(M,ue),Y=Ps.getState(),F=Sa(Y.availablePlatforms,Y.selectedPlatform,W),X=(Y.generalSettings?.outputLanguage||"en").trim()||"en",f=!!F?.singleWordOnly,T=f||Y.keywordSettings?.singleWordMode===!0,B=!f&&T&&Y.keywordSettings?.allowCompoundKeywords===!0,P=T?"single":"long-tail",G=Y.titleSettings?.enabled===!0,se=G&&Y.titleSettings?.titleCase===!0,le=G&&Y.titleSettings?.allCaps===!0,be=F?.titleLimit??200,Ke=cn(be,G,Y.titleSettings?.maxTitleChars),{minDescriptionChars:$e,maxDescriptionChars:Z}=mn(F?.descriptionLimit,G,Y.titleSettings?.maxDescriptionChars,Y.titleSettings?.minDescriptionChars),{minTitleKeywords:tt,maxTitleKeywords:Oe}=pn(G,Y.titleSettings?.minTitleKeywords,Y.titleSettings?.maxTitleKeywords),Ve=G?Math.min(Ke,Math.max(1,Y.titleSettings?.minTitleChars??140)):Math.min(140,Ke),We=M?.mediaType==="video"||/^video\//i.test(String(ue??""))||/\.(mp4|mov|m4v|avi|webm|mkv)(\?|$)/i.test(String(M.filename||"")),St=dn(G,Y.titleSettings?.maxTitleChars),Mt=un(G,Y.titleSettings?.minTitleChars,St,We),Je=!!M?.editorial||Xt&&Lt,Ze=gn(M,Je),ft=F?.keywordsLimit??50,jt=Math.min(ft,Math.max(1,Y.keywordSettings?.minKeywordCount||ft)),Nt={aiOperation:"regenerate",outputLanguage:X,locale:X,keywordMode:P,singleWordOnly:f,allowCompoundKeywords:B,keywordCount:jt,keywordsLimit:ft,titleCase:se,titleAllCaps:le,titleMinChars:Ve,titleMaxChars:Ke,titleSettingsEnabled:G,aiTitleMinChars:Mt,aiTitleMaxChars:St,editorialEnabled:Je,...Ze?{editorialSeed:Ze}:{},editorialPlatformLabel:F?.label??W??null,descriptionLimit:F?.descriptionLimit,maxDescriptionChars:Z,minDescriptionChars:$e,minTitleKeywords:tt,maxTitleKeywords:Oe,requiredStartingKeywords:Y.keywordSettings?.requiredStartingKeywords??"",requiredEndingKeywords:Y.keywordSettings?.requiredEndingKeywords??"",excludedKeywords:Y.keywordSettings?.excludedKeywords??"",prohibitedCharacters:Y.generalSettings?.prohibitedCharacters??"",optionalTitleElements:Y.titleSettings?.optionalElements??"",useFilenameForContext:Y.generalSettings?.useFilenameForContext===!0,useMetadataForContext:Y.generalSettings?.useMetadataForContext===!0,retryForId:I,...C?{mediaType:C}:{},hasTransparency:nn(M),analytics:!1};let As=null;try{As=await xp({sourceUrl:ce,filename:M.filename,mimeType:ue,mediaType:C})}catch(Fe){console.error("[ReviewEdit] regenerate input preparation failed",{id:I,filename:M.filename,mediaType:C,error:Fe}),v.push(I);continue}const Qe=`${I}
11::regenerate::${Date.now()}`,So=y?S+(Mi.current.completed??0)+1:void 0,Wr=await(oe?Tt.processAssetByUrl({signedUrl:ce,originalStoragePath:pe||"",mimeType:ue,filename:M.filename||`rewrite-${Date.now()}`,sessionId:q,sessionImageId:I,generationMode:y?"unlimited":"credits",runId:Qe,promptRequest:de,...As?{images:As}:{},extra:Nt}):a(ce).then(({base64:Fe,mime:Et})=>Tt.processImage(Fe,de,c.id,Et,{generationMode:y?"unlimited":"credits",usageCount:So,sessionId:q,filename:M.filename||`rewrite-${Date.now()}`,runId:Qe,extra:Nt}))),{metadata:Ts,error:Hr,aiError:Gr}=Wr??{};if(Hr||!Ts){const Fe=String(Gr||Hr?.message||"unknown_error");console.error("[ReviewEdit] regenerate failed for asset",{id:I,filename:M.filename,mediaType:C,aiError:Gr??null,error:Hr?.message??null}),v.push(I),A.includes(Fe)||A.push(Fe);continue}const Yr=hn(Ts)??{title:"",description:"",keywords:[]},Ds=Yr.title,Is=Yr.description,gs=ci(Yr.keywords);let Xr=M.categories||"";ks&&ia&&(Xr=Cr(gs,Ds,Is,M.categories));const Rs=ys(W,Xr)||Xr||"",Pt={baseTitle:Ds,baseDescription:Is,baseKeywords:gs,categories:Rs},Ms=ut(M,Pt)??kt({...M,baseTitle:Pt.baseTitle,baseDescription:Pt.baseDescription,baseKeywords:Pt.baseKeywords,categories:Pt.categories}),lr=Ms?.title??Ds,cr=Ms?.description??Is,dr=Ms?.keywords??gs,ur=Ms?.category??Rs,mr={title:lr,description:cr,keywords:dr,locale:"en",category:"general"},ss=await ha.evaluateAsset(mr,{refreshTrends:!0}),He=Io(mr,ss.keywordAnalyses??[]),rs={title:lr,keywords:dr.join(", "),description:cr,categories:ur||null,baseTitle:Ds,baseDescription:Is,baseKeywords:gs,analytics_unlocked:!0,score_payload:{sellingScorePercent:He.sellingScorePercent,titleScorePercent:He.titleScorePercent,descriptionScorePercent:He.descriptionScorePercent,keywordScorePercent:He.keywordScorePercent,strengths:He.strengths,hcv:He.hcv,keywordAnalyses:ss.keywordAnalyses},selling_score:He.sellingScorePercent,title_score:He.titleScorePercent,description_score:He.descriptionScorePercent,keyword_score:He.keywordScorePercent};if(W==="Blackbox"){const Fe=wr(M),Et=jr(ur??""),Bs=Et||Fe.category||"",rt=ls({...Fe,title:lr,description:cr,keywords:dr,category:Bs}),pr={category:rt.category,batchName:rt.batchName,editorial:rt.editorial,editorialText:rt.editorialText,editorialCity:rt.editorialCity,editorialState:rt.editorialState,editorialCountry:rt.editorialCountry,editorialDate:rt.editorialDate,shootingCountry:rt.shootingCountry,shootingDate:rt.shootingDate,sourceContext:rt.sourceContext??null};ye(I,"blackbox",pr),rs.platform_metadata={...M.platformMetadata??{},blackbox:pr},I===g&&(nt(rt),Ns(I),vt(!1),dt({}),es("")),rs.categories=Et||(Fe.category?Fe.category:null)}if(await we.updateSessionImage(I,rs),xe(I,{sellingScorePercent:He.sellingScorePercent,titleScorePercent:He.titleScorePercent,descriptionScorePercent:He.descriptionScorePercent,keywordScorePercent:He.keywordScorePercent,strengths:He.strengths,hcv:He.hcv,keywordAnalyses:ss.keywordAnalyses??null}),y)L(1);else{const Fe=typeof Wr?.creditsLeft=="number"?Wr.creditsLeft:null;typeof Fe=="number"&&R(Fe)}Ga(Fe=>{const Et={...Fe,completed:Math.min(Fe.total,Fe.completed+1)};return Mi.current=Et,Et}),Xa(Fe=>Fe.filter(Et=>Et!==I)),w.push(I)}catch(oe){console.error("[ReviewEdit] Regenerate failed for",I,oe),v.push(I)}}if(w.length>0){const I=v.length>0?`Metadata regenerated for ${w.length} file(s). ${v.length} failed`:`Metadata regenerated for ${w.length} file(s)`;r({title:"Regenerated",description:I})}else{const I=v.length||m.length,M=Array.from(new Set(A.map(te=>hm(te)))),q=M.length===1?` ${M[0]}`:"";r({title:"Regenerate failed",description:I===1?`Could not regenerate this file.${q}`:`Could not regenerate ${I} file(s).${q}`,variant:"destructive"})}}catch(h){console.error("Regenerate error",h),String(h?.message||h).toLowerCase().includes("insufficient")?r({title:"Insufficient credits",description:"We could not deduct credits for this regeneration.",variant:"destructive"}):r({title:"Regenerate Error",description:"Failed to regenerate metadata",variant:"destructive"})}finally{Ws(!1),Ha(!1);const h={completed:0,total:0};Mi.current=h,Ga(h),Xa([]),Ja(null)}};window._runRegen=()=>u(o)},Co=async(t,a="csv")=>{const n=Be();if(n.length===0){r({title:"No Selection",description:"Please select images to export",variant:"destructive"});return}const o=qe?.editorial_style,u=o?ya[o]:null;if(!!qe?.supports_editorial&&u&&n.filter(X=>{if(!X.editorial)return!1;const f=xs(X),T=X.editorialLocation??f.location??"",B=X.editorialCountry??f.country??"",P=X.editorialDate??f.date??"",G=Kt(P),se=String(X.editorialCaption??"").trim()||String(X.baseDescription??X.description??X.baseTitle??X.title??"").trim(),le=u.requiredFields.includes("location"),be=u.requiredFields.includes("country"),Ke=u.requiredFields.includes("date"),$e=u.requiredFields.includes("caption"),Z=le&&!T.trim(),tt=be&&!B.trim(),Oe=Ke&&(!P||!G),Ve=$e&&!String(se||"").trim();return Z||tt||Oe||Ve}).length>0){const X=u.requiredFields.filter(f=>f!=="category").map(f=>{switch(f){case"location":return"Location";case"country":return"Country";case"date":return"Date";case"caption":return"Caption";default:return f}}).join(", ");r({title:"Editorial metadata incomplete",description:`Some editorial images are missing required fields (${X}). Please fill them before exporting for ${W}.`,variant:"destructive"});return}ds(!0);const h=st==="istock"||st==="getty"?"getty":st==="adobe"||st==="shutterstock"||st==="pond5"?st:null,y=n.map(F=>{const X=Rt(F),f=String(X?.title??F.title??"").trim(),T=String(X?.description??F.description??"").trim(),B=Array.isArray(X?.keywords)?X.keywords:Array.isArray(F.keywords)?F.keywords:[],P=X?.category??(F.categories||""),G=xs(F),se=String(F.editorialCaption??"").trim(),le=Ls(String(F.editorialCity??"").trim(),F.editorialCountry??G.country),be=Kt(F.editorialDate??G.date),Ke=String(qe?.editorial_style||"").trim()||ct,$e=F.editorial?Fs(le,be,T,Ke):"",Z=F.editorial&&Or(F)&&(!se||se===f.trim()),tt=F.editorial?Z?$e:xa(se,Ke):void 0,Oe=W==="Shutterstock",Ve=W==="iStock"||W==="Getty Images";let We;(Oe||Ve)&&F.editorial?We=(tt??T)||f:Oe?We=f||T:We=T;const St=String(F.originalFilename||F.filename||"").trim(),Ze=(Ie[F.id]||[]).map(Qe=>Qe.releaseId).map(Qe=>
11Dr.get(Qe)).filter(Boolean),ft=h?Ze.filter(Qe=>hi(Qe,h).status!=="unsupported_for_platform"):Ze,jt=ft.map(Qe=>Qe.display_name).filter(Boolean),Nt=ft.filter(Qe=>Qe.type!=="property").map(Qe=>Qe.display_name).filter(Boolean),As=ft.filter(Qe=>Qe.type==="property").map(Qe=>Qe.display_name).filter(Boolean);return{filename:St,title:f,keywords:B.join($r),description:We,categories:P,releases:jt.join($r),model_releases:Nt.join($r),property_releases:As.join($r),image_url:F.imageUrl,editorial:!!F.editorial,editorialCaption:tt,editorialLocation:F.editorialCity??G.city??F.editorialLocation??G.location??void 0,editorialCountry:F.editorialCountry??G.country??void 0,editorialDate:Kt(F.editorialDate??G.date)??void 0,editorialCategory:F.editorialCategory??(P||void 0)}}),w=y.map(F=>({...F,categories:Hc(W,F.categories)}));let v=t&&t.length>0?t:qe?.columns??["Filename","Title","Description","Keywords"];if(W==="iStock"||W==="Getty Images"){const F=P=>{if(P.mediaType==="video")return!0;const G=String(P.filename||"");return/\.(mp4|mov|avi|webm|mkv)(\?|$)/i.test(G)},X=n.some(F),f=n.some(P=>!F(P));if(X&&f){r({title:"Mixed media types",description:"For Getty/iStock please export images and videos in separate CSV files (one type at a time).",variant:"destructive"}),ds(!1);return}const T=n.some(P=>!!P.editorial),B=n.some(P=>!P.editorial);if(!X&&T&&B){r({title:"Mixed creative and editorial",description:"For Getty/iStock please export creative and editorial images in separate CSV files.",variant:"destructive"}),ds(!1);return}X?v=["file name","keywords","description","title","country","poster timecode"]:T?v=["file name","created date","description","country","title","personalities","keywords"]:v=["file name","created date","description","country","brief code","title","keywords","releases"]}W==="Adobe Stock"&&(v=v.filter(F=>F.toLowerCase()!=="description"));const I=W.replace(/\s+/g,"_"),M=E?.id?E.id.substring(0,8):`${n.length}`,q=new Date,te=q.getFullYear(),me=String(q.getMonth()+1).padStart(2,"0"),pe=String(q.getDate()).padStart(2,"0"),ce=`${I}_${M}_${te}${me}${pe}`,oe=W==="Adobe Stock",ue=W==="iStock"||W==="Getty Images"||W==="Pond5"||oe?!1:Ad,de=oe?`\r
12`:`
13`,C=(F,X)=>ii.exportToCSV(F,X,{delimiter:"	",quote:'"',bom:!1,lineEnding:`
14`},qe).replace(/^\ufeff/,"").split(`
15`).filter(B=>B.length>0).slice(1).map(B=>{const P=B.split("	");return X.reduce((G,se,le)=>(G[se]=P[le]??"",G),{})});if(W==="Blackbox"){try{const F=qe?.separator??", ",X=n.map(G=>{const se=wr(G);return{"File Name":G.filename,Description:se.description,Keywords:se.keywords.join(F),Category:se.category,"Batch name":se.batchName??"",Editorial:ap(se.editorial),"Editorial Text":se.editorial?se.editorialText??"":"","Editorial City":se.editorial?se.editorialCity??"":"","Editorial State":se.editorial?se.editorialState??"":"","Editorial Country":se.editorial?se.editorialCountry??"":"","Editorial Date":se.editorial?Sc(se.editorialDate):"",Title:se.title??"","Shooting Country":se.shootingCountry??"","Shooting Date":Sc(se.shootingDate)}}),f=await ii.exportToXLSX(X,v,{sheetName:"Blackbox"}),T=new Blob([f],{type:"application/vnd.openxmlformats-officedocument.spreadsheetml.sheet"}),B=URL.createObjectURL(T),P=document.createElement("a");P.href=B,P.download=`${ce}.xlsx`,P.click(),URL.revokeObjectURL(B),r({title:"Exported",description:`Exported ${n.length} images to Blackbox XLSX`})}catch(F){console.error("Blackbox export error",F),r({title:"Export Error",description:"Failed to generate Blackbox XLSX",variant:"destructive"})}finally{ds(!1)}return}if(a==="xlsx"){try{const F=C(w,v),X=await ii.exportToXLSX(F,v,{sheetName:W.slice(0,31)||"Export"}),f=new Blob([X],{type:"application/vnd.openxmlformats-officedocument.spreadsheetml.sheet"});fc(f,`${ce}.xlsx`),pa.getState().noteExport(),r({title:"Exported",description:`Exported ${n.length} images to Excel`})}catch(F){console.error("Excel export error",F),r({title:"Export Error",description:"Failed to generate Excel export",variant:"destructive"})}finally{ds(!1)}return}go?.outputLanguage?.trim();let Y=ii.exportToCSV(w,v,{delimiter:zn,quote:Un,bom:ue,lineEnding:de},qe);(W==="iStock"||W==="Getty Images")&&Y&&Y.charCodeAt(0)===65279&&(Y=Y.slice(1));
15{const F=new Blob([Y],{type:"text/csv;charset=utf-8;"}),X=URL.createObjectURL(F),f=document.createElement("a");f.href=X,f.download=`${ce}.csv`,f.click(),URL.revokeObjectURL(X),pa.getState().noteExport()}if(sa?.enabled){const F=Array.isArray(sa.targetLanguages)?sa.targetLanguages:[];for(const X of F)try{const f=[];for(const le of y){const{metadata:be,error:Ke}=await Tt.translateMetadata({title:le.title,keywords:le.keywords,description:le.description},X);!Ke&&be?f.push({...le,title:String(be.title||""),keywords:Array.isArray(be.keywords)?be.keywords.join(", "):String(be.keywords||""),description:String(be.description||""),language:X,translated:!0,original_texts:{title:le.title,keywords:le.keywords,description:le.description}}):f.push(le)}const T=f.map(le=>({...le,categories:Hc(W,le.categories)}));let B=ii.exportToCSV(T,v,{delimiter:zn,quote:Un,bom:ue,lineEnding:de},qe);(W==="iStock"||W==="Getty Images")&&B&&B.charCodeAt(0)===65279&&(B=B.slice(1));const P=new Blob([B],{type:"text/csv;charset=utf-8;"}),G=URL.createObjectURL(P),se=document.createElement("a");se.href=G,se.download=`metadata_${X}.csv`,se.click(),URL.revokeObjectURL(G)}catch(f){console.error("Translation export error:",f)}}ds(!1),r({title:"Exported",description:`Exported ${n.length} images${sa?.enabled?" with translations":""}`})},Ql=async()=>Co(),Iu=async()=>{if(!Vs){Zn("Excel export");return}return Co(void 0,"xlsx")},Ru=async()=>{const t=Be();if(t.length===0){r({title:"No Selection",description:"Please select images to export",variant:"destructive"});return}if(!Vs){Zn("Downloading files with embedded metadata");return}const a=E?.id||s;if(!a){r({title:"Session unavailable",description:"Could not verify original files for this session.",variant:"destructive"});return}ds(!0);try{const{data:n,error:o}=await Do.from("session_images").select("id,image_path,created_at,mime_type,filename,original_filename").in("id",t.map(C=>C.id));if(o)throw o;const u=n??[],m=new Map(u.map(C=>[String(C.id),C])),h=t.filter(C=>!String(m.get(C.id)?.image_path||"").trim());if(h.length>0){r({title:"Original files unavailable",description:`${h.length} selected file${h.length===1?"":"s"} no longer have originals stored. Originals are available for up to 24 hours after processing.`,variant:"destructive"});return}const y=Date.now(),w=t.filter(C=>{const Y=m.get(C.id)?.created_at,F=typeof Y=="string"?Date.parse(Y):Number.NaN;return Number.isFinite(F)&&y-F>1440*60*1e3});if(w.length>0){r({title:"Originals expired",description:`${w.length} selected original${w.length===1?" is":"s are"} older than 24 hours. Re-upload originals before downloading embedded metadata files.`,variant:"destructive"});return}const v=t.filter(C=>{const Y=m.get(C.id),F=String(Y?.original_filename||C.originalFilename||Y?.filename||C.filename||""),X=String(Y?.mime_type||"").toLowerCase();return!/\.(jpe?g|png)$/i.test(F)&&!X.includes("jpeg")&&!X.includes("png")});if(v.length>0){r({title:"Unsupported embedded download",description:`Embedded metadata download currently supports JPG and PNG. ${v.length} selected file${v.length===1?"":"s"} must be exported as CSV/Excel or handled by CyberPusher.`,variant:"destructive"});return}const A=t.map(C=>String(m.get(C.id)?.image_path||"").trim()),{results:I}=await Tt.presignGetBatch({sessionId:a,storagePaths:A}),M=new Map;for(const C of I??[]){const Y=String(C?.storagePath||"").trim(),F=String(C?.signedGetUrl||"").trim();Y&&F&&M.set(Y,F)}const q=[];for(const C of t){const Y=m.get(C.id),F=String(Y?.image_path||"").trim(),X=M.get(F);if(!X)throw new Error(`Could not sign original for ${C.originalFilename||C.filename}`);const f=await fetch(X);if(!f.ok)throw new Error(`Could not download original for ${C.originalFilename||C.filename}`);const T=await f.blob(),P=String(Y?.original_filename||C.originalFilename||Y?.filename||C.filename||`asset-${C.id}.jpg`).trim().replace(/[\\/:*?"<>|]+/g,"-"),G=new File([T],P,{type:T.type||Y?.mime_type||void 0}),se=Rt(C),le=String(se?.title??C.title??"").trim(),be=String(se?.description??C.description??"").trim(),Ke=Array.isArray(se?.keywords)?se.keywords:Array.isArray(C.keywords)?C.keywords:[],$e=xs(C),Z=String(C.editorialCity??"").trim(),tt=String(C.editorialLocation??$e.location??"").trim(),Oe=String(C.editorialCountry??$e.country??"").trim(),Ve=Kt(C.editorialDate??$e.date)||"",We=Ve?Date.parse(Ve):Number.NaN,St=Number.isFinite(We)?new Date(We).toISOString():"",Mt=Ls(Z,Oe),Je=String(qe?.editorial_style||"").trim()||ct,Ze=C.editorial?Fs(Mt,Ve,be,Je):"",ft=C.editorial?xa(String(C.editorialCaption||Ze||be||le).trim(),Je):be,jt={title:le,description:ft||le,keywords:Ke,location:Mt||tt,country:Oe,dateCreated:St,intellectualGenre:String(C.editorialCategory||(C.editorial?"Editorial":"")||"").trim(),instructions:C.editorial?"Editorial Use Only":void 0,usageTerms:C.editorial?"Editorial Use Only":void 0},Nt=/\.(png)$/i.test(P)||G.type.includes("png")?await qm(G,jt):await Vm(G,jt);q.push({path:P,blob:Nt})}const te=W.replace(/\s+/g,"_"),me=E?.id?E.id.substring(0,8):`${t.length}`,pe=new Date,ce=pe.getFullYear(),oe=String(pe.getMonth()+1).padStart(2,"0"),ue=String(pe.getDate()).padStart(2,"0"),de=await Wm(q);fc(de,`${te}_${me}_${ce}${oe}${ue}_embedded_metadata.zip`),pa.getState().noteExport(),r({title:"Embedded files ready",description:`Downloaded ${q.length} file${q.length===1?"":"s"} with embedded metadata.`})}
15catch(n){console.error("Embedded metadata export error",n),r({title:"Embedded export failed",description:n instanceof Error?n.message:"Could not create embedded metadata files.",variant:"destructive"})}finally{ds(!1)}},Mu=async(t,a,n,o,u,m)=>{if(!N)return;const h=Be().filter(F=>F.id!==N.id);if(h.length===0)return;const y=N.baseTitle??N.title??"",w=N.baseDescription??N.description??"",v=(N.categories??"")||"",A=N?.keywords,I=Array.isArray(N.baseKeywords)?[...N.baseKeywords]:Array.isArray(N.keywords)?[...N.keywords]:typeof A=="string"&&A.trim().length>0?A.split(/,\s*/):[],M=I.join(", "),q=!!N.editorial,te=q?xs(N):{location:null,city:null,country:null,date:null},me=N.editorialCity??te.city??N.editorialLocation??te.location??"",pe=N.editorialCountry??te.country??"",ce=N.editorialDate??te.date??"",oe=ce?Kt(ce)??ce:"",ue=N.editorialCaption??"",de=N.editorialCategory??"",C=m?{...xr,...m}:xr,Y=[];h.forEach(F=>{const X={},f={};if(t&&(X.title=y,X.baseTitle=y,f.title=y,f.baseTitle=y),n&&(X.description=w,X.baseDescription=w,f.description=w,f.baseDescription=w),a&&(X.keywords=I,X.baseKeywords=I,f.keywords=M,f.baseKeywords=I),o&&(X.categories=v,f.categories=v),Object.keys(X).length>0&&Q(F.id,X),Object.keys(f).length>0&&Y.push(we.updateSessionImage(F.id,f)),u&&Ln){const T={editorial:q},B={editorial:q};C.location&&(T.editorialLocation=me,B.editorialLocation=me||null),C.country&&(T.editorialCountry=pe,B.editorialCountry=pe||null),C.date&&(T.editorialDate=oe,B.editorialDate=oe||null),C.caption&&(T.editorialCaption=ue,B.editorialCaption=ue||null),de&&(T.editorialCategory=de,B.editorialCategory=de||null),Q(F.id,T),Y.push(Ct(F.id,B,{silent:!0}))}}),Y.length>0&&await Promise.all(Y),r({title:"Applied",description:"Applied current fields to selected images"})},Bu=()=>{!N||!Fi||(qa(Mc),Ai({...xr}),Vn("metadata"),Nr(!0))},Lu=async()=>{if(!N)return;const{title:t,keywords:a,description:n,category:o,editorial:u}=_i,m=u&&Ys;if(!(t||a||n||o||m)){r({title:"Select fields",description:"Choose at least one metadata block to copy.",variant:"destructive"});return}Wn(!0);try{await Mu(t,a,n,o,m,m?Hn:void 0),Nr(!1)}catch(y){console.error("[ReviewEdit] Apply to selected failed",y),r({title:"Apply failed",description:"Could not copy metadata to selected assets.",variant:"destructive"})}finally{Wn(!1)}},Vr=d.useRef(null),ec=d.useRef(null);d.useEffect(()=>{if(!N?.id||na)return;const t=N,a=t.title??"",n=t.description??"",o=Array.isArray(t.keywords)?t.keywords.join(", "):String(t.keywords??""),u=t.baseTitle??t.title??"",m=t.baseDescription??t.description??"",h=Array.isArray(t.baseKeywords)?t.baseKeywords.join(", "):Array.isArray(t.keywords)?t.keywords.join(", "):String(t.keywords??""),y=`${t.id}::${a}::${n}::${o}::${u}::${m}::${h}`,w=ec.current,v=w?`${w.id}::${w.title}::${w.description}::${w.keywords}::${w.baseTitle}::${w.baseDescription}::${w.baseKeywords}`:"";if(y!==v)return Vr.current&&clearTimeout(Vr.current),Vr.current=setTimeout(()=>{ec.current={id:t.id,title:a,description:n,keywords:o,baseTitle:u,baseDescription:m,baseKeywords:h},we.updateSessionImage(t.id,{title:a,description:n,keywords:o,baseTitle:u,baseDescription:m,baseKeywords:Array.isArray(t.baseKeywords)?t.baseKeywords:Array.isArray(t.keywords)?t.keywords:[]}).catch(A=>console.warn("[ReviewEdit] Auto-save failed",t.id,A))},2e3),()=>{Vr.current&&clearTimeout(Vr.current)}},[N?.id,N?.title,N?.description,N?.keywords,N?.baseTitle,N?.baseDescription,N?.baseKeywords,na]);const Fu=async()=>{if(!(!E||!c))try{vi(!0);const t=b.filter(n=>!!n?.id).map(n=>()=>we.updateSessionImage(n.id,{title:n.title,keywords:Array.isArray(n.keywords)?n.keywords.join(", "):n.keywords||"",description:n.description,baseTitle:n.baseTitle??n.title??"",baseDescription:n.baseDescription??n.description??"",baseKeywords:Array.isArray(n.baseKeywords)?n.baseKeywords:Array.isArray(n.keywords)?n.keywords:[]})),a=10;for(let n=0;n<t.length;n+=a)await Promise.all(t.slice(n,n+a).map(o=>o()));r({title:"Session Saved",description:"All changes have been saved"})}catch{r({title:"Save Error",description:"Failed to save session",variant:"destructive"})}finally{vi(!1)}};if(En)return e.jsx("div",{className:"cs-page flex items-center justify-center",children:e.jsx(ga,{size:"lg",text:"Loading session..."})});if(!E)return e.jsx("div",{className:"cs-page flex items-center justify-center",children:e.jsxs("div",{className:"text-center",children:[e.jsx("h2",{className:"text-xl font-semibold mb-2",style:{color:"var(--cs-text-primary)"},children:"Session not found"}),e.jsx(Ro,{to:"/dashboard",children:e.jsx(K,{children:"Back to Dashboard"})})]})});if(bd&&pu&&Us){const t=Us.total_files||0,a=Us.processed_files||0,n=Us.failed_files||0,o=t>0?Math.min(100,Math.round((a+n)/t*100)):0;return e.jsxs("div",{className:"h-screen cs-page flex flex-col overflow-hidden",children:[e.jsxs("div",{className:"flex items-center h-14 px-4 border-b shrink-0",style:{borderColor:"var(--cs-border)"},children:[e.jsxs(Ro,{to:"/dashboard?tab=sessions",className:"inline-flex items-center gap-1.5 text-sm font-medium",style:{color:"var(--cs-text-secondary)"},children:[e.jsx(Mo,{className:"h-4 w-4"})," Back"]}),e.jsx("span",{className:"ml-3 text-sm font-semibold truncate",style:{color:"var(--cs-text-primary)"},children:E?.name||"CyberBatch session"})]}),e.jsx("div",{className:"flex-1 flex items-center justify-center px-4",children:e.jsxs("div",{className:"rounded-2xl p-10 border text-center max-w-lg w-full",style:{background:"var(--cs-bg-card)",borderColor:"var(--cs-border)"},children:[e.jsxs("div",{className:"relative inline-flex mb-5",children:[e.jsx("span",{className:"absolute inset-0 rounded-full animate-ping",style:{background:"rgba(123,97,255,.3)"}}),e.jsx("span",{className:"relative inline-flex items-center justify-center w-16 h-16 rounded-full",style:{background:"var(--cs-purple-400)"},children:e.jsx(em,{className:"h-8 w-8 text-white"})})]}),e.jsx("h2",{className:"text-2xl font-bold mb-2",style:{color:"var(--cs-text-primary)"},children:"Your files are being processed"}),e.jsx("p",{className:"text-sm max-w-md mx-auto mb-6",style:{color:"var(--cs-text-secondary)"},children:"CyberBatch is generating metadata for this session. This can take up to 24 hours (usually much faster). We'll email you a link as soon as it's ready — you can safely close this page."}),t>0&&e.jsxs(e.Fragment,{children:[e.jsxs("div",{className:"mb-1 text-3xl font-black tabular-nums",style:{color:"var(--cs-text-primary)"}
15,children:[a.toLocaleString(),e.jsxs("span",{className:"text-lg font-bold opacity-50",children:[" / ",t.toLocaleString()]})]}),e.jsx("div",{className:"max-w-md mx-auto h-2 rounded-full overflow-hidden mb-2",style:{background:"var(--cs-bg-elevated)"},children:e.jsx("div",{className:"h-full rounded-full transition-all duration-500",style:{width:`${o}%`,background:"linear-gradient(90deg, #7B61FF, #4BC0FF)"}})}),e.jsxs("p",{className:"text-xs mb-6",style:{color:"var(--cs-text-tertiary)"},children:[o,"% complete"]})]}),e.jsxs(K,{onClick:()=>i("/dashboard?tab=sessions"),variant:"outline",children:[e.jsx(Mo,{className:"h-4 w-4 mr-1"})," Back to Sessions"]})]})})]})}return e.jsxs("div",{className:"h-screen cs-page flex flex-col overflow-hidden",children:[e.jsx(Cm,{announcement:J,countdownLabel:J?.duration_hours?ot(J.id).label:"",onCtaClick:()=>J&&at(J),onOpenPopup:()=>J&&U(J.id)}),e.jsx("div",{className:"px-4 py-1.5 flex-shrink-0",style:{background:"var(--cs-bg-elevated)",borderBottom:"1px solid var(--cs-border)"},children:e.jsxs("div",{className:"max-w-[1800px] mx-auto flex flex-col gap-2 md:flex-row md:items-center md:justify-between",children:[e.jsxs("div",{className:"flex items-center gap-3",children:[e.jsx(Ro,{to:"/dashboard",children:e.jsxs(K,{variant:"outline",size:"sm",className:"h-7 text-xs",style:{borderColor:"var(--cs-purple-400)",color:"var(--cs-purple-400)"},children:[e.jsx(Mo,{className:"h-3 w-3 mr-1"}),"Back"]})}),e.jsxs("div",{children:[e.jsx("h1",{className:"text-[13px] font-semibold",style:{color:"var(--cs-text-primary)"},children:cu}),e.jsxs("p",{className:"text-xs",style:{color:"var(--cs-text-secondary)"},children:[b.length," images · ",ke," selected"]})]}),e.jsx("button",{onClick:()=>l.cycleTheme(),className:"h-7 w-7 rounded-md flex items-center justify-center transition-colors",style:{background:"transparent",color:"var(--cs-text-primary)"},onMouseEnter:t=>{t.currentTarget.style.background="var(--cs-bg-hover)"},onMouseLeave:t=>{t.currentTarget.style.background="transparent"},title:`Theme: ${l.theme}`,children:l.theme==="dark"?e.jsx(tm,{className:"h-3.5 w-3.5"}):l.theme==="asphalt"?e.jsx(sm,{className:"h-3.5 w-3.5"}):e.jsx(rm,{className:"h-3.5 w-3.5"})})]}),e.jsxs("div",{className:"flex items-center justify-end gap-2",children:[s&&e.jsx(K,{size:"sm","data-onboarding":"review-push",onClick:()=>i(`/pusher?session=${encodeURIComponent(s)}`),style:{background:"#F59E0B",color:"#fff",border:"none"},onMouseEnter:t=>{t.currentTarget.style.background="#D97706"},onMouseLeave:t=>{t.currentTarget.style.background="#F59E0B"},children:"Push"}),e.jsx(im,{onBuy:()=>{Wa("credits"),Ii(!0)}}),re&&O==="free"&&!D&&e.jsx("span",{className:"hidden md:block w-px h-5 mx-1",style:{background:"var(--cs-border)"},"aria-hidden":"true"}),re&&e.jsx(am,{tier:O,unlimitedActive:D,size:"md",onClick:()=>{Wa("unlimited"),Ii(!0)}})]})]})}),e.jsx("div",{className:"flex-1 overflow-hidden",children:e.jsxs("div",{className:"max-w-[1800px] mx-auto h-full px-3 py-2 flex flex-col gap-2 overflow-hidden",children:[fu,e.jsx("div",{className:"flex-1 overflow-hidden rounded-xl min-h-0",style:{border:"1px solid var(--cs-border)",background:"var(--cs-bg-card)",boxShadow:"var(--cs-shadow-card)"},children:e.jsxs(tp,{direction:"horizontal",className:"h-full min-h-0",children:[e.jsx(Vo,{defaultSize:16,minSize:14,className:"rounded-xl overflow-hidden min-h-0",style:{background:"var(--cs-bg-elevated)",border:"1px solid var(--cs-border)"},children:e.jsxs("div",{className:"flex h-full flex-col min-h-0",children:[e.jsxs("div",{className:"px-3 py-2.5 space-y-2",style:{borderBottom:"1px solid var(--cs-border)"},children:[e.jsx("div",{className:"flex items-center justify-between",children:e.jsxs("h3",{className:"text-xs font-semibold flex items-center gap-1.5",style:{color:"var(--cs-text-primary)"},children:["Thumbnails",e.jsxs("span",{className:"text-xs font-normal tabular-nums",style:{color:"var(--cs-text-secondary)"},children:["(",b.length.toLocaleString(),")"]}),_n==="loading"&&e.jsx($s,{className:"h-3 w-3 animate-spin transition-opacity duration-300",style:{color:"var(--cs-purple-400, #a78bfa)"}
15,"aria-label":`Loading more thumbnails, ${b.length.toLocaleString()} so far`}),_n==="done"&&e.jsx(om,{className:"h-3 w-3 transition-opacity duration-500",style:{color:"#22c55e"},"aria-label":"All thumbnails loaded"})]})}),e.jsxs("div",{className:"flex gap-2 items-center",children:[e.jsx(Ee,{delayDuration:150,children:e.jsxs(_e,{open:eo&&!rl?!0:void 0,children:[e.jsx(Ae,{asChild:!0,children:e.jsx(K,{variant:"outline",size:"sm","data-onboarding":"review-select-all",onClick:()=>{aa?j():(bt(),eo&&il(!1))},className:`flex-1 text-xs bg-gradient-to-r from-[#7B61FF] to-[#4BC0FF] text-white border-transparent shadow-sm transition-opacity ${aa?"opacity-100":"opacity-60 hover:opacity-90"}`,children:aa?"Deselect All":"Select All"})}),e.jsx(Te,{side:"bottom",className:"text-xs",children:eo?"Step 1: Select all photos you want to update":aa?"Deselect all images":"Select all images"})]})}),e.jsxs("div",{className:"ml-auto flex items-center gap-1",children:[e.jsx(Ee,{children:e.jsxs(_e,{children:[e.jsx(Ae,{asChild:!0,children:e.jsxs(oc,{children:[e.jsx(nc,{asChild:!0,children:e.jsx(K,{variant:"ghost",size:"icon",className:"h-8 w-8","aria-label":"Sort",children:e.jsx(Qm,{className:"h-4 w-4"})})}),e.jsxs(lc,{align:"end",className:"w-40",children:[e.jsx(os,{onClick:()=>au(),children:"Original order"}),e.jsx(os,{onClick:()=>Br(co,js==="desc"?"asc":"desc"),children:js==="desc"?"High → Low":"Low → High"}),e.jsx(os,{onClick:()=>Br("selling",js),children:"Selling"}),e.jsx(os,{onClick:()=>Br("title",js),children:"Title"}),e.jsx(os,{onClick:()=>Br("description",js),children:"Description"}),e.jsx(os,{onClick:()=>Br("keywords",js),children:"Keywords"})]})]})}),e.jsx(Te,{children:"Sorting"})]})}),e.jsx("span",{className:"text-xs ml-1 select-none hidden sm:inline",style:{color:"var(--cs-text-tertiary)"},children:Zs&&Zs.length>0?`${co.charAt(0).toUpperCase()+co.slice(1)} • ${js==="desc"?"High → Low":"Low → High"}`:"Original"})]})]})]}),e.jsx("div",{"data-onboarding":"review-thumbnails",className:"flex-1 p-2 space-y-2 overflow-y-auto",children:ou.map((t,a)=>{const n=t.hasError||t.processingStatus==="error";return e.jsxs("div",{className:`${g===t.id?"border":n?"border-2 border-red-500":""} ${oa(t.id)?"ring-2 ring-offset-2 ring-[#F59E0B] animate-pulse":Xl(t.id)?"border border-dashed border-[#FBBF24]":""} flex items-center gap-3 p-2 rounded-lg cursor-pointer transition-colors`,style:g===t.id?{background:"rgba(124,92,255,.12)",borderColor:"var(--cs-purple-400)"}:n?{}:{},onMouseEnter:o=>{g!==t.id&&!n&&(o.currentTarget.style.background="var(--cs-bg-hover)")},onMouseLeave:o=>{g!==t.id&&!n&&(o.currentTarget.style.background="")},onClick:()=>wo(t.id),children:[e.jsx("input",{type:"checkbox",checked:t.isSelected,onChange:()=>H(t.id),onClick:o=>o.stopPropagation(),className:"rounded"}),(t.thumbnailUrl||t.imageUrl)&&e.jsxs("div",{className:"relative",children:[oa(t.id)&&e.jsx("span",{className:"pointer-events-none absolute inset-[-4px] rounded-xl border-2 border-dashed border-[#F59E0B] animate-spin"}),!oa(t.id)&&Xl(t.id)&&e.jsx("span",{className:"pointer-events-none absolute inset-[-2px] rounded-lg border border-dashed border-[#FBBF24] animate-pulse"}),n&&!oa(t.id)&&e.jsx("span",{className:"pointer-events-none absolute inset-[-2px] rounded-lg border-2 border-red-500"}),e.jsx(gc,{src:t.thumbnailUrl??t.imageUrl??"",alt:t.filename,className:`h-12 w-12 rounded-lg object-cover ${n?"opacity-75":""}`}),e.jsx(th,{state:Zd(t.id)}),n&&e.jsx("span",{className:"absolute -top-1 -left-1 flex h-4 w-4 items-center justify-center rounded-full bg-red-500 text-white text-xs font-bold",children:"!"})]}),e.jsxs("div",{className:"flex-1 min-w-0 flex items-center gap-2",children:[e.jsx("span",{className:`shrink-0 inline-flex items-center justify-center h-7 w-7 text-xs font-semibold rounded-md ${n?"bg-red-100 text-red-700 border border-red-300":""}`,style:n?{}:{background:"rgba(124,92,255,.1)",color:"var(--cs-purple-300)",border:"1px solid rgba(124,92,255,.2)"},children:a+1}),e.jsx("p",{className:`text-xs font-medium truncate ${n?"text-red-700":""}`,style:n?{}:{color:"var(--cs-text-primary)"},title:String(t.originalFilename||t.filename||"Untitled").trim(),children:String(t.originalFilename||t.filename||"Untitled").trim()})]}),g===t.id&&e.jsx(xt,{className:"h-4 w-4",style:{color:"var(--cs-purple-400)"}})]},t.id)})})]})}),e.jsx(kc,{withHandle:!0}),e.jsx(Vo,{defaultSize:33,minSize:22,className:"rounded-xl overflow-hidden min-h-0",style:{background:"var(--cs-bg-page)",border:"1px solid var(--cs-border)"},children:e.jsxs("div",{className:"flex h-full flex-col",children:[e.jsxs("div",{className:"px-3 py-2 flex items-center justify-between",style:{borderBottom:"1px solid var(--cs-border)"},children:[e.jsxs("div",{className:"flex items-center gap-2 min-w-0",children:[e.jsx("h3",{className:"text-xs font-semibold",style:{color:"var(--cs-text-primary)"},children:"Preview"}),ca&&e.jsx(Ee,{delayDuration:150,children:e.jsxs(_e,{children:[e.jsx(Ae,{asChild:!0,children:e.jsxs("button",{type:"button","aria-label":"Custom prompt used for this batch",className:"inline-flex items-center gap-1 rounded-full px-2 py-0.5 text-[10px] font-semibold border transition-colors",style:{color:"var(--cs-purple-400)",borderColor:"var(--cs-purple-400)",background:"color-mix(in srgb, var(--cs-purple-400) 12%, transparent)"},onClick:()=>Ur(ca,"Custom prompt"),children:[e.jsx(bs,{className:"h-3 w-3"}),"Custom prompt"]})}),e.jsx(Te,{side:"bottom",align:"start",className:"max-w-sm",children:e.jsxs("div",{className:"space-y-2",children:[e.jsxs("div",{className:"flex items-center justify-between gap-2",children:[e.jsx("span",{className:"text-[11px] font-semibold uppercase tracking-wide",children:"Custom prompt used"}),e.jsxs("button",{type:"button",className:"inline-flex items-center gap-1 text-[11px] opacity-80 hover:opacity-100",onClick:t=>{t.stopPropagation(),Ur(ca,"Custom prompt")},children:[e.jsx(ns,{className:"h-3 w-3"})," Copy"]})]}),e.jsx("p",{className:"text-xs whitespace-pre-wrap break-words leading-relaxed max-h-60 overflow-auto",children:ca})]})})]})})]}),e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(K,{variant:"outline",size:"sm",onClick:Ed,children:e.jsx(Gm,{className:"h-3 w-3"})}),e.jsx(K,{variant:"outline",size:"sm",onClick:Nd,children:e.jsx(Ym,{className:"h-3 w-3"})}),e.jsx(K,{variant:"outline",size:"sm",onClick:jd,children:e.jsx(Xm,{className:"h-3 w-3"})})]})]}),e.jsx("div",{className:"flex-1 p-6 flex items-center justify-center overflow-auto",children:N?(()=>{const t=String(N.filename||"").toLowerCase(),n=String(N.mediaType||"").toLowerCase()==="video"||/\.(mp4|mov|avi|webm|mkv)(\?|$)/i.test(t),o=N.thumbnailUrl||N.imageUrl||"";return o?e.jsx("div",{className:"transition-transform duration-150 w-full max-w-[min(100%,980px)] max-h-full overflow-hidden rounded-lg shadow-sm",style:{transform:`scale(${Sd})`,transformOrigin:"center center"},children:e.jsx("div",{className:"relative",children:e.jsx(gc,{src:o,alt:N.filename,className:"w-full h-auto max-h-[72vh] object-contain",preservePrevious:!1,draggable:!1})})}):e.jsxs("div",{className:"text-center text-[var(--cs-text-secondary)]",children:[e.jsx(xc,{className:"h-16 w-16 mx-auto mb-4 opacity-50"}),e.jsx("p",{children:"Select an image to preview"})]})})():e.jsxs("div",{className:"text-center",style:{color:"var(--cs-text-tertiary)"},children:[e.jsx(xc,{className:"h-16 w-16 mx-auto mb-4 opacity-50"}),e.jsx("p",{children:"Select an image to preview"})]})})]})}),e.jsx(kc,{withHandle:!0}),e.jsx(Vo,{defaultSize:51,minSize:30,className:"rounded-xl overflow-hidden min-h-0",style:{background:"var(--cs-bg-elevated)",border:"1px solid var(--cs-border)"},children:e.jsxs("div",{className:"flex h-full flex-col min-h-0",children:[e.jsxs("div",{className:"px-3 py-2",style:{borderBottom:"1px solid var(--cs-border)"},children:[e.jsxs("div",{className:"flex items-center justify-between gap-3",children:[e.jsx("div",{className:"flex items-center gap-2 shrink-0",children:e.jsx("select",{"data-onboarding":"review-platform",value:W,onChange:t=>{const a=t.target.value;a==="Custom"?($a("Custom"),Si(!0)):$a(a)},className:"h-9 text-xs border rounded px-2 max-w-[220px]",style:{background:"var(--cs-input-bg)",color:"var(--cs-text-primary)",borderColor:"var(--cs-input-border)"},children:Oa.map(t=>e.jsx("option",{value:t,children:t},t))})}),e.jsxs("div",{className:"flex items-center justify-center gap-2 flex-1 flex-nowrap overflow-x-auto",children:[g&&!Se&&!er&&e.jsxs(e.Fragment,{children:[e.jsxs(K,{variant:"outline",size:"sm","data-onboarding":"review-regenerate",onClick:Du,className:"h-9 border-amber-500/50 text-amber-600 dar
15k:text-amber-400 hover:bg-amber-500 hover:text-white",children:[e.jsx(va,{className:"h-3 w-3 mr-1"}),"Regenerate"]}),e.jsxs(K,{variant:"outline",size:"sm",onClick:()=>Ye?du():wu(),className:"h-9 bg-blue-50 dark:bg-blue-500/10 text-blue-700 dark:text-blue-400 border-blue-200 dark:border-blue-500/30 hover:bg-blue-600 hover:text-white",children:[e.jsx(ui,{className:"h-3 w-3 mr-1"}),"Edit"]}),e.jsxs(Rm,{open:Rd,onOpenChange:Ei,children:[e.jsx(Ee,{delayDuration:150,children:e.jsxs(_e,{children:[e.jsx(Ae,{asChild:!0,children:e.jsx(Mm,{asChild:!0,children:e.jsxs(K,{type:"button",variant:"outline",size:"icon","data-onboarding":"review-releases",onClick:()=>Ei(!0),className:"relative h-10 w-10 rounded-full text-[14px] font-extrabold border-transparent hover:brightness-110",style:{background:Xd?"rgba(124,92,255,.52)":"var(--cs-bg-active)",color:"var(--cs-text-primary)",border:"2px solid var(--cs-text-primary)",boxShadow:"0 0 0 1px rgba(0,0,0,.12), 0 14px 30px rgba(0,0,0,.28)"},children:["R",Jd&&e.jsx("span",{className:"absolute -top-0.5 -right-0.5 h-2 w-2 rounded-full",style:{background:"var(--cs-amber-400)",boxShadow:"0 0 0 2px var(--cs-bg-elevated)"}})]})})}),e.jsx(Te,{side:"bottom",className:"text-xs",children:"Releases"})]})}),e.jsx(Bm,{side:"bottom",align:"start",sideOffset:10,className:"p-0 w-[min(520px,calc(100vw-24px))] rounded-2xl border overflow-hidden",style:{background:"var(--cs-bg-elevated)",borderColor:"var(--cs-border-strong)",boxShadow:"var(--cs-shadow-elevated)"},children:c?.id&&s&&g?e.jsx(Rc,{name:"ReleaseQuickPanel",title:"Releases panel failed",description:"The releases popover crashed while rendering.",children:e.jsx("div",{className:"p-4",children:e.jsx(Qp,{userId:c.id,sessionId:s,sessionImageId:g,platformId:st,faceMatchEnabled:It?.enabled===!0,scanBusy:Ba,onScanAsset:()=>bi({assetIds:[g],openResults:!0}),onScanSession:()=>bi({openResults:!0}),onOpenScanResults:()=>La(!0)})})}):e.jsx("div",{className:"p-4 text-[12px]",style:{color:"var(--cs-text-tertiary)"},children:"Select an asset to manage releases."})})]}),Li&&e.jsx("div",{className:"ml-1 h-9 flex items-center",children:e.jsx(ch,{status:Li.status,title:Li.reasons?.length?Li.reasons.join(", "):"Release readiness"})}),e.jsxs("div",{className:"flex items-center border rounded-md h-9",style:{borderColor:"var(--cs-border)"},children:[e.jsx(Ee,{delayDuration:150,children:e.jsxs(_e,{children:[e.jsx(Ae,{asChild:!0,children:e.jsx(K,{variant:"ghost",size:"icon",onClick:Hd,disabled:!Vd,className:"h-9 w-9 p-0 rounded-r-none",children:e.jsx(xm,{className:"h-3 w-3"})})}),e.jsxs(Te,{side:"bottom",className:"max-w-xs p-2 text-xs",children:[e.jsx("p",{className:"font-medium",children:"Undo"}),e.jsx("p",{className:"text-muted-foreground",children:"Revert the last metadata change for this image (up to 5 steps). Works with Edit, Regenerate, and Clear actions."})]})]})}),e.jsx("div",{className:"w-px h-5",style:{background:"var(--cs-border)"}}),e.jsx(Ee,{delayDuration:150,children:e.jsxs(_e,{children:[e.jsx(Ae,{asChild:!0,children:e.jsx(K,{variant:"ghost",size:"icon",onClick:Gd,disabled:!Wd,className:"h-9 w-9 p-0 rounded-l-none",children:e.jsx(bm,{className:"h-3 w-3"})})}),e.jsxs(Te,{side:"bottom",className:"max-w-xs p-2 text-xs",children:[e.jsx("p",{className:"font-medium",children:"Redo"}),e.jsx("p",{className:"text-muted-foreground",children:"Re-apply the last undone change for this image."})]})]})})]}),e.jsx(Ee,{delayDuration:150,children:e.jsxs(_e,{open:to&&!rl?!0:void 0,children:[e.jsx(Ae,{asChild:!0,children:e.jsx(K,{variant:"outline",size:"sm","data-onboarding":"review-apply-selected",onClick:()=>{Ye?Fl():Bu(),to&&al(!1)},disabled:Ye?gt===0:!Fi,className:(Ye?gt>0:Fi)?"!bg-[#F59E0B] hover:!bg-[#D97706] !text-white border-transparent":"bg-muted text-muted-foreground border-border hover:bg-accent hover:text-accent-foreground opacity-60 cursor-not-allowed",children:Ye?`Apply to Selected${gt>0?` (${gt})`:""}`:`Apply to Selected${ke>0?` (${ke})`:""}`})}),e.jsx(Te,{side:"bottom",className:"text-xs",children:to?"Step 2: Apply current editorial fields to selected photos":"Apply current metadata to selected images"})]})})]}),g&&Ye&&er&&e.jsxs(e.Fragment,{children:[e.jsxs(K,{variant:"outline",size:"sm",onClick:Ll,className:"text-white border-transparent hover:opacity-90",style:{background:"var(--cs-purple-400)"},children:[e.jsx(xt,{className:"h-3 w-3 mr-1"}),"Save"]}),e.jsxs(K,{variant:"outline",size:"sm",onClick:Bl,className:"border-border text-muted-foreground hover:bg-muted",children:[e.jsx(At,{className:"h-3 w-3 mr-1"}),"Cancel"]}),e.jsx(K,{variant:"outline",size:"sm",onClick:Fl,disabled:Math.max(0,ke-(g?1:0))===0,className:`border-violet-500 dark:border-violet-400 text-violet-600 dar
15k:text-violet-400 bg-[var(--cs-bg-card)] hover:bg-violet-50 dark:hover:bg-violet-500/10 ${Math.max(0,ke-(g?1:0))===0?"opacity-60 cursor-not-allowed":""}`,children:`Apply to Selected${Math.max(0,ke-(g?1:0))>0?` (${Math.max(0,ke-(g?1:0))})`:""}`})]})]})]}),qe?.description&&e.jsxs("div",{className:"mt-2 flex items-center gap-2 text-xs text-muted-foreground",children:[e.jsx(nm,{className:"h-3 w-3"}),e.jsx("span",{children:qe.description})]})]}),e.jsx("div",{className:"flex-1 px-3 py-3 space-y-4 overflow-y-auto",children:hu()})]})})]})}),e.jsxs("div",{className:"relative z-20 flex items-center justify-between px-3 py-2 rounded-lg flex-shrink-0",style:{background:"var(--cs-bg-card)",border:"1px solid var(--cs-border)",boxShadow:"var(--cs-shadow-card)"},children:[e.jsxs("div",{className:"flex items-center gap-4",children:[e.jsxs("span",{className:"text-sm",style:{color:"var(--cs-text-secondary)"},children:[Be().length," of ",b.length," selected"]}),e.jsxs("div",{className:"flex gap-2",children:[e.jsxs(K,{variant:"ghost",onClick:()=>{const t=b.map(o=>o.id),a=t.indexOf(g||""),n=t[(a-1+t.length)%t.length];n&&wo(n)},style:{background:"var(--cs-bg-hover)",color:"var(--cs-text-primary)"},children:[e.jsx(lm,{className:"h-4 w-4"})," Prev"]}),e.jsxs(K,{variant:"ghost",onClick:()=>{const t=b.map(o=>o.id),a=t.indexOf(g||""),n=t[(a+1)%t.length];n&&wo(n)},style:{background:"var(--cs-bg-hover)",color:"var(--cs-text-primary)"},children:["Next ",e.jsx(cm,{className:"h-4 w-4"})]})]})]}),e.jsxs("div",{className:"flex gap-3 items-center mr-16",children:[e.jsx(Ee,{delayDuration:150,children:e.jsxs(_e,{children:[e.jsx(Ae,{asChild:!0,children:e.jsx("span",{className:"inline-flex",children:e.jsxs("div",{"data-onboarding":"review-export",className:"inline-flex overflow-hidden rounded-md",children:[e.jsxs(K,{onClick:Ql,disabled:ke===0||Va,className:`rounded-r-none bg-gradient-to-r from-[#7B61FF] to-[#4BC0FF] text-white transition-opacity ${ke===0?"opacity-50 cursor-not-allowed":""}`,children:[Va?e.jsx($s,{className:"h-4 w-4 mr-2 animate-spin"}):e.jsx(bc,{className:"h-4 w-4 mr-2"}),"Export Selected (",ke,")"]}),e.jsxs(oc,{children:[e.jsx(nc,{asChild:!0,children:e.jsx(K,{type:"button",disabled:ke===0||Va,className:`rounded-l-none border-l border-white/20 bg-[#4BC0FF] px-2 text-white hover:bg-[#38AEEA] ${ke===0?"opacity-50 cursor-not-allowed":""}`,"aria-label":"Open export options",children:e.jsx(ac,{className:"h-4 w-4"})})}),e.jsxs(lc,{align:"end",className:"w-72",children:[e.jsx(dm,{children:"Download options"}),e.jsxs(os,{onClick:Ql,className:"cursor-pointer",children:[e.jsx(wc,{className:"mr-2 h-4 w-4"}),e.jsxs("div",{children:[e.jsx("div",{className:"font-medium",children:"Download CSV"}),e.jsx("div",{className:"text-[11px] text-muted-foreground",children:"Platform-ready metadata sheet"})]})]}),e.jsxs(os,{onClick:Iu,className:"cursor-pointer",children:[Vs?e.jsx(wc,{className:"mr-2 h-4 w-4"}):e.jsx(cc,{className:"mr-2 h-4 w-4 text-amber-500"}),e.jsxs("div",{children:[e.jsxs("div",{className:"flex items-center gap-2 font-medium",children:[e.jsx("span",{children:"Download Excel"}),!Vs&&e.jsxs("span",{className:"inline-flex items-center gap-1 rounded-full border border-amber-500/30 bg-amber-500/10 px-1.5 py-0.5 text-[10px] font-black uppercase text-amber-500",children:[e.jsx(bs,{className:"h-3 w-3"}),"Upgrade"]})]}),e.jsx("div",{className:"text-[11px] text-muted-foreground",children:"Editable XLSX workbook"})]})]}),e.jsx(um,{}),e.jsxs(os,{onClick:Ru,className:"cursor-pointer",children:[Vs?e.jsx(bc,{className:"mr-2 h-4 w-4"}):e.jsx(cc,{className:"mr-2 h-4 w-4 text-amber-500"}),e.jsxs("div",{children:[e.jsxs("div",{className:"flex items-center gap-2 font-medium",children:[e.jsx("span",{children:"Download files with embedded metadata"}),!Vs&&e.jsxs("span",{className:"inline-flex items-center gap-1 rounded-full border border-amber-500/30 bg-amber-500/10 px-1.5 py-0.5 text-[10px] font-black uppercase text-amber-500",children:[e.jsx(bs,{className:"h-3 w-3"}),"Upgrade"]})]}),e.jsx("div",{className:"text-[11px] text-muted-foreground",children:"Paid feature · originals available for up to 24h"})]})]})]})]})]})})}),e.jsx(Te,{side:"top",className:"text-xs",children:ke===0?"Select images you want so this button activates":"CSV export is available. Excel and embedded files require a paid plan."})]})}),e.jsx(K,{"data-onboarding":"review-save",onClick:Fu,disabled:Ka,className:`bg-[#34D399] text-white border border-transparent hover:bg-[#2BBF88] ${Ka?"opacity-80 curs
15or-not-allowed":""}`,children:Ka?e.jsxs(e.Fragment,{children:[e.jsx(ga,{size:"sm"}),"Saving..."]}):e.jsxs(e.Fragment,{children:[e.jsx(Jm,{className:"h-4 w-4 mr-2"}),"Save Session"]})})]})]})]})}),e.jsx(Zr,{open:Id,onOpenChange:t=>{Ni||Nr(t)},children:e.jsxs(Qr,{className:"w-full max-w-lg rounded-2xl border border-[var(--cs-border)]",children:[e.jsxs(ei,{children:[e.jsx(ti,{children:ji==="releases"?`Apply releases to ${gt} selected ${gt===1?"asset":"assets"}`:`Apply metadata to ${gt} selected ${gt===1?"asset":"assets"}`}),e.jsx(si,{className:"text-sm text-[#4B5563]",children:ji==="releases"?"Attach, replace, or remove releases across the selected items with a clear preview.":"Choose which fields from the current asset should overwrite the ones on the selected items."})]}),e.jsx("div",{className:"flex items-center gap-1 p-1 rounded-xl w-fit mb-2",style:{background:"var(--cs-bg-hover)",border:"1px solid var(--cs-border)"},children:[{id:"metadata",label:"Metadata"},{id:"releases",label:"Releases"}].map(t=>{const a=ji===t.id;return e.jsx("button",{type:"button",onClick:()=>Vn(t.id),className:"px-3 py-1.5 rounded-lg text-[12px] font-semibold transition-all",style:{background:a?"var(--cs-bg-card)":"transparent",color:a?"var(--cs-text-primary)":"var(--cs-text-tertiary)",border:a?"1px solid var(--cs-border)":"1px solid transparent"},children:t.label},t.id)})}),ji==="metadata"?e.jsxs(e.Fragment,{children:[e.jsx("div",{className:"space-y-4",children:uh.map(t=>{const a=t.key==="editorial"&&!Ys,n=_i[t.key];return e.jsxs("label",{htmlFor:`apply-field-${t.key}`,className:`flex items-start gap-3 rounded-xl border px-3 py-3 transition ${a?"opacity-60 cursor-not-allowed":"cursor-pointer hover:border-[#7B61FF]"}`,children:[e.jsx(hr,{id:`apply-field-${t.key}`,checked:n,disabled:a,onCheckedChange:o=>{a||qa(u=>({...u,[t.key]:!!o}))},className:"mt-1"}),e.jsxs("div",{children:[e.jsx("p",{className:"text-sm font-medium text-[var(--cs-text-primary)]",children:t.label}),e.jsx("p",{className:"text-xs text-[#6B7280]",children:t.description}),t.key==="editorial"&&!Ys&&e.jsx("p",{className:"mt-1 text-[11px] text-[#DC2626]",children:"Editorial mode must be enabled and the current asset must have editorial metadata."}),t.key==="editorial"&&Ys&&n&&e.jsx("div",{className:"mt-3 grid gap-2 sm:grid-cols-2",children:dh.map(o=>e.jsxs("label",{htmlFor:`apply-editorial-${o.key}`,className:"flex items-start gap-2 rounded-lg border border-[var(--cs-border)] bg-[var(--cs-bg-elevated)] px-3 py-2",children:[e.jsx(hr,{id:`apply-editorial-${o.key}`,checked:Hn[o.key],onCheckedChange:u=>Ai(m=>({...m,[o.key]:!!u})),className:"mt-1"}),e.jsxs("div",{children:[e.jsx("p",{className:"text-sm font-medium text-[#1F2433]",children:o.label}),e.jsx("p",{className:"text-[11px] text-[#6B7280]",children:o.description})]})]},o.key))})]})]},t.key)})}),e.jsxs(ri,{className:"flex flex-col sm:flex-row sm:items-center sm:justify-between gap-3",children:[e.jsx(K,{variant:"outline",disabled:Ni,onClick:()=>Nr(!1),children:"Cancel"}),e.jsx(K,{onClick:Lu,disabled:Ni||!Fi,className:"bg-[#7B61FF] text-white hover:bg-[#6745f5]",children:Ni?e.jsxs(e.Fragment,{children:[e.jsx(ga,{size:"sm"}),"Applying…"]}):e.jsxs(e.Fragment,{children:["Apply to ",gt," selected"]})})]})]}):e.jsx(e.Fragment,{children:c?.id&&s&&g?e.jsx(Rc,{name:"BulkReleasesApply",title:"Bulk releases failed",description:"The bulk releases modal crashed while rendering.",children:e.jsx(ih,{userId:c.id,sessionId:s,platformId:st,targetImageIds:Be().map(t=>t.id).filter(t=>t!==g),imagesById:Yd,onClose:()=>Nr(!1)})}):e.jsx("div",{className:"text-[12px]",style:{color:"var(--cs-text-tertiary)"},children:"Select assets to apply releases."})})]})}),e.jsx(Zr,{open:Md,onOpenChange:t=>{Di||Ti(t)},children:e.jsxs(Qr,{className:"w-full max-w-lg rounded-2xl border border-[var(--cs-border)]",children:[e.jsxs(ei,{children:[e.jsxs(ti,{children:["Apply Blackbox metadata to ",gt," selected ",gt===1?"asset":"assets"]}),e.jsx(si,{className:"text-sm text-[#4B5563]",children:"Choose which Blackbox fields from the current asset should overwrite the ones on the selected items."})]}),e.jsx("div",{className:"space-y-4",children:mh.map(t=>{const a=zt[t.key];return e.jsxs("label",{htmlFor:`bb-apply-field-${t.key}`,className:"flex items-start gap-3 rounded-xl border px-3 py-3 cursor-pointer hover:border-[#7B61FF]",children:[e.jsx(hr,{id:`bb-apply-field-${t.key}`,checked:a,onCheckedChange:n=>{Yn(o=>
15({...o,[t.key]:!!n}))},className:"mt-1"}),e.jsxs("div",{children:[e.jsx("p",{className:"text-sm font-medium text-[var(--cs-text-primary)]",children:t.label}),e.jsx("p",{className:"text-xs text-[#6B7280]",children:t.description}),t.key==="editorial"&&a&&e.jsx("div",{className:"mt-3 grid gap-2 sm:grid-cols-2",children:ph.map(n=>e.jsxs("label",{htmlFor:`bb-apply-editorial-${n.key}`,className:"flex items-start gap-2 rounded-lg border border-[var(--cs-border)] bg-[var(--cs-bg-elevated)] px-3 py-2",children:[e.jsx(hr,{id:`bb-apply-editorial-${n.key}`,checked:Cs[n.key],onCheckedChange:o=>Xn(u=>({...u,[n.key]:!!o})),className:"mt-1"}),e.jsxs("div",{children:[e.jsx("p",{className:"text-sm font-medium text-[#1F2433]",children:n.label}),e.jsx("p",{className:"text-[11px] text-[#6B7280]",children:n.description})]})]},n.key))})]})]},t.key)})}),e.jsxs(ri,{className:"flex flex-col sm:flex-row sm:items-center sm:justify-between gap-3",children:[e.jsx(K,{variant:"outline",disabled:Di,onClick:()=>Ti(!1),children:"Cancel"}),e.jsx(K,{onClick:uu,disabled:Di||gt===0,className:"bg-[#7B61FF] text-white hover:bg-[#6745f5]",children:Di?e.jsxs(e.Fragment,{children:[e.jsx(ga,{size:"sm"}),"Applying…"]}):e.jsxs(e.Fragment,{children:["Apply to ",gt," selected"]})})]})]})}),e.jsx(Zr,{open:_d,onOpenChange:Si,children:e.jsxs(Qr,{children:[e.jsxs(ei,{children:[e.jsx(ti,{children:"Custom CSV Configuration"}),e.jsx(si,{children:"Enter CSV column names one per line, in order. We export with UTF-8 (BOM) and comma separator by default."})]}),e.jsx("div",{className:"space-y-3",children:e.jsxs("div",{children:[e.jsx(Ne,{className:"text-sm",children:"Columns (one per line, in order)"}),e.jsx(as,{className:"mt-1",rows:6,value:qn,onChange:t=>Td(t.target.value),placeholder:`Filename
16Title
17Description
18Keywords`}),e.jsx("p",{className:"text-xs text-muted-foreground mt-1",children:"Supported names include: Filename, Title, Description, Keywords, Tags, Headline, Caption, Categories, Category, Editorial, Releases."})]})}),e.jsxs(ri,{children:[e.jsx(K,{variant:"outline",onClick:()=>Si(!1),children:"Cancel"}),e.jsx(K,{onClick:async()=>{const t=qn.split(/\r?\n/).map(a=>a.trim()).filter(Boolean);t.length>0&&Dd(t),Si(!1),await Co(t)},children:"Download CSV"})]})]})}),Ft&&Ut.total>0&&e.jsxs("div",{className:"fixed bottom-6 left-1/2 -translate-x-1/2 z-50 w-[420px] rounded-full bg-[#F59E0B] text-white shadow-lg px-5 py-3 flex items-center justify-between gap-4",children:[e.jsxs("div",{children:[e.jsx("p",{className:"text-sm font-semibold",children:"Regenerating metadata…"}),e.jsxs("p",{className:"text-xs text-white/90",children:[Ut.completed," of ",Ut.total," completed"]})]}),e.jsx("div",{className:"flex-1",children:e.jsx(Bo,{value:xo,indicatorClassName:"bg-[var(--cs-bg-card)]",className:"h-2 bg-[var(--cs-bg-card)]/30"})})]}),e.jsx(Zr,{open:tu,onOpenChange:da,children:e.jsxs(Qr,{className:"w-full max-w-xl sm:max-w-xl md:max-w-2xl rounded-2xl shadow-2xl border border-[var(--cs-border)] overflow-hidden",children:[e.jsxs(ei,{children:[e.jsx(ti,{className:"text-lg font-semibold text-[var(--cs-text-primary)]",children:"Enhance Selected Assets"}),e.jsx(si,{className:"text-sm text-[var(--cs-text-secondary)] break-words",children:ke===0?"Select images to run batch optimization.":`Optimize ${ke} selected ${ke===1?"asset":"assets"} for ${_u}.`})]}),e.jsxs("div",{className:"space-y-4",children:[e.jsxs("div",{children:[e.jsx("p",{className:"text-xs uppercase tracking-wide text-[#6B6F82] mb-2",children:"Optimization strategy"}),e.jsx("div",{className:"grid gap-2",children:Ah.map(t=>{const a=t.icon,n=fe.includes(t.value),o=()=>{vl(h=>{if(h.includes(t.value)){const v=h.filter(A=>A!==t.value);return v.length>0?v:ba}if(t.value==="all")return["all"];const w=[...h.filter(v=>v!=="all"),t.value];return w.length>0?w:ba})},u=(()=>{const h=t.value==="keywords"?Wi:t.value==="title"?qi:Vi;return h>0&&ae<h?"Not enough credits for this optimization.":null})(),m=!!u;return e.jsxs("label",{className:mt("flex flex-wrap min-w-0 cursor-pointer items-start gap-3 rounded-lg border px-3 py-2 text-sm transition-all",n?"border-[#4F46E5] bg-[#F5F3FF]":"border-[var(--cs-border)] bg-[var(--cs-bg-card)] hover:bg-[var(--cs-bg-elevated)]",m&&"cursor-not-allowed opacity-60"),children:[e.jsx("input",{type:"checkbox",name:`batch-field-${t.value}`,value:t.value,checked:n,onChange:o,disabled:ps||m,className:"mt-1"}),e.jsxs("div",{className:"flex-1 min-w-0",children:[e.jsxs("div",{className:"flex flex-wrap items-center gap-2 min-w-0",children:[e.jsx(a,{className:"h-4 w-4 text-[#4F46E5]"}),e.jsx("span",{className:"font-medium text-[var(--cs-text-primary)] break-words",children:t.label}),e.jsxs("span",{className:"text-[11px] text-[var(--cs-text-secondary)] whitespace-nowrap",children:[Yo(t.cost)," credit(s) per image"]})]}),e.jsx("p",{className:"mt-1 text-xs text-[var(--cs-text-secondary)] break-words",children:t.description}),u&&e.jsx("p",{className:"mt-1 text-xs text-rose-500",children:u})]})]},t.value)})})]}),e.jsxs("div",{className:"space-y-2 rounded-lg border border-[var(--cs-border)] bg-[var(--cs-bg-elevated)] p-3 text-sm",children:[e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsx("span",{className:"text-[var(--cs-text-primary)]",children:"Selected assets"}),e.jsx("span",{className:"font-medium text-[#4F46E5]",children:ke})]}),e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsx("span",{className:"text-[var(--cs-text-primary)]",children:"Estimated cost"}),e.jsxs("span",{className:"font-medium text-[#4F46E5]",children:[Yo(vo.total)," credits"]})]}),fe.includes("all")&&e.jsx("div",{className:"text-[11px] text-[var(--cs-text-secondary)]",children:"All bundle applied — 4 credits per image (discount)."})]}),ps&&e.jsxs("div",{className:"space-y-2 rounded-lg border border-[var(--cs-border)] bg-[var(--cs-bg-card)] p-3",children:[e.jsxs("div",{className:"flex items-center justify-between text-sm text-[var(--cs-text-primary)]",children:[e.jsx("span",{children:"Processing batch…"}),e.jsxs("span",{children:[Rr.processed,"/",Rr.total]})]}),e.jsx(Bo,{value:Nu,className:"h-2 bg-[#E6E8F0]"})]}),Pi&&e.jsxs("div",{className:"rounded-lg border border-[#C7F9CC] bg-[#F0FFF4] p-3 text-xs text-[#166534]",children:["Completed: ",Pi.processed," • Failed: ",Pi.failed," / ",Pi.total]})]}),e.jsxs(ri,{className:"flex flex-col gap-2 sm:flex-row sm:items-center sm:justify-between",children:[e.jsxs("div",{className:"text-xs text-[var(--cs-text-secondary)]",children:["Available credits: ",e.jsx("span",{className:"font-medium text-[var(--cs-text-primary)]",children:Yo(ae)})]}),e.jsxs("div",{className:"flex gap-2",children:[e.jsx(K,{variant:"outline",onClick:()=>da(!1),disabled:ps,children:"Cancel"}),e.jsxs(K,{onClick:Tu,disabled:Eu,className:"bg-[#4F46E5] text-white hover:bg-[#4338CA]",children:[ps?e.jsx($s,{className:"mr-2 h-4 w-4 animate-spin"}):e.jsx(bs,{className:"mr-2 h-4 w-4"}),ps?"Optimizing…":`Run ${Au}`]})]})]})]})}),e.jsx(mm,{open:Bd,onOpenChange:Ii,initialTab:Ld}),e.jsx(Zr,{open:kd,onOpenChange:za,children:e.jsxs(Qr,{className:"max-w-lg",children:[e.jsxs(ei,{children:[e.jsx(ti,{children:"How CyberPusher handles your originals"}),e.jsx(si,{children:"We temporarily store your original files in secure storage so we can send full‑quality images to stock agencies."})]}),e.jsxs("div",{className:"space-y-2 text-sm text-muted-foreground",children:[e.jsxs("p",{children:["Originals are kept for up to ",e.jsx("span",{className:"font-medium",children:"24 hours"})," after processing. After that, they are automatically deleted."]}),e.jsx("p",{children:"If you want to push a session later, CyberPusher may ask you to re‑upload the original files from your computer. We will match them to your processed images by filename."}),e.jsx("p",{children:"Previews and metadata stay in your CyberStock account; we only clean up large original files to keep storage under control."})]}),e.jsxs(ri,{className:"mt-4 flex flex-col gap-3 sm:flex-row sm:items-center sm:justify-between",children:[e.jsxs("div",{className:"flex items-center space-x-2",children:[e.jsx(hr,{id:"originals-ttl-dont-show",checked:On,onCheckedChange:t=>Cd(!!t)}),e.jsx(Ne,{htmlFor:"originals-ttl-dont-show",className:"text-xs text-muted-foreground",children:"Don't show this again"})]}),e.jsx(K,{type:"button",onClick:ku,children:"Got it"})]})]})}),e.jsx(vm,{open:Fd,onOpenChange:Jn}),e.jsx(Sm,{open:Pd,onOpenChange:Ha,children:e.jsxs(jm,{children:[e.jsxs(Nm,{children:[e.jsx(Em,{children:"Regenerate metadata?"}),e.jsxs(_m,{children:["This will re-run AI for ",Ri.length," file",Ri.length===1?"":"s"," and cost"," ",e.jsxs("span",{className:"font-semibold",children:[Ri.length*Ya," credit",Ri.length*Ya===1?"":"s"]}),". Continue?"]})]}),Ft&&Ut.total>0&&e.jsxs("div",{className:"space-y-3",children:[e.jsx(Bo,{value:xo,className:"h-2",indicatorClassName:"bg-[#7B61FF]"}),e.jsxs("p",{className:"text-sm text-[var(--cs-text-secondary)]",children:["Regenerating ",Ut.completed," of ",Ut.total," image",Ut.total===1?"":"s"," (",xo,"%)"]})]}),e.jsx("div",{className:"space-y-2",children:e.jsxs("div",{className:"space-y-1",children:[e.jsx(Ne,{className:"text-xs text-[var(--cs-text-secondary)]",children:"Direction (optional)"}),e.jsx(as,{value:Za,onChange:t=>Qn(t.target.value),rows:3,disabled:Ft,placeholder:"You can leave blank, or tell AI what to focus on (e.g., the landmark n
18ame, correct location, main subject).",className:"resize-none"}),e.jsx("p",{className:"text-[11px] text-[var(--cs-text-tertiary)]",children:'Example: "This is in Belgium, not Germany. Focus on fire truck + Brussels street."'})]})}),e.jsxs(Am,{children:[e.jsx(Tm,{disabled:Ft,children:"Cancel"}),e.jsx(Dm,{onClick:()=>window._runRegen?.(),disabled:Ft,children:Ft?"Regenerating…":`Start (${Ya} credit)`})]})]})}),c?.id&&s&&e.jsx(nh,{open:xd,onClose:()=>La(!1),userId:c.id,sessionId:s,scan:fd,images:b,onConfirmed:t=>Ra(t),onDismissed:t=>Ia([{session_image_id:t,suggestions:[],note:null,status:"no_match"}])}),ve.map(t=>e.jsx(Im,{announcement:t,open:_===t.id,onOpenChange:a=>U(a?t.id:null),countdownLabel:t.duration_hours?ot(t.id).label:"",onCtaClick:()=>at(t),onDismiss:()=>ze(t.id)},t.id))]})};export{wg as ReviewEditPage,wg as default};

Line numbers count LF bytes from the start of the resource, as the search results do. Vendor segments are library code the classifier recognised; they are stored but not indexed. Bytes are shown as Latin1 characters, one per byte.