1import{x as Ot,r as V,d as C,j as e,a as Kt,l as Pe,E as Yt,R as Ke,u as Ht,S as Vt,W as et,C as qt,D as tt,A as Zt,ay as pe,az as Qt,aA as Xt,aB as Ft,X as Gt,K as Jt,N as er,v as At,k as tr,aw as rr,F as sr,aC as ar,aD as nr,al as we,au as ir,at as or,as as cr,ar as lr,aE as dr,aF as ur,c as pr}from"./index-BXEFfDgc.js";import{u as mr}from"./useWorkAutoMatch-CDlYw63b.js";import{C as Rt}from"./checkbox-C3h3YvfD.js";import{I as It}from"./input-CEeAXjY4.js";import{I as gr,P as Ne}from"./PipelineStepProgress-DDJF1MU-.js";import{f as hr}from"./formatDuration-CXJzqVCb.js";import{U as fr}from"./user-BZuMUIT9.js";import{S as Ge}from"./shield-check-BQUuSjOj.js";import{M as yr}from"./music-2-BxYdHUdo.js";import{C as xr}from"./chevron-right-BI_xym7O.js";import"./button-mPweo0jW.js";import{Y as br}from"./YouTubePlayer-DtdXEy57.js";import{U as $t}from"./upload-0XEy29Yt.js";import{C as kr}from"./circle-alert-BmEYkPR3.js";import{L as wr}from"./link-2-CsR08m3P.js";import{c as _r}from"./confetti.module-Cx83yTHA.js";import{T as Sr}from"./PlanGate-Dg7dGjWj.js";import{D as Ce,a as Fe}from"./DataSourceButton-Dsepjeua.js";import"./index-DQaL21jl.js";import"./index-CFzElpHS.js";import"./chevron-up-Oq-3zpL0.js";import"./chevron-down-D1-nO6kk.js";import"./play-ZOd-Brt1.js";import"./useIntegrationSource-BWS03SHV.js";import"./eye-off-Clqr_icD.js";import"./eye-BRIyTspb.js";/** 2 * @license lucide-react v0.475.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 jr=[["path",{d:"m16 13 5.223 3.482a.5.5 0 0 0 .777-.416V7.87a.5.5 0 0 0-.752-.432L16 10.5",key:"ftymec"}],["rect",{x:"2",y:"6",width:"14",height:"12",rx:"2",key:"158x01"}]],vt=Ot("Video",jr);function Je(w){return w?w.toLowerCase().replace(/[''`´]/g,"'").replace(/[^\w\s']/g," ").replace(/\s+/g," ").trim():""}function Ae(w,I){if(!w||!I)return!1;const $=Je(w);if(!$)return!1;const P=I.artists||[];for(const D of P)if(Je(D.name)===$)return!0;const U=I.featured_artists||[];for(const D of U)if(Je(D)===$)return!0;const v=(I.name||"").toLowerCase();return!!(v.includes(`feat. ${$}`)||v.includes(`feat ${$}`)||v.includes(`ft. ${$}`)||v.includes(`ft ${$}`)||v.includes(`featuring ${$}`)||v.includes(`with ${$}`))}function Cr({album:w,selectedTrackIds:I,onSelectionChange:$,onBack:P,searchedArtistName:U}){var z,ne,Z;const[v,D]=V.useState([]),[N,B]=V.useState(!0);V.useEffect(()=>{u()},[w.id]);const u=async()=>{var de,G;B(!0);let g=[],Q=0;for(;;){const H=await C.functions.invoke("spotifyImport",{action:"get_album_tracks",album_id:w.id,batch_offset:Q,batch_limit:50});if(g=g.concat(((de=H.data)==null?void 0:de.tracks)||[]),!((G=H.data)!=null&&G.has_more))break;Q=H.data.next_offset}if(D(g),!I&&U){const H=g.filter(i=>Ae(U,i)).map(i=>i.id);H.length===0||H.length===g.length?$(g.map(i=>i.id)):$(H)}else I||$(g.map(H=>H.id));B(!1)},q=new Set(I||v.map(g=>g.id)),Y=v.length>0&&v.every(g=>q.has(g.id)),ae=U?v.filter(g=>Ae(U,g)).length:v.length,ee=g=>{const Q=new Set(q);Q.has(g)?Q.delete(g):Q.add(g),$([...Q])},me=()=>{$(Y?[]:v.map(g=>g.id))},h=()=>{const g=v.filter(Q=>Ae(U,Q)).map(Q=>Q.id);$(g)},F=g=>hr(g,"");return e.jsxs("div",{className:"flex flex-col h-full",children:[e.jsxs("div",{style:{display:"flex",alignItems:"center",gap:12,padding:"12px 14px",background:"rgba(124,58,237,0.06)",border:"1px solid rgba(124,58,237,0.2)",borderRadius:12,marginBottom:8},children:[e.jsxs("button",{onClick:P,style:{padding:"5px 10px",borderRadius:8,border:"1px solid rgba(255,255,255,0.15)",background:"transparent",color:"#B3B3B3",cursor:"pointer",display:"flex",alignItems:"center",gap:4,fontSize:12,fontWeight:600},children:[e.jsx(Kt,{style:{width:14,height:14}})," Back"]}),((ne=(z=w.images)==null?void 0:z[0])==null?void 0:ne.url)&&e.jsx("img",{src:w.images[0].url,alt:w.name,style:{width:48,height:48,borderRadius:8,objectFit:"cover"}}),e.jsxs("div",{style:{flex:1,minWidth:0},children:[e.jsx("p",{style:{fontWeight:600,fontSize:14,color:"#FFFFFF",margin:0},className:"truncate",children:w.name}),e.jsxs("p",{style:{fontSize:12,color:"#666",margin:"2px 0 0"},children:[w.total_tracks," tracks ⢠",(Z=w.release_date)==null?void 0:Z.split("-")[0]]})]})]}),N?e.jsxs("div",{className:"flex items-center justify-center py-12",children:[e.jsx(Pe,{className:"w-5 h-5 animate-spin text-purple-400"}),e.jsx("span",{className:"ml-2 text-sm",style:{color:"#666"},children:"Loading tracks..."})]}):e.jsxs(e.Fragment,{children:[e.jsxs("div",{style:{display:"flex",alignItems:"center",justifyContent:"space-between",padding:"6px 8px",marginBottom:4,flexWrap:"wrap",gap:6}
6,children:[e.jsxs("span",{style:{fontSize:12,color:"#9CA3AF",fontWeight:600},children:[q.size," of ",v.length," tracks selected",U&&ae<v.length&&e.jsxs("span",{style:{marginLeft:8,color:"#A78BFA"},children:["· ",ae," matching"]})]}),e.jsxs("div",{style:{display:"flex",gap:4},children:[U&&ae>0&&ae<v.length&&e.jsx("button",{onClick:h,style:{fontSize:12,fontWeight:600,color:"#A78BFA",background:"none",border:"none",cursor:"pointer",padding:"4px 8px",borderRadius:6},onMouseEnter:g=>g.currentTarget.style.background="rgba(124,58,237,0.1)",onMouseLeave:g=>g.currentTarget.style.background="none",children:"Select Matching"}),e.jsx("button",{onClick:me,style:{fontSize:12,fontWeight:600,color:"#A78BFA",background:"none",border:"none",cursor:"pointer",padding:"4px 8px",borderRadius:6},onMouseEnter:g=>g.currentTarget.style.background="rgba(124,58,237,0.1)",onMouseLeave:g=>g.currentTarget.style.background="none",children:Y?"Deselect All":"Select All"})]})]}),e.jsx("div",{className:"flex-1 overflow-y-auto space-y-1",children:v.map((g,Q)=>{var H;const de=q.has(g.id),G=U&&Ae(U,g);return e.jsxs("div",{onClick:()=>ee(g.id),style:{display:"flex",alignItems:"center",gap:10,padding:"8px 12px",borderRadius:8,cursor:"pointer",background:de?"rgba(124,58,237,0.06)":"transparent",border:`1px solid ${de?"rgba(124,58,237,0.2)":"transparent"}`,transition:"all 0.1s"},children:[e.jsx(Rt,{checked:de,onCheckedChange:()=>ee(g.id),onClick:i=>i.stopPropagation(),className:"border-white/40 data-[state=checked]:bg-emerald-500 data-[state=checked]:border-emerald-500 hover:border-white/60"}),e.jsx("span",{style:{fontSize:12,color:"#666",width:20,textAlign:"right",fontFamily:"monospace",flexShrink:0},children:g.track_number||Q+1}),e.jsxs("div",{style:{flex:1,minWidth:0},children:[e.jsxs("div",{style:{display:"flex",alignItems:"center",gap:6},children:[e.jsx("p",{style:{fontSize:13,fontWeight:500,color:de?"#FFFFFF":"#B3B3B3",margin:0},className:"truncate",children:g.name}),G&&e.jsxs("span",{style:{display:"inline-flex",alignItems:"center",gap:3,fontSize:10,fontWeight:700,color:"#4ADE80",background:"rgba(74,222,128,0.12)",padding:"1px 7px",borderRadius:999,whiteSpace:"nowrap",flexShrink:0},children:[e.jsx(fr,{style:{width:9,height:9}})," Matched"]})]}),e.jsx("p",{style:{fontSize:11,color:"#666",margin:0},className:"truncate",children:(H=g.artists)==null?void 0:H.map(i=>i.name).join(", ")})]}),e.jsx("span",{style:{fontSize:11,color:"#666",flexShrink:0},children:F(g.duration_ms)})]},g.id)})})]})]})}function Fr({onSuccess:w}){var lt;Yt();const[I,$]=V.useState(""),[P,U]=V.useState(!1),[v,D]=V.useState([]),[N,B]=V.useState(null),u=Ke.useRef(null),q=Ke.useRef(!1),Y=Ke.useRef(null),ae=Ke.useRef(0),{isImporting:ee,setIsImporting:me,importStatus:h,setImportStatus:F,importProgress:z,setImportProgress:ne,importDone:Z,setImportDone:g,importErrors:Q,setImportErrors:de,cancelledRef:G,importedSpotifyIdsRef:H,mlcCheckStatus:i,setMlcCheckStatus:W,mlcCheckResults:T,setMlcCheckResults:J,mlcCheckRunRef:fe,bpmEnrichStatus:ce,setBpmEnrichStatus:ye,bpmEnrichResults:be,setBpmEnrichResults:re,bpmEnrichRunRef:rt,lyricsStatus:Rr,setLyricsStatus:Ir,lyricsResults:$r,setLyricsResults:Tr,lyricsRunRef:Mr,scEnrichStatus:Ee,setScEnrichStatus:xe,scEnrichResults:ke,setScEnrichResults:ge,scEnrichRunRef:ve,sxIsrcStatus:Be,setSxIsrcStatus:ze,sxIsrcResults:Ue,setSxIsrcResults:Re,sxIsrcRunRef:Ye,proScanStatus:Ie,setProScanStatus:Le,proScanResults:He,setProScanResults:Ve,proScanRunRef:qe,resetState:Tt}=Ht(),$e=()=>{Tt(),u.current=null,ae.current+=1},_e=async(r=[])=>{if(!r.length)return[];const l=await C.auth.me(),o=[...new Set(r.filter(Boolean))],s=[],t=new Set;for(let n=0;n<o.length;n+=100){const a=o.slice(n,n+100),d=await C.entities.Track.filter({created_by:l.email,spotify_id:{$in:a}},"-created_date",200);for(const j of d)t.has(j.id)||(s.push(j),t.add(j.id))}return s},Mt=async r=>{var o,s;if(rt.current||r.length===0)return;rt.current=!0,ye("running");const l=Date.now();re({updated:0,total:0,current:0,startedAt:l});try{let t=[];for(let y=0;y<3&&(t=await _e(r),!(t.length>0));y++)await new Promise(c=>setTimeout(c,3e3));const n=t.length;let a=0;const d=[];for(let y=0;y<t.length;y++){const c=t[y];if(re({updated:a,total:n,current:y+1,trackName:c.title,startedAt:l}),c.bpm_manual){a++;continue}if(c.bpm&&c.bpm>0){a++;continue}d.push(c.id)}if(d.length>0){const y=n-d.length;re({updated:a,total:n,current:y,trackName:`BPM lookup for ${d.length} tracksâ¦`,startedAt:l});const c=25;let _=0;for(let E=0;E<d.length;E+=c){const x=d.slice(E,E+c);try{const b=await C.functions.invoke("enrichBPM",{track_ids:x});(o=b.data)!=null&&o.new_enriched&&(a+=b.data.new_enriched),(s=b.data)!=null&&s.already_had_bpm&&(a+=b.data.already_had_bpm)}catch{}_+=x.length,re({updated:a,total:n,current:y+_,trackName:`BPM lookup (${_}/${d.length})â¦`,startedAt:l})}}const f=(await _e(r)).filter(y=>y.bpm&&y.bpm>0).length,k=Math.max(a,f);re({updated:k,total:n,current:n}),ye("done"),pe(u.current,"bpm",{status:"done",updated:k,total:n}
6).catch(()=>{})}catch(t){console.error("Auto BPM enrich failed:",t),ye("error"),pe(u.current,"bpm",{status:"error"}).catch(()=>{})}},st=async(r=[])=>{var o,s,t;if(Ye.current||r.length===0)return;Ye.current=!0,ze("running");const l=Date.now();Re({current:0,total:0,found:0,startedAt:l});try{let n=[];for(let c=0;c<3&&(n=await _e(r),!(n.length>0));c++)await new Promise(_=>setTimeout(_,3e3));const a=n.filter(c=>c.isrc);if(a.length===0){ze("skipped"),Re({found:0,total:0,reason:"No tracks with ISRC"});return}const d=a.length,j=20;let f=0,k=0,y=0;for(let c=0;c<a.length;c+=j){const _=a.slice(c,c+j);Re({current:y,total:d,found:f,notFound:k,trackName:((o=_[0])==null?void 0:o.title)||"",startedAt:l});try{const x=((s=(await C.functions.invoke("soundexchangeVerify",{isrcs:_.map(b=>b.isrc),update_tracks:!0})).data)==null?void 0:s.results)||[];f+=x.filter(b=>b.status==="registered").length,k+=x.filter(b=>b.status==="not_found").length}catch{}y+=_.length,Re({current:y,total:d,found:f,notFound:k,trackName:((t=_[_.length-1])==null?void 0:t.title)||"",startedAt:l})}Re({found:f,notFound:k,total:d}),ze("done")}catch(n){console.error("[SX ISRC Pipeline] Error:",n),ze("error")}},at=async()=>{if(qe.current)return;qe.current=!0,Le("running"),Ve(null);const r=u.current,l=ae.current,o=()=>u.current===r&&ae.current===l;try{const t=(await C.functions.invoke("ipiDiscovery",{trigger:"post_import"})).data||{};if(t.needs_ipi)o()&&(Le("skipped"),Ve({reason:"Add your writer IPI in Settings to check PRO registrations."})),pe(r,"pro",{status:"identity_required"}).catch(()=>{});else{o()&&(Le(t.done?"done":"queued"),Ve({lookupId:t.lookupId,queued:!t.done})),pe(r,"pro",{status:t.done?"done":"queued",lookup_id:t.lookupId}).catch(()=>{});try{await C.functions.invoke("radarScan",{reconcileOnly:!0})}catch{}}}catch(s){console.error("[PRO Pipeline] Error:",s),o()&&Le("error"),pe(r,"pro",{status:"error"}).catch(()=>{})}},Nt=async(r,l)=>{var s,t;if(ve.current)return;ve.current=!0,xe("running");const o=Date.now();ge({current:0,total:0,trackName:"Waiting for MLC resultsâ¦",startedAt:o});try{let a=0,d=0,j=0,f=0;for(;;){if(r.length===0){if(l())break;await new Promise(y=>setTimeout(y,1500));continue}const k=r.splice(0,3);ge({current:f,total:f+k.length+r.length,trackName:"Enriching creditsâ¦",startedAt:o,enriched:a,notFound:j,failed:d});try{const c=((t=(s=(await C.functions.invoke("spotscraperApi",{action:"batch_enrich",track_ids:k})).data)==null?void 0:s.results)==null?void 0:t.details)||[];a+=c.filter(_=>_.status==="enriched").length,j+=c.filter(_=>_.status==="no_spotify_id_or_isrc"||_.status==="isrc_not_found_on_spotify").length,d+=c.filter(_=>_.status==="error"||_.status==="not_found_in_db").length}catch{d+=k.length}f+=k.length,ge({current:f,total:f+r.length,trackName:"",startedAt:o,enriched:a,notFound:j,failed:d})}if(f===0){xe("skipped"),ge({enriched:0,total:0,reason:"No tracks with missing/partial MLC status"});return}ge({enriched:a,failed:d,notFound:j,total:f}),xe(a===0&&d===f?"error":"done"),pe(u.current,"credits",{status:a===0&&d===f?"error":"done",enriched:a,not_found:j,failed:d,total:f}).catch(()=>{})}catch(n){console.error("[SpotScraper Streaming] Fatal error:",n),xe("error"),pe(u.current,"credits",{status:"error"}).catch(()=>{})}},Pt=async(r=[],l=null)=>{var s,t,n,a;if(ve.current||r.length===0)return;ve.current=!0,xe("running");const o=Date.now();ge({current:0,total:0,trackName:"Loading tracksâ¦",startedAt:o});try{let d=[];for(let x=0;x<5&&(d=await _e(r),!(d.length>0));x++)console.log(`[SpotScraper Pipeline] Track lookup attempt ${x+1} returned 0, retrying in 3s...`),await new Promise(b=>setTimeout(b,3e3));let j;if(l){const x=new Set(l);j=d.filter(b=>x.has(b.id)&&!b.spotscraper_enriched),console.log(`[SpotScraper Pipeline] Using ${l.length} pre-filtered MLC track IDs, ${j.length} eligible after dedup`)}else j=d.filter(x=>x.isrc&&(x.mlc_status==="missing"||x.mlc_status==="partial")&&!x.spotscraper_enriched),console.log(`[SpotScraper Pipeline] ${d.length} imported tracks, ${j.length} eligible (missing/partial MLC from DB)`);if(j.length===0){xe("skipped"),ge({enriched:0,total:0,reason:"No tracks with missing/partial MLC status"});return}const f=j.length,k=3;let y=0,c=0,_=0,E=0;for(let x=0;x<j.length;x+=k){const b=j.slice(x,x+k),te=b.map(M=>M.id);console.log(`[SpotScraper Pipeline] Sending chunk ${Math.floor(x/k)+1}/${Math.ceil(f/k)}: ${te.length} tracks`,te),ge({current:E,total:f,trackName:((s=b[0])==null?void 0:s.title)||"",startedAt:o,enriched:y,notFound:_,failed:c});try{const A=((n=(t=(await C.functions.invoke("spotscraperApi",{action:"batch_enrich",track_ids:te})).data)==null?void 0:t.results)==null?void 0:n.details)||[],L=A.filter(O=>O.status==="enriched").length,X=A.filter(O=>O.status==="no_spotify_id_or_isrc"||O.status==="isrc_not_found_on_spotify").length,le=A.filter(O=>O.status==="error"||O.status==="not_found_in_db").length;y+=L,_+=X,c+=le,console.log(`[SpotScraper Pipeline] Chunk result: ${L} enriched, ${X}
6 not found, ${le} failed`);for(const O of A)O.status!=="enriched"&&console.log(`[SpotScraper Pipeline] Track ${O.track_id} (${O.title||"unknown"}): ${O.status}${O.error?" - "+O.error:""}`)}catch(M){console.error("[SpotScraper Pipeline] Chunk failed:",M.message),c+=b.length}E+=b.length,ge({current:E,total:f,trackName:((a=b[b.length-1])==null?void 0:a.title)||"",startedAt:o,enriched:y,notFound:_,failed:c})}console.log(`[SpotScraper Pipeline] Complete: ${y}/${f} enriched, ${_} not found, ${c} failed`),y===0&&f>0&&console.warn(`[SpotScraper Pipeline] WARNING: Zero tracks enriched out of ${f} attempted`),ge({enriched:y,failed:c,notFound:_,total:f}),xe(y===0&&c===f?"error":"done"),pe(u.current,"credits",{status:y===0&&c===f?"error":"done",enriched:y,not_found:_,failed:c,total:f}).catch(()=>{})}catch(d){console.error("[SpotScraper Pipeline] Fatal error:",d),xe("error"),pe(u.current,"credits",{status:"error"}).catch(()=>{})}},nt=async(r=[])=>{var n,a,d;if(fe.current)return;fe.current=!0,W("running");const l=Date.now();J({current:0,total:0,trackName:"Loading tracksâ¦",startedAt:l});let o=!1;const s=[];let t=null;try{let j=[];for(let A=0;A<5&&(j=await _e(r),!(j.length>0));A++)console.log(`[MLC Pipeline] Track lookup attempt ${A+1} returned 0, retrying in 3s...`),await new Promise(L=>setTimeout(L,3e3));const f=j.filter(A=>A.isrc).sort((A,L)=>(L.spotify_popularity??-1)-(A.spotify_popularity??-1));if(console.log(`[MLC Pipeline] Found ${j.length} imported tracks, ${f.length} with ISRC`),f.length===0){W("error"),J({checked:0,registered:0,partial:0,missing:0});return}const k=f.length,y=40;let c=0,_=0,E=0,x=0,b=0;const te=[];t=Nt(s,()=>o);for(let A=0;A<f.length;A+=y){const L=f.slice(A,A+y),X=L.map(O=>O.id);console.log(`[MLC Pipeline] Sending chunk ${A/y+1}: track_ids=`,X),J({current:x,total:k,trackName:((n=L[0])==null?void 0:n.title)||"",startedAt:l,registered:c,partial:_,missing:E,failed:b});let le=0;try{const De=((a=(await C.functions.invoke("mlcApi",{action:"batch_check",track_ids:X})).data)==null?void 0:a.results)||[];for(const ue of De)ue.status==="registered"?(c+=1,le+=1):ue.status==="partial"?(_+=1,le+=1,te.push(ue.track_id),s.push(ue.track_id)):(ue.status==="missing"||ue.status==="not_registered")&&(E+=1,le+=1,te.push(ue.track_id),s.push(ue.track_id))}catch{}b+=Math.max(0,L.length-le),x+=L.length,J({current:x,total:k,trackName:((d=L[L.length-1])==null?void 0:d.title)||"",startedAt:l,registered:c,partial:_,missing:E,failed:b})}console.log(`[MLC Pipeline] Complete: ${c} registered, ${_} partial, ${E} missing. ${te.length} tracks for SpotScraper.`),J({checked:x,registered:c,partial:_,missing:E,failed:b}),W(b===k?"error":"done"),pe(u.current,"mlc",{status:b===k?"error":"done",registered:c,partial:_,missing:E,failed:b}).catch(()=>{}),o=!0,await t}catch(j){console.error("Auto MLC check failed:",j),W("error"),pe(u.current,"mlc",{status:"error"}).catch(()=>{}),o=!0,t&&await t.catch(()=>{})}},it=async()=>{var r,l,o,s,t,n,a,d,j,f,k,y,c,_;if(I.trim()){U(!0),D([]),B(null),$e();try{if(I.trim().includes("music.apple.com/")){F({type:"success",message:"Fetching from Apple Music..."});const x=await C.functions.invoke("appleImport",{url:I.trim()});if((r=x.data)!=null&&r.error)throw new Error(x.data.error);const b=((l=x.data)==null?void 0:l.tracks)||[];b.length>0?(F({type:"success",message:`Found: ${x.data.name||"Apple Music"} - ${b.length} tracks. Starting import...`}),await Se(b,null,"apple_music")):F({type:"error",message:"No importable tracks found at that Apple Music link."}),U(!1);return}if(I.trim().includes("spotify.com/")||I.trim().startsWith("spotify:")){const x=await C.functions.invoke("spotifyImport",{action:"parse_url",url:I});if((o=x.data)!=null&&o.error)throw new Error(x.data.error);const{type:b,id:te}=x.data;if(b==="artist"){const M=await C.functions.invoke("spotifyImport",{action:"get_artist",artist_id:te});if((s=M.data)!=null&&s.error)throw new Error(M.data.error);if((t=M.data)!=null&&t.artist){const A=await C.functions.invoke("spotifyImport",{action:"get_artist_albums",artist_id:te});if((n=A.data)!=null&&n.error)throw new Error(A.data.error);const L=A.data.albums||[];B({artist:M.data.artist,albums:L,totalTracks:L.reduce((X,le)=>X+(le.total_tracks||0),0)})}}else if(b==="album"){F({type:"success",message:"Fetching album tracks..."});const{tracks:M,album:A}=await Ze(te);M.length>0?(F({type:"success",message:`Found: ${(A==null?void 0:A.name)||"Album"} - ${M.length} tracks. Starting import...`}
6),await Se(M,A)):F({type:"error",message:"No tracks found in this album. It may be unavailable in your region."})}else if(b==="playlist"){F({type:"success",message:"Fetching playlist tracks..."});const M=[];let A=0,L="Playlist";for(;;){const X=await C.functions.invoke("spotifyImport",{action:"get_playlist_tracks",playlist_id:te,batch_offset:A,batch_limit:50});if((a=X.data)!=null&&a.error)throw new Error(X.data.error);if(M.push(...X.data.tracks||[]),L=((d=X.data.playlist)==null?void 0:d.name)||L,F({type:"success",message:`Fetching playlist tracks... ${M.length} of ${((j=X.data.playlist)==null?void 0:j.total_tracks)||M.length}`}),!X.data.has_more)break;A=X.data.next_offset}M.length>0?(F({type:"success",message:`Found: ${L} - ${M.length} tracks. Starting import...`}),await Se(M)):F({type:"error",message:"No tracks found in this playlist. It may be private or unavailable."})}else if(b==="track"){F({type:"success",message:"Fetching track..."});const M=await C.functions.invoke("spotifyImport",{action:"get_track",track_id:te});if((f=M.data)!=null&&f.error)throw new Error(M.data.error);if((k=M.data)!=null&&k.track){const A=M.data.track;F({type:"success",message:`Found: ${A.name} by ${(c=(y=A.artists)==null?void 0:y[0])==null?void 0:c.name}. Importing...`}),await Se([A])}else F({type:"error",message:"Track not found or unavailable."})}}else{const x=await C.functions.invoke("spotifyImport",{action:"search_artists",query:I});if((_=x.data)!=null&&_.error)throw new Error(x.data.error);D(x.data.artists||[])}}catch(E){console.error("Spotify search failed:",E),F({type:"error",message:`Search failed: ${E.message}`})}U(!1)}},Et=async r=>{var l;U(!0),D([]),$e();try{const o=await C.functions.invoke("spotifyImport",{action:"get_artist_albums",artist_id:r.id});if((l=o.data)!=null&&l.error)throw new Error(o.data.error);const s=o.data.albums||[];B({artist:r,albums:s,totalTracks:s.reduce((t,n)=>t+(n.total_tracks||0),0)})}catch(o){F({type:"error",message:`Preview failed: ${o.message}`})}U(!1)},Bt=async()=>{const r=new Set,l=new Map,o=await C.auth.me();let s=0;const t=1e4;for(;;){const n=await C.entities.Track.list("-created_date",t,s);for(const a of n)if(a.created_by===o.email&&(a.spotify_id&&r.add(a.spotify_id),a.isrc)){const d=a.isrc.toUpperCase().trim();l.has(d)||l.set(d,a)}if(n.length<t)break;s+=t}return{spotifyCache:r,isrcMap:l,me:o}},Se=async(r,l,o="spotify")=>{var y,c,_,E,x,b,te,M,A,L,X,le,O,De,ue,dt,ut,pt,mt,gt,ht,ft,yt,xt,bt;if(q.current)return;if(q.current=!0,me(!0),G.current=!1,Y.current){const se=Y.current;F({type:"success",message:"Finishing previous import..."}),await se.catch(()=>{}),Y.current===se&&(Y.current=null)}let s=0,t=0,n=0,a=0;const d=[],j=25,f=[],k=[];try{const se=await Qt({source:"spotify",searchQuery:I||((y=N==null?void 0:N.artist)==null?void 0:y.name)||""});u.current=(se==null?void 0:se.id)||null}catch{u.current=null}try{F({type:"success",message:"Checking existing catalog..."});const{spotifyCache:se,isrcMap:We,me:kt}=await Bt(),Lt=se.size>0||We.size>0,Qe=r.map(p=>{var S,K,R,m,ie,oe,he,Me;return l?{...p,album:{...p.album,upc:((S=p.album)==null?void 0:S.upc)||l.upc,name:((K=p.album)==null?void 0:K.name)||l.name,release_date:((R=p.album)==null?void 0:R.release_date)||l.release_date,images:(ie=(m=p.album)==null?void 0:m.images)!=null&&ie.length?p.album.images:l.images,label:((oe=p.album)==null?void 0:oe.label)||l.label,artists:((he=p.album)==null?void 0:he.artists)||l.artists,album_type:((Me=p.album)==null?void 0:Me.album_type)||l.album_type}}:p}),Te=[];for(const p of Qe){if(p.id&&se.has(p.id)){t++;continue}const S=p.isrc?p.isrc.toUpperCase().trim():null;if(S&&We.has(S)){const K=We.get(S),R=(c=p.album)==null?void 0:c.upc;K.id&&K.id!=="__pending__"&&R&&R!==K.upc&&(f.push({track_id:K.id,isrc:S,upc:R,release_title:((_=p.album)==null?void 0:_.name)||"",release_artist:((x=(E=p.artists)==null?void 0:E[0])==null?void 0:x.name)||((M=(te=(b=p.album)==null?void 0:b.artists)==null?void 0:te[0])==null?void 0:M.name)||"",label:((A=p.album)==null?void 0:A.label)||"",release_date:((L=p.album)==null?void 0:L.release_date)||"",cover_url:((O=(le=(X=p.album)==null?void 0:X.images)==null?void 0:le[0])==null?void 0:O.url)||"",track_number:p.track_number||null,duration_ms:p.duration_ms||null,spotify_album_id:((De=p.album)==null?void 0:De.id)||""}),a++),t++;continue}Te.push(p),p.id&&(se.add(p.id),k.push(p.id)),S&&We.set(S,{id:"__pending__",upc:(ue=p.album)==null?void 0:ue.upc})}const je=Qe.length;ne({current:t,total:je,imported:0,deduped:t,errors:0}),t>0&&F({type:"success",message:`Skipped ${t} already imported (${a} ISRC-merged). Importing ${Te.length} new tracks...`});for(let p=0;p<Te.length&&!G.current;p+=j){const S=Te.slice(p,p+j),K=S.map(m=>{var ie,oe,he,Me,wt,_t,St,jt;return{title:m.name,spotify_id:m.id,isrc:m.isrc?String(m.isrc).trim().toUpperCase():null,upc:(ie=m.album)==null?void 0:ie.upc,duration_ms:m.duration_ms,release_title:(oe=m.album)==null?void 0:oe.name,release_date:(he=m.album)==null?void 0:he.release_date,artists:(Me=m.artists)==null?void 0:Me.map(Ct=>({name:Ct.name,spotify_id:Ct.id})),cover_art_url:(St=(_t=(wt=m.album)==null?void 0:wt.images)==null?void 0:_t[0])==null?void 0:St.url,preview_url:m.preview_url,explicit:m.explicit,label:(jt=m.album)==null?void 0:jt.label,spotify_popularity:m.popularity||0,bpm:m.bpm||null,bpm_source:m.bpm?"spotify":null,track_number:m.track_number||1,...o==="spotify"?{spotify_last_synced:new Date().toISOString()}:{},source:o,appears_on_count:1}});try{await C.entities.Track.bulkCreate(K),s+=S.length}catch{for(let ie=0;ie<S.length;ie++)try{const oe=K[ie];let he=[];if(oe.isrc?he=await C.entities.Track.filter({isrc:oe.isrc,created_by:kt.email}):oe.spotify_id&&(he=await C.entities.Track.filter({spotify_id:oe.spotify_id,created_by:kt.email})),he.length>0){t++;continue}await C.entities.Track.create(oe),s++}catch(oe){d.push({trackName:S[ie].name||"Unknown",artist:((ut=(dt=S[ie].artists)==null?void 0:dt[0])==null?void 0:ut.name)||"",isrc:S[ie].isrc||"",message:oe.message}),n++}}const R=t+s+n;ne({current:R,total:je,imported:s,deduped:t,errors:n}),F({type:"success",message:`Importing... ${R}/${je} (${s} new, ${t} already in catalog)`})}if(f.length>0){const p=await C.entities.TrackAppearance.list("-created_date",1e4),S=new Set(p.map(R=>`${R.isrc}__${R.upc}`)),K=f.filter(R=>!S.has(`${R.isrc}__${R.upc}`));for(let R=0;R<K.length;R+=25)try{await C.entities.TrackAppearance.bulkCreate(K.slice(R,R+25))}catch{}}if(s>0){const p=await _e(k),S=await C.entities.TrackAppearance.list("-created_date",1e4),K=new Set(S.map(m=>`${m.isrc}__${m.upc}`)),R=[];for(const m of p)m.isrc&&m.upc&&!K.has(`${m.isrc.toUpperCase().trim()}__${m.upc}`)&&R.push({track_id:m.id,isrc:m.isrc.toUpperCase().trim(),upc:m.upc,release_title:m.release_title||"",release_artist:((mt=(pt=m.artists)==null?void 0:pt[0])==null?void 0:mt.name)||"",label:m.label||"",release_date:m.release_date||"",cover_url:m.cover_art_url||"",track_number:m.track_number||null,duration_ms:m.duration_ms||null});for(let m=0;m<R.length;m+=25)try{await C.entities.TrackAppearance.bulkCreate(R.slice(m,m+25))}catch{}}const Oe=new Map;for(const p of[...Te,...Qe.filter(S=>{const K=S.isrc?S.isrc.toUpperCase().trim():null;return K&&f.some(R=>{var m;return R.isrc===K&&R.upc===((m=S.album)==null?void 0:m.upc)})})]){const S=p.album;S!=null&&S.upc&&!Oe.has(S.upc)&&Oe.set(S.upc,{title:S.name||"",upc:S.upc,spotify_id:S.id||"",artist:((ht=(gt=S.artists)==null?void 0:gt[0])==null?void 0:ht.name)||((yt=(ft=p.artists)==null?void 0:ft[0])==null?void 0:yt.name)||"",cover_url:((bt=(xt=S.images)==null?void 0:xt[0])==null?void 0:bt.url)||"",label:S.label||"",release_date:S.release_date||"",release_type:S.album_type||"album",total_tracks:S.total_tracks||null,source:"spotify"})}if(Oe.size>0){const p=await C.entities.Release.list("-created_date",5e3),S=new Set(p.map(R=>
6R.upc).filter(Boolean)),K=[...Oe.values()].filter(R=>!S.has(R.upc));for(let R=0;R<K.length;R+=25)try{await C.entities.Release.bulkCreate(K.slice(R,R+25))}catch{}}s>0&&C.analytics.track({eventName:"track_imported",properties:{import_source:"spotify",count:s}});const Dt=G.current?`Cancelled. Imported ${s} new tracks, ${t} already in catalog.`:`â Done! ${s} new tracks imported.${t>0?` ${t} already in catalog.`:""}${n>0?` ${n} errors.`:""}`;if(F({type:G.current?"error":"success",message:Dt}),ne({current:je,total:je,imported:s,deduped:t,errors:n}),de(d),g(!0),H.current=k,s>0)try{localStorage.setItem("works_sort",Lt?"created_date:desc":"spotify_popularity:desc")}catch{}Xt(u.current,{totalTracks:je,newTracks:s,existingTracks:t,failedTracks:n,errors:d.map(p=>`${p.trackName}: ${p.message}`)}).catch(()=>{});let Xe=Promise.resolve();s>0&&!G.current&&(await Promise.all([nt(k),Mt(k),st(k)]),Xe=at(),Y.current=Xe);const Wt=u.current;Xe.catch(()=>{}).then(()=>Ft(Wt,{status:n>0?"partial":"success"}).catch(()=>{}))}catch(se){F({type:"error",message:`Import error: ${se.message}. ${s} tracks were imported before the error.`}),g(!0),Ft(u.current,{status:"failed",errors:[se.message]}).catch(()=>{})}q.current=!1,me(!1)},Ze=async r=>{var t,n,a,d,j,f;let l=[],o=0,s=null;for(;!G.current;){let k;for(let c=0;c<3;c++)try{k=await C.functions.invoke("spotifyImport",{action:"get_album_tracks",album_id:r,batch_offset:o,batch_limit:20});break}catch(_){if(c===2)throw _;await new Promise(E=>setTimeout(E,Math.min(1e3*Math.pow(2,c),8e3)))}if((t=k.data)!=null&&t.error)throw new Error(k.data.error);const y=((n=k.data)==null?void 0:n.tracks)||[];if(!s&&((a=k.data)!=null&&a.album)&&(s=k.data.album),!((d=k.data)!=null&&d.album)&&y.length===0||(l=l.concat(y),!((j=k.data)!=null&&j.has_more)||y.length===0))break;o=k.data.next_offset,await new Promise(c=>setTimeout(c,100))}return{tracks:l,album:s||((f=l[0])==null?void 0:f.album)||null}},zt=async()=>{var l;if(!N)return;const r=((l=N.artist)==null?void 0:l.name)||"";me(!0),$e();try{let o=[];for(let s=0;s<N.albums.length&&!G.current;s++){const t=N.albums[s];F({type:"success",message:`Fetching album ${s+1} of ${N.albums.length}: ${t.name}...`});let n=null;for(let a=0;a<5;a++)try{n=await Ze(t.id);break}catch{a===4?console.error(`Skipping album ${t.name}`):await new Promise(j=>setTimeout(j,2e3*Math.pow(2,a)))}if(n)if(r){const a=n.tracks.filter(d=>Ae(r,d));o=o.concat(a.length===0||a.length===n.tracks.length?n.tracks:a)}else o=o.concat(n.tracks);s<N.albums.length-1&&await new Promise(a=>setTimeout(a,50))}F({type:"success",message:`Fetched ${o.length} tracks. Starting import...`}),await Se(o)}catch(o){F({type:"error",message:`Import failed: ${o.message}`}),me(!1)}},Ut=()=>{z&&z.imported>0&&(C.functions.invoke("syncBMIToTracks",{}).catch(()=>{}),C.functions.invoke("syncSXToTracks",{}).catch(()=>{}),w&&w(`Imported ${z.imported} new tracks`)),$(""),D([]),B(null),$e()},ot=()=>{$(""),D([]),B(null),$e()},ct=I.trim().includes("spotify.com/")||I.trim().startsWith("spotify:");return e.jsxs("div",{children:[e.jsxs("div",{className:"flex flex-col sm:flex-row gap-3",children:[e.jsx(It,{value:I,onChange:r=>$(r.target.value),onKeyDown:r=>r.key==="Enter"&&!P&&!ee&&it(),placeholder:"Artist name or Spotify / Apple Music URL (playlist, album, or track)...",className:"flex-1 h-12 text-base",disabled:ee}),e.jsxs("button",{onClick:it,disabled:!I.trim()||P||ee,className:"rc-btn-primary h-12 px-6 flex items-center justify-center gap-2 disabled:opacity-40",children:[P?e.jsx(Pe,{className:"w-4 h-4 animate-spin"}):e.jsx(Vt,{className:"w-4 h-4"}),ct?"Import":"Search"]})]}),P&&e.jsx("div",{className:"flex items-center justify-center py-8",children:e.jsx(et,{size:"md",text:"Searching Spotify..."})}),z&&e.jsxs("div",{className:"mt-4 space-y-2",style:{background:"#1A1A1A",border:"1px solid rgba(255,255,255,0.08)",borderRadius:12,padding:16},children:[e.jsxs("div",{className:"flex items-center justify-between text-sm",children:[e.jsx("span",{style:{color:(h==null?void 0:h.type)==="error"?"#DC2626":"#A78BFA",fontWeight:600,fontSize:13},children:h==null?void 0:h.message}
6),e.jsxs("span",{style:{color:"#9CA3AF",fontVariantNumeric:"tabular-nums",fontSize:13},children:[z.current,"/",z.total]})]}),e.jsx("div",{style:{height:8,background:"rgba(255,255,255,0.06)",borderRadius:999,overflow:"hidden"},children:e.jsx("div",{style:{height:"100%",borderRadius:999,transition:"width 0.3s ease",background:Z?"#10B981":"#7C3AED",width:`${z.total>0?z.current/z.total*100:0}%`}})}),e.jsxs("div",{className:"flex items-center gap-4 text-xs",children:[e.jsxs("span",{style:{color:"#10B981",fontWeight:600},children:[z.imported," new"]}),e.jsxs("span",{style:{color:"#2563EB",fontWeight:600},children:[z.deduped," existing"]}),z.errors>0&&e.jsxs("span",{style:{color:"#DC2626",fontWeight:600},children:[z.errors," errors"]})]}),Z&&Q.length>0&&e.jsx(gr,{errors:Q}),Z&&e.jsx(Ne,{status:i,icon:Ge,label:"Checking for Missing Royalties",progress:i==="running"?T:null,doneMessage:T?`Missing Royalties: ${T.registered||0} registered, ${T.partial||0} partial, ${T.missing||0} not found${T.failed?`, ${T.failed} failed`:""}`:"Missing royalties check complete",errorMessage:"Missing royalties check could not finish.",onRetry:()=>{fe.current=!1,nt(H.current||[])}}),Z&&Ee!=="skipped"&&e.jsx(Ne,{status:Ee,icon:qt,label:"Importing Credits and Streaming Data",progress:Ee==="running"?ke:null,doneMessage:ke?`Streaming & Credits: ${ke.enriched} imported${ke.notFound>0?`, ${ke.notFound} not found`:""}${ke.failed>0?`, ${ke.failed} failed`:""}`:"Streaming & credits import complete",errorMessage:"Credits and streaming data import could not finish.",onRetry:()=>{ve.current=!1,Pt(H.current||[],null)}}),Z&&e.jsx(Ne,{status:ce,label:"BPM Enrichment",background:!0,progress:ce==="running"?be:null,doneMessage:be?`BPM: ${be.updated} of ${be.total} tracks enriched`:"BPM complete",errorMessage:"BPM fetch failed. Tracks imported without tempo data."}),Z&&Be!=="skipped"&&e.jsx(Ne,{status:Be,icon:Ge,label:"SoundExchange ISRC Verification",progress:Be==="running"?Ue:null,doneMessage:Ue?`SoundExchange: ${Ue.found} registered, ${Ue.notFound||0} not found`:"SoundExchange check complete",errorMessage:"SoundExchange ISRC check could not finish.",onRetry:()=>{Ye.current=!1,st(H.current||[])}}),Z&&Ie&&e.jsx(Ne,{status:Ie==="queued"?"done":Ie,icon:Ge,label:"PRO Composition Verification",doneMessage:Ie==="skipped"?He==null?void 0:He.reason:Ie==="queued"?"PRO verification queued and continuing in the background":"PRO verification complete",errorMessage:"PRO verification could not start.",onRetry:()=>{qe.current=!1,Y.current=at()}}),Z&&(()=>{const r=i==="running"||Ee==="running"||ce==="running"||Be==="running";return e.jsxs("button",{onClick:Ut,disabled:r,className:"w-full mt-2",style:{padding:"10px 0",borderRadius:500,border:"none",fontWeight:600,fontSize:14,background:"#7C3AED",color:"white",cursor:r?"not-allowed":"pointer",opacity:r?.6:1,boxShadow:"0 0 20px rgba(124,58,237,0.25)",display:"flex",alignItems:"center",justifyContent:"center",gap:8},children:[e.jsx(tt,{className:"w-4 h-4"})," ",r?"Finishing pipelineâ¦":"Done - View Catalog"]})})(),ee&&e.jsx("button",{onClick:()=>{G.current=!0},className:"w-full",style:{padding:"8px 0",borderRadius:10,border:"1px solid rgba(220,38,38,0.3)",background:"transparent",color:"#DC2626",fontSize:13,fontWeight:600,cursor:"pointer"},children:"Cancel Import"})]}),h&&!z&&!P&&e.jsxs("div",{className:"mt-4",style:{padding:"12px 16px",borderRadius:12,fontSize:13,fontWeight:600,background:h.type==="success"?"rgba(16,185,129,0.08)":"rgba(220,38,38,0.06)",border:`1px solid ${h.type==="success"?"rgba(16,185,129,0.25)":"rgba(220,38,38,0.25)"}`,color:h.type==="success"?"#059669":"#DC2626",display:"flex",alignItems:"center",justifyContent:"space-between",gap:12},children:[e.jsx("span",{children:h.message}),h.type==="error"&&e.jsx("button",{onClick:ot,style:{padding:"4px 12px",borderRadius:6,border:"1px solid rgba(220,38,38,0.3)",background:"transparent",color:"#DC2626",fontSize:12,fontWeight:600,cursor:"pointer",whiteSpace:"nowrap",flexShrink:0},children:"Try Again"})]}),!N&&!P&&v.length>0&&e.jsx("div",{className:"mt-4 space-y-0 rounded-xl overflow-hidden",style:{border:"1px solid rgba(255,255,255,0.08)"},children:v.map((r,l)=>{var o,s,t,n,a;return e.jsxs("button",{onClick:()=>Et(r),className:"w-full flex items-center gap-4 px-4 py-3 text-left transition-all",style:{background:l%2===0?"#161616":"#1A1A1A",borderBottom:l<v.length-1?"1px solid rgba(255,255,255,0.06)":"none",border:"none",cursor:"pointer"},onMouseEnter:d=>d.currentTarget.style.background="rgba(124,58,237,0.08)",onMouseLeave:d=>d.currentTarget.style.background=l%2===0?"#161616":"#1A1A1A",children:[e.jsx("div",{className:"w-12 h-12 rounded-lg overflow-hidden flex-shrink-0",style:{background:"#1A1A1A"},children:(s=(o=r.images)==null?void 0:o[0])!=null&&s.url?e.jsx("img",{src:r.images[0].url,alt:r.name,className:"w-full h-full object-cover"}):e.jsx("div",{className:"w-full h-full flex items-center justify-center",children:e.jsx(yr,{className:"w-5 h-5",style:{color:"#444"}})})}),e.jsxs("div",{className:"flex-1 min-w-0",children:[e.jsx("p",{className:"font-semibold text-sm truncate",style:{color:"#FFFFFF"},children:r.name}),e.jsxs("p",{className:"text-xs",style:{color:"#666"},children:[(n=(t=r.followers)==null?void 0:t.total)==null?void 0:n.toLocaleStr
6ing()," followers",((a=r.genres)==null?void 0:a.length)>0&&` · ${r.genres.slice(0,2).join(", ")}`]})]}),e.jsx(Zt,{className:"w-4 h-4 flex-shrink-0",style:{color:"#A78BFA"}})]},r.id)})}),!P&&v.length===0&&I&&!ct&&!N&&!h&&e.jsx("p",{className:"text-center py-6 text-sm",style:{color:"#444"},children:"No results found. Try a different name."}),N&&!z&&e.jsx(Ar,{preview:N,onBack:ot,onImport:zt,isImporting:ee,fetchAlbumTracksBatched:Ze,importTracksBatched:Se,cancelledRef:G,setImportStatus:F,searchedArtistName:((lt=N.artist)==null?void 0:lt.name)||I.trim()})]})}function Ar({preview:w,onBack:I,onImport:$,isImporting:P,fetchAlbumTracksBatched:U,importTracksBatched:v,cancelledRef:D,setImportStatus:N,searchedArtistName:B}){var G,H;const[u,q]=V.useState(new Set(w.albums.map(i=>i.id))),[Y,ae]=V.useState(null),[ee,me]=V.useState({}),h=i=>{q(W=>{const T=new Set(W);return T.has(i)?T.delete(i):T.add(i),T})},F=()=>q(new Set(w.albums.map(i=>i.id))),z=()=>q(new Set),ne=u.size===w.albums.length,Z=w.albums.filter(i=>u.has(i.id));Z.reduce((i,W)=>{const T=ee[W.id];return i+(T?T.length:W.total_tracks||0)},0);const g=Z.some(i=>!ee[i.id]),Q=(i,W)=>{me(T=>({...T,[i]:W})),W.length>0?q(T=>new Set([...T,i])):q(T=>{const J=new Set(T);return J.delete(i),J})},de=async()=>{let i=[];for(let W=0;W<Z.length&&!D.current;W++){const T=Z[W];N({type:"success",message:`Fetching album ${W+1} of ${Z.length}: ${T.name}...`});const J=await U(T.id);if(J){const fe=ee[T.id];if(fe)i=i.concat(J.tracks.filter(ce=>fe.includes(ce.id)));else if(B){const ce=J.tracks.filter(ye=>Ae(B,ye));i=i.concat(ce.length===0||ce.length===J.tracks.length?J.tracks:ce)}else i=i.concat(J.tracks)}}N({type:"success",message:`Fetched ${i.length} tracks. Starting import...`}),await v(i)};return Y?e.jsx("div",{className:"mt-4",style:{background:"#1A1A1A",border:"1px solid rgba(255,255,255,0.08)",borderRadius:14,padding:16,maxHeight:500,overflow:"auto"},children:e.jsx(Cr,{album:Y,selectedTrackIds:ee[Y.id],onSelectionChange:i=>Q(Y.id,i),onBack:()=>ae(null),searchedArtistName:B})}):e.jsxs("div",{className:"mt-4 space-y-3",children:[e.jsxs("div",{style:{display:"flex",alignItems:"center",gap:14,padding:"14px 16px",background:"rgba(124,58,237,0.06)",border:"1px solid rgba(124,58,237,0.2)",borderRadius:14},children:[((H=(G=w.artist.images)==null?void 0:G[0])==null?void 0:H.url)&&e.jsx("img",{src:w.artist.images[0].url,alt:w.artist.name,style:{width:56,height:56,borderRadius:12,objectFit:"cover"}}),e.jsxs("div",{style:{flex:1},children:[e.jsx("h3",{style:{fontWeight:600,fontSize:17,color:"#FFFFFF",margin:0},children:w.artist.name}),e.jsxs("p",{style:{fontSize:13,color:"#B3B3B3",margin:"2px 0 0"},children:[w.totalTracks," tracks"]})]}),e.jsx("button",{onClick:I,style:{padding:"7px 14px",borderRadius:9,border:"1px solid rgba(255,255,255,0.15)",background:"transparent",fontSize:13,fontWeight:600,color:"#B3B3B3",cursor:"pointer"},children:e.jsx(Gt,{className:"w-4 h-4"})})]}),e.jsxs("div",{style:{display:"flex",alignItems:"center",justifyContent:"space-between",padding:"0 4px"},children:[e.jsxs("span",{style:{fontSize:12,color:"#9CA3AF",fontWeight:600},children:[u.size," of ",w.albums.length," albums selected"]}),e.jsx("button",{onClick:ne?z:F,style:{fontSize:12,fontWeight:600,color:"#A78BFA",background:"none",border:"none",cursor:"pointer",padding:"4px 10px",borderRadius:6},children:ne?"Deselect All":"Select All"})]}),e.jsx("div",{style:{maxHeight:360,overflowY:"auto"},className:"space-y-1",children:w.albums.map(i=>{var ce,ye,be;const W=u.has(i.id),T=ee[i.id],J=!!T,fe=T?T.length:i.total_tracks;return e.jsx("div",{style:{background:W?"rgba(124,58,237,0.06)":"#1A1A1A",border:`1px solid ${W?"rgba(124,58,237,0.25)":"rgba(255,255,255,0.06)"}`,borderRadius:10,padding:"10px 14px",cursor:"pointer",transition:"all 0.15s"},children:e.jsxs("div",{className:"flex gap-3 items-center",children:[e.jsx(Rt,{checked:W,onCheckedChange:()=>h(i.id),onClick:re=>re.stopPropagation(),className:"border-white/40 data-[state=checked]:bg-emerald-500 data-[state=checked]:border-emerald-500 hover:border-white/60"}),e.jsxs("div",{className:"flex gap-3 items-center flex-1 min-w-0",onClick:()=>h(i.id),children:[((ye=(ce=i.images)==null?void 0:ce[0])==null?void 0:ye.url)&&e.jsx("img",{src:i.images[0].url,alt:i.name,style:{width:44,height:44,borderRadius:8,objectFit:"cover",border:"1px solid rgba(255,255,255,0.06)"}}),e.jsxs("div",{className:"flex-1 min-w-0",children:[e.jsx("p",{style:{fontWeight:600,fontSize:13,color:"#FFFFFF",margin:0},className:"truncate",children:i.name}),e.jsx("p",{style:{fontSize:12,color:"#666",margin:"2px 0 0"},children:J?e.jsxs("span",{style:{color:"#A78BFA"},children:[fe," of ",i.total_tracks," tracks selected"]}):e.jsxs(e.Fragment,{children:[i.total_tracks," tracks ⢠",(be=i.release_date)==null?void 0:be.split("-")[0]]})})]})]}),e.jsxs("button",{onClick:re=>{re.stopPropagation(),ae(i)},style:{padding:"5px 8px",borderRadius:6,border:"1px solid rgba(255,255,255,0.1)",background:"transparent",color:"#9
6CA3AF",cursor:"pointer",display:"flex",alignItems:"center",gap:3,fontSize:11,fontWeight:500,flexShrink:0},onMouseEnter:re=>{re.currentTarget.style.borderColor="#7C3AED",re.currentTarget.style.color="#A78BFA"},onMouseLeave:re=>{re.currentTarget.style.borderColor="rgba(255,255,255,0.1)",re.currentTarget.style.color="#9CA3AF"},children:["Tracks ",e.jsx(xr,{style:{width:12,height:12}})]})]})},i.id)})}),e.jsx("button",{onClick:de,disabled:P||u.size===0,style:{width:"100%",height:48,borderRadius:500,border:"none",fontWeight:600,fontSize:15,background:"#7C3AED",color:"#FFFFFF",cursor:P||u.size===0?"not-allowed":"pointer",opacity:P||u.size===0?.5:1,boxShadow:"0 0 30px rgba(124,58,237,0.30)",display:"flex",alignItems:"center",justifyContent:"center",gap:10,transition:"all 0.2s"},children:P?e.jsxs(e.Fragment,{children:[e.jsx(Pe,{className:"w-5 h-5 animate-spin"})," Importing..."]}):e.jsxs(e.Fragment,{children:[e.jsx(tt,{className:"w-5 h-5"})," Import ",u.size," Albums"]})}),B&&g&&!P&&e.jsxs("p",{style:{fontSize:11,color:"#9CA3AF",textAlign:"center",marginTop:6},children:["Only tracks credited to ",e.jsx("strong",{style:{color:"#A78BFA"},children:B})," will be imported from each album. Open an album to customize."]})]})}function vr({open:w,onClose:I,onSuccess:$}){const[P,U]=V.useState("audio"),[v,D]=V.useState(!1),[N,B]=V.useState(null),[u,q]=V.useState(""),Y=V.useRef(null),ae=async h=>{if(h){D(!0),B({type:"info",message:"Uploading audio file..."});try{const z=(await C.integrations.Core.UploadFile({file:h})).file_url,ne=h.name.replace(/\.[^/.]+$/,""),Z=await C.entities.Track.create({title:ne,audio_file_url:z,audio_file_format:h.type||(h.name.endsWith(".zip")?"application/zip":"audio"),source:"audio_upload",spotify_last_synced:new Date().toISOString()});B({type:"success",message:`â Uploaded "${ne}"`}),setTimeout(()=>{$&&$(`Added "${ne}" to catalog`),I()},1500)}catch(F){console.error("Upload failed:",F),B({type:"error",message:`Failed: ${F.message}`})}D(!1)}},ee=async()=>{if(!u.trim()){B({type:"error",message:"Please enter a YouTube URL"});return}D(!0),B({type:"info",message:"Processing YouTube video..."});try{const h=await C.functions.invoke("youtubeExtractor",{url:u});if(h.data.error)throw new Error(h.data.error);const F=await C.entities.Track.create({title:h.data.title,cover_art_url:h.data.thumbnail,preview_url:u,source:"youtube",spotify_last_synced:new Date().toISOString()});B({type:"success",message:`â Imported "${h.data.title}"`}),setTimeout(()=>{$&&$(`Added "${h.data.title}" to catalog`),I()},1500)}catch(h){console.error("YouTube import failed:",h),B({type:"error",message:`Failed: ${h.message}`})}D(!1)},me=h=>{var z;const F=(z=h.target.files)==null?void 0:z[0];F&&ae(F)};return e.jsx(Jt,{open:w,onOpenChange:I,children:e.jsxs(er,{className:"max-w-2xl p-0",style:{background:"#161616",border:"1px solid rgba(255,255,255,0.08)",borderRadius:20},children:[e.jsx("div",{style:{padding:"28px 28px 0"},children:e.jsxs("div",{style:{display:"flex",alignItems:"center",gap:14},children:[e.jsx("div",{style:{width:44,height:44,borderRadius:12,background:"linear-gradient(135deg, #7C3AED, #A78BFA)",display:"flex",alignItems:"center",justifyContent:"center",flexShrink:0,boxShadow:"0 4px 12px rgba(124,58,237,0.25)"},children:e.jsx(At,{style:{width:22,height:22,color:"#FFFFFF"}})}),e.jsxs("div",{children:[e.jsx("h2",{style:{fontFamily:"'Satoshi','Inter',sans-serif",fontWeight:900,fontSize:20,color:"#FFFFFF",letterSpacing:"-0.02em",margin:0},children:"Add Song Manually"}),e.jsx("p",{style:{fontSize:13,color:"#9CA3AF",margin:"2px 0 0"},children:"Upload an audio file or import from YouTube"})]})]})}),e.jsxs("div",{style:{padding:"20px 28px 28px"},className:"space-y-4",children:[e.jsxs("div",{style:{display:"flex",gap:6,padding:4,background:"rgba(255,255,255,0.04)",borderRadius:12},children:[e.jsxs("button",{onClick:()=>U("audio"),style:{flex:1,padding:"10px 16px",borderRadius:9,fontSize:13,fontWeight:600,border:"none",cursor:"pointer",transition:"all 0.15s",display:"flex",alignItems:"center",justifyContent:"center",gap:7,background:P==="audio"?"#7C3AED":"transparent",color:P==="audio"?"#FFFFFF":"#9CA3AF"},children:[e.jsx($t,{style:{width:14,height:14}}),"Audio File"]}),e.jsxs("button",{onClick:()=>U("youtube"),style:{flex:1,padding:"10px 16px",borderRadius:9,fontSize:13,fontWeight:600,border:"none",cursor:"pointer",transition:"all 0.15s",display:"flex",alignItems:"center",justifyContent:"center",gap:7,background:P==="youtube"?"#7C3AED":"transparent",color:P==="youtube"?"#FFFFFF":"#9CA3AF"},children:[e.jsx(vt,{style:{width:14,height:14}}),"YouTube"]})]}),N&&e.jsxs("div",{className:tr("p-4 rounded-lg border flex items-start gap-3",N.type==="success"?"bg-emerald-500/10 border-emerald-500/30 text-emerald-400":N.type==="error"?"bg-red-500/10 border-red-500/30 text-red-400":"bg-blue-500/10 border-blue-500/30 text-blue-400"),children:[N.type==="success"?e.jsx(tt,{className:"w-5 h-5 flex-shrink-0 mt-0.5"}):N.type==="error"?e.jsx(kr,{className:"w-5 h-5 flex-shrink-0 mt-0.5"}):e.jsx(Pe,{className:"w-5 h-5 flex-shrink-0 mt-0.5 animate-spin"}),e.jsx("span",{className:"text-sm",children:N.message})]}),P==="audio"&&e.jsxs("div",{children:[e.jsx("button",{onClick:()=>{var h;
6return(h=Y.current)==null?void 0:h.click()},disabled:v,style:{width:"100%",background:"rgba(255,255,255,0.02)",borderRadius:14,border:"2px dashed rgba(124,58,237,0.3)",padding:48,textAlign:"center",cursor:v?"not-allowed":"pointer",opacity:v?.5:1,transition:"all 0.2s"},onMouseEnter:h=>{v||(h.currentTarget.style.borderColor="rgba(124,58,237,0.5)")},onMouseLeave:h=>{h.currentTarget.style.borderColor="rgba(124,58,237,0.3)"},children:v?e.jsx(et,{size:"sm",text:"Uploading..."}):e.jsxs(e.Fragment,{children:[e.jsx(At,{style:{width:48,height:48,color:"#A78BFA",margin:"0 auto 12px"}}),e.jsx("p",{style:{color:"#FFFFFF",fontWeight:600,marginBottom:4},children:"Drop audio or zip file here"}),e.jsx("p",{style:{fontSize:12,color:"#9CA3AF"},children:"or click to browse"}),e.jsx("p",{style:{fontSize:10,color:"#666666",marginTop:8},children:"MP3, WAV, FLAC, M4A, ZIP (Max 500MB)"})]})}),e.jsx("input",{ref:Y,type:"file",accept:"audio/*,.zip,application/zip",onChange:me,className:"hidden"})]}),P==="youtube"&&e.jsxs("div",{className:"space-y-3",children:[e.jsx("div",{className:"flex gap-2",children:e.jsx(It,{placeholder:"Paste YouTube URL...",value:u,onChange:h=>q(h.target.value),disabled:v,style:{background:"rgba(255,255,255,0.04)",border:"1px solid rgba(255,255,255,0.08)",color:"#FFFFFF",borderRadius:10}})}),u.trim()&&u.includes("youtu")?e.jsx(br,{videoUrl:u,trackTitle:"Preview"}):e.jsxs("div",{style:{background:"rgba(255,255,255,0.02)",border:"1px solid rgba(255,255,255,0.08)",borderRadius:12,padding:16},children:[e.jsxs("p",{className:"flex items-center gap-2 mb-2",style:{fontSize:13,color:"#B3B3B3"},children:[e.jsx(wr,{style:{width:16,height:16,color:"#A78BFA"}}),"Example URL: https://www.youtube.com/watch?v=..."]}),e.jsx("p",{style:{fontSize:11,color:"#666666"},children:"We'll extract the title, thumbnail, and create a track entry"})]}),e.jsx("button",{onClick:ee,disabled:v||!u.trim(),className:"rc-btn-primary w-full",style:{height:44,borderRadius:12,opacity:v||!u.trim()?.4:1},children:v?e.jsxs(e.Fragment,{children:[e.jsx(Pe,{className:"w-4 h-4 mr-2 animate-spin"}),"Processing..."]}):e.jsxs(e.Fragment,{children:[e.jsx(vt,{className:"w-4 h-4 mr-2"}),"Import from YouTube"]})})]}),e.jsx("div",{style:{background:"rgba(245,158,11,0.06)",border:"1px solid rgba(245,158,11,0.15)",borderRadius:12,padding:"12px 16px",fontSize:12,color:"#F59E0B"},children:"ð¡ After uploading, you can view the track in your catalog and add lyrics, metadata, and more."})]})]})})}function is(){rr();const[w,I]=V.useState(null),[$,P]=V.useState(!1),{runWorkAutoMatch:U}=mr();V.useEffect(()=>{C.auth.me().then(I).catch(u=>console.error("Import user load failed:",u))},[]);const{data:v=[],isLoading:D,refetch:N}=sr({queryKey:["tracks",w==null?void 0:w.email],queryFn:async()=>w?C.entities.Track.filter({created_by:w.email},"-created_date",500):[],enabled:!!w});V.useEffect(()=>{if(D||!window.location.hash)return;const u=window.location.hash.slice(1),q=window.requestAnimationFrame(()=>{var Y;(Y=document.getElementById(u))==null||Y.scrollIntoView({behavior:"smooth",block:"start"})});return()=>window.cancelAnimationFrame(q)},[D]);const B=u=>{N(),we({title:"Import Successful",description:u||"Your catalog has been updated."}),U(),setTimeout(()=>{_r({particleCount:100,spread:70,origin:{y:.6}}),setTimeout(()=>{window.location.href=pr("Catalog")},1e3)},500)};return D?e.jsx("div",{className:"flex items-center justify-center min-h-[60vh]",children:e.jsx(et,{size:"lg",text:"Loading..."})}):e.jsxs("div",{className:"space-y-10",style:{width:"100%"},children:[e.jsx(Sr,{}),e.jsx("div",{className:"flex items-center justify-between",children:e.jsx("div",{children:e.jsxs("div",{children:[e.jsx("h1",{className:"text-lg sm:text-2xl md:text-[26px]",style:{fontFamily:"'Inter',-apple-system,sans-serif",fontWeight:650,letterSpacing:"-0.025em",color:"#FFFFFF",margin:"2px 0 2px",lineHeight:1.15},children:"Import Your Catalog"}),e.jsx("p",{style:{fontSize:13.5,color:"#8b8b90",margin:"2px 0 0"},children:"Search and add your releases, and connect your rights orgs."})]})})}),e.jsxs("div",{id:"add-music",style:{background:"#161616",border:"1px solid rgba(255,255,255,0.08)",borderRadius:16,overflow:"hidden",scrollMarginTop:24},children:[e.jsxs("div",{style:{padding:"20px 24px",display:"flex",alignItems:"center",gap:16,borderBottom:"1px solid rgba(255,255,255,0.06)"},children:[e.jsxs("div",{style:{display:"flex",alignItems:"center",gap:10,flexShrink:0},children:[e.jsx("div",{style:{width:52,height:52,borderRadius:14,overflow:"hidden",background:"#1DB954",display:"flex",alignItems:"center",justifyContent:"center",boxShadow:"0 4px 14px rgba(29,185,84,0.2)"},children:e.jsx(ar,{size:30})}),e.jsx(nr,{size:52})]}),e.jsx("div",{style:{flex:1},children:e.jsx("div",{style:{display:"flex",alignItems:"center",gap:8},children:e.jsx("h2",{style:{fontFamily:"'Inter',-apple-system,sans-serif",fontWeight:600,fontSize:18,color:"#FFFFFF",margin:0},children:"Spotify / Apple Music Import"})})})]}),e.jsx("div",{className:"p-6",children:e.jsx(Fr,{onSuccess:B})})]}),e.jsxs("div",{className:"flex items-center gap-4",children:[e.jsx("div",{className:"flex-1 h-px",style:{background:"var(--rc-border)"}}
6),e.jsx("span",{className:"text-xs font-medium",style:{color:"var(--rc-text-faint)"},children:"Or"}),e.jsx("div",{className:"flex-1 h-px",style:{background:"var(--rc-border)"}})]}),e.jsxs("button",{onClick:()=>P(!0),style:{width:"100%",padding:"15px",borderRadius:12,display:"flex",alignItems:"center",justifyContent:"center",gap:8,fontSize:14,fontWeight:600,background:"rgba(255,255,255,0.03)",color:"#E4E4E7",border:"1px solid rgba(255,255,255,0.12)",cursor:"pointer",transition:"all 0.15s"},onMouseEnter:u=>{u.currentTarget.style.background="rgba(255,255,255,0.06)",u.currentTarget.style.borderColor="rgba(255,255,255,0.22)"},onMouseLeave:u=>{u.currentTarget.style.background="rgba(255,255,255,0.03)",u.currentTarget.style.borderColor="rgba(255,255,255,0.12)"},children:[e.jsx($t,{style:{width:16,height:16}}),"Upload a file"]}),e.jsxs("div",{id:"connect-sources",style:{scrollMarginTop:24},children:[e.jsx("h2",{style:{fontFamily:"'Inter',-apple-system,sans-serif",fontWeight:600,fontSize:18,color:"#FFFFFF",marginBottom:6},children:"Connect Your Accounts"}),e.jsx("div",{style:{display:"flex",alignItems:"center",gap:10,padding:"12px 14px",borderRadius:10,background:"rgba(124,58,237,0.08)",border:"1px solid rgba(124,58,237,0.18)",marginBottom:20},children:e.jsx("span",{style:{fontSize:13,color:"#A78BFA",fontWeight:500},children:"Connect your accounts to surface unmatched recordings, held money, and missing registrations."})}),e.jsxs("div",{style:{display:"grid",gridTemplateColumns:"repeat(auto-fill, minmax(260px, 1fr))",gap:12},children:[e.jsx(Ce,{name:"MLC",color:"#7C3AED",source:"mlc",logo:ir,disclaimer:Fe("The MLC"),onUpload:()=>we({title:"Upload MLC files",description:"Use the MLC import option in Settings."})}),e.jsx(Ce,{name:"SoundExchange",color:"#3B82F6",source:"soundexchange",logo:or,disclaimer:Fe("SoundExchange"),onUpload:()=>we({title:"Upload SoundExchange files",description:"Use the SoundExchange import option in Settings."})}),e.jsx(Ce,{name:"BMI",color:"#F59E0B",source:"bmi",logo:cr,disclaimer:Fe("BMI"),onUpload:()=>we({title:"Upload BMI files",description:"Use the BMI import option in Settings."})}),e.jsx(Ce,{name:"ASCAP",color:"#EF4444",source:"ascap",logo:lr,disclaimer:Fe("ASCAP"),onUpload:()=>we({title:"Upload ASCAP files",description:"Use the ASCAP import option in Settings."})}),(w==null?void 0:w.role)==="admin"&&e.jsx(Ce,{name:"DistroKid",color:"#14B8A6",source:"distrokid",logo:dr,disclaimer:Fe("DistroKid"),onUpload:()=>we({title:"Upload DistroKid files",description:"Use Upload Statement in Royalty Intelligence."})}),e.jsx(Ce,{name:"Music Reports",color:"#DB2777",source:"musicreports",logo:ur,disclaimer:Fe("Music Reports"),onUpload:()=>we({title:"Upload Music Reports files",description:"Use Upload Statement in Royalty Intelligence."})})]})]}),e.jsx(vr,{open:$,onClose:()=>P(!1),onSuccess:B})]})}export{is 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.