const __vite__mapDeps=(i,m=__vite__mapDeps,d=(m.f||(m.f=["assets/FeaturedPlaylists-B8noy_cw.js","assets/ui-vendor-DYHpVWUc.js","assets/react-vendor-Dv0pxvir.js","assets/FAQSection-DYdRED9D.js","assets/AdditionalInfoSection-DphltVm4.js"])))=>i.map(i=>d[i]); var Yn=Object.defineProperty;var Qn=(s,e,r)=>e in s?Yn(s,e,{enumerable:!0,configurable:!0,writable:!0,value:r}):s[e]=r;var Ae=(s,e,r)=>Qn(s,typeof e!="symbol"?e+"":e,r);import{j as t,u as Zn,C as Xn,a as ea,b as mr,D as ta,c as sa,S as ra,v as na,s as aa,K as ia,P as oa,L as Kr,T as zr,d as Wr,R as la}from"./ui-vendor-DYHpVWUc.js";import{a as Vr,g as is,r as b,R as Ze,c as ca,d as Se,L as ee,u as it,e as Xe,f as Jr,h as os,N as Yr,O as da,i as ua,j as he,B as ha}from"./react-vendor-Dv0pxvir.js";(function(){const e=document.createElement("link").relList;if(e&&e.supports&&e.supports("modulepreload"))return;for(const a of document.querySelectorAll('link[rel="modulepreload"]'))n(a);new MutationObserver(a=>{for(const i of a)if(i.type==="childList")for(const o of i.addedNodes)o.tagName==="LINK"&&o.rel==="modulepreload"&&n(o)}).observe(document,{childList:!0,subtree:!0});function r(a){const i={};return a.integrity&&(i.integrity=a.integrity),a.referrerPolicy&&(i.referrerPolicy=a.referrerPolicy),a.crossOrigin==="use-credentials"?i.credentials="include":a.crossOrigin==="anonymous"?i.credentials="omit":i.credentials="same-origin",i}function n(a){if(a.ep)return;a.ep=!0;const i=r(a);fetch(a.href,i)}})();var Qr,gr=Vr;Qr=gr.createRoot,gr.hydrateRoot;var fa=typeof Element<"u",ma=typeof Map=="function",ga=typeof Set=="function",pa=typeof ArrayBuffer=="function"&&!!ArrayBuffer.isView;function Yt(s,e){if(s===e)return!0;if(s&&e&&typeof s=="object"&&typeof e=="object"){if(s.constructor!==e.constructor)return!1;var r,n,a;if(Array.isArray(s)){if(r=s.length,r!=e.length)return!1;for(n=r;n--!==0;)if(!Yt(s[n],e[n]))return!1;return!0}var i;if(ma&&s instanceof Map&&e instanceof Map){if(s.size!==e.size)return!1;for(i=s.entries();!(n=i.next()).done;)if(!e.has(n.value[0]))return!1;for(i=s.entries();!(n=i.next()).done;)if(!Yt(n.value[1],e.get(n.value[0])))return!1;return!0}if(ga&&s instanceof Set&&e instanceof Set){if(s.size!==e.size)return!1;for(i=s.entries();!(n=i.next()).done;)if(!e.has(n.value[0]))return!1;return!0}if(pa&&ArrayBuffer.isView(s)&&ArrayBuffer.isView(e)){if(r=s.length,r!=e.length)return!1;for(n=r;n--!==0;)if(s[n]!==e[n])return!1;return!0}if(s.constructor===RegExp)return s.source===e.source&&s.flags===e.flags;if(s.valueOf!==Object.prototype.valueOf&&typeof s.valueOf=="function"&&typeof e.valueOf=="function")return s.valueOf()===e.valueOf();if(s.toString!==Object.prototype.toString&&typeof s.toString=="function"&&typeof e.toString=="function")return s.toString()===e.toString();if(a=Object.keys(s),r=a.length,r!==Object.keys(e).length)return!1;for(n=r;n--!==0;)if(!Object.prototype.hasOwnProperty.call(e,a[n]))return!1;if(fa&&s instanceof Element)return!1;for(n=r;n--!==0;)if(!((a[n]==="_owner"||a[n]==="__v"||a[n]==="__o")&&s.$$typeof)&&!Yt(s[a[n]],e[a[n]]))return!1;return!0}return s!==s&&e!==e}var ya=function(e,r){try{return Yt(e,r)}catch(n){if((n.message||"").match(/stack|recursion/i))return console.warn("react-fast-compare cannot handle circular refs"),!1;throw n}};const xa=is(ya);var ba=function(s,e,r,n,a,i,o,l){if(!s){var d;if(e===void 0)d=new Error("Minified exception occurred; use the non-minified dev environment for the full error message and additional helpful warnings.");else{var c=[r,n,a,i,o,l],u=0;d=new Error(e.replace(/%s/g,function(){return c[u++]})),d.name="Invariant Violation"}throw d.framesToPop=1,d}},wa=ba;const pr=is(wa);var va=function(e,r,n,a){var i=n?n.call(a,e,r):void 0;if(i!==void 0)return!!i;if(e===r)return!0;if(typeof e!="object"||!e||typeof r!="object"||!r)return!1;var o=Object.keys(e),l=Object.keys(r);if(o.length!==l.length)return!1;for(var d=Object.prototype.hasOwnProperty.bind(r),c=0;c<o.length;c++){var u=o[c];if(!d(u))return!1;var h=e[u],f=r[u];if(i=n?n.call(a,h,f,u):void 0,i===!1||i===void 0&&h!==f)return!1}return!0};const ja=is(va);var Zr=(s=>(s.BASE="base",s.BODY="body",s.HEAD="head",s.HTML="html",s.LINK="link",s.META="meta",s.NOSCRIPT="noscript",s.SCRIPT="script",s.STYLE="style",s.TITLE="title",s.FRAGMENT="Symbol(react.fragment)",s))(Zr||{}),xs={link:{rel:["amphtml","canonical","alternate"]},script:{type:["application/ld+json"]},meta:{charset:"",name:["generator","robots","description"],property:["og:type","og:title","og:url","og:image","og:image:alt","og:description","twitter:url","twitter:title","twitter:description","twitter:image","twitter:image:alt","twitter:card","twitter:site"]}},yr=Object.values(Zr),Ys={accesskey:"accessKey",charset:"charSet",class:"className",contenteditable:"contentEditable",contextmenu:"contextMenu","http-equiv":"httpEquiv",itemprop:"itemProp",tabindex:"tabIndex"},_a=Object.entries(Ys).reduce((s,[e,r])=>(s[r]=e,s),{}),Le="data-rh",yt={DEFAULT_TITLE:"defaultTitle",DEFER:"defer",ENCODE_SPECIAL_CHARACTERS:"encodeSpecialCharacters",ON_CHANGE_CLIENT_STATE:"onChangeClientState",TITLE_TEMPLATE:"titleTemplate",PRIORITIZE_SEO_TAGS:"prioritizeSeoTags"},xt=(s,e)=>{for(let r=s.length-1;r>=0;r-=1){const n=s[r];if(Object.prototype.hasOwnProperty.call(n,e))return n[e]}return null},Na=s=>{let e=xt(s,"title");const r=xt(s,yt.TITLE_TEMPLATE);if(Array.isArray(e)&&(e=e.join("")),r&&e)return r.replace(/%s/g,()=>e);const n=xt(s,yt.DEFAULT_TITLE);return e||n||void 0},Sa=s=>xt(s,yt.ON_CHANGE_CLIENT_STATE)||(()=>{}),bs=(s,e)=>e.filter(r=>typeof r[s]<"u").map(r=>r[s]).reduce((r,n)=>({...r,...n}),{}),ka=(s,e)=>e.filter(r=>typeof r.base<"u").map(r=>r.base).reverse().reduce((r,n)=>{if(!r.length){const a=Object.keys(n);for(let i=0;i<a.length;i+=1){const l=a[i].toLowerCase();if(s.indexOf(l)!==-1&&n[l])return r.concat(n)}}return r},[]),Ea=s=>console&&typeof console.warn=="function"&&console.warn(s),Tt=(s,e,r)=>{const n={};return r.filter(a=>Array.isArray(a[s])?!0:(typeof a[s]<"u"&&Ea(`Helmet: ${s} should be of type "Array". Instead found type "${typeof a[s]}"`),!1)).map(a=>a[s]).reverse().reduce((a,i)=>{const o={};i.filter(d=>{let c;const u=Object.keys(d);for(let f=0;f<u.length;f+=1){const g=u[f],x=g.toLowerCase();e.indexOf(x)!==-1&&!(c==="rel"&&d[c].toLowerCase()==="canonical")&&!(x==="rel"&&d[x].toLowerCase()==="stylesheet")&&(c=x),e.indexOf(g)!==-1&&(g==="innerHTML"||g==="cssText"||g==="itemprop")&&(c=g)}if(!c||!d[c])return!1;const h=d[c].toLowerCase();return n[c]||(n[c]={}),o[c]||(o[c]={}),n[c][h]?!1:(o[c][h]=!0,!0)}).reverse().forEach(d=>a.push(d));const l=Object.keys(o);for(let d=0;d<l.length;d+=1){const c=l[d],u={...n[c],...o[c]};n[c]=u}return a},[]).reverse()},Ta=(s,e)=>{if(Array.isArray(s)&&s.length){for(let r=0;r<s.length;r+=1)if(s[r][e])return!0}return!1},Ca=s=>({baseTag:ka(["href"],s),bodyAttributes:bs("bodyAttributes",s),defer:xt(s,yt.DEFER),encode:xt(s,yt.ENCODE_SPECIAL_CHARACTERS),htmlAttributes:bs("htmlAttributes",s),linkTags:Tt("link",["rel","href"],s),metaTags:Tt("meta",["name","charset","http-equiv","property","itemprop"],s),noscriptTags:Tt("noscript",["innerHTML"],s),onChangeClientState:Sa(s),scriptTags:Tt("script",["src","innerHTML"],s),styleTags:Tt("style",["cssText"],s),title:Na(s),titleAttributes:bs("titleAttributes",s),prioritizeSeoTags:Ta(s,yt.PRIORITIZE_SEO_TAGS)}),Xr=s=>Array.isArray(s)?s.join(""):s,Pa=(s,e)=>{const r=Object.keys(s);for(let n=0;n<r.length;n+=1)if(e[r[n]]&&e[r[n]].includes(s[r[n]]))return!0;return!1},ws=(s,e)=>Array.isArray(s)?s.reduce((r,n)=>(Pa(n,e)?r.priority.push(n):r.default.push(n),r),{priority:[],default:[]}):{default:s,priority:[]},xr=(s,e)=>({...s,[e]:void 0}),Aa=["noscript","script","style"],As=(s,e=!0)=>e===!1?String(s):String(s).replace(/&/g,"&").replace(/</g,"<").replace(/>/g,">").replace(/"/g,""").replace(/'/g,"'"),en=s=>Object.keys(s).reduce((e,r)=>{const n=typeof s[r]<"u"?`${r}="${s[r]}"`:`${r}`;return e?`${e} ${n}`:n},""),Oa=(s,e,r,n)=>{const a=en(r),i=Xr(e);return a?`<${s} ${Le}="true" ${a}>${As(i,n)}</${s}>`:`<${s} ${Le}="true">${As(i,n)}</${s}>`},Ia=(s,e,r=!0)=>e.reduce((n,a)=>{const i=a,o=Object.keys(i).filter(c=>!(c==="innerHTML"||c==="cssText")).reduce((c,u)=>{const h=typeof i[u]>"u"?u:`${u}="${As(i[u],r)}"`;return c?`${c} ${h}`:h},""),l=i.innerHTML||i.cssText||"",d=Aa.indexOf(s)===-1;return`${n}<${s} ${Le}="true" ${o}${d?"/>":`>${l}</${s}>`}`},""),tn=(s,e={})=>Object.keys(s).reduce((r,n)=>{const a=Ys[n];return r[a||n]=s[n],r},e),La=(s,e,r)=>{const n={key:e,[Le]:!0},a=tn(r,n);return[Ze.createElement("title",a,e)]},Qt=(s,e)=>e.map((r,n)=>{const a={key:n,[Le]:!0};return Object.keys(r).forEach(i=>{const l=Ys[i]||i;if(l==="innerHTML"||l==="cssText"){const d=r.innerHTML||r.cssText;a.dangerouslySetInnerHTML={__html:d}}else a[l]=r[i]}),Ze.createElement(s,a)}),Ce=(s,e,r=!0)=>{switch(s){case"title":return{toComponent:()=>La(s,e.title,e.titleAttributes),toString:()=>Oa(s,e.title,e.titleAttributes,r)};case"bodyAttributes":case"htmlAttributes":return{toComponent:()=>tn(e),toString:()=>en(e)};default:return{toComponent:()=>Qt(s,e),toString:()=>Ia(s,e,r)}}},Ra=({metaTags:s,linkTags:e,scriptTags:r,encode:n})=>{const a=ws(s,xs.meta),i=ws(e,xs.link),o=ws(r,xs.script);return{priorityMethods:{toComponent:()=>[...Qt("meta",a.priority),...Qt("link",i.priority),...Qt("script",o.priority)],toString:()=>`${Ce("meta",a.priority,n)} ${Ce("link",i.priority,n)} ${Ce("script",o.priority,n)}`},metaTags:a.default,linkTags:i.default,scriptTags:o.default}},Da=s=>{const{baseTag:e,bodyAttributes:r,encode:n=!0,htmlAttributes:a,noscriptTags:i,styleTags:o,title:l="",titleAttributes:d,prioritizeSeoTags:c}=s;let{linkTags:u,metaTags:h,scriptTags:f}=s,g={toComponent:()=>{},toString:()=>""};return c&&({priorityMethods:g,linkTags:u,metaTags:h,scriptTags:f}=Ra(s)),{priority:g,base:Ce("base",e,n),bodyAttributes:Ce("bodyAttributes",r,n),htmlAttributes:Ce("htmlAttributes",a,n),link:Ce("link",u,n),meta:Ce("meta",h,n),noscript:Ce("noscript",i,n),script:Ce("script",f,n),style:Ce("style",o,n),title:Ce("title",{title:l,titleAttributes:d},n)}},Os=Da,Ht=[],sn=!!(typeof window<"u"&&window.document&&window.document.createElement),Is=class{constructor(s,e){Ae(this,"instances",[]);Ae(this,"canUseDOM",sn);Ae(this,"context");Ae(this,"value",{setHelmet:s=>{this.context.helmet=s},helmetInstances:{get:()=>this.canUseDOM?Ht:this.instances,add:s=>{(this.canUseDOM?Ht:this.instances).push(s)},remove:s=>{const e=(this.canUseDOM?Ht:this.instances).indexOf(s);(this.canUseDOM?Ht:this.instances).splice(e,1)}}});this.context=s,this.canUseDOM=e||!1,e||(s.helmet=Os({baseTag:[],bodyAttributes:{},htmlAttributes:{},linkTags:[],metaTags:[],noscriptTags:[],scriptTags:[],styleTags:[],title:"",titleAttributes:{}}))}},$a={},rn=Ze.createContext($a),at,nn=(at=class extends b.Component{constructor(r){super(r);Ae(this,"helmetData");this.helmetData=new Is(this.props.context||{},at.canUseDOM)}render(){return Ze.createElement(rn.Provider,{value:this.helmetData.value},this.props.children)}},Ae(at,"canUseDOM",sn),at),ct=(s,e)=>{const r=document.head||document.querySelector("head"),n=r.querySelectorAll(`${s}[${Le}]`),a=[].slice.call(n),i=[];let o;return e&&e.length&&e.forEach(l=>{const d=document.createElement(s);for(const c in l)if(Object.prototype.hasOwnProperty.call(l,c))if(c==="innerHTML")d.innerHTML=l.innerHTML;else if(c==="cssText")d.styleSheet?d.styleSheet.cssText=l.cssText:d.appendChild(document.createTextNode(l.cssText));else{const u=c,h=typeof l[u]>"u"?"":l[u];d.setAttribute(c,h)}d.setAttribute(Le,"true"),a.some((c,u)=>(o=u,d.isEqualNode(c)))?a.splice(o,1):i.push(d)}),a.forEach(l=>{var d;return(d=l.parentNode)==null?void 0:d.removeChild(l)}),i.forEach(l=>r.appendChild(l)),{oldTags:a,newTags:i}},Ls=(s,e)=>{const r=document.getElementsByTagName(s)[0];if(!r)return;const n=r.getAttribute(Le),a=n?n.split(","):[],i=[...a],o=Object.keys(e);for(const l of o){const d=e[l]||"";r.getAttribute(l)!==d&&r.setAttribute(l,d),a.indexOf(l)===-1&&a.push(l);const c=i.indexOf(l);c!==-1&&i.splice(c,1)}for(let l=i.length-1;l>=0;l-=1)r.removeAttribute(i[l]);a.length===i.length?r.removeAttribute(Le):r.getAttribute(Le)!==o.join(",")&&r.setAttribute(Le,o.join(","))},Ua=(s,e)=>{typeof s<"u"&&document.title!==s&&(document.title=Xr(s)),Ls("title",e)},br=(s,e)=>{const{baseTag:r,bodyAttributes:n,htmlAttributes:a,linkTags:i,metaTags:o,noscriptTags:l,onChangeClientState:d,scriptTags:c,styleTags:u,title:h,titleAttributes:f}=s;Ls("body",n),Ls("html",a),Ua(h,f);const g={baseTag:ct("base",r),linkTags:ct("link",i),metaTags:ct("meta",o),noscriptTags:ct("noscript",l),scriptTags:ct("script",c),styleTags:ct("style",u)},x={},v={};Object.keys(g).forEach(y=>{const{newTags:w,oldTags:P}=g[y];w.length&&(x[y]=w),P.length&&(v[y]=g[y].oldTags)}),e&&e(),d(s,x,v)},Ct=null,Ma=s=>{Ct&&cancelAnimationFrame(Ct),s.defer?Ct=requestAnimationFrame(()=>{br(s,()=>{Ct=null})}):(br(s),Ct=null)},Ba=Ma,wr=class extends b.Component{constructor(){super(...arguments);Ae(this,"rendered",!1)}shouldComponentUpdate(e){return!ja(e,this.props)}componentDidUpdate(){this.emitChange()}componentWillUnmount(){const{helmetInstances:e}=this.props.context;e.remove(this),this.emitChange()}emitChange(){const{helmetInstances:e,setHelmet:r}=this.props.context;let n=null;const a=Ca(e.get().map(i=>{const o={...i.props};return delete o.context,o}));nn.canUseDOM?Ba(a):Os&&(n=Os(a)),r(n)}init(){if(this.rendered)return;this.rendered=!0;const{helmetInstances:e}=this.props.context;e.add(this),this.emitChange()}render(){return this.init(),null}},Ps,Fa=(Ps=class extends b.Component{shouldComponentUpdate(s){return!xa(xr(this.props,"helmetData"),xr(s,"helmetData"))}mapNestedChildrenToProps(s,e){if(!e)return null;switch(s.type){case"script":case"noscript":return{innerHTML:e};case"style":return{cssText:e};default:throw new Error(`<${s.type} /> elements are self-closing and can not contain children. Refer to our API for more information.`)}}flattenArrayTypeChildren(s,e,r,n){return{...e,[s.type]:[...e[s.type]||[],{...r,...this.mapNestedChildrenToProps(s,n)}]}}mapObjectTypeChildren(s,e,r,n){switch(s.type){case"title":return{...e,[s.type]:n,titleAttributes:{...r}};case"body":return{...e,bodyAttributes:{...r}};case"html":return{...e,htmlAttributes:{...r}};default:return{...e,[s.type]:{...r}}}}mapArrayTypeChildrenToProps(s,e){let r={...e};return Object.keys(s).forEach(n=>{r={...r,[n]:s[n]}}),r}warnOnInvalidChildren(s,e){return pr(yr.some(r=>s.type===r),typeof s.type=="function"?"You may be attempting to nest <Helmet> components within each other, which is not allowed. Refer to our API for more information.":`Only elements types ${yr.join(", ")} are allowed. Helmet does not support rendering <${s.type}> elements. Refer to our API for more information.`),pr(!e||typeof e=="string"||Array.isArray(e)&&!e.some(r=>typeof r!="string"),`Helmet expects a string as a child of <${s.type}>. Did you forget to wrap your children in braces? ( <${s.type}>{\`\`}</${s.type}> ) Refer to our API for more information.`),!0}mapChildrenToProps(s,e){let r={};return Ze.Children.forEach(s,n=>{if(!n||!n.props)return;const{children:a,...i}=n.props,o=Object.keys(i).reduce((d,c)=>(d[_a[c]||c]=i[c],d),{});let{type:l}=n;switch(typeof l=="symbol"?l=l.toString():this.warnOnInvalidChildren(n,a),l){case"Symbol(react.fragment)":e=this.mapChildrenToProps(a,e);break;case"link":case"meta":case"noscript":case"script":case"style":r=this.flattenArrayTypeChildren(n,r,o,a);break;default:e=this.mapObjectTypeChildren(n,e,o,a);break}}),this.mapArrayTypeChildrenToProps(r,e)}render(){const{children:s,...e}=this.props;let r={...e},{helmetData:n}=e;if(s&&(r=this.mapChildrenToProps(s,r)),n&&!(n instanceof Is)){const a=n;n=new Is(a.context,!0),delete r.helmetData}return n?Ze.createElement(wr,{...r,context:n.value}):Ze.createElement(rn.Consumer,null,a=>Ze.createElement(wr,{...r,context:a}))}},Ae(Ps,"defaultProps",{defer:!0,encodeSpecialCharacters:!0,prioritizeSeoTags:!1}),Ps);const qa="modulepreload",Ga=function(s){return"/"+s},vr={},Ve=function(e,r,n){let a=Promise.resolve();if(r&&r.length>0){document.getElementsByTagName("link");const o=document.querySelector("meta[property=csp-nonce]"),l=(o==null?void 0:o.nonce)||(o==null?void 0:o.getAttribute("nonce"));a=Promise.allSettled(r.map(d=>{if(d=Ga(d),d in vr)return;vr[d]=!0;const c=d.endsWith(".css"),u=c?'[rel="stylesheet"]':"";if(document.querySelector(`link[href="${d}"]${u}`))return;const h=document.createElement("link");if(h.rel=c?"stylesheet":qa,c||(h.as="script"),h.crossOrigin="",h.href=d,l&&h.setAttribute("nonce",l),document.head.appendChild(h),c)return new Promise((f,g)=>{h.addEventListener("load",f),h.addEventListener("error",()=>g(new Error(`Unable to preload CSS for ${d}`)))})}))}function i(o){const l=new Event("vite:preloadError",{cancelable:!0});if(l.payload=o,window.dispatchEvent(l),!l.defaultPrevented)throw o}return a.then(o=>{for(const l of o||[])l.status==="rejected"&&i(l.reason);return e().catch(i)})},Ha=s=>{let e;return s?e=s:typeof fetch>"u"?e=(...r)=>Ve(async()=>{const{default:n}=await Promise.resolve().then(()=>_t);return{default:n}},void 0).then(({default:n})=>n(...r)):e=fetch,(...r)=>e(...r)};class Qs extends Error{constructor(e,r="FunctionsError",n){super(e),this.name=r,this.context=n}}class Ka extends Qs{constructor(e){super("Failed to send a request to the Edge Function","FunctionsFetchError",e)}}class za extends Qs{constructor(e){super("Relay Error invoking the Edge Function","FunctionsRelayError",e)}}class Wa extends Qs{constructor(e){super("Edge Function returned a non-2xx status code","FunctionsHttpError",e)}}var Rs;(function(s){s.Any="any",s.ApNortheast1="ap-northeast-1",s.ApNortheast2="ap-northeast-2",s.ApSouth1="ap-south-1",s.ApSoutheast1="ap-southeast-1",s.ApSoutheast2="ap-southeast-2",s.CaCentral1="ca-central-1",s.EuCentral1="eu-central-1",s.EuWest1="eu-west-1",s.EuWest2="eu-west-2",s.EuWest3="eu-west-3",s.SaEast1="sa-east-1",s.UsEast1="us-east-1",s.UsWest1="us-west-1",s.UsWest2="us-west-2"})(Rs||(Rs={}));var Va=function(s,e,r,n){function a(i){return i instanceof r?i:new r(function(o){o(i)})}return new(r||(r=Promise))(function(i,o){function l(u){try{c(n.next(u))}catch(h){o(h)}}function d(u){try{c(n.throw(u))}catch(h){o(h)}}function c(u){u.done?i(u.value):a(u.value).then(l,d)}c((n=n.apply(s,e||[])).next())})};class Ja{constructor(e,{headers:r={},customFetch:n,region:a=Rs.Any}={}){this.url=e,this.headers=r,this.region=a,this.fetch=Ha(n)}setAuth(e){this.headers.Authorization=`Bearer ${e}`}invoke(e,r={}){var n;return Va(this,void 0,void 0,function*(){try{const{headers:a,method:i,body:o}=r;let l={},{region:d}=r;d||(d=this.region),d&&d!=="any"&&(l["x-region"]=d);let c;o&&(a&&!Object.prototype.hasOwnProperty.call(a,"Content-Type")||!a)&&(typeof Blob<"u"&&o instanceof Blob||o instanceof ArrayBuffer?(l["Content-Type"]="application/octet-stream",c=o):typeof o=="string"?(l["Content-Type"]="text/plain",c=o):typeof FormData<"u"&&o instanceof FormData?c=o:(l["Content-Type"]="application/json",c=JSON.stringify(o)));const u=yield this.fetch(`${this.url}/${e}`,{method:i||"POST",headers:Object.assign(Object.assign(Object.assign({},l),this.headers),a),body:c}).catch(x=>{throw new Ka(x)}),h=u.headers.get("x-relay-error");if(h&&h==="true")throw new za(u);if(!u.ok)throw new Wa(u);let f=((n=u.headers.get("Content-Type"))!==null&&n!==void 0?n:"text/plain").split(";")[0].trim(),g;return f==="application/json"?g=yield u.json():f==="application/octet-stream"?g=yield u.blob():f==="text/event-stream"?g=u:f==="multipart/form-data"?g=yield u.formData():g=yield u.text(),{data:g,error:null}}catch(a){return{data:null,error:a}}})}}var Ne={},Zs={},ls={},Mt={},cs={},ds={},Ya=function(){if(typeof self<"u")return self;if(typeof window<"u")return window;if(typeof global<"u")return global;throw new Error("unable to locate global object")},bt=Ya();const Qa=bt.fetch,an=bt.fetch.bind(bt),on=bt.Headers,Za=bt.Request,Xa=bt.Response,_t=Object.freeze(Object.defineProperty({__proto__:null,Headers:on,Request:Za,Response:Xa,default:an,fetch:Qa},Symbol.toStringTag,{value:"Module"})),ei=ca(_t);var us={};Object.defineProperty(us,"__esModule",{value:!0});let ti=class extends Error{constructor(e){super(e.message),this.name="PostgrestError",this.details=e.details,this.hint=e.hint,this.code=e.code}};us.default=ti;var ln=Se&&Se.__importDefault||function(s){return s&&s.__esModule?s:{default:s}};Object.defineProperty(ds,"__esModule",{value:!0});const si=ln(ei),ri=ln(us);let ni=class{constructor(e){this.shouldThrowOnError=!1,this.method=e.method,this.url=e.url,this.headers=e.headers,this.schema=e.schema,this.body=e.body,this.shouldThrowOnError=e.shouldThrowOnError,this.signal=e.signal,this.isMaybeSingle=e.isMaybeSingle,e.fetch?this.fetch=e.fetch:typeof fetch>"u"?this.fetch=si.default:this.fetch=fetch}throwOnError(){return this.shouldThrowOnError=!0,this}setHeader(e,r){return this.headers=Object.assign({},this.headers),this.headers[e]=r,this}then(e,r){this.schema===void 0||(["GET","HEAD"].includes(this.method)?this.headers["Accept-Profile"]=this.schema:this.headers["Content-Profile"]=this.schema),this.method!=="GET"&&this.method!=="HEAD"&&(this.headers["Content-Type"]="application/json");const n=this.fetch;let a=n(this.url.toString(),{method:this.method,headers:this.headers,body:JSON.stringify(this.body),signal:this.signal}).then(async i=>{var o,l,d;let c=null,u=null,h=null,f=i.status,g=i.statusText;if(i.ok){if(this.method!=="HEAD"){const w=await i.text();w===""||(this.headers.Accept==="text/csv"||this.headers.Accept&&this.headers.Accept.includes("application/vnd.pgrst.plan+text")?u=w:u=JSON.parse(w))}const v=(o=this.headers.Prefer)===null||o===void 0?void 0:o.match(/count=(exact|planned|estimated)/),y=(l=i.headers.get("content-range"))===null||l===void 0?void 0:l.split("/");v&&y&&y.length>1&&(h=parseInt(y[1])),this.isMaybeSingle&&this.method==="GET"&&Array.isArray(u)&&(u.length>1?(c={code:"PGRST116",details:`Results contain ${u.length} rows, application/vnd.pgrst.object+json requires 1 row`,hint:null,message:"JSON object requested, multiple (or no) rows returned"},u=null,h=null,f=406,g="Not Acceptable"):u.length===1?u=u[0]:u=null)}else{const v=await i.text();try{c=JSON.parse(v),Array.isArray(c)&&i.status===404&&(u=[],c=null,f=200,g="OK")}catch{i.status===404&&v===""?(f=204,g="No Content"):c={message:v}}if(c&&this.isMaybeSingle&&(!((d=c==null?void 0:c.details)===null||d===void 0)&&d.includes("0 rows"))&&(c=null,f=200,g="OK"),c&&this.shouldThrowOnError)throw new ri.default(c)}return{error:c,data:u,count:h,status:f,statusText:g}});return this.shouldThrowOnError||(a=a.catch(i=>{var o,l,d;return{error:{message:`${(o=i==null?void 0:i.name)!==null&&o!==void 0?o:"FetchError"}: ${i==null?void 0:i.message}`,details:`${(l=i==null?void 0:i.stack)!==null&&l!==void 0?l:""}`,hint:"",code:`${(d=i==null?void 0:i.code)!==null&&d!==void 0?d:""}`},data:null,count:null,status:0,statusText:""}})),a.then(e,r)}returns(){return this}overrideTypes(){return this}};ds.default=ni;var ai=Se&&Se.__importDefault||function(s){return s&&s.__esModule?s:{default:s}};Object.defineProperty(cs,"__esModule",{value:!0});const ii=ai(ds);let oi=class extends ii.default{select(e){let r=!1;const n=(e??"*").split("").map(a=>/\s/.test(a)&&!r?"":(a==='"'&&(r=!r),a)).join("");return this.url.searchParams.set("select",n),this.headers.Prefer&&(this.headers.Prefer+=","),this.headers.Prefer+="return=representation",this}order(e,{ascending:r=!0,nullsFirst:n,foreignTable:a,referencedTable:i=a}={}){const o=i?`${i}.order`:"order",l=this.url.searchParams.get(o);return this.url.searchParams.set(o,`${l?`${l},`:""}${e}.${r?"asc":"desc"}${n===void 0?"":n?".nullsfirst":".nullslast"}`),this}limit(e,{foreignTable:r,referencedTable:n=r}={}){const a=typeof n>"u"?"limit":`${n}.limit`;return this.url.searchParams.set(a,`${e}`),this}range(e,r,{foreignTable:n,referencedTable:a=n}={}){const i=typeof a>"u"?"offset":`${a}.offset`,o=typeof a>"u"?"limit":`${a}.limit`;return this.url.searchParams.set(i,`${e}`),this.url.searchParams.set(o,`${r-e+1}`),this}abortSignal(e){return this.signal=e,this}single(){return this.headers.Accept="application/vnd.pgrst.object+json",this}maybeSingle(){return this.method==="GET"?this.headers.Accept="application/json":this.headers.Accept="application/vnd.pgrst.object+json",this.isMaybeSingle=!0,this}csv(){return this.headers.Accept="text/csv",this}geojson(){return this.headers.Accept="application/geo+json",this}explain({analyze:e=!1,verbose:r=!1,settings:n=!1,buffers:a=!1,wal:i=!1,format:o="text"}={}){var l;const d=[e?"analyze":null,r?"verbose":null,n?"settings":null,a?"buffers":null,i?"wal":null].filter(Boolean).join("|"),c=(l=this.headers.Accept)!==null&&l!==void 0?l:"application/json";return this.headers.Accept=`application/vnd.pgrst.plan+${o}; for="${c}"; options=${d};`,o==="json"?this:this}rollback(){var e;return((e=this.headers.Prefer)!==null&&e!==void 0?e:"").trim().length>0?this.headers.Prefer+=",tx=rollback":this.headers.Prefer="tx=rollback",this}returns(){return this}};cs.default=oi;var li=Se&&Se.__importDefault||function(s){return s&&s.__esModule?s:{default:s}};Object.defineProperty(Mt,"__esModule",{value:!0});const ci=li(cs);let di=class extends ci.default{eq(e,r){return this.url.searchParams.append(e,`eq.${r}`),this}neq(e,r){return this.url.searchParams.append(e,`neq.${r}`),this}gt(e,r){return this.url.searchParams.append(e,`gt.${r}`),this}gte(e,r){return this.url.searchParams.append(e,`gte.${r}`),this}lt(e,r){return this.url.searchParams.append(e,`lt.${r}`),this}lte(e,r){return this.url.searchParams.append(e,`lte.${r}`),this}like(e,r){return this.url.searchParams.append(e,`like.${r}`),this}likeAllOf(e,r){return this.url.searchParams.append(e,`like(all).{${r.join(",")}}`),this}likeAnyOf(e,r){return this.url.searchParams.append(e,`like(any).{${r.join(",")}}`),this}ilike(e,r){return this.url.searchParams.append(e,`ilike.${r}`),this}ilikeAllOf(e,r){return this.url.searchParams.append(e,`ilike(all).{${r.join(",")}}`),this}ilikeAnyOf(e,r){return this.url.searchParams.append(e,`ilike(any).{${r.join(",")}}`),this}is(e,r){return this.url.searchParams.append(e,`is.${r}`),this}in(e,r){const n=Array.from(new Set(r)).map(a=>typeof a=="string"&&new RegExp("[,()]").test(a)?`"${a}"`:`${a}`).join(",");return this.url.searchParams.append(e,`in.(${n})`),this}contains(e,r){return typeof r=="string"?this.url.searchParams.append(e,`cs.${r}`):Array.isArray(r)?this.url.searchParams.append(e,`cs.{${r.join(",")}}`):this.url.searchParams.append(e,`cs.${JSON.stringify(r)}`),this}containedBy(e,r){return typeof r=="string"?this.url.searchParams.append(e,`cd.${r}`):Array.isArray(r)?this.url.searchParams.append(e,`cd.{${r.join(",")}}`):this.url.searchParams.append(e,`cd.${JSON.stringify(r)}`),this}rangeGt(e,r){return this.url.searchParams.append(e,`sr.${r}`),this}rangeGte(e,r){return this.url.searchParams.append(e,`nxl.${r}`),this}rangeLt(e,r){return this.url.searchParams.append(e,`sl.${r}`),this}rangeLte(e,r){return this.url.searchParams.append(e,`nxr.${r}`),this}rangeAdjacent(e,r){return this.url.searchParams.append(e,`adj.${r}`),this}overlaps(e,r){return typeof r=="string"?this.url.searchParams.append(e,`ov.${r}`):this.url.searchParams.append(e,`ov.{${r.join(",")}}`),this}textSearch(e,r,{config:n,type:a}={}){let i="";a==="plain"?i="pl":a==="phrase"?i="ph":a==="websearch"&&(i="w");const o=n===void 0?"":`(${n})`;return this.url.searchParams.append(e,`${i}fts${o}.${r}`),this}match(e){return Object.entries(e).forEach(([r,n])=>{this.url.searchParams.append(r,`eq.${n}`)}),this}not(e,r,n){return this.url.searchParams.append(e,`not.${r}.${n}`),this}or(e,{foreignTable:r,referencedTable:n=r}={}){const a=n?`${n}.or`:"or";return this.url.searchParams.append(a,`(${e})`),this}filter(e,r,n){return this.url.searchParams.append(e,`${r}.${n}`),this}};Mt.default=di;var ui=Se&&Se.__importDefault||function(s){return s&&s.__esModule?s:{default:s}};Object.defineProperty(ls,"__esModule",{value:!0});const Pt=ui(Mt);let hi=class{constructor(e,{headers:r={},schema:n,fetch:a}){this.url=e,this.headers=r,this.schema=n,this.fetch=a}select(e,{head:r=!1,count:n}={}){const a=r?"HEAD":"GET";let i=!1;const o=(e??"*").split("").map(l=>/\s/.test(l)&&!i?"":(l==='"'&&(i=!i),l)).join("");return this.url.searchParams.set("select",o),n&&(this.headers.Prefer=`count=${n}`),new Pt.default({method:a,url:this.url,headers:this.headers,schema:this.schema,fetch:this.fetch,allowEmpty:!1})}insert(e,{count:r,defaultToNull:n=!0}={}){const a="POST",i=[];if(this.headers.Prefer&&i.push(this.headers.Prefer),r&&i.push(`count=${r}`),n||i.push("missing=default"),this.headers.Prefer=i.join(","),Array.isArray(e)){const o=e.reduce((l,d)=>l.concat(Object.keys(d)),[]);if(o.length>0){const l=[...new Set(o)].map(d=>`"${d}"`);this.url.searchParams.set("columns",l.join(","))}}return new Pt.default({method:a,url:this.url,headers:this.headers,schema:this.schema,body:e,fetch:this.fetch,allowEmpty:!1})}upsert(e,{onConflict:r,ignoreDuplicates:n=!1,count:a,defaultToNull:i=!0}={}){const o="POST",l=[`resolution=${n?"ignore":"merge"}-duplicates`];if(r!==void 0&&this.url.searchParams.set("on_conflict",r),this.headers.Prefer&&l.push(this.headers.Prefer),a&&l.push(`count=${a}`),i||l.push("missing=default"),this.headers.Prefer=l.join(","),Array.isArray(e)){const d=e.reduce((c,u)=>c.concat(Object.keys(u)),[]);if(d.length>0){const c=[...new Set(d)].map(u=>`"${u}"`);this.url.searchParams.set("columns",c.join(","))}}return new Pt.default({method:o,url:this.url,headers:this.headers,schema:this.schema,body:e,fetch:this.fetch,allowEmpty:!1})}update(e,{count:r}={}){const n="PATCH",a=[];return this.headers.Prefer&&a.push(this.headers.Prefer),r&&a.push(`count=${r}`),this.headers.Prefer=a.join(","),new Pt.default({method:n,url:this.url,headers:this.headers,schema:this.schema,body:e,fetch:this.fetch,allowEmpty:!1})}delete({count:e}={}){const r="DELETE",n=[];return e&&n.push(`count=${e}`),this.headers.Prefer&&n.unshift(this.headers.Prefer),this.headers.Prefer=n.join(","),new Pt.default({method:r,url:this.url,headers:this.headers,schema:this.schema,fetch:this.fetch,allowEmpty:!1})}};ls.default=hi;var hs={},fs={};Object.defineProperty(fs,"__esModule",{value:!0});fs.version=void 0;fs.version="0.0.0-automated";Object.defineProperty(hs,"__esModule",{value:!0});hs.DEFAULT_HEADERS=void 0;const fi=fs;hs.DEFAULT_HEADERS={"X-Client-Info":`postgrest-js/${fi.version}`};var cn=Se&&Se.__importDefault||function(s){return s&&s.__esModule?s:{default:s}};Object.defineProperty(Zs,"__esModule",{value:!0});const mi=cn(ls),gi=cn(Mt),pi=hs;let yi=class dn{constructor(e,{headers:r={},schema:n,fetch:a}={}){this.url=e,this.headers=Object.assign(Object.assign({},pi.DEFAULT_HEADERS),r),this.schemaName=n,this.fetch=a}from(e){const r=new URL(`${this.url}/${e}`);return new mi.default(r,{headers:Object.assign({},this.headers),schema:this.schemaName,fetch:this.fetch})}schema(e){return new dn(this.url,{headers:this.headers,schema:e,fetch:this.fetch})}rpc(e,r={},{head:n=!1,get:a=!1,count:i}={}){let o;const l=new URL(`${this.url}/rpc/${e}`);let d;n||a?(o=n?"HEAD":"GET",Object.entries(r).filter(([u,h])=>h!==void 0).map(([u,h])=>[u,Array.isArray(h)?`{${h.join(",")}}`:`${h}`]).forEach(([u,h])=>{l.searchParams.append(u,h)})):(o="POST",d=r);const c=Object.assign({},this.headers);return i&&(c.Prefer=`count=${i}`),new gi.default({method:o,url:l,headers:c,schema:this.schemaName,body:d,fetch:this.fetch,allowEmpty:!1})}};Zs.default=yi;var Nt=Se&&Se.__importDefault||function(s){return s&&s.__esModule?s:{default:s}};Object.defineProperty(Ne,"__esModule",{value:!0});Ne.PostgrestError=Ne.PostgrestBuilder=Ne.PostgrestTransformBuilder=Ne.PostgrestFilterBuilder=Ne.PostgrestQueryBuilder=Ne.PostgrestClient=void 0;const un=Nt(Zs);Ne.PostgrestClient=un.default;const hn=Nt(ls);Ne.PostgrestQueryBuilder=hn.default;const fn=Nt(Mt);Ne.PostgrestFilterBuilder=fn.default;const mn=Nt(cs);Ne.PostgrestTransformBuilder=mn.default;const gn=Nt(ds);Ne.PostgrestBuilder=gn.default;const pn=Nt(us);Ne.PostgrestError=pn.default;var xi=Ne.default={PostgrestClient:un.default,PostgrestQueryBuilder:hn.default,PostgrestFilterBuilder:fn.default,PostgrestTransformBuilder:mn.default,PostgrestBuilder:gn.default,PostgrestError:pn.default};const{PostgrestClient:bi,PostgrestQueryBuilder:gd,PostgrestFilterBuilder:pd,PostgrestTransformBuilder:yd,PostgrestBuilder:xd,PostgrestError:bd}=xi;function wi(){if(typeof WebSocket<"u")return WebSocket;if(typeof global.WebSocket<"u")return global.WebSocket;if(typeof window.WebSocket<"u")return window.WebSocket;if(typeof self.WebSocket<"u")return self.WebSocket;throw new Error("`WebSocket` is not supported in this environment")}const vi=wi(),ji="2.11.13",_i={"X-Client-Info":`realtime-js/${ji}`},Ni="1.0.0",yn=1e4,Si=1e3;var It;(function(s){s[s.connecting=0]="connecting",s[s.open=1]="open",s[s.closing=2]="closing",s[s.closed=3]="closed"})(It||(It={}));var be;(function(s){s.closed="closed",s.errored="errored",s.joined="joined",s.joining="joining",s.leaving="leaving"})(be||(be={}));var Ie;(function(s){s.close="phx_close",s.error="phx_error",s.join="phx_join",s.reply="phx_reply",s.leave="phx_leave",s.access_token="access_token"})(Ie||(Ie={}));var Ds;(function(s){s.websocket="websocket"})(Ds||(Ds={}));var rt;(function(s){s.Connecting="connecting",s.Open="open",s.Closing="closing",s.Closed="closed"})(rt||(rt={}));class ki{constructor(){this.HEADER_LENGTH=1}decode(e,r){return e.constructor===ArrayBuffer?r(this._binaryDecode(e)):r(typeof e=="string"?JSON.parse(e):{})}_binaryDecode(e){const r=new DataView(e),n=new TextDecoder;return this._decodeBroadcast(e,r,n)}_decodeBroadcast(e,r,n){const a=r.getUint8(1),i=r.getUint8(2);let o=this.HEADER_LENGTH+2;const l=n.decode(e.slice(o,o+a));o=o+a;const d=n.decode(e.slice(o,o+i));o=o+i;const c=JSON.parse(n.decode(e.slice(o,e.byteLength)));return{ref:null,topic:l,event:d,payload:c}}}class xn{constructor(e,r){this.callback=e,this.timerCalc=r,this.timer=void 0,this.tries=0,this.callback=e,this.timerCalc=r}reset(){this.tries=0,clearTimeout(this.timer)}scheduleTimeout(){clearTimeout(this.timer),this.timer=setTimeout(()=>{this.tries=this.tries+1,this.callback()},this.timerCalc(this.tries+1))}}var oe;(function(s){s.abstime="abstime",s.bool="bool",s.date="date",s.daterange="daterange",s.float4="float4",s.float8="float8",s.int2="int2",s.int4="int4",s.int4range="int4range",s.int8="int8",s.int8range="int8range",s.json="json",s.jsonb="jsonb",s.money="money",s.numeric="numeric",s.oid="oid",s.reltime="reltime",s.text="text",s.time="time",s.timestamp="timestamp",s.timestamptz="timestamptz",s.timetz="timetz",s.tsrange="tsrange",s.tstzrange="tstzrange"})(oe||(oe={}));const jr=(s,e,r={})=>{var n;const a=(n=r.skipTypes)!==null&&n!==void 0?n:[];return Object.keys(e).reduce((i,o)=>(i[o]=Ei(o,s,e,a),i),{})},Ei=(s,e,r,n)=>{const a=e.find(l=>l.name===s),i=a==null?void 0:a.type,o=r[s];return i&&!n.includes(i)?bn(i,o):$s(o)},bn=(s,e)=>{if(s.charAt(0)==="_"){const r=s.slice(1,s.length);return Ai(e,r)}switch(s){case oe.bool:return Ti(e);case oe.float4:case oe.float8:case oe.int2:case oe.int4:case oe.int8:case oe.numeric:case oe.oid:return Ci(e);case oe.json:case oe.jsonb:return Pi(e);case oe.timestamp:return Oi(e);case oe.abstime:case oe.date:case oe.daterange:case oe.int4range:case oe.int8range:case oe.money:case oe.reltime:case oe.text:case oe.time:case oe.timestamptz:case oe.timetz:case oe.tsrange:case oe.tstzrange:return $s(e);default:return $s(e)}},$s=s=>s,Ti=s=>{switch(s){case"t":return!0;case"f":return!1;default:return s}},Ci=s=>{if(typeof s=="string"){const e=parseFloat(s);if(!Number.isNaN(e))return e}return s},Pi=s=>{if(typeof s=="string")try{return JSON.parse(s)}catch(e){return console.log(`JSON parse error: ${e}`),s}return s},Ai=(s,e)=>{if(typeof s!="string")return s;const r=s.length-1,n=s[r];if(s[0]==="{"&&n==="}"){let i;const o=s.slice(1,r);try{i=JSON.parse("["+o+"]")}catch{i=o?o.split(","):[]}return i.map(l=>bn(e,l))}return s},Oi=s=>typeof s=="string"?s.replace(" ","T"):s,wn=s=>{let e=s;return e=e.replace(/^ws/i,"http"),e=e.replace(/(\/socket\/websocket|\/socket|\/websocket)\/?$/i,""),e.replace(/\/+$/,"")};class vs{constructor(e,r,n={},a=yn){this.channel=e,this.event=r,this.payload=n,this.timeout=a,this.sent=!1,this.timeoutTimer=void 0,this.ref="",this.receivedResp=null,this.recHooks=[],this.refEvent=null}resend(e){this.timeout=e,this._cancelRefEvent(),this.ref="",this.refEvent=null,this.receivedResp=null,this.sent=!1,this.send()}send(){this._hasReceived("timeout")||(this.startTimeout(),this.sent=!0,this.channel.socket.push({topic:this.channel.topic,event:this.event,payload:this.payload,ref:this.ref,join_ref:this.channel._joinRef()}))}updatePayload(e){this.payload=Object.assign(Object.assign({},this.payload),e)}receive(e,r){var n;return this._hasReceived(e)&&r((n=this.receivedResp)===null||n===void 0?void 0:n.response),this.recHooks.push({status:e,callback:r}),this}startTimeout(){if(this.timeoutTimer)return;this.ref=this.channel.socket._makeRef(),this.refEvent=this.channel._replyEventName(this.ref);const e=r=>{this._cancelRefEvent(),this._cancelTimeout(),this.receivedResp=r,this._matchReceive(r)};this.channel._on(this.refEvent,{},e),this.timeoutTimer=setTimeout(()=>{this.trigger("timeout",{})},this.timeout)}trigger(e,r){this.refEvent&&this.channel._trigger(this.refEvent,{status:e,response:r})}destroy(){this._cancelRefEvent(),this._cancelTimeout()}_cancelRefEvent(){this.refEvent&&this.channel._off(this.refEvent,{})}_cancelTimeout(){clearTimeout(this.timeoutTimer),this.timeoutTimer=void 0}_matchReceive({status:e,response:r}){this.recHooks.filter(n=>n.status===e).forEach(n=>n.callback(r))}_hasReceived(e){return this.receivedResp&&this.receivedResp.status===e}}var _r;(function(s){s.SYNC="sync",s.JOIN="join",s.LEAVE="leave"})(_r||(_r={}));class Lt{constructor(e,r){this.channel=e,this.state={},this.pendingDiffs=[],this.joinRef=null,this.caller={onJoin:()=>{},onLeave:()=>{},onSync:()=>{}};const n=(r==null?void 0:r.events)||{state:"presence_state",diff:"presence_diff"};this.channel._on(n.state,{},a=>{const{onJoin:i,onLeave:o,onSync:l}=this.caller;this.joinRef=this.channel._joinRef(),this.state=Lt.syncState(this.state,a,i,o),this.pendingDiffs.forEach(d=>{this.state=Lt.syncDiff(this.state,d,i,o)}),this.pendingDiffs=[],l()}),this.channel._on(n.diff,{},a=>{const{onJoin:i,onLeave:o,onSync:l}=this.caller;this.inPendingSyncState()?this.pendingDiffs.push(a):(this.state=Lt.syncDiff(this.state,a,i,o),l())}),this.onJoin((a,i,o)=>{this.channel._trigger("presence",{event:"join",key:a,currentPresences:i,newPresences:o})}),this.onLeave((a,i,o)=>{this.channel._trigger("presence",{event:"leave",key:a,currentPresences:i,leftPresences:o})}),this.onSync(()=>{this.channel._trigger("presence",{event:"sync"})})}static syncState(e,r,n,a){const i=this.cloneDeep(e),o=this.transformState(r),l={},d={};return this.map(i,(c,u)=>{o[c]||(d[c]=u)}),this.map(o,(c,u)=>{const h=i[c];if(h){const f=u.map(y=>y.presence_ref),g=h.map(y=>y.presence_ref),x=u.filter(y=>g.indexOf(y.presence_ref)<0),v=h.filter(y=>f.indexOf(y.presence_ref)<0);x.length>0&&(l[c]=x),v.length>0&&(d[c]=v)}else l[c]=u}),this.syncDiff(i,{joins:l,leaves:d},n,a)}static syncDiff(e,r,n,a){const{joins:i,leaves:o}={joins:this.transformState(r.joins),leaves:this.transformState(r.leaves)};return n||(n=()=>{}),a||(a=()=>{}),this.map(i,(l,d)=>{var c;const u=(c=e[l])!==null&&c!==void 0?c:[];if(e[l]=this.cloneDeep(d),u.length>0){const h=e[l].map(g=>g.presence_ref),f=u.filter(g=>h.indexOf(g.presence_ref)<0);e[l].unshift(...f)}n(l,u,d)}),this.map(o,(l,d)=>{let c=e[l];if(!c)return;const u=d.map(h=>h.presence_ref);c=c.filter(h=>u.indexOf(h.presence_ref)<0),e[l]=c,a(l,c,d),c.length===0&&delete e[l]}),e}static map(e,r){return Object.getOwnPropertyNames(e).map(n=>r(n,e[n]))}static transformState(e){return e=this.cloneDeep(e),Object.getOwnPropertyNames(e).reduce((r,n)=>{const a=e[n];return"metas"in a?r[n]=a.metas.map(i=>(i.presence_ref=i.phx_ref,delete i.phx_ref,delete i.phx_ref_prev,i)):r[n]=a,r},{})}static cloneDeep(e){return JSON.parse(JSON.stringify(e))}onJoin(e){this.caller.onJoin=e}onLeave(e){this.caller.onLeave=e}onSync(e){this.caller.onSync=e}inPendingSyncState(){return!this.joinRef||this.joinRef!==this.channel._joinRef()}}var Nr;(function(s){s.ALL="*",s.INSERT="INSERT",s.UPDATE="UPDATE",s.DELETE="DELETE"})(Nr||(Nr={}));var Sr;(function(s){s.BROADCAST="broadcast",s.PRESENCE="presence",s.POSTGRES_CHANGES="postgres_changes",s.SYSTEM="system"})(Sr||(Sr={}));var ze;(function(s){s.SUBSCRIBED="SUBSCRIBED",s.TIMED_OUT="TIMED_OUT",s.CLOSED="CLOSED",s.CHANNEL_ERROR="CHANNEL_ERROR"})(ze||(ze={}));class Xs{constructor(e,r={config:{}},n){this.topic=e,this.params=r,this.socket=n,this.bindings={},this.state=be.closed,this.joinedOnce=!1,this.pushBuffer=[],this.subTopic=e.replace(/^realtime:/i,""),this.params.config=Object.assign({broadcast:{ack:!1,self:!1},presence:{key:""},private:!1},r.config),this.timeout=this.socket.timeout,this.joinPush=new vs(this,Ie.join,this.params,this.timeout),this.rejoinTimer=new xn(()=>this._rejoinUntilConnected(),this.socket.reconnectAfterMs),this.joinPush.receive("ok",()=>{this.state=be.joined,this.rejoinTimer.reset(),this.pushBuffer.forEach(a=>a.send()),this.pushBuffer=[]}),this._onClose(()=>{this.rejoinTimer.reset(),this.socket.log("channel",`close ${this.topic} ${this._joinRef()}`),this.state=be.closed,this.socket._remove(this)}),this._onError(a=>{this._isLeaving()||this._isClosed()||(this.socket.log("channel",`error ${this.topic}`,a),this.state=be.errored,this.rejoinTimer.scheduleTimeout())}),this.joinPush.receive("timeout",()=>{this._isJoining()&&(this.socket.log("channel",`timeout ${this.topic}`,this.joinPush.timeout),this.state=be.errored,this.rejoinTimer.scheduleTimeout())}),this._on(Ie.reply,{},(a,i)=>{this._trigger(this._replyEventName(i),a)}),this.presence=new Lt(this),this.broadcastEndpointURL=wn(this.socket.endPoint)+"/api/broadcast",this.private=this.params.config.private||!1}subscribe(e,r=this.timeout){var n,a;if(this.socket.isConnected()||this.socket.connect(),this.state==be.closed){const{config:{broadcast:i,presence:o,private:l}}=this.params;this._onError(u=>e==null?void 0:e(ze.CHANNEL_ERROR,u)),this._onClose(()=>e==null?void 0:e(ze.CLOSED));const d={},c={broadcast:i,presence:o,postgres_changes:(a=(n=this.bindings.postgres_changes)===null||n===void 0?void 0:n.map(u=>u.filter))!==null&&a!==void 0?a:[],private:l};this.socket.accessTokenValue&&(d.access_token=this.socket.accessTokenValue),this.updateJoinPayload(Object.assign({config:c},d)),this.joinedOnce=!0,this._rejoin(r),this.joinPush.receive("ok",async({postgres_changes:u})=>{var h;if(this.socket.setAuth(),u===void 0){e==null||e(ze.SUBSCRIBED);return}else{const f=this.bindings.postgres_changes,g=(h=f==null?void 0:f.length)!==null&&h!==void 0?h:0,x=[];for(let v=0;v<g;v++){const y=f[v],{filter:{event:w,schema:P,table:C,filter:D}}=y,k=u&&u[v];if(k&&k.event===w&&k.schema===P&&k.table===C&&k.filter===D)x.push(Object.assign(Object.assign({},y),{id:k.id}));else{this.unsubscribe(),this.state=be.errored,e==null||e(ze.CHANNEL_ERROR,new Error("mismatch between server and client bindings for postgres changes"));return}}this.bindings.postgres_changes=x,e&&e(ze.SUBSCRIBED);return}}).receive("error",u=>{this.state=be.errored,e==null||e(ze.CHANNEL_ERROR,new Error(JSON.stringify(Object.values(u).join(", ")||"error")))}).receive("timeout",()=>{e==null||e(ze.TIMED_OUT)})}return this}presenceState(){return this.presence.state}async track(e,r={}){return await this.send({type:"presence",event:"track",payload:e},r.timeout||this.timeout)}async untrack(e={}){return await this.send({type:"presence",event:"untrack"},e)}on(e,r,n){return this._on(e,r,n)}async send(e,r={}){var n,a;if(!this._canPush()&&e.type==="broadcast"){const{event:i,payload:o}=e,d={method:"POST",headers:{Authorization:this.socket.accessTokenValue?`Bearer ${this.socket.accessTokenValue}`:"",apikey:this.socket.apiKey?this.socket.apiKey:"","Content-Type":"application/json"},body:JSON.stringify({messages:[{topic:this.subTopic,event:i,payload:o,private:this.private}]})};try{const c=await this._fetchWithTimeout(this.broadcastEndpointURL,d,(n=r.timeout)!==null&&n!==void 0?n:this.timeout);return await((a=c.body)===null||a===void 0?void 0:a.cancel()),c.ok?"ok":"error"}catch(c){return c.name==="AbortError"?"timed out":"error"}}else return new Promise(i=>{var o,l,d;const c=this._push(e.type,e,r.timeout||this.timeout);e.type==="broadcast"&&!(!((d=(l=(o=this.params)===null||o===void 0?void 0:o.config)===null||l===void 0?void 0:l.broadcast)===null||d===void 0)&&d.ack)&&i("ok"),c.receive("ok",()=>i("ok")),c.receive("error",()=>i("error")),c.receive("timeout",()=>i("timed out"))})}updateJoinPayload(e){this.joinPush.updatePayload(e)}unsubscribe(e=this.timeout){this.state=be.leaving;const r=()=>{this.socket.log("channel",`leave ${this.topic}`),this._trigger(Ie.close,"leave",this._joinRef())};this.joinPush.destroy();let n=null;return new Promise(a=>{n=new vs(this,Ie.leave,{},e),n.receive("ok",()=>{r(),a("ok")}).receive("timeout",()=>{r(),a("timed out")}).receive("error",()=>{a("error")}),n.send(),this._canPush()||n.trigger("ok",{})}).finally(()=>{n==null||n.destroy()})}teardown(){this.pushBuffer.forEach(e=>e.destroy()),this.rejoinTimer&&clearTimeout(this.rejoinTimer.timer),this.joinPush.destroy()}async _fetchWithTimeout(e,r,n){const a=new AbortController,i=setTimeout(()=>a.abort(),n),o=await this.socket.fetch(e,Object.assign(Object.assign({},r),{signal:a.signal}));return clearTimeout(i),o}_push(e,r,n=this.timeout){if(!this.joinedOnce)throw`tried to push '${e}' to '${this.topic}' before joining. Use channel.subscribe() before pushing events`;let a=new vs(this,e,r,n);return this._canPush()?a.send():(a.startTimeout(),this.pushBuffer.push(a)),a}_onMessage(e,r,n){return r}_isMember(e){return this.topic===e}_joinRef(){return this.joinPush.ref}_trigger(e,r,n){var a,i;const o=e.toLocaleLowerCase(),{close:l,error:d,leave:c,join:u}=Ie;if(n&&[l,d,c,u].indexOf(o)>=0&&n!==this._joinRef())return;let f=this._onMessage(o,r,n);if(r&&!f)throw"channel onMessage callbacks must return the payload, modified or unmodified";["insert","update","delete"].includes(o)?(a=this.bindings.postgres_changes)===null||a===void 0||a.filter(g=>{var x,v,y;return((x=g.filter)===null||x===void 0?void 0:x.event)==="*"||((y=(v=g.filter)===null||v===void 0?void 0:v.event)===null||y===void 0?void 0:y.toLocaleLowerCase())===o}).map(g=>g.callback(f,n)):(i=this.bindings[o])===null||i===void 0||i.filter(g=>{var x,v,y,w,P,C;if(["broadcast","presence","postgres_changes"].includes(o))if("id"in g){const D=g.id,k=(x=g.filter)===null||x===void 0?void 0:x.event;return D&&((v=r.ids)===null||v===void 0?void 0:v.includes(D))&&(k==="*"||(k==null?void 0:k.toLocaleLowerCase())===((y=r.data)===null||y===void 0?void 0:y.type.toLocaleLowerCase()))}else{const D=(P=(w=g==null?void 0:g.filter)===null||w===void 0?void 0:w.event)===null||P===void 0?void 0:P.toLocaleLowerCase();return D==="*"||D===((C=r==null?void 0:r.event)===null||C===void 0?void 0:C.toLocaleLowerCase())}else return g.type.toLocaleLowerCase()===o}).map(g=>{if(typeof f=="object"&&"ids"in f){const x=f.data,{schema:v,table:y,commit_timestamp:w,type:P,errors:C}=x;f=Object.assign(Object.assign({},{schema:v,table:y,commit_timestamp:w,eventType:P,new:{},old:{},errors:C}),this._getPayloadRecords(x))}g.callback(f,n)})}_isClosed(){return this.state===be.closed}_isJoined(){return this.state===be.joined}_isJoining(){return this.state===be.joining}_isLeaving(){return this.state===be.leaving}_replyEventName(e){return`chan_reply_${e}`}_on(e,r,n){const a=e.toLocaleLowerCase(),i={type:a,filter:r,callback:n};return this.bindings[a]?this.bindings[a].push(i):this.bindings[a]=[i],this}_off(e,r){const n=e.toLocaleLowerCase();return this.bindings[n]=this.bindings[n].filter(a=>{var i;return!(((i=a.type)===null||i===void 0?void 0:i.toLocaleLowerCase())===n&&Xs.isEqual(a.filter,r))}),this}static isEqual(e,r){if(Object.keys(e).length!==Object.keys(r).length)return!1;for(const n in e)if(e[n]!==r[n])return!1;return!0}_rejoinUntilConnected(){this.rejoinTimer.scheduleTimeout(),this.socket.isConnected()&&this._rejoin()}_onClose(e){this._on(Ie.close,{},e)}_onError(e){this._on(Ie.error,{},r=>e(r))}_canPush(){return this.socket.isConnected()&&this._isJoined()}_rejoin(e=this.timeout){this._isLeaving()||(this.socket._leaveOpenTopic(this.topic),this.state=be.joining,this.joinPush.resend(e))}_getPayloadRecords(e){const r={new:{},old:{}};return(e.type==="INSERT"||e.type==="UPDATE")&&(r.new=jr(e.columns,e.record)),(e.type==="UPDATE"||e.type==="DELETE")&&(r.old=jr(e.columns,e.old_record)),r}}const kr=()=>{},Ii=` addEventListener("message", (e) => { if (e.data.event === "start") { setInterval(() => postMessage({ event: "keepAlive" }), e.data.interval); } });`;class Li{constructor(e,r){var n;this.accessTokenValue=null,this.apiKey=null,this.channels=new Array,this.endPoint="",this.httpEndpoint="",this.headers=_i,this.params={},this.timeout=yn,this.heartbeatIntervalMs=25e3,this.heartbeatTimer=void 0,this.pendingHeartbeatRef=null,this.heartbeatCallback=kr,this.ref=0,this.logger=kr,this.conn=null,this.sendBuffer=[],this.serializer=new ki,this.stateChangeCallbacks={open:[],close:[],error:[],message:[]},this.accessToken=null,this._resolveFetch=i=>{let o;return i?o=i:typeof fetch>"u"?o=(...l)=>Ve(async()=>{const{default:d}=await Promise.resolve().then(()=>_t);return{default:d}},void 0).then(({default:d})=>d(...l)):o=fetch,(...l)=>o(...l)},this.endPoint=`${e}/${Ds.websocket}`,this.httpEndpoint=wn(e),r!=null&&r.transport?this.transport=r.transport:this.transport=null,r!=null&&r.params&&(this.params=r.params),r!=null&&r.headers&&(this.headers=Object.assign(Object.assign({},this.headers),r.headers)),r!=null&&r.timeout&&(this.timeout=r.timeout),r!=null&&r.logger&&(this.logger=r.logger),(r!=null&&r.logLevel||r!=null&&r.log_level)&&(this.logLevel=r.logLevel||r.log_level,this.params=Object.assign(Object.assign({},this.params),{log_level:this.logLevel})),r!=null&&r.heartbeatIntervalMs&&(this.heartbeatIntervalMs=r.heartbeatIntervalMs);const a=(n=r==null?void 0:r.params)===null||n===void 0?void 0:n.apikey;if(a&&(this.accessTokenValue=a,this.apiKey=a),this.reconnectAfterMs=r!=null&&r.reconnectAfterMs?r.reconnectAfterMs:i=>[1e3,2e3,5e3,1e4][i-1]||1e4,this.encode=r!=null&&r.encode?r.encode:(i,o)=>o(JSON.stringify(i)),this.decode=r!=null&&r.decode?r.decode:this.serializer.decode.bind(this.serializer),this.reconnectTimer=new xn(async()=>{this.disconnect(),this.connect()},this.reconnectAfterMs),this.fetch=this._resolveFetch(r==null?void 0:r.fetch),r!=null&&r.worker){if(typeof window<"u"&&!window.Worker)throw new Error("Web Worker is not supported");this.worker=(r==null?void 0:r.worker)||!1,this.workerUrl=r==null?void 0:r.workerUrl}this.accessToken=(r==null?void 0:r.accessToken)||null}connect(){this.conn||(this.transport||(this.transport=vi),this.conn=new this.transport(this.endpointURL(),void 0,{headers:this.headers}),this.setupConnection())}endpointURL(){return this._appendParams(this.endPoint,Object.assign({},this.params,{vsn:Ni}))}disconnect(e,r){this.conn&&(this.conn.onclose=function(){},e?this.conn.close(e,r??""):this.conn.close(),this.conn=null,this.heartbeatTimer&&clearInterval(this.heartbeatTimer),this.reconnectTimer.reset(),this.channels.forEach(n=>n.teardown()))}getChannels(){return this.channels}async removeChannel(e){const r=await e.unsubscribe();return this.channels.length===0&&this.disconnect(),r}async removeAllChannels(){const e=await Promise.all(this.channels.map(r=>r.unsubscribe()));return this.channels=[],this.disconnect(),e}log(e,r,n){this.logger(e,r,n)}connectionState(){switch(this.conn&&this.conn.readyState){case It.connecting:return rt.Connecting;case It.open:return rt.Open;case It.closing:return rt.Closing;default:return rt.Closed}}isConnected(){return this.connectionState()===rt.Open}channel(e,r={config:{}}){const n=`realtime:${e}`,a=this.getChannels().find(i=>i.topic===n);if(a)return a;{const i=new Xs(`realtime:${e}`,r,this);return this.channels.push(i),i}}push(e){const{topic:r,event:n,payload:a,ref:i}=e,o=()=>{this.encode(e,l=>{var d;(d=this.conn)===null||d===void 0||d.send(l)})};this.log("push",`${r} ${n} (${i})`,a),this.isConnected()?o():this.sendBuffer.push(o)}async setAuth(e=null){let r=e||this.accessToken&&await this.accessToken()||this.accessTokenValue;this.accessTokenValue!=r&&(this.accessTokenValue=r,this.channels.forEach(n=>{r&&n.updateJoinPayload({access_token:r,version:this.headers&&this.headers["X-Client-Info"]}),n.joinedOnce&&n._isJoined()&&n._push(Ie.access_token,{access_token:r})}))}async sendHeartbeat(){var e;if(!this.isConnected()){this.heartbeatCallback("disconnected");return}if(this.pendingHeartbeatRef){this.pendingHeartbeatRef=null,this.log("transport","heartbeat timeout. Attempting to re-establish connection"),this.heartbeatCallback("timeout"),(e=this.conn)===null||e===void 0||e.close(Si,"hearbeat timeout");return}this.pendingHeartbeatRef=this._makeRef(),this.push({topic:"phoenix",event:"heartbeat",payload:{},ref:this.pendingHeartbeatRef}),this.heartbeatCallback("sent"),await this.setAuth()}onHeartbeat(e){this.heartbeatCallback=e}flushSendBuffer(){this.isConnected()&&this.sendBuffer.length>0&&(this.sendBuffer.forEach(e=>e()),this.sendBuffer=[])}_makeRef(){let e=this.ref+1;return e===this.ref?this.ref=0:this.ref=e,this.ref.toString()}_leaveOpenTopic(e){let r=this.channels.find(n=>n.topic===e&&(n._isJoined()||n._isJoining()));r&&(this.log("transport",`leaving duplicate topic "${e}"`),r.unsubscribe())}_remove(e){this.channels=this.channels.filter(r=>r.topic!==e.topic)}setupConnection(){this.conn&&(this.conn.binaryType="arraybuffer",this.conn.onopen=()=>this._onConnOpen(),this.conn.onerror=e=>this._onConnError(e),this.conn.onmessage=e=>this._onConnMessage(e),this.conn.onclose=e=>this._onConnClose(e))}_onConnMessage(e){this.decode(e.data,r=>{let{topic:n,event:a,payload:i,ref:o}=r;n==="phoenix"&&a==="phx_reply"&&this.heartbeatCallback(r.payload.status=="ok"?"ok":"error"),o&&o===this.pendingHeartbeatRef&&(this.pendingHeartbeatRef=null),this.log("receive",`${i.status||""} ${n} ${a} ${o&&"("+o+")"||""}`,i),Array.from(this.channels).filter(l=>l._isMember(n)).forEach(l=>l._trigger(a,i,o)),this.stateChangeCallbacks.message.forEach(l=>l(r))})}_onConnOpen(){this.log("transport",`connected to ${this.endpointURL()}`),this.flushSendBuffer(),this.reconnectTimer.reset(),this.worker?this.workerRef||this._startWorkerHeartbeat():this._startHeartbeat(),this.stateChangeCallbacks.open.forEach(e=>e())}_startHeartbeat(){this.heartbeatTimer&&clearInterval(this.heartbeatTimer),this.heartbeatTimer=setInterval(()=>this.sendHeartbeat(),this.heartbeatIntervalMs)}_startWorkerHeartbeat(){this.workerUrl?this.log("worker",`starting worker for from ${this.workerUrl}`):this.log("worker","starting default worker");const e=this._workerObjectUrl(this.workerUrl);this.workerRef=new Worker(e),this.workerRef.onerror=r=>{this.log("worker","worker error",r.message),this.workerRef.terminate()},this.workerRef.onmessage=r=>{r.data.event==="keepAlive"&&this.sendHeartbeat()},this.workerRef.postMessage({event:"start",interval:this.heartbeatIntervalMs})}_onConnClose(e){this.log("transport","close",e),this._triggerChanError(),this.heartbeatTimer&&clearInterval(this.heartbeatTimer),this.reconnectTimer.scheduleTimeout(),this.stateChangeCallbacks.close.forEach(r=>r(e))}_onConnError(e){this.log("transport",`${e}`),this._triggerChanError(),this.stateChangeCallbacks.error.forEach(r=>r(e))}_triggerChanError(){this.channels.forEach(e=>e._trigger(Ie.error))}_appendParams(e,r){if(Object.keys(r).length===0)return e;const n=e.match(/\?/)?"&":"?",a=new URLSearchParams(r);return`${e}${n}${a}`}_workerObjectUrl(e){let r;if(e)r=e;else{const n=new Blob([Ii],{type:"application/javascript"});r=URL.createObjectURL(n)}return r}}class er extends Error{constructor(e){super(e),this.__isStorageError=!0,this.name="StorageError"}}function pe(s){return typeof s=="object"&&s!==null&&"__isStorageError"in s}class Ri extends er{constructor(e,r){super(e),this.name="StorageApiError",this.status=r}toJSON(){return{name:this.name,message:this.message,status:this.status}}}class Us extends er{constructor(e,r){super(e),this.name="StorageUnknownError",this.originalError=r}}var Di=function(s,e,r,n){function a(i){return i instanceof r?i:new r(function(o){o(i)})}return new(r||(r=Promise))(function(i,o){function l(u){try{c(n.next(u))}catch(h){o(h)}}function d(u){try{c(n.throw(u))}catch(h){o(h)}}function c(u){u.done?i(u.value):a(u.value).then(l,d)}c((n=n.apply(s,e||[])).next())})};const vn=s=>{let e;return s?e=s:typeof fetch>"u"?e=(...r)=>Ve(async()=>{const{default:n}=await Promise.resolve().then(()=>_t);return{default:n}},void 0).then(({default:n})=>n(...r)):e=fetch,(...r)=>e(...r)},$i=()=>Di(void 0,void 0,void 0,function*(){return typeof Response>"u"?(yield Ve(()=>Promise.resolve().then(()=>_t),void 0)).Response:Response}),Ms=s=>{if(Array.isArray(s))return s.map(r=>Ms(r));if(typeof s=="function"||s!==Object(s))return s;const e={};return Object.entries(s).forEach(([r,n])=>{const a=r.replace(/([-_][a-z])/gi,i=>i.toUpperCase().replace(/[-_]/g,""));e[a]=Ms(n)}),e};var ot=function(s,e,r,n){function a(i){return i instanceof r?i:new r(function(o){o(i)})}return new(r||(r=Promise))(function(i,o){function l(u){try{c(n.next(u))}catch(h){o(h)}}function d(u){try{c(n.throw(u))}catch(h){o(h)}}function c(u){u.done?i(u.value):a(u.value).then(l,d)}c((n=n.apply(s,e||[])).next())})};const js=s=>s.msg||s.message||s.error_description||s.error||JSON.stringify(s),Ui=(s,e,r)=>ot(void 0,void 0,void 0,function*(){const n=yield $i();s instanceof n&&!(r!=null&&r.noResolveJson)?s.json().then(a=>{e(new Ri(js(a),s.status||500))}).catch(a=>{e(new Us(js(a),a))}):e(new Us(js(s),s))}),Mi=(s,e,r,n)=>{const a={method:s,headers:(e==null?void 0:e.headers)||{}};return s==="GET"?a:(a.headers=Object.assign({"Content-Type":"application/json"},e==null?void 0:e.headers),n&&(a.body=JSON.stringify(n)),Object.assign(Object.assign({},a),r))};function Bt(s,e,r,n,a,i){return ot(this,void 0,void 0,function*(){return new Promise((o,l)=>{s(r,Mi(e,n,a,i)).then(d=>{if(!d.ok)throw d;return n!=null&&n.noResolveJson?d:d.json()}).then(d=>o(d)).catch(d=>Ui(d,l,n))})})}function es(s,e,r,n){return ot(this,void 0,void 0,function*(){return Bt(s,"GET",e,r,n)})}function Ye(s,e,r,n,a){return ot(this,void 0,void 0,function*(){return Bt(s,"POST",e,n,a,r)})}function Bi(s,e,r,n,a){return ot(this,void 0,void 0,function*(){return Bt(s,"PUT",e,n,a,r)})}function Fi(s,e,r,n){return ot(this,void 0,void 0,function*(){return Bt(s,"HEAD",e,Object.assign(Object.assign({},r),{noResolveJson:!0}),n)})}function jn(s,e,r,n,a){return ot(this,void 0,void 0,function*(){return Bt(s,"DELETE",e,n,a,r)})}var _e=function(s,e,r,n){function a(i){return i instanceof r?i:new r(function(o){o(i)})}return new(r||(r=Promise))(function(i,o){function l(u){try{c(n.next(u))}catch(h){o(h)}}function d(u){try{c(n.throw(u))}catch(h){o(h)}}function c(u){u.done?i(u.value):a(u.value).then(l,d)}c((n=n.apply(s,e||[])).next())})};const qi={limit:100,offset:0,sortBy:{column:"name",order:"asc"}},Er={cacheControl:"3600",contentType:"text/plain;charset=UTF-8",upsert:!1};class Gi{constructor(e,r={},n,a){this.url=e,this.headers=r,this.bucketId=n,this.fetch=vn(a)}uploadOrUpdate(e,r,n,a){return _e(this,void 0,void 0,function*(){try{let i;const o=Object.assign(Object.assign({},Er),a);let l=Object.assign(Object.assign({},this.headers),e==="POST"&&{"x-upsert":String(o.upsert)});const d=o.metadata;typeof Blob<"u"&&n instanceof Blob?(i=new FormData,i.append("cacheControl",o.cacheControl),d&&i.append("metadata",this.encodeMetadata(d)),i.append("",n)):typeof FormData<"u"&&n instanceof FormData?(i=n,i.append("cacheControl",o.cacheControl),d&&i.append("metadata",this.encodeMetadata(d))):(i=n,l["cache-control"]=`max-age=${o.cacheControl}`,l["content-type"]=o.contentType,d&&(l["x-metadata"]=this.toBase64(this.encodeMetadata(d)))),a!=null&&a.headers&&(l=Object.assign(Object.assign({},l),a.headers));const c=this._removeEmptyFolders(r),u=this._getFinalPath(c),h=yield this.fetch(`${this.url}/object/${u}`,Object.assign({method:e,body:i,headers:l},o!=null&&o.duplex?{duplex:o.duplex}:{})),f=yield h.json();return h.ok?{data:{path:c,id:f.Id,fullPath:f.Key},error:null}:{data:null,error:f}}catch(i){if(pe(i))return{data:null,error:i};throw i}})}upload(e,r,n){return _e(this,void 0,void 0,function*(){return this.uploadOrUpdate("POST",e,r,n)})}uploadToSignedUrl(e,r,n,a){return _e(this,void 0,void 0,function*(){const i=this._removeEmptyFolders(e),o=this._getFinalPath(i),l=new URL(this.url+`/object/upload/sign/${o}`);l.searchParams.set("token",r);try{let d;const c=Object.assign({upsert:Er.upsert},a),u=Object.assign(Object.assign({},this.headers),{"x-upsert":String(c.upsert)});typeof Blob<"u"&&n instanceof Blob?(d=new FormData,d.append("cacheControl",c.cacheControl),d.append("",n)):typeof FormData<"u"&&n instanceof FormData?(d=n,d.append("cacheControl",c.cacheControl)):(d=n,u["cache-control"]=`max-age=${c.cacheControl}`,u["content-type"]=c.contentType);const h=yield this.fetch(l.toString(),{method:"PUT",body:d,headers:u}),f=yield h.json();return h.ok?{data:{path:i,fullPath:f.Key},error:null}:{data:null,error:f}}catch(d){if(pe(d))return{data:null,error:d};throw d}})}createSignedUploadUrl(e,r){return _e(this,void 0,void 0,function*(){try{let n=this._getFinalPath(e);const a=Object.assign({},this.headers);r!=null&&r.upsert&&(a["x-upsert"]="true");const i=yield Ye(this.fetch,`${this.url}/object/upload/sign/${n}`,{},{headers:a}),o=new URL(this.url+i.url),l=o.searchParams.get("token");if(!l)throw new er("No token returned by API");return{data:{signedUrl:o.toString(),path:e,token:l},error:null}}catch(n){if(pe(n))return{data:null,error:n};throw n}})}update(e,r,n){return _e(this,void 0,void 0,function*(){return this.uploadOrUpdate("PUT",e,r,n)})}move(e,r,n){return _e(this,void 0,void 0,function*(){try{return{data:yield Ye(this.fetch,`${this.url}/object/move`,{bucketId:this.bucketId,sourceKey:e,destinationKey:r,destinationBucket:n==null?void 0:n.destinationBucket},{headers:this.headers}),error:null}}catch(a){if(pe(a))return{data:null,error:a};throw a}})}copy(e,r,n){return _e(this,void 0,void 0,function*(){try{return{data:{path:(yield Ye(this.fetch,`${this.url}/object/copy`,{bucketId:this.bucketId,sourceKey:e,destinationKey:r,destinationBucket:n==null?void 0:n.destinationBucket},{headers:this.headers})).Key},error:null}}catch(a){if(pe(a))return{data:null,error:a};throw a}})}createSignedUrl(e,r,n){return _e(this,void 0,void 0,function*(){try{let a=this._getFinalPath(e),i=yield Ye(this.fetch,`${this.url}/object/sign/${a}`,Object.assign({expiresIn:r},n!=null&&n.transform?{transform:n.transform}:{}),{headers:this.headers});const o=n!=null&&n.download?`&download=${n.download===!0?"":n.download}`:"";return i={signedUrl:encodeURI(`${this.url}${i.signedURL}${o}`)},{data:i,error:null}}catch(a){if(pe(a))return{data:null,error:a};throw a}})}createSignedUrls(e,r,n){return _e(this,void 0,void 0,function*(){try{const a=yield Ye(this.fetch,`${this.url}/object/sign/${this.bucketId}`,{expiresIn:r,paths:e},{headers:this.headers}),i=n!=null&&n.download?`&download=${n.download===!0?"":n.download}`:"";return{data:a.map(o=>Object.assign(Object.assign({},o),{signedUrl:o.signedURL?encodeURI(`${this.url}${o.signedURL}${i}`):null})),error:null}}catch(a){if(pe(a))return{data:null,error:a};throw a}})}download(e,r){return _e(this,void 0,void 0,function*(){const a=typeof(r==null?void 0:r.transform)<"u"?"render/image/authenticated":"object",i=this.transformOptsToQueryString((r==null?void 0:r.transform)||{}),o=i?`?${i}`:"";try{const l=this._getFinalPath(e);return{data:yield(yield es(this.fetch,`${this.url}/${a}/${l}${o}`,{headers:this.headers,noResolveJson:!0})).blob(),error:null}}catch(l){if(pe(l))return{data:null,error:l};throw l}})}info(e){return _e(this,void 0,void 0,function*(){const r=this._getFinalPath(e);try{const n=yield es(this.fetch,`${this.url}/object/info/${r}`,{headers:this.headers});return{data:Ms(n),error:null}}catch(n){if(pe(n))return{data:null,error:n};throw n}})}exists(e){return _e(this,void 0,void 0,function*(){const r=this._getFinalPath(e);try{return yield Fi(this.fetch,`${this.url}/object/${r}`,{headers:this.headers}),{data:!0,error:null}}catch(n){if(pe(n)&&n instanceof Us){const a=n.originalError;if([400,404].includes(a==null?void 0:a.status))return{data:!1,error:n}}throw n}})}getPublicUrl(e,r){const n=this._getFinalPath(e),a=[],i=r!=null&&r.download?`download=${r.download===!0?"":r.download}`:"";i!==""&&a.push(i);const l=typeof(r==null?void 0:r.transform)<"u"?"render/image":"object",d=this.transformOptsToQueryString((r==null?void 0:r.transform)||{});d!==""&&a.push(d);let c=a.join("&");return c!==""&&(c=`?${c}`),{data:{publicUrl:encodeURI(`${this.url}/${l}/public/${n}${c}`)}}}remove(e){return _e(this,void 0,void 0,function*(){try{return{data:yield jn(this.fetch,`${this.url}/object/${this.bucketId}`,{prefixes:e},{headers:this.headers}),error:null}}catch(r){if(pe(r))return{data:null,error:r};throw r}})}list(e,r,n){return _e(this,void 0,void 0,function*(){try{const a=Object.assign(Object.assign(Object.assign({},qi),r),{prefix:e||""});return{data:yield Ye(this.fetch,`${this.url}/object/list/${this.bucketId}`,a,{headers:this.headers},n),error:null}}catch(a){if(pe(a))return{data:null,error:a};throw a}})}encodeMetadata(e){return JSON.stringify(e)}toBase64(e){return typeof Buffer<"u"?Buffer.from(e).toString("base64"):btoa(e)}_getFinalPath(e){return`${this.bucketId}/${e}`}_removeEmptyFolders(e){return e.replace(/^\/|\/$/g,"").replace(/\/+/g,"/")}transformOptsToQueryString(e){const r=[];return e.width&&r.push(`width=${e.width}`),e.height&&r.push(`height=${e.height}`),e.resize&&r.push(`resize=${e.resize}`),e.format&&r.push(`format=${e.format}`),e.quality&&r.push(`quality=${e.quality}`),r.join("&")}}const Hi="2.7.1",Ki={"X-Client-Info":`storage-js/${Hi}`};var dt=function(s,e,r,n){function a(i){return i instanceof r?i:new r(function(o){o(i)})}return new(r||(r=Promise))(function(i,o){function l(u){try{c(n.next(u))}catch(h){o(h)}}function d(u){try{c(n.throw(u))}catch(h){o(h)}}function c(u){u.done?i(u.value):a(u.value).then(l,d)}c((n=n.apply(s,e||[])).next())})};class zi{constructor(e,r={},n){this.url=e,this.headers=Object.assign(Object.assign({},Ki),r),this.fetch=vn(n)}listBuckets(){return dt(this,void 0,void 0,function*(){try{return{data:yield es(this.fetch,`${this.url}/bucket`,{headers:this.headers}),error:null}}catch(e){if(pe(e))return{data:null,error:e};throw e}})}getBucket(e){return dt(this,void 0,void 0,function*(){try{return{data:yield es(this.fetch,`${this.url}/bucket/${e}`,{headers:this.headers}),error:null}}catch(r){if(pe(r))return{data:null,error:r};throw r}})}createBucket(e,r={public:!1}){return dt(this,void 0,void 0,function*(){try{return{data:yield Ye(this.fetch,`${this.url}/bucket`,{id:e,name:e,public:r.public,file_size_limit:r.fileSizeLimit,allowed_mime_types:r.allowedMimeTypes},{headers:this.headers}),error:null}}catch(n){if(pe(n))return{data:null,error:n};throw n}})}updateBucket(e,r){return dt(this,void 0,void 0,function*(){try{return{data:yield Bi(this.fetch,`${this.url}/bucket/${e}`,{id:e,name:e,public:r.public,file_size_limit:r.fileSizeLimit,allowed_mime_types:r.allowedMimeTypes},{headers:this.headers}),error:null}}catch(n){if(pe(n))return{data:null,error:n};throw n}})}emptyBucket(e){return dt(this,void 0,void 0,function*(){try{return{data:yield Ye(this.fetch,`${this.url}/bucket/${e}/empty`,{},{headers:this.headers}),error:null}}catch(r){if(pe(r))return{data:null,error:r};throw r}})}deleteBucket(e){return dt(this,void 0,void 0,function*(){try{return{data:yield jn(this.fetch,`${this.url}/bucket/${e}`,{},{headers:this.headers}),error:null}}catch(r){if(pe(r))return{data:null,error:r};throw r}})}}class Wi extends zi{constructor(e,r={},n){super(e,r,n)}from(e){return new Gi(this.url,this.headers,e,this.fetch)}}const Vi="2.50.1";let Ot="";typeof Deno<"u"?Ot="deno":typeof document<"u"?Ot="web":typeof navigator<"u"&&navigator.product==="ReactNative"?Ot="react-native":Ot="node";const Ji={"X-Client-Info":`supabase-js-${Ot}/${Vi}`},Yi={headers:Ji},Qi={schema:"public"},Zi={autoRefreshToken:!0,persistSession:!0,detectSessionInUrl:!0,flowType:"implicit"},Xi={};var eo=function(s,e,r,n){function a(i){return i instanceof r?i:new r(function(o){o(i)})}return new(r||(r=Promise))(function(i,o){function l(u){try{c(n.next(u))}catch(h){o(h)}}function d(u){try{c(n.throw(u))}catch(h){o(h)}}function c(u){u.done?i(u.value):a(u.value).then(l,d)}c((n=n.apply(s,e||[])).next())})};const to=s=>{let e;return s?e=s:typeof fetch>"u"?e=an:e=fetch,(...r)=>e(...r)},so=()=>typeof Headers>"u"?on:Headers,ro=(s,e,r)=>{const n=to(r),a=so();return(i,o)=>eo(void 0,void 0,void 0,function*(){var l;const d=(l=yield e())!==null&&l!==void 0?l:s;let c=new a(o==null?void 0:o.headers);return c.has("apikey")||c.set("apikey",s),c.has("Authorization")||c.set("Authorization",`Bearer ${d}`),n(i,Object.assign(Object.assign({},o),{headers:c}))})};var no=function(s,e,r,n){function a(i){return i instanceof r?i:new r(function(o){o(i)})}return new(r||(r=Promise))(function(i,o){function l(u){try{c(n.next(u))}catch(h){o(h)}}function d(u){try{c(n.throw(u))}catch(h){o(h)}}function c(u){u.done?i(u.value):a(u.value).then(l,d)}c((n=n.apply(s,e||[])).next())})};function ao(s){return s.endsWith("/")?s:s+"/"}function io(s,e){var r,n;const{db:a,auth:i,realtime:o,global:l}=s,{db:d,auth:c,realtime:u,global:h}=e,f={db:Object.assign(Object.assign({},d),a),auth:Object.assign(Object.assign({},c),i),realtime:Object.assign(Object.assign({},u),o),global:Object.assign(Object.assign(Object.assign({},h),l),{headers:Object.assign(Object.assign({},(r=h==null?void 0:h.headers)!==null&&r!==void 0?r:{}),(n=l==null?void 0:l.headers)!==null&&n!==void 0?n:{})}),accessToken:()=>no(this,void 0,void 0,function*(){return""})};return s.accessToken?f.accessToken=s.accessToken:delete f.accessToken,f}const _n="2.70.0",gt=30*1e3,Bs=3,_s=Bs*gt,oo="http://localhost:9999",lo="supabase.auth.token",co={"X-Client-Info":`gotrue-js/${_n}`},Fs="X-Supabase-Api-Version",Nn={"2024-01-01":{timestamp:Date.parse("2024-01-01T00:00:00.0Z"),name:"2024-01-01"}},uo=/^([a-z0-9_-]{4})*($|[a-z0-9_-]{3}$|[a-z0-9_-]{2}$)$/i,ho=6e5;class tr extends Error{constructor(e,r,n){super(e),this.__isAuthError=!0,this.name="AuthError",this.status=r,this.code=n}}function J(s){return typeof s=="object"&&s!==null&&"__isAuthError"in s}class fo extends tr{constructor(e,r,n){super(e,r,n),this.name="AuthApiError",this.status=r,this.code=n}}function mo(s){return J(s)&&s.name==="AuthApiError"}class Sn extends tr{constructor(e,r){super(e),this.name="AuthUnknownError",this.originalError=r}}class et extends tr{constructor(e,r,n,a){super(e,n,a),this.name=r,this.status=n}}class Je extends et{constructor(){super("Auth session missing!","AuthSessionMissingError",400,void 0)}}function go(s){return J(s)&&s.name==="AuthSessionMissingError"}class Kt extends et{constructor(){super("Auth session or user missing","AuthInvalidTokenResponseError",500,void 0)}}class zt extends et{constructor(e){super(e,"AuthInvalidCredentialsError",400,void 0)}}class Wt extends et{constructor(e,r=null){super(e,"AuthImplicitGrantRedirectError",500,void 0),this.details=null,this.details=r}toJSON(){return{name:this.name,message:this.message,status:this.status,details:this.details}}}function po(s){return J(s)&&s.name==="AuthImplicitGrantRedirectError"}class Tr extends et{constructor(e,r=null){super(e,"AuthPKCEGrantCodeExchangeError",500,void 0),this.details=null,this.details=r}toJSON(){return{name:this.name,message:this.message,status:this.status,details:this.details}}}class qs extends et{constructor(e,r){super(e,"AuthRetryableFetchError",r,void 0)}}function Ns(s){return J(s)&&s.name==="AuthRetryableFetchError"}class Cr extends et{constructor(e,r,n){super(e,"AuthWeakPasswordError",r,"weak_password"),this.reasons=n}}class Rt extends et{constructor(e){super(e,"AuthInvalidJwtError",400,"invalid_jwt")}}const ts="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_".split(""),Pr=` \r=`.split(""),yo=(()=>{const s=new Array(128);for(let e=0;e<s.length;e+=1)s[e]=-1;for(let e=0;e<Pr.length;e+=1)s[Pr[e].charCodeAt(0)]=-2;for(let e=0;e<ts.length;e+=1)s[ts[e].charCodeAt(0)]=e;return s})();function Ar(s,e,r){if(s!==null)for(e.queue=e.queue<<8|s,e.queuedBits+=8;e.queuedBits>=6;){const n=e.queue>>e.queuedBits-6&63;r(ts[n]),e.queuedBits-=6}else if(e.queuedBits>0)for(e.queue=e.queue<<6-e.queuedBits,e.queuedBits=6;e.queuedBits>=6;){const n=e.queue>>e.queuedBits-6&63;r(ts[n]),e.queuedBits-=6}}function kn(s,e,r){const n=yo[s];if(n>-1)for(e.queue=e.queue<<6|n,e.queuedBits+=6;e.queuedBits>=8;)r(e.queue>>e.queuedBits-8&255),e.queuedBits-=8;else{if(n===-2)return;throw new Error(`Invalid Base64-URL character "${String.fromCharCode(s)}"`)}}function Or(s){const e=[],r=o=>{e.push(String.fromCodePoint(o))},n={utf8seq:0,codepoint:0},a={queue:0,queuedBits:0},i=o=>{wo(o,n,r)};for(let o=0;o<s.length;o+=1)kn(s.charCodeAt(o),a,i);return e.join("")}function xo(s,e){if(s<=127){e(s);return}else if(s<=2047){e(192|s>>6),e(128|s&63);return}else if(s<=65535){e(224|s>>12),e(128|s>>6&63),e(128|s&63);return}else if(s<=1114111){e(240|s>>18),e(128|s>>12&63),e(128|s>>6&63),e(128|s&63);return}throw new Error(`Unrecognized Unicode codepoint: ${s.toString(16)}`)}function bo(s,e){for(let r=0;r<s.length;r+=1){let n=s.charCodeAt(r);if(n>55295&&n<=56319){const a=(n-55296)*1024&65535;n=(s.charCodeAt(r+1)-56320&65535|a)+65536,r+=1}xo(n,e)}}function wo(s,e,r){if(e.utf8seq===0){if(s<=127){r(s);return}for(let n=1;n<6;n+=1)if(!(s>>7-n&1)){e.utf8seq=n;break}if(e.utf8seq===2)e.codepoint=s&31;else if(e.utf8seq===3)e.codepoint=s&15;else if(e.utf8seq===4)e.codepoint=s&7;else throw new Error("Invalid UTF-8 sequence");e.utf8seq-=1}else if(e.utf8seq>0){if(s<=127)throw new Error("Invalid UTF-8 sequence");e.codepoint=e.codepoint<<6|s&63,e.utf8seq-=1,e.utf8seq===0&&r(e.codepoint)}}function vo(s){const e=[],r={queue:0,queuedBits:0},n=a=>{e.push(a)};for(let a=0;a<s.length;a+=1)kn(s.charCodeAt(a),r,n);return new Uint8Array(e)}function jo(s){const e=[];return bo(s,r=>e.push(r)),new Uint8Array(e)}function _o(s){const e=[],r={queue:0,queuedBits:0},n=a=>{e.push(a)};return s.forEach(a=>Ar(a,r,n)),Ar(null,r,n),e.join("")}function No(s){return Math.round(Date.now()/1e3)+s}function So(){return"xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx".replace(/[xy]/g,function(s){const e=Math.random()*16|0;return(s=="x"?e:e&3|8).toString(16)})}const Oe=()=>typeof window<"u"&&typeof document<"u",tt={tested:!1,writable:!1},Dt=()=>{if(!Oe())return!1;try{if(typeof globalThis.localStorage!="object")return!1}catch{return!1}if(tt.tested)return tt.writable;const s=`lswt-${Math.random()}${Math.random()}`;try{globalThis.localStorage.setItem(s,s),globalThis.localStorage.removeItem(s),tt.tested=!0,tt.writable=!0}catch{tt.tested=!0,tt.writable=!1}return tt.writable};function ko(s){const e={},r=new URL(s);if(r.hash&&r.hash[0]==="#")try{new URLSearchParams(r.hash.substring(1)).forEach((a,i)=>{e[i]=a})}catch{}return r.searchParams.forEach((n,a)=>{e[a]=n}),e}const En=s=>{let e;return s?e=s:typeof fetch>"u"?e=(...r)=>Ve(async()=>{const{default:n}=await Promise.resolve().then(()=>_t);return{default:n}},void 0).then(({default:n})=>n(...r)):e=fetch,(...r)=>e(...r)},Eo=s=>typeof s=="object"&&s!==null&&"status"in s&&"ok"in s&&"json"in s&&typeof s.json=="function",Tn=async(s,e,r)=>{await s.setItem(e,JSON.stringify(r))},Vt=async(s,e)=>{const r=await s.getItem(e);if(!r)return null;try{return JSON.parse(r)}catch{return r}},Jt=async(s,e)=>{await s.removeItem(e)};class ms{constructor(){this.promise=new ms.promiseConstructor((e,r)=>{this.resolve=e,this.reject=r})}}ms.promiseConstructor=Promise;function Ss(s){const e=s.split(".");if(e.length!==3)throw new Rt("Invalid JWT structure");for(let n=0;n<e.length;n++)if(!uo.test(e[n]))throw new Rt("JWT not in base64url format");return{header:JSON.parse(Or(e[0])),payload:JSON.parse(Or(e[1])),signature:vo(e[2]),raw:{header:e[0],payload:e[1]}}}async function To(s){return await new Promise(e=>{setTimeout(()=>e(null),s)})}function Co(s,e){return new Promise((n,a)=>{(async()=>{for(let i=0;i<1/0;i++)try{const o=await s(i);if(!e(i,null,o)){n(o);return}}catch(o){if(!e(i,o)){a(o);return}}})()})}function Po(s){return("0"+s.toString(16)).substr(-2)}function Ao(){const e=new Uint32Array(56);if(typeof crypto>"u"){const r="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-._~",n=r.length;let a="";for(let i=0;i<56;i++)a+=r.charAt(Math.floor(Math.random()*n));return a}return crypto.getRandomValues(e),Array.from(e,Po).join("")}async function Oo(s){const r=new TextEncoder().encode(s),n=await crypto.subtle.digest("SHA-256",r),a=new Uint8Array(n);return Array.from(a).map(i=>String.fromCharCode(i)).join("")}async function Io(s){if(!(typeof crypto<"u"&&typeof crypto.subtle<"u"&&typeof TextEncoder<"u"))return console.warn("WebCrypto API is not supported. Code challenge method will default to use plain instead of sha256."),s;const r=await Oo(s);return btoa(r).replace(/\+/g,"-").replace(/\//g,"_").replace(/=+$/,"")}async function ut(s,e,r=!1){const n=Ao();let a=n;r&&(a+="/PASSWORD_RECOVERY"),await Tn(s,`${e}-code-verifier`,a);const i=await Io(n);return[i,n===i?"plain":"s256"]}const Lo=/^2[0-9]{3}-(0[1-9]|1[0-2])-(0[1-9]|1[0-9]|2[0-9]|3[0-1])$/i;function Ro(s){const e=s.headers.get(Fs);if(!e||!e.match(Lo))return null;try{return new Date(`${e}T00:00:00.0Z`)}catch{return null}}function Do(s){if(!s)throw new Error("Missing exp claim");const e=Math.floor(Date.now()/1e3);if(s<=e)throw new Error("JWT has expired")}function $o(s){switch(s){case"RS256":return{name:"RSASSA-PKCS1-v1_5",hash:{name:"SHA-256"}};case"ES256":return{name:"ECDSA",namedCurve:"P-256",hash:{name:"SHA-256"}};default:throw new Error("Invalid alg claim")}}const Uo=/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/;function ht(s){if(!Uo.test(s))throw new Error("@supabase/auth-js: Expected parameter to be UUID but is not")}var Mo=function(s,e){var r={};for(var n in s)Object.prototype.hasOwnProperty.call(s,n)&&e.indexOf(n)<0&&(r[n]=s[n]);if(s!=null&&typeof Object.getOwnPropertySymbols=="function")for(var a=0,n=Object.getOwnPropertySymbols(s);a<n.length;a++)e.indexOf(n[a])<0&&Object.prototype.propertyIsEnumerable.call(s,n[a])&&(r[n[a]]=s[n[a]]);return r};const st=s=>s.msg||s.message||s.error_description||s.error||JSON.stringify(s),Bo=[502,503,504];async function Ir(s){var e;if(!Eo(s))throw new qs(st(s),0);if(Bo.includes(s.status))throw new qs(st(s),s.status);let r;try{r=await s.json()}catch(i){throw new Sn(st(i),i)}let n;const a=Ro(s);if(a&&a.getTime()>=Nn["2024-01-01"].timestamp&&typeof r=="object"&&r&&typeof r.code=="string"?n=r.code:typeof r=="object"&&r&&typeof r.error_code=="string"&&(n=r.error_code),n){if(n==="weak_password")throw new Cr(st(r),s.status,((e=r.weak_password)===null||e===void 0?void 0:e.reasons)||[]);if(n==="session_not_found")throw new Je}else if(typeof r=="object"&&r&&typeof r.weak_password=="object"&&r.weak_password&&Array.isArray(r.weak_password.reasons)&&r.weak_password.reasons.length&&r.weak_password.reasons.reduce((i,o)=>i&&typeof o=="string",!0))throw new Cr(st(r),s.status,r.weak_password.reasons);throw new fo(st(r),s.status||500,n)}const Fo=(s,e,r,n)=>{const a={method:s,headers:(e==null?void 0:e.headers)||{}};return s==="GET"?a:(a.headers=Object.assign({"Content-Type":"application/json;charset=UTF-8"},e==null?void 0:e.headers),a.body=JSON.stringify(n),Object.assign(Object.assign({},a),r))};async function te(s,e,r,n){var a;const i=Object.assign({},n==null?void 0:n.headers);i[Fs]||(i[Fs]=Nn["2024-01-01"].name),n!=null&&n.jwt&&(i.Authorization=`Bearer ${n.jwt}`);const o=(a=n==null?void 0:n.query)!==null&&a!==void 0?a:{};n!=null&&n.redirectTo&&(o.redirect_to=n.redirectTo);const l=Object.keys(o).length?"?"+new URLSearchParams(o).toString():"",d=await qo(s,e,r+l,{headers:i,noResolveJson:n==null?void 0:n.noResolveJson},{},n==null?void 0:n.body);return n!=null&&n.xform?n==null?void 0:n.xform(d):{data:Object.assign({},d),error:null}}async function qo(s,e,r,n,a,i){const o=Fo(e,n,a,i);let l;try{l=await s(r,Object.assign({},o))}catch(d){throw console.error(d),new qs(st(d),0)}if(l.ok||await Ir(l),n!=null&&n.noResolveJson)return l;try{return await l.json()}catch(d){await Ir(d)}}function Ke(s){var e;let r=null;zo(s)&&(r=Object.assign({},s),s.expires_at||(r.expires_at=No(s.expires_in)));const n=(e=s.user)!==null&&e!==void 0?e:s;return{data:{session:r,user:n},error:null}}function Lr(s){const e=Ke(s);return!e.error&&s.weak_password&&typeof s.weak_password=="object"&&Array.isArray(s.weak_password.reasons)&&s.weak_password.reasons.length&&s.weak_password.message&&typeof s.weak_password.message=="string"&&s.weak_password.reasons.reduce((r,n)=>r&&typeof n=="string",!0)&&(e.data.weak_password=s.weak_password),e}function Qe(s){var e;return{data:{user:(e=s.user)!==null&&e!==void 0?e:s},error:null}}function Go(s){return{data:s,error:null}}function Ho(s){const{action_link:e,email_otp:r,hashed_token:n,redirect_to:a,verification_type:i}=s,o=Mo(s,["action_link","email_otp","hashed_token","redirect_to","verification_type"]),l={action_link:e,email_otp:r,hashed_token:n,redirect_to:a,verification_type:i},d=Object.assign({},o);return{data:{properties:l,user:d},error:null}}function Ko(s){return s}function zo(s){return s.access_token&&s.refresh_token&&s.expires_in}const ks=["global","local","others"];var Wo=function(s,e){var r={};for(var n in s)Object.prototype.hasOwnProperty.call(s,n)&&e.indexOf(n)<0&&(r[n]=s[n]);if(s!=null&&typeof Object.getOwnPropertySymbols=="function")for(var a=0,n=Object.getOwnPropertySymbols(s);a<n.length;a++)e.indexOf(n[a])<0&&Object.prototype.propertyIsEnumerable.call(s,n[a])&&(r[n[a]]=s[n[a]]);return r};class Vo{constructor({url:e="",headers:r={},fetch:n}){this.url=e,this.headers=r,this.fetch=En(n),this.mfa={listFactors:this._listFactors.bind(this),deleteFactor:this._deleteFactor.bind(this)}}async signOut(e,r=ks[0]){if(ks.indexOf(r)<0)throw new Error(`@supabase/auth-js: Parameter scope must be one of ${ks.join(", ")}`);try{return await te(this.fetch,"POST",`${this.url}/logout?scope=${r}`,{headers:this.headers,jwt:e,noResolveJson:!0}),{data:null,error:null}}catch(n){if(J(n))return{data:null,error:n};throw n}}async inviteUserByEmail(e,r={}){try{return await te(this.fetch,"POST",`${this.url}/invite`,{body:{email:e,data:r.data},headers:this.headers,redirectTo:r.redirectTo,xform:Qe})}catch(n){if(J(n))return{data:{user:null},error:n};throw n}}async generateLink(e){try{const{options:r}=e,n=Wo(e,["options"]),a=Object.assign(Object.assign({},n),r);return"newEmail"in n&&(a.new_email=n==null?void 0:n.newEmail,delete a.newEmail),await te(this.fetch,"POST",`${this.url}/admin/generate_link`,{body:a,headers:this.headers,xform:Ho,redirectTo:r==null?void 0:r.redirectTo})}catch(r){if(J(r))return{data:{properties:null,user:null},error:r};throw r}}async createUser(e){try{return await te(this.fetch,"POST",`${this.url}/admin/users`,{body:e,headers:this.headers,xform:Qe})}catch(r){if(J(r))return{data:{user:null},error:r};throw r}}async listUsers(e){var r,n,a,i,o,l,d;try{const c={nextPage:null,lastPage:0,total:0},u=await te(this.fetch,"GET",`${this.url}/admin/users`,{headers:this.headers,noResolveJson:!0,query:{page:(n=(r=e==null?void 0:e.page)===null||r===void 0?void 0:r.toString())!==null&&n!==void 0?n:"",per_page:(i=(a=e==null?void 0:e.perPage)===null||a===void 0?void 0:a.toString())!==null&&i!==void 0?i:""},xform:Ko});if(u.error)throw u.error;const h=await u.json(),f=(o=u.headers.get("x-total-count"))!==null&&o!==void 0?o:0,g=(d=(l=u.headers.get("link"))===null||l===void 0?void 0:l.split(","))!==null&&d!==void 0?d:[];return g.length>0&&(g.forEach(x=>{const v=parseInt(x.split(";")[0].split("=")[1].substring(0,1)),y=JSON.parse(x.split(";")[1].split("=")[1]);c[`${y}Page`]=v}),c.total=parseInt(f)),{data:Object.assign(Object.assign({},h),c),error:null}}catch(c){if(J(c))return{data:{users:[]},error:c};throw c}}async getUserById(e){ht(e);try{return await te(this.fetch,"GET",`${this.url}/admin/users/${e}`,{headers:this.headers,xform:Qe})}catch(r){if(J(r))return{data:{user:null},error:r};throw r}}async updateUserById(e,r){ht(e);try{return await te(this.fetch,"PUT",`${this.url}/admin/users/${e}`,{body:r,headers:this.headers,xform:Qe})}catch(n){if(J(n))return{data:{user:null},error:n};throw n}}async deleteUser(e,r=!1){ht(e);try{return await te(this.fetch,"DELETE",`${this.url}/admin/users/${e}`,{headers:this.headers,body:{should_soft_delete:r},xform:Qe})}catch(n){if(J(n))return{data:{user:null},error:n};throw n}}async _listFactors(e){ht(e.userId);try{const{data:r,error:n}=await te(this.fetch,"GET",`${this.url}/admin/users/${e.userId}/factors`,{headers:this.headers,xform:a=>({data:{factors:a},error:null})});return{data:r,error:n}}catch(r){if(J(r))return{data:null,error:r};throw r}}async _deleteFactor(e){ht(e.userId),ht(e.id);try{return{data:await te(this.fetch,"DELETE",`${this.url}/admin/users/${e.userId}/factors/${e.id}`,{headers:this.headers}),error:null}}catch(r){if(J(r))return{data:null,error:r};throw r}}}const Jo={getItem:s=>Dt()?globalThis.localStorage.getItem(s):null,setItem:(s,e)=>{Dt()&&globalThis.localStorage.setItem(s,e)},removeItem:s=>{Dt()&&globalThis.localStorage.removeItem(s)}};function Rr(s={}){return{getItem:e=>s[e]||null,setItem:(e,r)=>{s[e]=r},removeItem:e=>{delete s[e]}}}function Yo(){if(typeof globalThis!="object")try{Object.defineProperty(Object.prototype,"__magic__",{get:function(){return this},configurable:!0}),__magic__.globalThis=__magic__,delete Object.prototype.__magic__}catch{typeof self<"u"&&(self.globalThis=self)}}const ft={debug:!!(globalThis&&Dt()&&globalThis.localStorage&&globalThis.localStorage.getItem("supabase.gotrue-js.locks.debug")==="true")};class Cn extends Error{constructor(e){super(e),this.isAcquireTimeout=!0}}class Qo extends Cn{}async function Zo(s,e,r){ft.debug&&console.log("@supabase/gotrue-js: navigatorLock: acquire lock",s,e);const n=new globalThis.AbortController;return e>0&&setTimeout(()=>{n.abort(),ft.debug&&console.log("@supabase/gotrue-js: navigatorLock acquire timed out",s)},e),await Promise.resolve().then(()=>globalThis.navigator.locks.request(s,e===0?{mode:"exclusive",ifAvailable:!0}:{mode:"exclusive",signal:n.signal},async a=>{if(a){ft.debug&&console.log("@supabase/gotrue-js: navigatorLock: acquired",s,a.name);try{return await r()}finally{ft.debug&&console.log("@supabase/gotrue-js: navigatorLock: released",s,a.name)}}else{if(e===0)throw ft.debug&&console.log("@supabase/gotrue-js: navigatorLock: not immediately available",s),new Qo(`Acquiring an exclusive Navigator LockManager lock "${s}" immediately failed`);if(ft.debug)try{const i=await globalThis.navigator.locks.query();console.log("@supabase/gotrue-js: Navigator LockManager state",JSON.stringify(i,null," "))}catch(i){console.warn("@supabase/gotrue-js: Error when querying Navigator LockManager state",i)}return console.warn("@supabase/gotrue-js: Navigator LockManager returned a null lock when using #request without ifAvailable set to true, it appears this browser is not following the LockManager spec https://developer.mozilla.org/en-US/docs/Web/API/LockManager/request"),await r()}}))}Yo();const Xo={url:oo,storageKey:lo,autoRefreshToken:!0,persistSession:!0,detectSessionInUrl:!0,headers:co,flowType:"implicit",debug:!1,hasCustomAuthorizationHeader:!1};async function Dr(s,e,r){return await r()}class $t{constructor(e){var r,n;this.memoryStorage=null,this.stateChangeEmitters=new Map,this.autoRefreshTicker=null,this.visibilityChangedCallback=null,this.refreshingDeferred=null,this.initializePromise=null,this.detectSessionInUrl=!0,this.hasCustomAuthorizationHeader=!1,this.suppressGetSessionWarning=!1,this.lockAcquired=!1,this.pendingInLock=[],this.broadcastChannel=null,this.logger=console.log,this.instanceID=$t.nextInstanceID,$t.nextInstanceID+=1,this.instanceID>0&&Oe()&&console.warn("Multiple GoTrueClient instances detected in the same browser context. It is not an error, but this should be avoided as it may produce undefined behavior when used concurrently under the same storage key.");const a=Object.assign(Object.assign({},Xo),e);if(this.logDebugMessages=!!a.debug,typeof a.debug=="function"&&(this.logger=a.debug),this.persistSession=a.persistSession,this.storageKey=a.storageKey,this.autoRefreshToken=a.autoRefreshToken,this.admin=new Vo({url:a.url,headers:a.headers,fetch:a.fetch}),this.url=a.url,this.headers=a.headers,this.fetch=En(a.fetch),this.lock=a.lock||Dr,this.detectSessionInUrl=a.detectSessionInUrl,this.flowType=a.flowType,this.hasCustomAuthorizationHeader=a.hasCustomAuthorizationHeader,a.lock?this.lock=a.lock:Oe()&&(!((r=globalThis==null?void 0:globalThis.navigator)===null||r===void 0)&&r.locks)?this.lock=Zo:this.lock=Dr,this.jwks={keys:[]},this.jwks_cached_at=Number.MIN_SAFE_INTEGER,this.mfa={verify:this._verify.bind(this),enroll:this._enroll.bind(this),unenroll:this._unenroll.bind(this),challenge:this._challenge.bind(this),listFactors:this._listFactors.bind(this),challengeAndVerify:this._challengeAndVerify.bind(this),getAuthenticatorAssuranceLevel:this._getAuthenticatorAssuranceLevel.bind(this)},this.persistSession?a.storage?this.storage=a.storage:Dt()?this.storage=Jo:(this.memoryStorage={},this.storage=Rr(this.memoryStorage)):(this.memoryStorage={},this.storage=Rr(this.memoryStorage)),Oe()&&globalThis.BroadcastChannel&&this.persistSession&&this.storageKey){try{this.broadcastChannel=new globalThis.BroadcastChannel(this.storageKey)}catch(i){console.error("Failed to create a new BroadcastChannel, multi-tab state changes will not be available",i)}(n=this.broadcastChannel)===null||n===void 0||n.addEventListener("message",async i=>{this._debug("received broadcast notification from other tab or client",i),await this._notifyAllSubscribers(i.data.event,i.data.session,!1)})}this.initialize()}_debug(...e){return this.logDebugMessages&&this.logger(`GoTrueClient@${this.instanceID} (${_n}) ${new Date().toISOString()}`,...e),this}async initialize(){return this.initializePromise?await this.initializePromise:(this.initializePromise=(async()=>await this._acquireLock(-1,async()=>await this._initialize()))(),await this.initializePromise)}async _initialize(){var e;try{const r=ko(window.location.href);let n="none";if(this._isImplicitGrantCallback(r)?n="implicit":await this._isPKCECallback(r)&&(n="pkce"),Oe()&&this.detectSessionInUrl&&n!=="none"){const{data:a,error:i}=await this._getSessionFromURL(r,n);if(i){if(this._debug("#_initialize()","error detecting session from URL",i),po(i)){const d=(e=i.details)===null||e===void 0?void 0:e.code;if(d==="identity_already_exists"||d==="identity_not_found"||d==="single_identity_not_deletable")return{error:i}}return await this._removeSession(),{error:i}}const{session:o,redirectType:l}=a;return this._debug("#_initialize()","detected session in URL",o,"redirect type",l),await this._saveSession(o),setTimeout(async()=>{l==="recovery"?await this._notifyAllSubscribers("PASSWORD_RECOVERY",o):await this._notifyAllSubscribers("SIGNED_IN",o)},0),{error:null}}return await this._recoverAndRefresh(),{error:null}}catch(r){return J(r)?{error:r}:{error:new Sn("Unexpected error during initialization",r)}}finally{await this._handleVisibilityChange(),this._debug("#_initialize()","end")}}async signInAnonymously(e){var r,n,a;try{const i=await te(this.fetch,"POST",`${this.url}/signup`,{headers:this.headers,body:{data:(n=(r=e==null?void 0:e.options)===null||r===void 0?void 0:r.data)!==null&&n!==void 0?n:{},gotrue_meta_security:{captcha_token:(a=e==null?void 0:e.options)===null||a===void 0?void 0:a.captchaToken}},xform:Ke}),{data:o,error:l}=i;if(l||!o)return{data:{user:null,session:null},error:l};const d=o.session,c=o.user;return o.session&&(await this._saveSession(o.session),await this._notifyAllSubscribers("SIGNED_IN",d)),{data:{user:c,session:d},error:null}}catch(i){if(J(i))return{data:{user:null,session:null},error:i};throw i}}async signUp(e){var r,n,a;try{let i;if("email"in e){const{email:u,password:h,options:f}=e;let g=null,x=null;this.flowType==="pkce"&&([g,x]=await ut(this.storage,this.storageKey)),i=await te(this.fetch,"POST",`${this.url}/signup`,{headers:this.headers,redirectTo:f==null?void 0:f.emailRedirectTo,body:{email:u,password:h,data:(r=f==null?void 0:f.data)!==null&&r!==void 0?r:{},gotrue_meta_security:{captcha_token:f==null?void 0:f.captchaToken},code_challenge:g,code_challenge_method:x},xform:Ke})}else if("phone"in e){const{phone:u,password:h,options:f}=e;i=await te(this.fetch,"POST",`${this.url}/signup`,{headers:this.headers,body:{phone:u,password:h,data:(n=f==null?void 0:f.data)!==null&&n!==void 0?n:{},channel:(a=f==null?void 0:f.channel)!==null&&a!==void 0?a:"sms",gotrue_meta_security:{captcha_token:f==null?void 0:f.captchaToken}},xform:Ke})}else throw new zt("You must provide either an email or phone number and a password");const{data:o,error:l}=i;if(l||!o)return{data:{user:null,session:null},error:l};const d=o.session,c=o.user;return o.session&&(await this._saveSession(o.session),await this._notifyAllSubscribers("SIGNED_IN",d)),{data:{user:c,session:d},error:null}}catch(i){if(J(i))return{data:{user:null,session:null},error:i};throw i}}async signInWithPassword(e){try{let r;if("email"in e){const{email:i,password:o,options:l}=e;r=await te(this.fetch,"POST",`${this.url}/token?grant_type=password`,{headers:this.headers,body:{email:i,password:o,gotrue_meta_security:{captcha_token:l==null?void 0:l.captchaToken}},xform:Lr})}else if("phone"in e){const{phone:i,password:o,options:l}=e;r=await te(this.fetch,"POST",`${this.url}/token?grant_type=password`,{headers:this.headers,body:{phone:i,password:o,gotrue_meta_security:{captcha_token:l==null?void 0:l.captchaToken}},xform:Lr})}else throw new zt("You must provide either an email or phone number and a password");const{data:n,error:a}=r;return a?{data:{user:null,session:null},error:a}:!n||!n.session||!n.user?{data:{user:null,session:null},error:new Kt}:(n.session&&(await this._saveSession(n.session),await this._notifyAllSubscribers("SIGNED_IN",n.session)),{data:Object.assign({user:n.user,session:n.session},n.weak_password?{weakPassword:n.weak_password}:null),error:a})}catch(r){if(J(r))return{data:{user:null,session:null},error:r};throw r}}async signInWithOAuth(e){var r,n,a,i;return await this._handleProviderSignIn(e.provider,{redirectTo:(r=e.options)===null||r===void 0?void 0:r.redirectTo,scopes:(n=e.options)===null||n===void 0?void 0:n.scopes,queryParams:(a=e.options)===null||a===void 0?void 0:a.queryParams,skipBrowserRedirect:(i=e.options)===null||i===void 0?void 0:i.skipBrowserRedirect})}async exchangeCodeForSession(e){return await this.initializePromise,this._acquireLock(-1,async()=>this._exchangeCodeForSession(e))}async signInWithWeb3(e){const{chain:r}=e;if(r==="solana")return await this.signInWithSolana(e);throw new Error(`@supabase/auth-js: Unsupported chain "${r}"`)}async signInWithSolana(e){var r,n,a,i,o,l,d,c,u,h,f,g;let x,v;if("message"in e)x=e.message,v=e.signature;else{const{chain:y,wallet:w,statement:P,options:C}=e;let D;if(Oe())if(typeof w=="object")D=w;else{const N=window;if("solana"in N&&typeof N.solana=="object"&&("signIn"in N.solana&&typeof N.solana.signIn=="function"||"signMessage"in N.solana&&typeof N.solana.signMessage=="function"))D=N.solana;else throw new Error("@supabase/auth-js: No compatible Solana wallet interface on the window object (window.solana) detected. Make sure the user already has a wallet installed and connected for this app. Prefer passing the wallet interface object directly to signInWithWeb3({ chain: 'solana', wallet: resolvedUserWallet }) instead.")}else{if(typeof w!="object"||!(C!=null&&C.url))throw new Error("@supabase/auth-js: Both wallet and url must be specified in non-browser environments.");D=w}const k=new URL((r=C==null?void 0:C.url)!==null&&r!==void 0?r:window.location.href);if("signIn"in D&&D.signIn){const N=await D.signIn(Object.assign(Object.assign(Object.assign({issuedAt:new Date().toISOString()},C==null?void 0:C.signInWithSolana),{version:"1",domain:k.host,uri:k.href}),P?{statement:P}:null));let j;if(Array.isArray(N)&&N[0]&&typeof N[0]=="object")j=N[0];else if(N&&typeof N=="object"&&"signedMessage"in N&&"signature"in N)j=N;else throw new Error("@supabase/auth-js: Wallet method signIn() returned unrecognized value");if("signedMessage"in j&&"signature"in j&&(typeof j.signedMessage=="string"||j.signedMessage instanceof Uint8Array)&&j.signature instanceof Uint8Array)x=typeof j.signedMessage=="string"?j.signedMessage:new TextDecoder().decode(j.signedMessage),v=j.signature;else throw new Error("@supabase/auth-js: Wallet method signIn() API returned object without signedMessage and signature fields")}else{if(!("signMessage"in D)||typeof D.signMessage!="function"||!("publicKey"in D)||typeof D!="object"||!D.publicKey||!("toBase58"in D.publicKey)||typeof D.publicKey.toBase58!="function")throw new Error("@supabase/auth-js: Wallet does not have a compatible signMessage() and publicKey.toBase58() API");x=[`${k.host} wants you to sign in with your Solana account:`,D.publicKey.toBase58(),...P?["",P,""]:[""],"Version: 1",`URI: ${k.href}`,`Issued At: ${(a=(n=C==null?void 0:C.signInWithSolana)===null||n===void 0?void 0:n.issuedAt)!==null&&a!==void 0?a:new Date().toISOString()}`,...!((i=C==null?void 0:C.signInWithSolana)===null||i===void 0)&&i.notBefore?[`Not Before: ${C.signInWithSolana.notBefore}`]:[],...!((o=C==null?void 0:C.signInWithSolana)===null||o===void 0)&&o.expirationTime?[`Expiration Time: ${C.signInWithSolana.expirationTime}`]:[],...!((l=C==null?void 0:C.signInWithSolana)===null||l===void 0)&&l.chainId?[`Chain ID: ${C.signInWithSolana.chainId}`]:[],...!((d=C==null?void 0:C.signInWithSolana)===null||d===void 0)&&d.nonce?[`Nonce: ${C.signInWithSolana.nonce}`]:[],...!((c=C==null?void 0:C.signInWithSolana)===null||c===void 0)&&c.requestId?[`Request ID: ${C.signInWithSolana.requestId}`]:[],...!((h=(u=C==null?void 0:C.signInWithSolana)===null||u===void 0?void 0:u.resources)===null||h===void 0)&&h.length?["Resources",...C.signInWithSolana.resources.map(j=>`- ${j}`)]:[]].join(` `);const N=await D.signMessage(new TextEncoder().encode(x),"utf8");if(!N||!(N instanceof Uint8Array))throw new Error("@supabase/auth-js: Wallet signMessage() API returned an recognized value");v=N}}try{const{data:y,error:w}=await te(this.fetch,"POST",`${this.url}/token?grant_type=web3`,{headers:this.headers,body:Object.assign({chain:"solana",message:x,signature:_o(v)},!((f=e.options)===null||f===void 0)&&f.captchaToken?{gotrue_meta_security:{captcha_token:(g=e.options)===null||g===void 0?void 0:g.captchaToken}}:null),xform:Ke});if(w)throw w;return!y||!y.session||!y.user?{data:{user:null,session:null},error:new Kt}:(y.session&&(await this._saveSession(y.session),await this._notifyAllSubscribers("SIGNED_IN",y.session)),{data:Object.assign({},y),error:w})}catch(y){if(J(y))return{data:{user:null,session:null},error:y};throw y}}async _exchangeCodeForSession(e){const r=await Vt(this.storage,`${this.storageKey}-code-verifier`),[n,a]=(r??"").split("/");try{const{data:i,error:o}=await te(this.fetch,"POST",`${this.url}/token?grant_type=pkce`,{headers:this.headers,body:{auth_code:e,code_verifier:n},xform:Ke});if(await Jt(this.storage,`${this.storageKey}-code-verifier`),o)throw o;return!i||!i.session||!i.user?{data:{user:null,session:null,redirectType:null},error:new Kt}:(i.session&&(await this._saveSession(i.session),await this._notifyAllSubscribers("SIGNED_IN",i.session)),{data:Object.assign(Object.assign({},i),{redirectType:a??null}),error:o})}catch(i){if(J(i))return{data:{user:null,session:null,redirectType:null},error:i};throw i}}async signInWithIdToken(e){try{const{options:r,provider:n,token:a,access_token:i,nonce:o}=e,l=await te(this.fetch,"POST",`${this.url}/token?grant_type=id_token`,{headers:this.headers,body:{provider:n,id_token:a,access_token:i,nonce:o,gotrue_meta_security:{captcha_token:r==null?void 0:r.captchaToken}},xform:Ke}),{data:d,error:c}=l;return c?{data:{user:null,session:null},error:c}:!d||!d.session||!d.user?{data:{user:null,session:null},error:new Kt}:(d.session&&(await this._saveSession(d.session),await this._notifyAllSubscribers("SIGNED_IN",d.session)),{data:d,error:c})}catch(r){if(J(r))return{data:{user:null,session:null},error:r};throw r}}async signInWithOtp(e){var r,n,a,i,o;try{if("email"in e){const{email:l,options:d}=e;let c=null,u=null;this.flowType==="pkce"&&([c,u]=await ut(this.storage,this.storageKey));const{error:h}=await te(this.fetch,"POST",`${this.url}/otp`,{headers:this.headers,body:{email:l,data:(r=d==null?void 0:d.data)!==null&&r!==void 0?r:{},create_user:(n=d==null?void 0:d.shouldCreateUser)!==null&&n!==void 0?n:!0,gotrue_meta_security:{captcha_token:d==null?void 0:d.captchaToken},code_challenge:c,code_challenge_method:u},redirectTo:d==null?void 0:d.emailRedirectTo});return{data:{user:null,session:null},error:h}}if("phone"in e){const{phone:l,options:d}=e,{data:c,error:u}=await te(this.fetch,"POST",`${this.url}/otp`,{headers:this.headers,body:{phone:l,data:(a=d==null?void 0:d.data)!==null&&a!==void 0?a:{},create_user:(i=d==null?void 0:d.shouldCreateUser)!==null&&i!==void 0?i:!0,gotrue_meta_security:{captcha_token:d==null?void 0:d.captchaToken},channel:(o=d==null?void 0:d.channel)!==null&&o!==void 0?o:"sms"}});return{data:{user:null,session:null,messageId:c==null?void 0:c.message_id},error:u}}throw new zt("You must provide either an email or phone number.")}catch(l){if(J(l))return{data:{user:null,session:null},error:l};throw l}}async verifyOtp(e){var r,n;try{let a,i;"options"in e&&(a=(r=e.options)===null||r===void 0?void 0:r.redirectTo,i=(n=e.options)===null||n===void 0?void 0:n.captchaToken);const{data:o,error:l}=await te(this.fetch,"POST",`${this.url}/verify`,{headers:this.headers,body:Object.assign(Object.assign({},e),{gotrue_meta_security:{captcha_token:i}}),redirectTo:a,xform:Ke});if(l)throw l;if(!o)throw new Error("An error occurred on token verification.");const d=o.session,c=o.user;return d!=null&&d.access_token&&(await this._saveSession(d),await this._notifyAllSubscribers(e.type=="recovery"?"PASSWORD_RECOVERY":"SIGNED_IN",d)),{data:{user:c,session:d},error:null}}catch(a){if(J(a))return{data:{user:null,session:null},error:a};throw a}}async signInWithSSO(e){var r,n,a;try{let i=null,o=null;return this.flowType==="pkce"&&([i,o]=await ut(this.storage,this.storageKey)),await te(this.fetch,"POST",`${this.url}/sso`,{body:Object.assign(Object.assign(Object.assign(Object.assign(Object.assign({},"providerId"in e?{provider_id:e.providerId}:null),"domain"in e?{domain:e.domain}:null),{redirect_to:(n=(r=e.options)===null||r===void 0?void 0:r.redirectTo)!==null&&n!==void 0?n:void 0}),!((a=e==null?void 0:e.options)===null||a===void 0)&&a.captchaToken?{gotrue_meta_security:{captcha_token:e.options.captchaToken}}:null),{skip_http_redirect:!0,code_challenge:i,code_challenge_method:o}),headers:this.headers,xform:Go})}catch(i){if(J(i))return{data:null,error:i};throw i}}async reauthenticate(){return await this.initializePromise,await this._acquireLock(-1,async()=>await this._reauthenticate())}async _reauthenticate(){try{return await this._useSession(async e=>{const{data:{session:r},error:n}=e;if(n)throw n;if(!r)throw new Je;const{error:a}=await te(this.fetch,"GET",`${this.url}/reauthenticate`,{headers:this.headers,jwt:r.access_token});return{data:{user:null,session:null},error:a}})}catch(e){if(J(e))return{data:{user:null,session:null},error:e};throw e}}async resend(e){try{const r=`${this.url}/resend`;if("email"in e){const{email:n,type:a,options:i}=e,{error:o}=await te(this.fetch,"POST",r,{headers:this.headers,body:{email:n,type:a,gotrue_meta_security:{captcha_token:i==null?void 0:i.captchaToken}},redirectTo:i==null?void 0:i.emailRedirectTo});return{data:{user:null,session:null},error:o}}else if("phone"in e){const{phone:n,type:a,options:i}=e,{data:o,error:l}=await te(this.fetch,"POST",r,{headers:this.headers,body:{phone:n,type:a,gotrue_meta_security:{captcha_token:i==null?void 0:i.captchaToken}}});return{data:{user:null,session:null,messageId:o==null?void 0:o.message_id},error:l}}throw new zt("You must provide either an email or phone number and a type")}catch(r){if(J(r))return{data:{user:null,session:null},error:r};throw r}}async getSession(){return await this.initializePromise,await this._acquireLock(-1,async()=>this._useSession(async r=>r))}async _acquireLock(e,r){this._debug("#_acquireLock","begin",e);try{if(this.lockAcquired){const n=this.pendingInLock.length?this.pendingInLock[this.pendingInLock.length-1]:Promise.resolve(),a=(async()=>(await n,await r()))();return this.pendingInLock.push((async()=>{try{await a}catch{}})()),a}return await this.lock(`lock:${this.storageKey}`,e,async()=>{this._debug("#_acquireLock","lock acquired for storage key",this.storageKey);try{this.lockAcquired=!0;const n=r();for(this.pendingInLock.push((async()=>{try{await n}catch{}})()),await n;this.pendingInLock.length;){const a=[...this.pendingInLock];await Promise.all(a),this.pendingInLock.splice(0,a.length)}return await n}finally{this._debug("#_acquireLock","lock released for storage key",this.storageKey),this.lockAcquired=!1}})}finally{this._debug("#_acquireLock","end")}}async _useSession(e){this._debug("#_useSession","begin");try{const r=await this.__loadSession();return await e(r)}finally{this._debug("#_useSession","end")}}async __loadSession(){this._debug("#__loadSession()","begin"),this.lockAcquired||this._debug("#__loadSession()","used outside of an acquired lock!",new Error().stack);try{let e=null;const r=await Vt(this.storage,this.storageKey);if(this._debug("#getSession()","session from storage",r),r!==null&&(this._isValidSession(r)?e=r:(this._debug("#getSession()","session from storage is not valid"),await this._removeSession())),!e)return{data:{session:null},error:null};const n=e.expires_at?e.expires_at*1e3-Date.now()<_s:!1;if(this._debug("#__loadSession()",`session has${n?"":" not"} expired`,"expires_at",e.expires_at),!n){if(this.storage.isServer){let o=this.suppressGetSessionWarning;e=new Proxy(e,{get:(d,c,u)=>(!o&&c==="user"&&(console.warn("Using the user object as returned from supabase.auth.getSession() or from some supabase.auth.onAuthStateChange() events could be insecure! This value comes directly from the storage medium (usually cookies on the server) and may not be authentic. Use supabase.auth.getUser() instead which authenticates the data by contacting the Supabase Auth server."),o=!0,this.suppressGetSessionWarning=!0),Reflect.get(d,c,u))})}return{data:{session:e},error:null}}const{session:a,error:i}=await this._callRefreshToken(e.refresh_token);return i?{data:{session:null},error:i}:{data:{session:a},error:null}}finally{this._debug("#__loadSession()","end")}}async getUser(e){return e?await this._getUser(e):(await this.initializePromise,await this._acquireLock(-1,async()=>await this._getUser()))}async _getUser(e){try{return e?await te(this.fetch,"GET",`${this.url}/user`,{headers:this.headers,jwt:e,xform:Qe}):await this._useSession(async r=>{var n,a,i;const{data:o,error:l}=r;if(l)throw l;return!(!((n=o.session)===null||n===void 0)&&n.access_token)&&!this.hasCustomAuthorizationHeader?{data:{user:null},error:new Je}:await te(this.fetch,"GET",`${this.url}/user`,{headers:this.headers,jwt:(i=(a=o.session)===null||a===void 0?void 0:a.access_token)!==null&&i!==void 0?i:void 0,xform:Qe})})}catch(r){if(J(r))return go(r)&&(await this._removeSession(),await Jt(this.storage,`${this.storageKey}-code-verifier`)),{data:{user:null},error:r};throw r}}async updateUser(e,r={}){return await this.initializePromise,await this._acquireLock(-1,async()=>await this._updateUser(e,r))}async _updateUser(e,r={}){try{return await this._useSession(async n=>{const{data:a,error:i}=n;if(i)throw i;if(!a.session)throw new Je;const o=a.session;let l=null,d=null;this.flowType==="pkce"&&e.email!=null&&([l,d]=await ut(this.storage,this.storageKey));const{data:c,error:u}=await te(this.fetch,"PUT",`${this.url}/user`,{headers:this.headers,redirectTo:r==null?void 0:r.emailRedirectTo,body:Object.assign(Object.assign({},e),{code_challenge:l,code_challenge_method:d}),jwt:o.access_token,xform:Qe});if(u)throw u;return o.user=c.user,await this._saveSession(o),await this._notifyAllSubscribers("USER_UPDATED",o),{data:{user:o.user},error:null}})}catch(n){if(J(n))return{data:{user:null},error:n};throw n}}async setSession(e){return await this.initializePromise,await this._acquireLock(-1,async()=>await this._setSession(e))}async _setSession(e){try{if(!e.access_token||!e.refresh_token)throw new Je;const r=Date.now()/1e3;let n=r,a=!0,i=null;const{payload:o}=Ss(e.access_token);if(o.exp&&(n=o.exp,a=n<=r),a){const{session:l,error:d}=await this._callRefreshToken(e.refresh_token);if(d)return{data:{user:null,session:null},error:d};if(!l)return{data:{user:null,session:null},error:null};i=l}else{const{data:l,error:d}=await this._getUser(e.access_token);if(d)throw d;i={access_token:e.access_token,refresh_token:e.refresh_token,user:l.user,token_type:"bearer",expires_in:n-r,expires_at:n},await this._saveSession(i),await this._notifyAllSubscribers("SIGNED_IN",i)}return{data:{user:i.user,session:i},error:null}}catch(r){if(J(r))return{data:{session:null,user:null},error:r};throw r}}async refreshSession(e){return await this.initializePromise,await this._acquireLock(-1,async()=>await this._refreshSession(e))}async _refreshSession(e){try{return await this._useSession(async r=>{var n;if(!e){const{data:o,error:l}=r;if(l)throw l;e=(n=o.session)!==null&&n!==void 0?n:void 0}if(!(e!=null&&e.refresh_token))throw new Je;const{session:a,error:i}=await this._callRefreshToken(e.refresh_token);return i?{data:{user:null,session:null},error:i}:a?{data:{user:a.user,session:a},error:null}:{data:{user:null,session:null},error:null}})}catch(r){if(J(r))return{data:{user:null,session:null},error:r};throw r}}async _getSessionFromURL(e,r){try{if(!Oe())throw new Wt("No browser detected.");if(e.error||e.error_description||e.error_code)throw new Wt(e.error_description||"Error in URL with unspecified error_description",{error:e.error||"unspecified_error",code:e.error_code||"unspecified_code"});switch(r){case"implicit":if(this.flowType==="pkce")throw new Tr("Not a valid PKCE flow url.");break;case"pkce":if(this.flowType==="implicit")throw new Wt("Not a valid implicit grant flow url.");break;default:}if(r==="pkce"){if(this._debug("#_initialize()","begin","is PKCE flow",!0),!e.code)throw new Tr("No code detected.");const{data:P,error:C}=await this._exchangeCodeForSession(e.code);if(C)throw C;const D=new URL(window.location.href);return D.searchParams.delete("code"),window.history.replaceState(window.history.state,"",D.toString()),{data:{session:P.session,redirectType:null},error:null}}const{provider_token:n,provider_refresh_token:a,access_token:i,refresh_token:o,expires_in:l,expires_at:d,token_type:c}=e;if(!i||!l||!o||!c)throw new Wt("No session defined in URL");const u=Math.round(Date.now()/1e3),h=parseInt(l);let f=u+h;d&&(f=parseInt(d));const g=f-u;g*1e3<=gt&&console.warn(`@supabase/gotrue-js: Session as retrieved from URL expires in ${g}s, should have been closer to ${h}s`);const x=f-h;u-x>=120?console.warn("@supabase/gotrue-js: Session as retrieved from URL was issued over 120s ago, URL could be stale",x,f,u):u-x<0&&console.warn("@supabase/gotrue-js: Session as retrieved from URL was issued in the future? Check the device clock for skew",x,f,u);const{data:v,error:y}=await this._getUser(i);if(y)throw y;const w={provider_token:n,provider_refresh_token:a,access_token:i,expires_in:h,expires_at:f,refresh_token:o,token_type:c,user:v.user};return window.location.hash="",this._debug("#_getSessionFromURL()","clearing window.location.hash"),{data:{session:w,redirectType:e.type},error:null}}catch(n){if(J(n))return{data:{session:null,redirectType:null},error:n};throw n}}_isImplicitGrantCallback(e){return!!(e.access_token||e.error_description)}async _isPKCECallback(e){const r=await Vt(this.storage,`${this.storageKey}-code-verifier`);return!!(e.code&&r)}async signOut(e={scope:"global"}){return await this.initializePromise,await this._acquireLock(-1,async()=>await this._signOut(e))}async _signOut({scope:e}={scope:"global"}){return await this._useSession(async r=>{var n;const{data:a,error:i}=r;if(i)return{error:i};const o=(n=a.session)===null||n===void 0?void 0:n.access_token;if(o){const{error:l}=await this.admin.signOut(o,e);if(l&&!(mo(l)&&(l.status===404||l.status===401||l.status===403)))return{error:l}}return e!=="others"&&(await this._removeSession(),await Jt(this.storage,`${this.storageKey}-code-verifier`)),{error:null}})}onAuthStateChange(e){const r=So(),n={id:r,callback:e,unsubscribe:()=>{this._debug("#unsubscribe()","state change callback with id removed",r),this.stateChangeEmitters.delete(r)}};return this._debug("#onAuthStateChange()","registered callback with id",r),this.stateChangeEmitters.set(r,n),(async()=>(await this.initializePromise,await this._acquireLock(-1,async()=>{this._emitInitialSession(r)})))(),{data:{subscription:n}}}async _emitInitialSession(e){return await this._useSession(async r=>{var n,a;try{const{data:{session:i},error:o}=r;if(o)throw o;await((n=this.stateChangeEmitters.get(e))===null||n===void 0?void 0:n.callback("INITIAL_SESSION",i)),this._debug("INITIAL_SESSION","callback id",e,"session",i)}catch(i){await((a=this.stateChangeEmitters.get(e))===null||a===void 0?void 0:a.callback("INITIAL_SESSION",null)),this._debug("INITIAL_SESSION","callback id",e,"error",i),console.error(i)}})}async resetPasswordForEmail(e,r={}){let n=null,a=null;this.flowType==="pkce"&&([n,a]=await ut(this.storage,this.storageKey,!0));try{return await te(this.fetch,"POST",`${this.url}/recover`,{body:{email:e,code_challenge:n,code_challenge_method:a,gotrue_meta_security:{captcha_token:r.captchaToken}},headers:this.headers,redirectTo:r.redirectTo})}catch(i){if(J(i))return{data:null,error:i};throw i}}async getUserIdentities(){var e;try{const{data:r,error:n}=await this.getUser();if(n)throw n;return{data:{identities:(e=r.user.identities)!==null&&e!==void 0?e:[]},error:null}}catch(r){if(J(r))return{data:null,error:r};throw r}}async linkIdentity(e){var r;try{const{data:n,error:a}=await this._useSession(async i=>{var o,l,d,c,u;const{data:h,error:f}=i;if(f)throw f;const g=await this._getUrlForProvider(`${this.url}/user/identities/authorize`,e.provider,{redirectTo:(o=e.options)===null||o===void 0?void 0:o.redirectTo,scopes:(l=e.options)===null||l===void 0?void 0:l.scopes,queryParams:(d=e.options)===null||d===void 0?void 0:d.queryParams,skipBrowserRedirect:!0});return await te(this.fetch,"GET",g,{headers:this.headers,jwt:(u=(c=h.session)===null||c===void 0?void 0:c.access_token)!==null&&u!==void 0?u:void 0})});if(a)throw a;return Oe()&&!(!((r=e.options)===null||r===void 0)&&r.skipBrowserRedirect)&&window.location.assign(n==null?void 0:n.url),{data:{provider:e.provider,url:n==null?void 0:n.url},error:null}}catch(n){if(J(n))return{data:{provider:e.provider,url:null},error:n};throw n}}async unlinkIdentity(e){try{return await this._useSession(async r=>{var n,a;const{data:i,error:o}=r;if(o)throw o;return await te(this.fetch,"DELETE",`${this.url}/user/identities/${e.identity_id}`,{headers:this.headers,jwt:(a=(n=i.session)===null||n===void 0?void 0:n.access_token)!==null&&a!==void 0?a:void 0})})}catch(r){if(J(r))return{data:null,error:r};throw r}}async _refreshAccessToken(e){const r=`#_refreshAccessToken(${e.substring(0,5)}...)`;this._debug(r,"begin");try{const n=Date.now();return await Co(async a=>(a>0&&await To(200*Math.pow(2,a-1)),this._debug(r,"refreshing attempt",a),await te(this.fetch,"POST",`${this.url}/token?grant_type=refresh_token`,{body:{refresh_token:e},headers:this.headers,xform:Ke})),(a,i)=>{const o=200*Math.pow(2,a);return i&&Ns(i)&&Date.now()+o-n<gt})}catch(n){if(this._debug(r,"error",n),J(n))return{data:{session:null,user:null},error:n};throw n}finally{this._debug(r,"end")}}_isValidSession(e){return typeof e=="object"&&e!==null&&"access_token"in e&&"refresh_token"in e&&"expires_at"in e}async _handleProviderSignIn(e,r){const n=await this._getUrlForProvider(`${this.url}/authorize`,e,{redirectTo:r.redirectTo,scopes:r.scopes,queryParams:r.queryParams});return this._debug("#_handleProviderSignIn()","provider",e,"options",r,"url",n),Oe()&&!r.skipBrowserRedirect&&window.location.assign(n),{data:{provider:e,url:n},error:null}}async _recoverAndRefresh(){var e;const r="#_recoverAndRefresh()";this._debug(r,"begin");try{const n=await Vt(this.storage,this.storageKey);if(this._debug(r,"session from storage",n),!this._isValidSession(n)){this._debug(r,"session is not valid"),n!==null&&await this._removeSession();return}const a=((e=n.expires_at)!==null&&e!==void 0?e:1/0)*1e3-Date.now()<_s;if(this._debug(r,`session has${a?"":" not"} expired with margin of ${_s}s`),a){if(this.autoRefreshToken&&n.refresh_token){const{error:i}=await this._callRefreshToken(n.refresh_token);i&&(console.error(i),Ns(i)||(this._debug(r,"refresh failed with a non-retryable error, removing the session",i),await this._removeSession()))}}else await this._notifyAllSubscribers("SIGNED_IN",n)}catch(n){this._debug(r,"error",n),console.error(n);return}finally{this._debug(r,"end")}}async _callRefreshToken(e){var r,n;if(!e)throw new Je;if(this.refreshingDeferred)return this.refreshingDeferred.promise;const a=`#_callRefreshToken(${e.substring(0,5)}...)`;this._debug(a,"begin");try{this.refreshingDeferred=new ms;const{data:i,error:o}=await this._refreshAccessToken(e);if(o)throw o;if(!i.session)throw new Je;await this._saveSession(i.session),await this._notifyAllSubscribers("TOKEN_REFRESHED",i.session);const l={session:i.session,error:null};return this.refreshingDeferred.resolve(l),l}catch(i){if(this._debug(a,"error",i),J(i)){const o={session:null,error:i};return Ns(i)||await this._removeSession(),(r=this.refreshingDeferred)===null||r===void 0||r.resolve(o),o}throw(n=this.refreshingDeferred)===null||n===void 0||n.reject(i),i}finally{this.refreshingDeferred=null,this._debug(a,"end")}}async _notifyAllSubscribers(e,r,n=!0){const a=`#_notifyAllSubscribers(${e})`;this._debug(a,"begin",r,`broadcast = ${n}`);try{this.broadcastChannel&&n&&this.broadcastChannel.postMessage({event:e,session:r});const i=[],o=Array.from(this.stateChangeEmitters.values()).map(async l=>{try{await l.callback(e,r)}catch(d){i.push(d)}});if(await Promise.all(o),i.length>0){for(let l=0;l<i.length;l+=1)console.error(i[l]);throw i[0]}}finally{this._debug(a,"end")}}async _saveSession(e){this._debug("#_saveSession()",e),this.suppressGetSessionWarning=!0,await Tn(this.storage,this.storageKey,e)}async _removeSession(){this._debug("#_removeSession()"),await Jt(this.storage,this.storageKey),await this._notifyAllSubscribers("SIGNED_OUT",null)}_removeVisibilityChangedCallback(){this._debug("#_removeVisibilityChangedCallback()");const e=this.visibilityChangedCallback;this.visibilityChangedCallback=null;try{e&&Oe()&&(window!=null&&window.removeEventListener)&&window.removeEventListener("visibilitychange",e)}catch(r){console.error("removing visibilitychange callback failed",r)}}async _startAutoRefresh(){await this._stopAutoRefresh(),this._debug("#_startAutoRefresh()");const e=setInterval(()=>this._autoRefreshTokenTick(),gt);this.autoRefreshTicker=e,e&&typeof e=="object"&&typeof e.unref=="function"?e.unref():typeof Deno<"u"&&typeof Deno.unrefTimer=="function"&&Deno.unrefTimer(e),setTimeout(async()=>{await this.initializePromise,await this._autoRefreshTokenTick()},0)}async _stopAutoRefresh(){this._debug("#_stopAutoRefresh()");const e=this.autoRefreshTicker;this.autoRefreshTicker=null,e&&clearInterval(e)}async startAutoRefresh(){this._removeVisibilityChangedCallback(),await this._startAutoRefresh()}async stopAutoRefresh(){this._removeVisibilityChangedCallback(),await this._stopAutoRefresh()}async _autoRefreshTokenTick(){this._debug("#_autoRefreshTokenTick()","begin");try{await this._acquireLock(0,async()=>{try{const e=Date.now();try{return await this._useSession(async r=>{const{data:{session:n}}=r;if(!n||!n.refresh_token||!n.expires_at){this._debug("#_autoRefreshTokenTick()","no session");return}const a=Math.floor((n.expires_at*1e3-e)/gt);this._debug("#_autoRefreshTokenTick()",`access token expires in ${a} ticks, a tick lasts ${gt}ms, refresh threshold is ${Bs} ticks`),a<=Bs&&await this._callRefreshToken(n.refresh_token)})}catch(r){console.error("Auto refresh tick failed with error. This is likely a transient error.",r)}}finally{this._debug("#_autoRefreshTokenTick()","end")}})}catch(e){if(e.isAcquireTimeout||e instanceof Cn)this._debug("auto refresh token tick lock not available");else throw e}}async _handleVisibilityChange(){if(this._debug("#_handleVisibilityChange()"),!Oe()||!(window!=null&&window.addEventListener))return this.autoRefreshToken&&this.startAutoRefresh(),!1;try{this.visibilityChangedCallback=async()=>await this._onVisibilityChanged(!1),window==null||window.addEventListener("visibilitychange",this.visibilityChangedCallback),await this._onVisibilityChanged(!0)}catch(e){console.error("_handleVisibilityChange",e)}}async _onVisibilityChanged(e){const r=`#_onVisibilityChanged(${e})`;this._debug(r,"visibilityState",document.visibilityState),document.visibilityState==="visible"?(this.autoRefreshToken&&this._startAutoRefresh(),e||(await this.initializePromise,await this._acquireLock(-1,async()=>{if(document.visibilityState!=="visible"){this._debug(r,"acquired the lock to recover the session, but the browser visibilityState is no longer visible, aborting");return}await this._recoverAndRefresh()}))):document.visibilityState==="hidden"&&this.autoRefreshToken&&this._stopAutoRefresh()}async _getUrlForProvider(e,r,n){const a=[`provider=${encodeURIComponent(r)}`];if(n!=null&&n.redirectTo&&a.push(`redirect_to=${encodeURIComponent(n.redirectTo)}`),n!=null&&n.scopes&&a.push(`scopes=${encodeURIComponent(n.scopes)}`),this.flowType==="pkce"){const[i,o]=await ut(this.storage,this.storageKey),l=new URLSearchParams({code_challenge:`${encodeURIComponent(i)}`,code_challenge_method:`${encodeURIComponent(o)}`});a.push(l.toString())}if(n!=null&&n.queryParams){const i=new URLSearchParams(n.queryParams);a.push(i.toString())}return n!=null&&n.skipBrowserRedirect&&a.push(`skip_http_redirect=${n.skipBrowserRedirect}`),`${e}?${a.join("&")}`}async _unenroll(e){try{return await this._useSession(async r=>{var n;const{data:a,error:i}=r;return i?{data:null,error:i}:await te(this.fetch,"DELETE",`${this.url}/factors/${e.factorId}`,{headers:this.headers,jwt:(n=a==null?void 0:a.session)===null||n===void 0?void 0:n.access_token})})}catch(r){if(J(r))return{data:null,error:r};throw r}}async _enroll(e){try{return await this._useSession(async r=>{var n,a;const{data:i,error:o}=r;if(o)return{data:null,error:o};const l=Object.assign({friendly_name:e.friendlyName,factor_type:e.factorType},e.factorType==="phone"?{phone:e.phone}:{issuer:e.issuer}),{data:d,error:c}=await te(this.fetch,"POST",`${this.url}/factors`,{body:l,headers:this.headers,jwt:(n=i==null?void 0:i.session)===null||n===void 0?void 0:n.access_token});return c?{data:null,error:c}:(e.factorType==="totp"&&(!((a=d==null?void 0:d.totp)===null||a===void 0)&&a.qr_code)&&(d.totp.qr_code=`data:image/svg+xml;utf-8,${d.totp.qr_code}`),{data:d,error:null})})}catch(r){if(J(r))return{data:null,error:r};throw r}}async _verify(e){return this._acquireLock(-1,async()=>{try{return await this._useSession(async r=>{var n;const{data:a,error:i}=r;if(i)return{data:null,error:i};const{data:o,error:l}=await te(this.fetch,"POST",`${this.url}/factors/${e.factorId}/verify`,{body:{code:e.code,challenge_id:e.challengeId},headers:this.headers,jwt:(n=a==null?void 0:a.session)===null||n===void 0?void 0:n.access_token});return l?{data:null,error:l}:(await this._saveSession(Object.assign({expires_at:Math.round(Date.now()/1e3)+o.expires_in},o)),await this._notifyAllSubscribers("MFA_CHALLENGE_VERIFIED",o),{data:o,error:l})})}catch(r){if(J(r))return{data:null,error:r};throw r}})}async _challenge(e){return this._acquireLock(-1,async()=>{try{return await this._useSession(async r=>{var n;const{data:a,error:i}=r;return i?{data:null,error:i}:await te(this.fetch,"POST",`${this.url}/factors/${e.factorId}/challenge`,{body:{channel:e.channel},headers:this.headers,jwt:(n=a==null?void 0:a.session)===null||n===void 0?void 0:n.access_token})})}catch(r){if(J(r))return{data:null,error:r};throw r}})}async _challengeAndVerify(e){const{data:r,error:n}=await this._challenge({factorId:e.factorId});return n?{data:null,error:n}:await this._verify({factorId:e.factorId,challengeId:r.id,code:e.code})}async _listFactors(){const{data:{user:e},error:r}=await this.getUser();if(r)return{data:null,error:r};const n=(e==null?void 0:e.factors)||[],a=n.filter(o=>o.factor_type==="totp"&&o.status==="verified"),i=n.filter(o=>o.factor_type==="phone"&&o.status==="verified");return{data:{all:n,totp:a,phone:i},error:null}}async _getAuthenticatorAssuranceLevel(){return this._acquireLock(-1,async()=>await this._useSession(async e=>{var r,n;const{data:{session:a},error:i}=e;if(i)return{data:null,error:i};if(!a)return{data:{currentLevel:null,nextLevel:null,currentAuthenticationMethods:[]},error:null};const{payload:o}=Ss(a.access_token);let l=null;o.aal&&(l=o.aal);let d=l;((n=(r=a.user.factors)===null||r===void 0?void 0:r.filter(h=>h.status==="verified"))!==null&&n!==void 0?n:[]).length>0&&(d="aal2");const u=o.amr||[];return{data:{currentLevel:l,nextLevel:d,currentAuthenticationMethods:u},error:null}}))}async fetchJwk(e,r={keys:[]}){let n=r.keys.find(o=>o.kid===e);if(n||(n=this.jwks.keys.find(o=>o.kid===e),n&&this.jwks_cached_at+ho>Date.now()))return n;const{data:a,error:i}=await te(this.fetch,"GET",`${this.url}/.well-known/jwks.json`,{headers:this.headers});if(i)throw i;if(!a.keys||a.keys.length===0)throw new Rt("JWKS is empty");if(this.jwks=a,this.jwks_cached_at=Date.now(),n=a.keys.find(o=>o.kid===e),!n)throw new Rt("No matching signing key found in JWKS");return n}async getClaims(e,r={keys:[]}){try{let n=e;if(!n){const{data:g,error:x}=await this.getSession();if(x||!g.session)return{data:null,error:x};n=g.session.access_token}const{header:a,payload:i,signature:o,raw:{header:l,payload:d}}=Ss(n);if(Do(i.exp),!a.kid||a.alg==="HS256"||!("crypto"in globalThis&&"subtle"in globalThis.crypto)){const{error:g}=await this.getUser(n);if(g)throw g;return{data:{claims:i,header:a,signature:o},error:null}}const c=$o(a.alg),u=await this.fetchJwk(a.kid,r),h=await crypto.subtle.importKey("jwk",u,c,!0,["verify"]);if(!await crypto.subtle.verify(c,h,o,jo(`${l}.${d}`)))throw new Rt("Invalid JWT signature");return{data:{claims:i,header:a,signature:o},error:null}}catch(n){if(J(n))return{data:null,error:n};throw n}}}$t.nextInstanceID=0;const el=$t;class tl extends el{constructor(e){super(e)}}var sl=function(s,e,r,n){function a(i){return i instanceof r?i:new r(function(o){o(i)})}return new(r||(r=Promise))(function(i,o){function l(u){try{c(n.next(u))}catch(h){o(h)}}function d(u){try{c(n.throw(u))}catch(h){o(h)}}function c(u){u.done?i(u.value):a(u.value).then(l,d)}c((n=n.apply(s,e||[])).next())})};class rl{constructor(e,r,n){var a,i,o;if(this.supabaseUrl=e,this.supabaseKey=r,!e)throw new Error("supabaseUrl is required.");if(!r)throw new Error("supabaseKey is required.");const l=ao(e),d=new URL(l);this.realtimeUrl=new URL("realtime/v1",d),this.realtimeUrl.protocol=this.realtimeUrl.protocol.replace("http","ws"),this.authUrl=new URL("auth/v1",d),this.storageUrl=new URL("storage/v1",d),this.functionsUrl=new URL("functions/v1",d);const c=`sb-${d.hostname.split(".")[0]}-auth-token`,u={db:Qi,realtime:Xi,auth:Object.assign(Object.assign({},Zi),{storageKey:c}),global:Yi},h=io(n??{},u);this.storageKey=(a=h.auth.storageKey)!==null&&a!==void 0?a:"",this.headers=(i=h.global.headers)!==null&&i!==void 0?i:{},h.accessToken?(this.accessToken=h.accessToken,this.auth=new Proxy({},{get:(f,g)=>{throw new Error(`@supabase/supabase-js: Supabase Client is configured with the accessToken option, accessing supabase.auth.${String(g)} is not possible`)}})):this.auth=this._initSupabaseAuthClient((o=h.auth)!==null&&o!==void 0?o:{},this.headers,h.global.fetch),this.fetch=ro(r,this._getAccessToken.bind(this),h.global.fetch),this.realtime=this._initRealtimeClient(Object.assign({headers:this.headers,accessToken:this._getAccessToken.bind(this)},h.realtime)),this.rest=new bi(new URL("rest/v1",d).href,{headers:this.headers,schema:h.db.schema,fetch:this.fetch}),h.accessToken||this._listenForAuthEvents()}get functions(){return new Ja(this.functionsUrl.href,{headers:this.headers,customFetch:this.fetch})}get storage(){return new Wi(this.storageUrl.href,this.headers,this.fetch)}from(e){return this.rest.from(e)}schema(e){return this.rest.schema(e)}rpc(e,r={},n={}){return this.rest.rpc(e,r,n)}channel(e,r={config:{}}){return this.realtime.channel(e,r)}getChannels(){return this.realtime.getChannels()}removeChannel(e){return this.realtime.removeChannel(e)}removeAllChannels(){return this.realtime.removeAllChannels()}_getAccessToken(){var e,r;return sl(this,void 0,void 0,function*(){if(this.accessToken)return yield this.accessToken();const{data:n}=yield this.auth.getSession();return(r=(e=n.session)===null||e===void 0?void 0:e.access_token)!==null&&r!==void 0?r:null})}_initSupabaseAuthClient({autoRefreshToken:e,persistSession:r,detectSessionInUrl:n,storage:a,storageKey:i,flowType:o,lock:l,debug:d},c,u){const h={Authorization:`Bearer ${this.supabaseKey}`,apikey:`${this.supabaseKey}`};return new tl({url:this.authUrl.href,headers:Object.assign(Object.assign({},h),c),storageKey:i,autoRefreshToken:e,persistSession:r,detectSessionInUrl:n,storage:a,flowType:o,lock:l,debug:d,fetch:u,hasCustomAuthorizationHeader:"Authorization"in this.headers})}_initRealtimeClient(e){return new Li(this.realtimeUrl.href,Object.assign(Object.assign({},e),{params:Object.assign({apikey:this.supabaseKey},e==null?void 0:e.params)}))}_listenForAuthEvents(){return this.auth.onAuthStateChange((r,n)=>{this._handleTokenChanged(r,"CLIENT",n==null?void 0:n.access_token)})}_handleTokenChanged(e,r,n){(e==="TOKEN_REFRESHED"||e==="SIGNED_IN")&&this.changedAccessToken!==n?this.changedAccessToken=n:e==="SIGNED_OUT"&&(this.realtime.setAuth(),r=="STORAGE"&&this.auth.signOut(),this.changedAccessToken=void 0)}}const nl=(s,e,r)=>new rl(s,e,r),al="https://ftwlzdhkzqfuosdorgjt.supabase.co",il="eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJpc3MiOiJzdXBhYmFzZSIsInJlZiI6ImZ0d2x6ZGhrenFmdW9zZG9yZ2p0Iiwicm9sZSI6ImFub24iLCJpYXQiOjE3MzE1Mjc0MzksImV4cCI6MjA0NzEwMzQzOX0.msaWtaLGNMDiyuxIOFDwULWee0nqcM7p_LAYWB14j1k",W=nl(al,il,{auth:{persistSession:!0,autoRefreshToken:!0,detectSessionInUrl:!0}}),Pn=b.createContext({user:null,isAdmin:!1,loading:!0,signIn:async()=>{},signOut:async()=>{}}),Es="ben@phippsmusic.com";function ol({children:s}){const[e,r]=b.useState(null),[n,a]=b.useState(!1),[i,o]=b.useState(!0);b.useEffect(()=>{W.auth.getSession().then(({data:{session:u}})=>{u!=null&&u.user&&(r({id:u.user.id,email:u.user.email||""}),a(u.user.email===Es)),o(!1)});const{data:{subscription:c}}=W.auth.onAuthStateChange((u,h)=>{h!=null&&h.user?(r({id:h.user.id,email:h.user.email||""}),a(h.user.email===Es)):(r(null),a(!1)),o(!1)});return()=>{c.unsubscribe()}},[]);const l=async(c,u)=>{o(!0);try{const{data:h,error:f}=await W.auth.signInWithPassword({email:c,password:u});if(f)throw f;if(h.user.email!==Es)throw await W.auth.signOut(),new Error("Unauthorized access");r({id:h.user.id,email:h.user.email}),a(!0)}catch(h){throw console.error("Sign in failed:",h),h}finally{o(!1)}},d=async()=>{try{await W.auth.signOut(),r(null),a(!1)}catch(c){throw console.error("Sign out failed:",c),c}};return t.jsx(Pn.Provider,{value:{user:e,isAdmin:n,loading:i,signIn:l,signOut:d},children:s})}function sr(){return b.useContext(Pn)}/** * @license lucide-react v0.344.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */var ll={xmlns:"http://www.w3.org/2000/svg",width:24,height:24,viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:2,strokeLinecap:"round",strokeLinejoin:"round"};/** * @license lucide-react v0.344.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const cl=s=>s.replace(/([a-z0-9])([A-Z])/g,"$1-$2").toLowerCase().trim(),z=(s,e)=>{const r=b.forwardRef(({color:n="currentColor",size:a=24,strokeWidth:i=2,absoluteStrokeWidth:o,className:l="",children:d,...c},u)=>b.createElement("svg",{ref:u,...ll,width:a,height:a,stroke:n,strokeWidth:o?Number(i)*24/Number(a):i,className:["lucide",`lucide-${cl(s)}`,l].join(" "),...c},[...e.map(([h,f])=>b.createElement(h,f)),...Array.isArray(d)?d:[d]]));return r.displayName=`${s}`,r};/** * @license lucide-react v0.344.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const fe=z("AlertCircle",[["circle",{cx:"12",cy:"12",r:"10",key:"1mglay"}],["line",{x1:"12",x2:"12",y1:"8",y2:"12",key:"1pkeuh"}],["line",{x1:"12",x2:"12.01",y1:"16",y2:"16",key:"4dfq90"}]]);/** * @license lucide-react v0.344.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const dl=z("AlertTriangle",[["path",{d:"m21.73 18-8-14a2 2 0 0 0-3.48 0l-8 14A2 2 0 0 0 4 21h16a2 2 0 0 0 1.73-3Z",key:"c3ski4"}],["path",{d:"M12 9v4",key:"juzpu7"}],["path",{d:"M12 17h.01",key:"p32p05"}]]);/** * @license lucide-react v0.344.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const We=z("ArrowLeft",[["path",{d:"m12 19-7-7 7-7",key:"1l729n"}],["path",{d:"M19 12H5",key:"x3x0zl"}]]);/** * @license lucide-react v0.344.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const Ut=z("ArrowRight",[["path",{d:"M5 12h14",key:"1ays0h"}],["path",{d:"m12 5 7 7-7 7",key:"xquz4c"}]]);/** * @license lucide-react v0.344.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const rr=z("Calendar",[["path",{d:"M8 2v4",key:"1cmpym"}],["path",{d:"M16 2v4",key:"4m81vk"}],["rect",{width:"18",height:"18",x:"3",y:"4",rx:"2",key:"1hopcy"}],["path",{d:"M3 10h18",key:"8toen8"}]]);/** * @license lucide-react v0.344.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const Gs=z("CheckCircle2",[["circle",{cx:"12",cy:"12",r:"10",key:"1mglay"}],["path",{d:"m9 12 2 2 4-4",key:"dzmm74"}]]);/** * @license lucide-react v0.344.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const nt=z("CheckCircle",[["path",{d:"M22 11.08V12a10 10 0 1 1-5.93-9.14",key:"g774vq"}],["path",{d:"m9 11 3 3L22 4",key:"1pflzl"}]]);/** * @license lucide-react v0.344.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const An=z("Check",[["path",{d:"M20 6 9 17l-5-5",key:"1gmf2c"}]]);/** * @license lucide-react v0.344.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const ul=z("ChevronRight",[["path",{d:"m9 18 6-6-6-6",key:"mthhwq"}]]);/** * @license lucide-react v0.344.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const ss=z("Clock",[["circle",{cx:"12",cy:"12",r:"10",key:"1mglay"}],["polyline",{points:"12 6 12 12 16 14",key:"68esgv"}]]);/** * @license lucide-react v0.344.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const hl=z("Disc",[["circle",{cx:"12",cy:"12",r:"10",key:"1mglay"}],["circle",{cx:"12",cy:"12",r:"2",key:"1c9p78"}]]);/** * @license lucide-react v0.344.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const fl=z("ExternalLink",[["path",{d:"M15 3h6v6",key:"1q9fwt"}],["path",{d:"M10 14 21 3",key:"gplh6r"}],["path",{d:"M18 13v6a2 2 0 0 1-2 2H5a2 2 0 0 1-2-2V8a2 2 0 0 1 2-2h6",key:"a6xqqp"}]]);/** * @license lucide-react v0.344.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const ml=z("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"}]]);/** * @license lucide-react v0.344.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const gl=z("Heart",[["path",{d:"M19 14c1.49-1.46 3-3.21 3-5.5A5.5 5.5 0 0 0 16.5 3c-1.76 0-3 .5-4.5 2-1.5-1.5-2.74-2-4.5-2A5.5 5.5 0 0 0 2 8.5c0 2.3 1.5 4.05 3 5.5l7 7Z",key:"c3ymky"}]]);/** * @license lucide-react v0.344.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const pl=z("History",[["path",{d:"M3 12a9 9 0 1 0 9-9 9.75 9.75 0 0 0-6.74 2.74L3 8",key:"1357e3"}],["path",{d:"M3 3v5h5",key:"1xhq8a"}],["path",{d:"M12 7v5l4 2",key:"1fdv2h"}]]);/** * @license lucide-react v0.344.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const On=z("Image",[["rect",{width:"18",height:"18",x:"3",y:"3",rx:"2",ry:"2",key:"1m3agn"}],["circle",{cx:"9",cy:"9",r:"2",key:"af1f0g"}],["path",{d:"m21 15-3.086-3.086a2 2 0 0 0-2.828 0L6 21",key:"1xmnt7"}]]);/** * @license lucide-react v0.344.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const yl=z("Inbox",[["polyline",{points:"22 12 16 12 14 15 10 15 8 12 2 12",key:"o97t9d"}],["path",{d:"M5.45 5.11 2 12v6a2 2 0 0 0 2 2h16a2 2 0 0 0 2-2v-6l-3.45-6.89A2 2 0 0 0 16.76 4H7.24a2 2 0 0 0-1.79 1.11z",key:"oot6mr"}]]);/** * @license lucide-react v0.344.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const xl=z("LayoutDashboard",[["rect",{width:"7",height:"9",x:"3",y:"3",rx:"1",key:"10lvy0"}],["rect",{width:"7",height:"5",x:"14",y:"3",rx:"1",key:"16une8"}],["rect",{width:"7",height:"9",x:"14",y:"12",rx:"1",key:"1hutg5"}],["rect",{width:"7",height:"5",x:"3",y:"16",rx:"1",key:"ldoo1y"}]]);/** * @license lucide-react v0.344.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const Hs=z("Link",[["path",{d:"M10 13a5 5 0 0 0 7.54.54l3-3a5 5 0 0 0-7.07-7.07l-1.72 1.71",key:"1cjeqo"}],["path",{d:"M14 11a5 5 0 0 0-7.54-.54l-3 3a5 5 0 0 0 7.07 7.07l1.71-1.71",key:"19qd67"}]]);/** * @license lucide-react v0.344.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const In=z("ListMusic",[["path",{d:"M21 15V6",key:"h1cx4g"}],["path",{d:"M18.5 18a2.5 2.5 0 1 0 0-5 2.5 2.5 0 0 0 0 5Z",key:"8saifv"}],["path",{d:"M12 12H3",key:"18klou"}],["path",{d:"M16 6H3",key:"1wxfjs"}],["path",{d:"M12 18H3",key:"11ftsu"}]]);/** * @license lucide-react v0.344.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const bl=z("List",[["line",{x1:"8",x2:"21",y1:"6",y2:"6",key:"7ey8pc"}],["line",{x1:"8",x2:"21",y1:"12",y2:"12",key:"rjfblc"}],["line",{x1:"8",x2:"21",y1:"18",y2:"18",key:"c3b1m8"}],["line",{x1:"3",x2:"3.01",y1:"6",y2:"6",key:"1g7gq3"}],["line",{x1:"3",x2:"3.01",y1:"12",y2:"12",key:"1pjlvk"}],["line",{x1:"3",x2:"3.01",y1:"18",y2:"18",key:"28t2mc"}]]);/** * @license lucide-react v0.344.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const me=z("Loader2",[["path",{d:"M21 12a9 9 0 1 1-6.219-8.56",key:"13zald"}]]);/** * @license lucide-react v0.344.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const wl=z("Lock",[["rect",{width:"18",height:"11",x:"3",y:"11",rx:"2",ry:"2",key:"1w4ew1"}],["path",{d:"M7 11V7a5 5 0 0 1 10 0v4",key:"fwvmzm"}]]);/** * @license lucide-react v0.344.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const vl=z("LogOut",[["path",{d:"M9 21H5a2 2 0 0 1-2-2V5a2 2 0 0 1 2-2h4",key:"1uf3rs"}],["polyline",{points:"16 17 21 12 16 7",key:"1gabdz"}],["line",{x1:"21",x2:"9",y1:"12",y2:"12",key:"1uyos4"}]]);/** * @license lucide-react v0.344.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const Ln=z("Mail",[["rect",{width:"20",height:"16",x:"2",y:"4",rx:"2",key:"18n3k1"}],["path",{d:"m22 7-8.97 5.7a1.94 1.94 0 0 1-2.06 0L2 7",key:"1ocrg3"}]]);/** * @license lucide-react v0.344.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const jl=z("Menu",[["line",{x1:"4",x2:"20",y1:"12",y2:"12",key:"1e0a9i"}],["line",{x1:"4",x2:"20",y1:"6",y2:"6",key:"1owob3"}],["line",{x1:"4",x2:"20",y1:"18",y2:"18",key:"yk5zj1"}]]);/** * @license lucide-react v0.344.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const Rn=z("MessageSquare",[["path",{d:"M21 15a2 2 0 0 1-2 2H7l-4 4V5a2 2 0 0 1 2-2h14a2 2 0 0 1 2 2z",key:"1lielz"}]]);/** * @license lucide-react v0.344.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const ve=z("Music2",[["circle",{cx:"8",cy:"18",r:"4",key:"1fc0mg"}],["path",{d:"M12 18V2l7 4",key:"g04rme"}]]);/** * @license lucide-react v0.344.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const gs=z("Music4",[["path",{d:"M9 18V5l12-2v13",key:"1jmyc2"}],["path",{d:"m9 9 12-2",key:"1e64n2"}],["circle",{cx:"6",cy:"18",r:"3",key:"fqmcym"}],["circle",{cx:"18",cy:"16",r:"3",key:"1hluhg"}]]);/** * @license lucide-react v0.344.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const _l=z("Newspaper",[["path",{d:"M4 22h16a2 2 0 0 0 2-2V4a2 2 0 0 0-2-2H8a2 2 0 0 0-2 2v16a2 2 0 0 1-2 2Zm0 0a2 2 0 0 1-2-2v-9c0-1.1.9-2 2-2h2",key:"7pis2x"}],["path",{d:"M18 14h-8",key:"sponae"}],["path",{d:"M15 18h-5",key:"95g1m2"}],["path",{d:"M10 6h8v4h-8V6Z",key:"smlsk5"}]]);/** * @license lucide-react v0.344.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const Nl=z("Pen",[["path",{d:"M17 3a2.85 2.83 0 1 1 4 4L7.5 20.5 2 22l1.5-5.5Z",key:"5qss01"}]]);/** * @license lucide-react v0.344.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const nr=z("Plus",[["path",{d:"M5 12h14",key:"1ays0h"}],["path",{d:"M12 5v14",key:"s699le"}]]);/** * @license lucide-react v0.344.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const wt=z("RefreshCw",[["path",{d:"M3 12a9 9 0 0 1 9-9 9.75 9.75 0 0 1 6.74 2.74L21 8",key:"v9h5vc"}],["path",{d:"M21 3v5h-5",key:"1q7to0"}],["path",{d:"M21 12a9 9 0 0 1-9 9 9.75 9.75 0 0 1-6.74-2.74L3 16",key:"3uifl3"}],["path",{d:"M8 16H3v5",key:"1cv678"}]]);/** * @license lucide-react v0.344.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const Sl=z("Save",[["path",{d:"M19 21H5a2 2 0 0 1-2-2V5a2 2 0 0 1 2-2h11l5 5v11a2 2 0 0 1-2 2z",key:"1owoqh"}],["polyline",{points:"17 21 17 13 7 13 7 21",key:"1md35c"}],["polyline",{points:"7 3 7 8 15 8",key:"8nz8an"}]]);/** * @license lucide-react v0.344.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const ps=z("Search",[["circle",{cx:"11",cy:"11",r:"8",key:"4ej97u"}],["path",{d:"m21 21-4.3-4.3",key:"1qie3q"}]]);/** * @license lucide-react v0.344.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const Dn=z("Send",[["path",{d:"m22 2-7 20-4-9-9-4Z",key:"1q3vgg"}],["path",{d:"M22 2 11 13",key:"nzbqef"}]]);/** * @license lucide-react v0.344.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const kl=z("Settings",[["path",{d:"M12.22 2h-.44a2 2 0 0 0-2 2v.18a2 2 0 0 1-1 1.73l-.43.25a2 2 0 0 1-2 0l-.15-.08a2 2 0 0 0-2.73.73l-.22.38a2 2 0 0 0 .73 2.73l.15.1a2 2 0 0 1 1 1.72v.51a2 2 0 0 1-1 1.74l-.15.09a2 2 0 0 0-.73 2.73l.22.38a2 2 0 0 0 2.73.73l.15-.08a2 2 0 0 1 2 0l.43.25a2 2 0 0 1 1 1.73V20a2 2 0 0 0 2 2h.44a2 2 0 0 0 2-2v-.18a2 2 0 0 1 1-1.73l.43-.25a2 2 0 0 1 2 0l.15.08a2 2 0 0 0 2.73-.73l.22-.39a2 2 0 0 0-.73-2.73l-.15-.08a2 2 0 0 1-1-1.74v-.5a2 2 0 0 1 1-1.74l.15-.09a2 2 0 0 0 .73-2.73l-.22-.38a2 2 0 0 0-2.73-.73l-.15.08a2 2 0 0 1-2 0l-.43-.25a2 2 0 0 1-1-1.73V4a2 2 0 0 0-2-2z",key:"1qme2f"}],["circle",{cx:"12",cy:"12",r:"3",key:"1v7zrd"}]]);/** * @license lucide-react v0.344.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const El=z("Sparkles",[["path",{d:"m12 3-1.912 5.813a2 2 0 0 1-1.275 1.275L3 12l5.813 1.912a2 2 0 0 1 1.275 1.275L12 21l1.912-5.813a2 2 0 0 1 1.275-1.275L21 12l-5.813-1.912a2 2 0 0 1-1.275-1.275L12 3Z",key:"17u4zn"}],["path",{d:"M5 3v4",key:"bklmnn"}],["path",{d:"M19 17v4",key:"iiml17"}],["path",{d:"M3 5h4",key:"nem4j1"}],["path",{d:"M17 19h4",key:"lbex7p"}]]);/** * @license lucide-react v0.344.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const $n=z("SquarePen",[["path",{d:"M12 3H5a2 2 0 0 0-2 2v14a2 2 0 0 0 2 2h14a2 2 0 0 0 2-2v-7",key:"1m0v6g"}],["path",{d:"M18.375 2.625a2.121 2.121 0 1 1 3 3L12 15l-4 1 1-4Z",key:"1lpok0"}]]);/** * @license lucide-react v0.344.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const ar=z("Star",[["polygon",{points:"12 2 15.09 8.26 22 9.27 17 14.14 18.18 21.02 12 17.77 5.82 21.02 7 14.14 2 9.27 8.91 8.26 12 2",key:"8f66p6"}]]);/** * @license lucide-react v0.344.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const Ks=z("Tag",[["path",{d:"M12.586 2.586A2 2 0 0 0 11.172 2H4a2 2 0 0 0-2 2v7.172a2 2 0 0 0 .586 1.414l8.704 8.704a2.426 2.426 0 0 0 3.42 0l6.58-6.58a2.426 2.426 0 0 0 0-3.42z",key:"vktsd0"}],["circle",{cx:"7.5",cy:"7.5",r:".5",fill:"currentColor",key:"kqv944"}]]);/** * @license lucide-react v0.344.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const ir=z("Trash2",[["path",{d:"M3 6h18",key:"d0wm0j"}],["path",{d:"M19 6v14c0 1-1 2-2 2H7c-1 0-2-1-2-2V6",key:"4alrt4"}],["path",{d:"M8 6V4c0-1 1-2 2-2h4c1 0 2 1 2 2v2",key:"v07s0e"}],["line",{x1:"10",x2:"10",y1:"11",y2:"17",key:"1uufr5"}],["line",{x1:"14",x2:"14",y1:"11",y2:"17",key:"xtxkd"}]]);/** * @license lucide-react v0.344.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const rs=z("Upload",[["path",{d:"M21 15v4a2 2 0 0 1-2 2H5a2 2 0 0 1-2-2v-4",key:"ih7n3h"}],["polyline",{points:"17 8 12 3 7 8",key:"t8dd8p"}],["line",{x1:"12",x2:"12",y1:"3",y2:"15",key:"widbto"}]]);/** * @license lucide-react v0.344.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const Ft=z("User",[["path",{d:"M19 21v-2a4 4 0 0 0-4-4H9a4 4 0 0 0-4 4v2",key:"975kel"}],["circle",{cx:"12",cy:"7",r:"4",key:"17ys0d"}]]);/** * @license lucide-react v0.344.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const qt=z("Users",[["path",{d:"M16 21v-2a4 4 0 0 0-4-4H6a4 4 0 0 0-4 4v2",key:"1yyitq"}],["circle",{cx:"9",cy:"7",r:"4",key:"nufk8"}],["path",{d:"M22 21v-2a4 4 0 0 0-3-3.87",key:"kshegd"}],["path",{d:"M16 3.13a4 4 0 0 1 0 7.75",key:"1da9ce"}]]);/** * @license lucide-react v0.344.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const $r=z("XCircle",[["circle",{cx:"12",cy:"12",r:"10",key:"1mglay"}],["path",{d:"m15 9-6 6",key:"1uzhvr"}],["path",{d:"m9 9 6 6",key:"z0biqf"}]]);/** * @license lucide-react v0.344.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const we=z("X",[["path",{d:"M18 6 6 18",key:"1bl5f8"}],["path",{d:"m6 6 12 12",key:"d8bk6v"}]]);/** * @license lucide-react v0.344.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const Tl=z("Zap",[["polygon",{points:"13 2 3 14 12 14 11 22 21 10 12 10 13 2",key:"45s27k"}]]);class Un extends b.Component{constructor(){super(...arguments);Ae(this,"state",{hasError:!1,error:null});Ae(this,"handleRetry",()=>{window.location.reload()})}static getDerivedStateFromError(r){return{hasError:!0,error:r}}componentDidCatch(r,n){console.error("Uncaught error:",r,n)}render(){var r,n;if(this.state.hasError){const i=((r=this.state.error)==null?void 0:r.message.includes("Supabase"))?"Unable to connect to the database. Please check your connection and try again.":"Something went wrong. Please try refreshing the page.";return t.jsx("div",{className:"min-h-screen flex items-center justify-center bg-gray-50 p-4",children:t.jsxs("div",{className:"bg-white p-6 rounded-lg shadow-lg max-w-md w-full",children:[t.jsxs("div",{className:"flex items-center gap-3 text-red-600 mb-4",children:[t.jsx(dl,{className:"w-6 h-6"}),t.jsx("h2",{className:"text-lg font-semibold",children:"Error"})]}),t.jsx("p",{className:"text-gray-600 mb-4",children:i}),((n=this.state.error)==null?void 0:n.message)&&t.jsx("pre",{className:"bg-gray-50 p-3 rounded text-sm text-gray-700 mb-4 overflow-auto",children:this.state.error.message}),t.jsxs("button",{onClick:this.handleRetry,className:"w-full bg-red-600 text-white py-2 rounded-lg hover:bg-red-700 transition-colors flex items-center justify-center gap-2",children:[t.jsx(wt,{className:"w-4 h-4"}),"Retry"]})]})})}return this.props.children}}function Be(){const[s,e]=b.useState([]),[r,n]=b.useState(!0),[a,i]=b.useState(null);return b.useEffect(()=>{async function o(){try{n(!0),i(null);const{data:l,error:d}=await W.from("genres").select("*").order("display_order");if(d)throw d;const{data:c,error:u}=await W.from("sub_genres").select("*").order("name");if(u)throw u;const h=l.map(f=>({...f,subGenres:c.filter(g=>g.genre_id===f.id).map(g=>({id:g.id,name:g.name,description:g.description}))}));e(h)}catch(l){console.error("Failed to fetch genres:",l),i(l instanceof Error?l:new Error("Failed to fetch genres"))}finally{n(!1)}}o()},[]),{genres:s,loading:r,error:a}}function Me(s){return s?s.toLowerCase().includes("r&b")?"rnb-soul":s.toString().toLowerCase().trim().replace(/[^\w\s-]/g,"").replace(/\s+/g,"-").replace(/-+/g,"-").replace(/^-+|-+$/g,""):""}function Cl(s){return s>=1e6?(s/1e6).toFixed(1)+"M":s>=1e3?(s/1e3).toFixed(1)+"K":s.toString()}function Ur(){const s=new Date;return`${s.getFullYear()}-${s.getMonth()+1}-${s.getDate()}`}function mt(s){let e=0;for(let r=0;r<s.length;r++){const n=s.charCodeAt(r);e=(e<<5)-e+n,e=e&e}return e}function Pl({onClose:s}){const{genres:e,loading:r}=Be();if(r)return t.jsx("div",{className:"p-6",children:t.jsx("div",{className:"grid grid-cols-3 gap-4",children:[...Array(6)].map((a,i)=>t.jsx("div",{className:"h-12 bg-gray-100 rounded-lg animate-pulse"},`skeleton-${i}`))})});const n=e.reduce((a,i,o)=>{const l=Math.floor(o/Math.ceil(e.length/3));return a[l]||(a[l]=[]),a[l].push(i),a},[]);return t.jsxs("div",{className:"p-6",children:[t.jsxs(ee,{to:"/genres",onClick:s,className:"flex items-center gap-2 p-3 mb-4 text-gray-600 hover:text-green-600 hover:bg-gray-50 rounded-lg transition-colors",children:[t.jsx(In,{className:"w-5 h-5"}),t.jsx("span",{className:"font-medium",children:"View All Genres & Sub-genres"})]}),t.jsx("div",{className:"grid grid-cols-3 gap-6",children:n.map((a,i)=>t.jsx("div",{className:"space-y-1",children:a.map(o=>t.jsxs(ee,{to:`/genre/${Me(o.name)}`,onClick:s,className:"flex items-center gap-2 p-3 rounded-lg hover:bg-gray-50 text-gray-900 group",children:[t.jsx("div",{className:"p-1.5 bg-gray-50 rounded group-hover:bg-green-50 transition-colors",children:t.jsx(ve,{className:"w-4 h-4 text-gray-500 group-hover:text-green-600"})}),t.jsx("span",{className:"font-medium",children:o.name})]},o.id))},i))})]})}function ke(){const s=it(),[e,r]=b.useState(!1),[n,a]=b.useState(!1),i=b.useRef();b.useRef(null);const o=s.pathname.startsWith("/submit"),l=()=>{i.current&&clearTimeout(i.current),r(!0)},d=()=>{i.current=setTimeout(()=>{r(!1)},300)};return b.useEffect(()=>{a(!1)},[s.pathname]),b.useEffect(()=>()=>{i.current&&clearTimeout(i.current)},[]),t.jsx("header",{className:"bg-gradient-to-r from-green-500 to-green-600 text-white relative z-50",children:t.jsxs("div",{className:"container mx-auto px-4",children:[t.jsxs("div",{className:"flex justify-between items-center h-16",children:[t.jsxs(ee,{to:"/",className:"flex items-center gap-3 hover:opacity-90 transition-opacity",children:[t.jsx(gs,{className:"w-8 h-8"}),t.jsx("h1",{className:"text-2xl font-bold whitespace-nowrap",children:"Playlist Partner"})]}),!o&&t.jsx(ee,{to:"/submit",className:"md:hidden flex items-center gap-2 bg-white text-green-600 px-4 py-2 rounded-lg hover:bg-green-50 transition-colors",children:"Submit"}),t.jsx("button",{onClick:()=>a(!n),className:"md:hidden p-2 hover:bg-white/10 rounded-lg ml-2","aria-label":"Toggle menu",children:n?t.jsx(we,{className:"w-6 h-6"}):t.jsx(jl,{className:"w-6 h-6"})}),t.jsxs("div",{className:"hidden md:flex items-center gap-8",children:[t.jsx(ee,{to:"/playlists",className:"flex items-center gap-2 text-white hover:text-white/90 transition-colors py-2 px-3 -ml-3",children:"Browse Playlists"}),t.jsxs("div",{onMouseEnter:l,onMouseLeave:d,className:"relative",children:[t.jsx(ee,{to:"/genres",className:"flex items-center gap-2 text-white hover:text-white/90 transition-colors py-2 px-3 -ml-3",children:"Browse Genres"}),e&&t.jsxs("div",{className:"absolute top-full right-0 w-[800px] bg-white shadow-xl rounded-lg mt-1",children:[t.jsx("div",{className:"absolute h-3 -top-3 inset-x-0"}),t.jsx(Pl,{onClose:()=>r(!1)})]})]}),t.jsx(ee,{to:"/for-curators",className:"flex items-center gap-2 text-white hover:text-white/90 transition-colors py-2 px-3 -ml-3",children:"For Curators"}),t.jsx(ee,{to:"/about",className:"flex items-center gap-2 text-white hover:text-white/90 transition-colors py-2 px-3 -ml-3",children:"About"}),t.jsx(ee,{to:"/blog",className:"flex items-center gap-2 text-white hover:text-white/90 transition-colors py-2 px-3 -ml-3",children:"Blog"}),!o&&t.jsx(ee,{to:"/submit",className:"flex items-center gap-2 bg-white text-green-600 px-4 py-2 rounded-lg hover:bg-green-50 transition-colors",children:"Submit Track"})]})]}),n&&t.jsx("div",{className:"md:hidden border-t border-white/10",children:t.jsxs("nav",{className:"py-4 space-y-2",children:[t.jsx(ee,{to:"/playlists",className:"block px-4 py-2 hover:bg-white/10 rounded-lg",onClick:()=>a(!1),children:"Browse Playlists"}),t.jsx(ee,{to:"/genres",className:"block px-4 py-2 hover:bg-white/10 rounded-lg",onClick:()=>a(!1),children:"Browse Genres"}),t.jsx(ee,{to:"/for-curators",className:"block px-4 py-2 hover:bg-white/10 rounded-lg",onClick:()=>a(!1),children:"For Curators"}),t.jsx(ee,{to:"/about",className:"block px-4 py-2 hover:bg-white/10 rounded-lg",onClick:()=>a(!1),children:"About"}),t.jsx(ee,{to:"/blog",className:"block px-4 py-2 hover:bg-white/10 rounded-lg",onClick:()=>a(!1),children:"Blog"})]})})]})})}function Ee(){const{genres:s}=Be();return t.jsx("footer",{className:"bg-gray-900 text-gray-300 mt-auto",children:t.jsxs("div",{className:"container mx-auto px-4 py-12",children:[t.jsxs("div",{className:"mb-12",children:[t.jsxs("div",{className:"flex items-center gap-3 mb-4",children:[t.jsx(gs,{className:"w-8 h-8"}),t.jsx("h2",{className:"text-2xl font-bold",children:"Playlist Partner"})]}),t.jsx("p",{className:"text-gray-400 max-w-2xl",children:"Artists have made over 100,000+ successful submissions through Playlist Partner. No barriers, no fees—just music finding its rightful audience. Your next fan is waiting."})]}),t.jsxs("div",{className:"border-t border-gray-800 pt-8",children:[t.jsx("h3",{className:"text-lg font-semibold mb-6",children:"Browse Genres"}),t.jsx("div",{className:"grid grid-cols-2 sm:grid-cols-3 md:grid-cols-4 lg:grid-cols-6 gap-x-4 gap-y-3",children:s.map(e=>t.jsx(ee,{to:`/genre/${e.slug}`,className:"text-gray-400 hover:text-green-500 transition-colors",children:e.name},e.id))})]}),t.jsx("div",{className:"border-t border-gray-800 mt-12 pt-8 text-center text-sm text-gray-500",children:t.jsxs("p",{children:["© ",new Date().getFullYear()," PlaylistPartner. All rights reserved."]})})]})})}function Fe({title:s,description:e,image:r="https://ftwlzdhkzqfuosdorgjt.supabase.co/storage/v1/object/public/playlistpartner%20public/playlistpartner%20og%20image.png",url:n,type:a="website",noIndex:i=!1,playlist:o,article:l,structuredData:d}){var x;const c=o?`Submit Music to ${o.name} - Free Spotify Playlist Submission`:s||"Free Spotify Playlist Submission – No Signup | PlaylistPartner",u=o?`Get your music featured on ${o.name}, a Spotify playlist curated by ${o.curator_name} with ${o.followers.toLocaleString()} followers. No account needed! Access ${((x=o.genre_count)==null?void 0:x.toLocaleString())||"thousands of"} ${o.genre||"playlists"} and connect with curators on PlaylistPartner.com.`:"Submit your music to thousands of independent Spotify playlist curators for free. No signup required—connect with curators and grow your audience today with PlaylistPartner.",h=e||u,f=n||window.location.href.split("?")[0],g=window.location.origin;return t.jsxs(Fa,{children:[t.jsx("title",{children:c}),t.jsx("meta",{name:"description",content:h,"data-react-helmet":"true"}),t.jsx("link",{rel:"canonical",href:f}),t.jsx("meta",{name:"robots",content:i?"noindex, nofollow":"index, follow, max-snippet:-1, max-image-preview:large, max-video-preview:-1"}),t.jsx("meta",{property:"og:site_name",content:"PlaylistPartner"}),t.jsx("meta",{property:"og:title",content:c,"data-react-helmet":"true"}),t.jsx("meta",{property:"og:description",content:h,"data-react-helmet":"true"}),t.jsx("meta",{property:"og:type",content:a}),t.jsx("meta",{property:"og:url",content:f}),t.jsx("meta",{property:"og:image",content:r,"data-react-helmet":"true"}),t.jsx("meta",{property:"og:image:width",content:"1200"}),t.jsx("meta",{property:"og:image:height",content:"630"}),t.jsx("meta",{name:"twitter:card",content:"summary_large_image"}),t.jsx("meta",{name:"twitter:title",content:c,"data-react-helmet":"true"}),t.jsx("meta",{name:"twitter:description",content:h,"data-react-helmet":"true"}),t.jsx("meta",{name:"twitter:image",content:r,"data-react-helmet":"true"}),t.jsx("meta",{name:"twitter:site",content:"@playlistpartner"}),l&&t.jsxs(t.Fragment,{children:[t.jsx("meta",{property:"article:published_time",content:l.publishedTime}),l.modifiedTime&&t.jsx("meta",{property:"article:modified_time",content:l.modifiedTime}),l.author&&t.jsx("meta",{property:"article:author",content:l.author}),l.section&&t.jsx("meta",{property:"article:section",content:l.section})]}),t.jsx("script",{type:"application/ld+json",children:JSON.stringify(d||{"@context":"https://schema.org","@type":"WebSite",name:"PlaylistPartner",url:g,inLanguage:"en-US",description:"Submit your music to thousands of independent Spotify playlist curators for free. No signup required—connect with curators and grow your audience today with PlaylistPartner.",publisher:{"@type":"Organization",name:"PlaylistPartner",logo:{"@type":"ImageObject",url:"https://ftwlzdhkzqfuosdorgjt.supabase.co/storage/v1/object/public/playlistpartner%20public//playlist%20partner%20logo%20square.png",width:"500",height:"500"}},potentialAction:{"@type":"ViewAction",target:f}})})]})}const ns="last_submission_data",Al=30*24*60*60*1e3;function Mn(s){try{const e={artistName:s.artistName,email:s.email,lastTrack:s.track,lastUpdated:Date.now()};localStorage.setItem(ns,JSON.stringify(e))}catch(e){console.error("Failed to save submission data:",e)}}function vt(){try{const s=localStorage.getItem(ns);if(!s)return null;const e=JSON.parse(s);return Date.now()-e.lastUpdated>Al?(localStorage.removeItem(ns),null):{artistName:e.artistName,email:e.email,lastTrack:e.lastTrack}}catch(s){return console.error("Failed to retrieve submission data:",s),null}}function Bn(){try{localStorage.removeItem(ns),localStorage.removeItem("trackSubmissions"),localStorage.removeItem("playlist_submissions"),localStorage.removeItem("spotify_token"),sessionStorage.clear()}catch(s){console.error("Failed to reset storage data:",s)}}const or=[{id:"6bHa6vnOHiKZdRjQaIWE5G",title:"Announcing Our New Music Marketing Guide Series",slug:"announcing-our-new-music-marketing-guide-series",body:{data:{},content:[{data:{},content:[{data:{},marks:[],value:"Since launching Playlist Partner and diving into the world of playlist submissions, we've always had bigger dreams. Today, we're excited to announce our upcoming series of music marketing guides, designed to help you expand your reach and build a sustainable career far beyond just playlist placements.",nodeType:"text"}],nodeType:"paragraph"},{data:{},content:[{data:{},marks:[],value:"We're collaborating with some amazing experts in the music marketing space to deliver insightful, actionable guides that will cover essential topics such as:",nodeType:"text"}],nodeType:"paragraph"},{data:{},content:[{data:{},content:[{data:{},content:[{data:{},marks:[{type:"bold"}],value:"Marketing Strategy and Release Planning",nodeType:"text"},{data:{},marks:[],value:" – How to strategically execute your releases for maximum impact across all platforms.",nodeType:"text"}],nodeType:"paragraph"}],nodeType:"list-item"},{data:{},content:[{data:{},content:[{data:{},marks:[{type:"bold"}],value:"Email Marketing",nodeType:"text"},{data:{},marks:[],value:" – Learn how building and nurturing a dedicated email list can significantly boost your career growth.",nodeType:"text"}],nodeType:"paragraph"}],nodeType:"list-item"},{data:{},content:[{data:{},content:[{data:{},marks:[{type:"bold"}],value:"Fanbase Loyalty",nodeType:"text"},{data:{},marks:[],value:" – Practical ways to build lasting, meaningful relationships with your fans.",nodeType:"text"}],nodeType:"paragraph"}],nodeType:"list-item"},{data:{},content:[{data:{},content:[{data:{},marks:[{type:"bold"}],value:"Playlist Placement Strategies",nodeType:"text"},{data:{},marks:[],value:" – Proven tactics to improve your chances of getting featured on playlists.",nodeType:"text"}],nodeType:"paragraph"}],nodeType:"list-item"},{data:{},content:[{data:{},content:[{data:{},marks:[{type:"bold"}],value:"Spotify Editorial Playlists",nodeType:"text"},{data:{},marks:[],value:" – Discover how Spotify selects tracks for their exclusive editorial playlists and how to increase your odds.",nodeType:"text"}],nodeType:"paragraph"}],nodeType:"list-item"},{data:{},content:[{data:{},content:[{data:{},marks:[{type:"bold"}],value:"Spotify Algorithmic Playlists and Radio",nodeType:"text"},{data:{},marks:[],value:" – Tips on maximizing your music’s presence on Spotify Radio and other algorithmic playlists.",nodeType:"text"}],nodeType:"paragraph"}],nodeType:"list-item"},{data:{},content:[{data:{},content:[{data:{},marks:[{type:"bold"}],value:"Social Media Mastery",nodeType:"text"},{data:{},marks:[],value:" – Building your brand authentically and effectively on social platforms.",nodeType:"text"}],nodeType:"paragraph"}],nodeType:"list-item"},{data:{},content:[{data:{},content:[{data:{},marks:[{type:"bold"}],value:"Networking and Collaboration",nodeType:"text"},{data:{},marks:[],value:" – How to find and nurture collaborations that can amplify your exposure and credibility.",nodeType:"text"}],nodeType:"paragraph"}],nodeType:"list-item"},{data:{},content:[{data:{},content:[{data:{},marks:[{type:"bold"}],value:"Digital Advertising for Musicians",nodeType:"text"},{data:{},marks:[],value:" – Leverage ads on social media and streaming platforms to grow your audience strategically.",nodeType:"text"}],nodeType:"paragraph"}],nodeType:"list-item"}],nodeType:"unordered-list"},{data:{},content:[{data:{},marks:[],value:"Stay tuned—we’re committed to giving you the tools and insights needed to amplify your music and reach new heights in your career.",nodeType:"text"}],nodeType:"paragraph"},{data:{},content:[{data:{},marks:[],value:"Thanks for your continued support and here's to growing together!",nodeType:"text"}],nodeType:"paragraph"},{data:{},content:[{data:{},marks:[],value:"— TEAM Playlist Partner",nodeType:"text"}],nodeType:"paragraph"}],nodeType:"document"},excerpt:"Introducing our new music marketing guide series! Learn how to maximize your impact with strategic release planning, playlist placements, email marketing, and more.",category:"News",featuredImage:{url:"//images.ctfassets.net/b3nqx2d7xn8z/6mcBY1GpfQvml3Y7NmlFuI/2161aefa678e313657baef0297599483/spotify_marketing_guides.jpg",title:"Illustration of music marketing concepts with icons on a blue background."},publishDate:"2025-06-23T00:00-07:00",featured:!1,createdAt:"2025-06-23T23:16:50.555Z",updatedAt:"2025-06-23T23:16:50.555Z"},{id:"5TT2Cna5qQIGiOl6rKVlHo",title:"Recent Fixes and Updates",slug:"recent-fixes-and-updates",body:{nodeType:"document",data:{},content:[{nodeType:"paragraph",data:{},content:[{nodeType:"text",value:"Thanks to everyone for submitting feedback on Playlist Partner 2.0 - we truly appreciate it!",marks:[],data:{}}]},{nodeType:"paragraph",data:{},content:[{nodeType:"text",value:"Here's what we've addressed in the last few weeks:",marks:[],data:{}}]},{nodeType:"unordered-list",data:{},content:[{nodeType:"list-item",data:{},content:[{nodeType:"paragraph",data:{},content:[{nodeType:"text",value:"Search Improvements",marks:[{type:"bold"}],data:{}},{nodeType:"text",value:": Search now works much better when applying multiple filters. We'd say it's pretty flawless now. 😊",marks:[],data:{}}]}]},{nodeType:"list-item",data:{},content:[{nodeType:"paragraph",data:{},content:[{nodeType:"text",value:"Song Selection Saved",marks:[{type:"bold"}],data:{}},{nodeType:"text",value:": Your song selections are now preserved even if you close your browser window.",marks:[],data:{}}]}]},{nodeType:"list-item",data:{},content:[{nodeType:"paragraph",data:{},content:[{nodeType:"text",value:"Daily Metadata Updates",marks:[{type:"bold"}],data:{}},{nodeType:"text",value:": Playlist metadata, such as follower count and track count, is now updated daily.",marks:[],data:{}}]}]},{nodeType:"list-item",data:{},content:[{nodeType:"paragraph",data:{},content:[{nodeType:"text",value:"Featured Playlists",marks:[{type:"bold"}],data:{}},{nodeType:"text",value:": We've added a new section to highlight some of our favorite playlists and curators.",marks:[],data:{}}]}]},{nodeType:"list-item",data:{},content:[{nodeType:"paragraph",data:{},content:[{nodeType:"text",value:"Clearer Notifications",marks:[{type:"bold"}],data:{}},{nodeType:"text",value:': Introduced clear "toast" messages to confirm all actions.',marks:[],data:{}}]}]},{nodeType:"list-item",data:{},content:[{nodeType:"paragraph",data:{},content:[{nodeType:"text",value:"More Playlists",marks:[{type:"bold"}],data:{}},{nodeType:"text",value:": We're actively onboarding even more playlists!",marks:[],data:{}}]}]}]},{nodeType:"paragraph",data:{},content:[{nodeType:"text",value:"We've got plenty of exciting features in the pipeline - not just bug fixes. Stay tuned!",marks:[],data:{}}]},{nodeType:"paragraph",data:{},content:[{nodeType:"text",value:"Thanks again for your continued support.",marks:[],data:{}}]},{nodeType:"paragraph",data:{},content:[{nodeType:"text",value:"-",marks:[],data:{}},{nodeType:"text",value:" TEAM Playlist Partner",marks:[],data:{}}]}]},excerpt:"We've tackled your top requests and improved Playlist Partner 2.0! Enjoy smoother search, saved selections, daily metadata updates, and more.",category:"News",featuredImage:{url:"//images.ctfassets.net/b3nqx2d7xn8z/7ds4PCuy0lCKDJCIUV1xUY/93fe1218873ae3a1bdf424e00c2a3367/bug_fixes.png",title:"Cheerful ladybug illustration with the title “Recent Fixes and Updates†on a blue background"},publishDate:"2025-05-08T09:54-07:00",featured:!1,createdAt:"2025-06-23T22:36:46.075Z",updatedAt:"2025-06-23T23:33:34.006Z"},{id:"2s8044B1fJGMzeDA0NL700",title:"Introducing Playlist Partner 2.0",slug:"introducing-playlistpartner-2-0",body:{data:{},content:[{data:{},content:[{data:{},marks:[],value:"After getting frustrated by the existing playlist submission options, we, a small group of indie musicians, came together one weekend and quickly hacked together the first version of Playlist Partner. It was a scrappy patchwork of code, platforms, and duct tape holding it all together. This rough-and-ready MVP was our way of testing if there was interest in a 100% free, community-driven project created purely out of love for music.",nodeType:"text"}],nodeType:"paragraph"},{data:{},content:[{data:{},marks:[],value:"Our goal was clear: create a new kind of site that didn’t destroy your Spotify account by forcing you to follow countless playlists that might not even feature your song, or artists you'd never listen to. Instead, we wanted to foster genuine connections and a mutual exchange of value agreed upon directly by artists and curators, not dictated by the platform.",nodeType:"text"}],nodeType:"paragraph"},{data:{},content:[{data:{},marks:[],value:"We were blown away by the response and the love our weekend experiment received. With your invaluable feedback in hand, we went back to the drawing board and meticulously rebuilt the platform from the ground up. And now, here we are on launch day!",nodeType:"text"}],nodeType:"paragraph"},{data:{},content:[{data:{},marks:[],value:"PlaylistPartner 2.0 is smoother, faster, and more intuitive, both on the frontend and backend. It provides artists and curators with a robust, reliable foundation, enabling us to roll out even more powerful features in the future. Expect a snappier interface, a streamlined user experience, and a powerful new engine built to amplify your music's reach.",nodeType:"text"}],nodeType:"paragraph"},{data:{},content:[{data:{},marks:[],value:"Over the coming weeks, you’ll notice a little feedback button floating around the right side of the site. Please use it to report any issues or submit your feature requests, we're excited to keep improving based on your input.",nodeType:"text"}],nodeType:"paragraph"},{data:{},content:[{data:{},marks:[],value:"Thanks for supporting our project, and may the odds ever be in your favor!",nodeType:"text"}],nodeType:"paragraph"},{data:{},content:[{data:{},marks:[],value:"— TEAM Playlist Partner",nodeType:"text"}],nodeType:"paragraph"}],nodeType:"document"},excerpt:"PlaylistPartner 2.0 is here, rebuilt from scratch! Now smoother, faster, and built specifically for artists and curators. Check out the new features, give us your feedback, and help shape the future of free playlist submissions.",category:"News",featuredImage:{url:"//images.ctfassets.net/b3nqx2d7xn8z/18zwyIaISSiy1k32iYFKwm/db3f8c7ad0bfe902cdd29baea9b4276f/playlist_partner_2.0_featured_image_2.png",title:"Playlist Partner 2.0 Announcement"},publishDate:"2025-04-02T14:14-07:00",featured:!1,createdAt:"2025-06-23T22:23:06.179Z",updatedAt:"2025-06-23T22:26:31.945Z"}];function Ol(){const e=or.filter(a=>a.category==="News").slice(0,2);function r(a){return new Date(a).toLocaleDateString("en-US",{month:"short",day:"numeric"})}function n(a){return a.startsWith("//")?`https:${a}`:a}return e.length===0?null:t.jsx("div",{className:"my-16",children:t.jsxs("div",{className:"max-w-[1400px] mx-auto",children:[t.jsx("h2",{className:"text-2xl font-semibold text-gray-900 mb-8",children:"Latest News from Playlist Partner"}),t.jsxs("div",{className:"grid md:grid-cols-3 gap-6",children:[e.map(a=>{var i;return t.jsxs(ee,{to:`/blog/news/${a.slug}`,className:"group bg-white border border-gray-200 rounded-lg overflow-hidden hover:border-green-500 hover:shadow-md transition-all",children:[((i=a.featuredImage)==null?void 0:i.url)&&t.jsx("div",{className:"aspect-[3/2] overflow-hidden",children:t.jsx("img",{src:n(a.featuredImage.url),alt:a.featuredImage.title||a.title,className:"w-full h-full object-cover group-hover:scale-105 transition-transform duration-300"})}),t.jsxs("div",{className:"p-6",children:[t.jsx("h3",{className:"text-lg font-semibold text-gray-900 group-hover:text-green-600 transition-colors line-clamp-2 mb-3",children:a.title}),a.excerpt&&t.jsx("p",{className:"text-gray-600 text-sm mb-4 line-clamp-2",children:a.excerpt}),t.jsxs("div",{className:"flex items-center justify-between",children:[t.jsxs("div",{className:"flex items-center gap-1 text-xs text-gray-500",children:[t.jsx(rr,{className:"w-3 h-3"}),t.jsx("span",{children:r(a.publishDate||a.createdAt)})]}),t.jsxs("span",{className:"text-green-600 text-sm flex items-center gap-1 group-hover:gap-2 transition-all",children:["Read",t.jsx(Ut,{className:"w-4 h-4"})]})]})]})]},a.id)}),t.jsx(ee,{to:"/blog",className:"group bg-gradient-to-br from-green-50 to-green-100 border border-green-200 rounded-lg overflow-hidden hover:border-green-500 hover:shadow-md transition-all flex flex-col",children:t.jsxs("div",{className:"flex-1 flex flex-col justify-center items-center text-center p-6",children:[t.jsx("div",{className:"mb-4",children:t.jsx("div",{className:"w-16 h-16 bg-green-600 rounded-full flex items-center justify-center group-hover:scale-110 transition-transform",children:t.jsx(Ut,{className:"w-8 h-8 text-white"})})}),t.jsx("h3",{className:"text-lg font-semibold text-gray-900 mb-2",children:"View All Posts"}),t.jsx("p",{className:"text-gray-600 text-sm",children:"Explore all blog posts and updates"})]})})]})]})})}const Il=b.lazy(()=>Ve(()=>import("./FeaturedPlaylists-B8noy_cw.js"),__vite__mapDeps([0,1,2])).then(s=>({default:s.FeaturedPlaylists}))),Ll=b.lazy(()=>Ve(()=>Promise.resolve().then(()=>oc),void 0).then(s=>({default:s.SubmissionModal}))),Rl=()=>t.jsx("div",{className:"bg-gradient-to-b from-green-50 to-white",children:t.jsx("div",{className:"container mx-auto px-4 py-12",children:t.jsxs("div",{className:"max-w-[1400px] mx-auto",children:[t.jsxs("div",{className:"text-center mb-12",children:[t.jsx("h1",{className:"text-4xl font-bold text-gray-900 mb-4",children:"Free Spotify Playlist Submissions - No Signup"}),t.jsx("h2",{className:"text-xl text-gray-600",children:"Connect Instantly with Thousands of Independent Playlist Curators"})]}),t.jsxs("div",{className:"grid md:grid-cols-3 gap-8 text-left",children:[t.jsxs("div",{className:"bg-white border border-gray-200 p-8 hover:border-green-500 transition-colors rounded-md",children:[t.jsx("h3",{className:"text-lg font-semibold text-gray-900 mb-3",children:"Direct Connections"}),t.jsx("p",{className:"text-gray-600",children:"Skip the middlemen and connect with real playlist curators who are passionate about discovering new music. Our platform eliminates gatekeepers, letting your music speak directly to those who can share it with their audiences."})]}),t.jsxs("div",{className:"bg-white border border-gray-200 p-8 hover:border-green-500 transition-colors rounded-md",children:[t.jsx("h3",{className:"text-lg font-semibold text-gray-900 mb-3",children:"Zero Barriers"}),t.jsx("p",{className:"text-gray-600",children:"No accounts, no credits—just instant Spotify submissions without hassle. Paste your track link and start submitting to playlists immediately. We've removed every obstacle between independent artists and playlist opportunities."})]}),t.jsxs("div",{className:"bg-white border border-gray-200 p-8 hover:border-green-500 transition-colors rounded-md",children:[t.jsx("h3",{className:"text-lg font-semibold text-gray-900 mb-3",children:"Community-Driven"}),t.jsx("p",{className:"text-gray-600",children:"Built by independent musicians for the indie community. Our platform fosters genuine relationships between artists and curators based on mutual appreciation rather than transactional expectations."})]})]})]})})}),Dl=()=>{var e,r;const s=vt();return t.jsx("div",{className:"my-8 pt-8 border-t border-gray-200",children:t.jsxs("div",{className:"max-w-[1400px] mx-auto",children:[t.jsxs("h2",{className:"text-2xl font-semibold text-gray-900 mb-6",children:["Today's Featured Playlists - ",new Date().toLocaleDateString("en-US",{weekday:"long",month:"long",day:"numeric"})]}),(s==null?void 0:s.lastTrack)&&t.jsxs("div",{className:"mb-6 flex items-center justify-between bg-white p-4 shadow-sm rounded-lg",children:[t.jsxs("div",{className:"flex items-center gap-4",children:[t.jsx("img",{src:(e=s.lastTrack.album.images[2])==null?void 0:e.url,alt:s.lastTrack.name,className:"w-12 h-12 object-cover rounded-md",loading:"lazy"}),t.jsxs("div",{children:[t.jsx("p",{className:"font-medium",children:s.lastTrack.name}),t.jsx("p",{className:"text-sm text-gray-600",children:(r=s.lastTrack.artists[0])==null?void 0:r.name})]})]}),t.jsx("button",{onClick:()=>{Bn(),window.location.reload()},className:"p-2 hover:bg-gray-100 rounded-full transition-colors",title:"Clear selected track",children:t.jsx(we,{className:"w-5 h-5 text-gray-500"})})]}),t.jsx("div",{className:"border-l-4 border-green-500 pl-6",children:t.jsx(b.Suspense,{fallback:t.jsx("div",{className:"h-32 flex items-center justify-center",children:t.jsx(me,{className:"w-8 h-8 animate-spin"})}),children:t.jsx(Il,{})})})]})})},$l=()=>t.jsx("div",{className:"bg-gradient-to-b from-gray-50 via-gray-100 to-gray-50 py-12 mt-16 mb-16 border-y border-gray-200",children:t.jsxs("div",{className:"text-center max-w-[1400px] mx-auto px-4",children:[t.jsx("p",{className:"text-gray-800 text-xl font-medium mb-6",children:"Find the Perfect Playlist for Your Music"}),t.jsx(ee,{to:"/playlists",className:"inline-block px-12 py-5 bg-blue-600 text-white text-xl font-semibold rounded-lg hover:bg-blue-700 transition-all transform hover:scale-105 shadow-lg hover:shadow-xl",children:"Explore All Playlists"})]})});function Ul(){const[s,e]=b.useState(null);return t.jsxs(t.Fragment,{children:[t.jsx(Fe,{}),t.jsxs("main",{children:[t.jsx(Rl,{}),t.jsxs("div",{className:"container mx-auto px-4 pb-12",children:[t.jsx(b.Suspense,{fallback:null,children:t.jsx(Dl,{})}),t.jsx($l,{}),t.jsx(Ol,{}),t.jsxs(b.Suspense,{fallback:null,children:[t.jsx(Ml,{}),t.jsx(Bl,{})]})]}),s&&t.jsx(b.Suspense,{fallback:null,children:t.jsx(Ll,{playlist:s,onClose:()=>e(null),onSubmit:()=>e(null)})})]})]})}const Ml=b.lazy(()=>Ve(()=>import("./FAQSection-DYdRED9D.js"),__vite__mapDeps([3,1,2]))),Bl=b.lazy(()=>Ve(()=>import("./AdditionalInfoSection-DphltVm4.js"),__vite__mapDeps([4,1,2])));function Fl(s){const[e,r]=b.useState(null),[n,a]=b.useState(!0),[i,o]=b.useState(null),[l,d]=b.useState([]);return b.useEffect(()=>{let c=!0;async function u(){if(!s){o(new Error("Invalid playlist URL")),a(!1);return}try{a(!0),o(null);const{data:h,error:f}=await W.from("playlist_details").select("*").eq("slug",s).limit(1);if(f)throw f;if(!h||h.length===0)throw new Error("Playlist not found");const g=h[0];if(c){r(g);const{data:x,error:v}=await W.from("playlist_details").select("*").eq("genre",g.genre).neq("id",g.id).order("followers",{ascending:!1}).limit(4);!v&&x&&d(x)}}catch(h){console.error("Failed to fetch playlist:",h),c&&(o(h instanceof Error?h:new Error("Failed to fetch playlist")),r(null),d([]))}finally{c&&a(!1)}}return u(),()=>{c=!1}},[s]),{playlist:e,loading:n,error:i,relatedPlaylists:l,isNotFound:(i==null?void 0:i.message)==="Playlist not found"}}const zs="playlist_submissions";function ql(s,e){try{const r=JSON.parse(localStorage.getItem(zs)||"[]"),n=r.find(a=>a.playlistId===s);n?n.tracks.some(a=>a.spotifyUrl===e)||n.tracks.push({spotifyUrl:e,timestamp:Date.now()}):r.push({playlistId:s,tracks:[{spotifyUrl:e,timestamp:Date.now()}]}),localStorage.setItem(zs,JSON.stringify(r))}catch(r){console.error("Failed to track submission:",r)}}function Fn(s,e){try{const n=JSON.parse(localStorage.getItem(zs)||"[]").find(a=>a.playlistId===s);return!!(n!=null&&n.tracks.some(a=>a.spotifyUrl===e))}catch(r){return console.error("Failed to check submission status:",r),!1}}const Ws="scrollPositions",Gl=5*60*1e3,Hl=10,Kl=100;function Mr(){try{return JSON.parse(sessionStorage.getItem(Ws)||"[]")}catch{return[]}}const qn={savePosition(s,e){try{const r=Mr(),n=window.scrollY;if(n>0){r.push({pathname:s,position:n,timestamp:Date.now(),searchParams:e==null?void 0:e.toString()});const a=r.filter(i=>Date.now()-i.timestamp<Gl);sessionStorage.setItem(Ws,JSON.stringify(a))}}catch(r){console.error("Failed to save scroll position:",r)}},restorePosition(s,e){try{const r=Mr(),n=r.find(a=>a.pathname===s);if(n){const a=r.filter(l=>l!==n);sessionStorage.setItem(Ws,JSON.stringify(a)),n.searchParams&&e&&e(new URLSearchParams(n.searchParams));let i=0;const o=()=>{const l=document.documentElement.scrollHeight,d=n.position;if(l>=d||i>=Hl){window.scrollTo({top:d,behavior:"instant"});return}i++,setTimeout(o,Kl)};setTimeout(o,50)}}catch(r){console.error("Failed to restore scroll position:",r)}}};function Gn(s){if(!s)return null;const e=new Date,r=new Date(s),n=new Date(e.getFullYear(),e.getMonth(),e.getDate()),a=new Date(n);a.setDate(a.getDate()-1);const i=new Date(n);i.setDate(i.getDate()-7);const o=new Date(r.getFullYear(),r.getMonth(),r.getDate());return o.getTime()===n.getTime()?"today":o.getTime()===a.getTime()?"yesterday":o>i?"this-week":null}function lr({playlist:s,onSubmit:e,isRelated:r,priority:n=!1,hideSubmit:a=!1}){const i=Xe(),o=it(),[l]=Jr(),[d,c]=b.useState(!1),u=vt(),h=(u==null?void 0:u.lastTrack)&&Fn(s.id,u.lastTrack.external_urls.spotify),f=g=>{g.preventDefault(),r||qn.savePosition(o.pathname,l);const x=o.pathname.startsWith("/genre/");window.scrollTo({top:0,behavior:"instant"}),i(`/playlist/${s.slug}`,{state:{from:x?"genre":"home"}})};return t.jsxs("div",{className:"bg-white shadow-sm hover:shadow-md transition-shadow h-full flex flex-col",children:[t.jsxs("div",{className:"flex-1",children:[t.jsxs("a",{href:`/playlist/${s.slug}`,onClick:f,className:"cursor-pointer no-js-fallback",children:[t.jsxs("div",{className:"relative pb-[100%] bg-gray-100",children:[d||!s.image_url?t.jsx("div",{className:"absolute inset-0 flex items-center justify-center bg-gradient-to-br from-gray-100 to-gray-200",children:t.jsxs("div",{className:"text-center",children:[t.jsx(On,{className:"w-12 h-12 text-gray-400 mx-auto mb-2"}),t.jsx("div",{className:"text-sm text-gray-500 font-medium px-4 truncate max-w-[200px]",children:s.name})]})}):t.jsx("img",{src:s.image_url,alt:s.name,className:"absolute inset-0 w-full h-full object-cover sm:rounded-[2px] lg:rounded-[4px]",loading:n?"eager":"lazy",onError:()=>c(!0)}),s.featured&&t.jsxs("div",{className:"absolute top-2 right-2 bg-yellow-400 text-yellow-900 px-2 py-1 rounded-full text-xs font-medium flex items-center gap-1",children:[t.jsx(ar,{className:"w-3 h-3"}),"Featured"]})]}),t.jsx("h3",{className:"text-base font-bold text-gray-900 mb-1 line-clamp-1 hover:text-green-600 transition-colors p-4 pb-0",children:s.name})]}),t.jsxs("div",{className:"p-4 pt-2",children:[t.jsx("p",{className:"text-sm text-gray-600 mb-2 line-clamp-2 flex-1",children:s.description}),t.jsxs("div",{className:"space-y-2",children:[t.jsxs("div",{className:"flex items-center gap-4 text-sm",children:[t.jsxs(ee,{to:`/genre/${s.genre_slug}`,onClick:g=>g.stopPropagation(),className:"flex items-center text-gray-700 hover:text-green-600 transition-colors",children:[t.jsx(ve,{className:"w-4 h-4 mr-1 flex-shrink-0"}),t.jsx("span",{className:"truncate",children:s.genre})]}),t.jsxs("div",{className:"flex items-center text-gray-700",children:[t.jsx(qt,{className:"w-4 h-4 mr-1 flex-shrink-0"}),t.jsx("span",{children:s.followers.toLocaleString()})]})]}),s.curator_name&&t.jsxs("div",{className:"flex items-center gap-2 text-sm text-gray-600",children:[t.jsx(Ft,{className:"w-4 h-4 flex-shrink-0"}),s.curator_profile_url?t.jsx("a",{href:s.curator_profile_url,target:"_blank",rel:"noopener noreferrer",onClick:g=>g.stopPropagation(),className:"truncate hover:text-green-600 transition-colors",children:s.curator_name}):t.jsx("span",{className:"truncate",children:s.curator_name})]})]})]})]}),!a&&t.jsxs("div",{className:"px-4 py-3 border-t border-gray-100 mt-auto flex items-center justify-between",children:[h?t.jsxs("div",{className:"flex items-center gap-1.5 bg-gray-100 text-gray-500 px-3 py-1.5 rounded-full text-sm",children:[t.jsx(An,{className:"w-3.5 h-3.5"}),"Submitted"]}):t.jsxs("button",{onClick:g=>{g.stopPropagation(),e(s.id)},className:"flex items-center gap-1.5 bg-green-500 text-white px-3 py-1.5 rounded-full text-sm hover:bg-green-600 transition-colors",children:[t.jsx(Dn,{className:"w-3.5 h-3.5"}),"Submit"]}),(()=>{const g=Gn(s.published_at);if(!g)return null;const v={today:{text:"Added Today",bg:"bg-gray-100",textColor:"text-gray-600"},yesterday:{text:"Added Yesterday",bg:"bg-gray-100",textColor:"text-gray-600"},"this-week":{text:"Added This Week",bg:"bg-gray-100",textColor:"text-gray-600"}}[g];return t.jsxs("div",{className:`${v.bg} ${v.textColor} px-2 py-1 rounded-full text-xs font-medium flex items-center gap-1`,children:[t.jsx(ss,{className:"w-3 h-3"}),v.text]})})()]})]})}const as=10,Ts=24*60*60*1e3;function Zt(s){return Vl(s,"track")||s}function zl(s,e){try{if(!s||!e)return{allowed:!1,remainingSubmissions:0,timeUntilReset:null,totalSubmissions:0,alreadySubmittedToPlaylist:!1};const r=JSON.parse(localStorage.getItem("trackSubmissions")||"[]"),n=Date.now(),a=Zt(s),i=r.filter(d=>n-d.timestamp<Ts);i.length<r.length&&localStorage.setItem("trackSubmissions",JSON.stringify(i));const o=i.find(d=>Zt(d.spotifyUrl)===a&&d.playlistId===e);if(o)return{allowed:!1,remainingSubmissions:0,timeUntilReset:Math.max(0,Ts-(n-o.timestamp)),totalSubmissions:i.length,alreadySubmittedToPlaylist:!0};const l=i.filter(d=>Zt(d.spotifyUrl)===a);if(l.length>=as){const d=l.reduce((u,h)=>h.timestamp<u.timestamp?h:u);return{allowed:!1,remainingSubmissions:0,timeUntilReset:Math.max(0,Ts-(n-d.timestamp)),totalSubmissions:l.length,alreadySubmittedToPlaylist:!1}}return{allowed:!0,remainingSubmissions:as-l.length,timeUntilReset:null,totalSubmissions:l.length,alreadySubmittedToPlaylist:!1}}catch(r){return console.error("Rate limit check failed:",r),{allowed:!1,remainingSubmissions:0,timeUntilReset:null,totalSubmissions:0,alreadySubmittedToPlaylist:!1}}}function Wl(s,e){if(!(!s||!e))try{const r=JSON.parse(localStorage.getItem("trackSubmissions")||"[]");r.push({timestamp:Date.now(),spotifyUrl:Zt(s),playlistId:e}),localStorage.setItem("trackSubmissions",JSON.stringify(r))}catch(r){console.error("Failed to record submission:",r)}}function Vl(s,e){if(!s)return null;try{const r=[new RegExp(`${e}/([a-zA-Z0-9]+)`),new RegExp(`${e}:([a-zA-Z0-9]+)`)];for(const n of r){const a=s.match(n);if(a&&a[1])return a[1]}return null}catch(r){return console.error("Failed to extract ID:",r),null}}const Br=/([a-zA-Z0-9._-]+@[a-zA-Z0-9._-]+\.[a-zA-Z0-9._-]+)/gi,Jl=/(?:e-?mail|email)\s*:*\s*/gi,Yl=/(?:https?:\/\/)?(?:(?:www|bit|t|tinyurl)\.[a-z]{2,}|[a-z0-9-]+(?:\.[a-z]{2,})+)(?:\/[^\s]*)?/gi,Ql=/(?:https?:\/\/|;to\/|\.com\/|\.co\/|\.ly\/|\.be\/|href=")[^\s]*/gi,Zl=/<[^>]*>|<[^>]*$/g,Xl=/&([a-z0-9]+|#[0-9]{1,6}|#x[0-9a-fA-F]{1,6});/gi,ec=/(?:@[\w-]+|#[\w-]+)/g;function tc(s){const e=document.createElement("textarea");return s.replace(Xl,(r,n)=>(e.innerHTML=r,e.value||r))}function Hn(s){let e=s,r=null;const n=s.match(Br);return n&&(r=n[0].toLowerCase(),e=e.replace(Br,"")),e=e.replace(Jl,""),e=e.replace(Yl,"").replace(Ql,""),e=e.replace(Zl,""),e=e.replace(ec,""),e=tc(e),e=e.replace(/(?:submit|send|dm|message|follow|contact)(?:\s+(?:your?|us|me|tracks?|music|demos?|here))?\s*(?:@|at|to|via|through)\s*[^\n.]*/gi,"").replace(/;[^\s;]{2,}/g,"").replace(/([!?,.]){2,}/g,"$1").replace(/\s+/g," ").replace(/\n\s*\n/g,` `).trim(),{description:e,extractedEmail:r}}const sc="5285db074532404885ad78daec8e7640",rc="4a1752bc53e241bca760677d06c5a9b2",Fr=15e3;let qr=0;function nc(s){try{if(s.startsWith("spotify:")){const r=s.split(":");return`https://open.spotify.com/${r[1]}/${r[2]}`}return`https://open.spotify.com${new URL(s).pathname}`}catch{return s}}function jt(s,e){if(!s)return null;try{const r=nc(s),n=[new RegExp(`${e}/([a-zA-Z0-9]+)`),new RegExp(`${e}:([a-zA-Z0-9]+)`)];for(const a of n){const i=r.match(a);if(i&&i[1])return i[1]}return null}catch(r){return console.error("Failed to extract ID:",r),null}}async function cr(){try{const s=localStorage.getItem("spotify_token");if(s){const a=JSON.parse(s);if(a.expires_at>Date.now())return a.access_token}const e=await fetch("https://accounts.spotify.com/api/token",{method:"POST",headers:{"Content-Type":"application/x-www-form-urlencoded",Authorization:`Basic ${btoa(`${sc}:${rc}`)}`},body:"grant_type=client_credentials"});if(!e.ok)throw new Error(`Failed to get access token: ${e.status} ${e.statusText}`);const r=await e.json(),n={access_token:r.access_token,expires_at:Date.now()+r.expires_in*1e3};return localStorage.setItem("spotify_token",JSON.stringify(n)),n.access_token}catch(s){throw console.error("Failed to get Spotify access token:",s),new Error("Failed to authenticate with Spotify")}}async function dr(s){const r=Date.now()-qr;return r<Fr&&await new Promise(n=>setTimeout(n,Fr-r)),qr=Date.now(),s()}async function ur(s){try{return await dr(async()=>{const e=await cr(),r=await fetch(`https://api.spotify.com/v1/playlists/${s}?fields=id,name,description,images,followers,owner(id,display_name,external_urls),tracks(total)`,{headers:{Authorization:`Bearer ${e}`}});if(!r.ok){if(r.status===404)return null;throw r.status===429?new Error("Rate limit exceeded. Please try again later."):new Error(`Failed to fetch playlist: ${r.status} ${r.statusText}`)}const n=await r.json(),{description:a,extractedEmail:i}=Hn(n.description||"");return{...n,description:a,curator_email:i}})}catch(e){throw console.error("Failed to fetch playlist:",e),e instanceof Error?e:new Error("Failed to fetch playlist data")}}async function ac(s){if(!s.trim())return[];try{return await dr(async()=>{var a;const e=await cr(),r=await fetch(`https://api.spotify.com/v1/search?q=${encodeURIComponent(s)}&type=track&limit=5`,{headers:{Authorization:`Bearer ${e}`}});if(!r.ok)throw r.status===429?new Error("Rate limit exceeded. Please try again later."):new Error(`Search failed: ${r.status} ${r.statusText}`);const n=await r.json();if(!((a=n.tracks)!=null&&a.items))throw new Error("Invalid response format from Spotify API");return n.tracks.items})}catch(e){throw console.error("Failed to search tracks:",e),e instanceof Error?e:new Error("Failed to search tracks")}}async function Gr(s){if(!s)return null;try{return await dr(async()=>{const e=await cr(),r=await fetch(`https://api.spotify.com/v1/tracks/${encodeURIComponent(s)}`,{headers:{Authorization:`Bearer ${e}`}});if(!r.ok){if(r.status===404)return null;throw r.status===429?new Error("Rate limit exceeded. Please try again later."):new Error(`Failed to fetch track: ${r.status} ${r.statusText}`)}const n=await r.json();if(!n.id||!n.name||!n.artists||!n.album)throw new Error("Invalid track data received from Spotify API");return n})}catch(e){throw console.error("Failed to fetch track:",e),e instanceof Error?e:new Error("Failed to fetch track data")}}function ic(s,e){const[r,n]=b.useState(s);return b.useEffect(()=>{const a=setTimeout(()=>{n(s)},e);return()=>{clearTimeout(a)}},[s,e]),r}function Kn({onTrackSelect:s,initialUrl:e,selectedTrack:r,onClearTrack:n}){var D;const[a,i]=b.useState(""),[o,l]=b.useState([]),[d,c]=b.useState(!1),[u,h]=b.useState(!1),[f,g]=b.useState(null),x=ic(a,300),v=b.useRef(null);b.useEffect(()=>{const k=N=>{v.current&&!v.current.contains(N.target)&&h(!1)};return document.addEventListener("mousedown",k),()=>document.removeEventListener("mousedown",k)},[]),b.useEffect(()=>{async function k(){if(!x.trim()){l([]);return}c(!0),g(null);try{const N=await ac(x);N.length===0&&g("No tracks found"),l(N),h(!0)}catch(N){console.error("Failed to fetch tracks:",N),g("Failed to search tracks. Please try again.")}finally{c(!1)}}k()},[x]),b.useEffect(()=>{async function k(){if(e){const N=jt(e,"track");if(N){c(!0),g(null);try{const j=await Gr(N);j?s(j):g("Track not found")}catch(j){console.error("Failed to fetch initial track:",j),g("Failed to load track. Please try again.")}finally{c(!1)}}}}k()},[e,s]);const y=async k=>{s(k),h(!1),i(""),g(null)},w=async k=>{i(k),g(null);const N=jt(k,"track");if(N){c(!0);try{const j=await Gr(N);j?y(j):g("Invalid Spotify URL or track not found")}catch(j){console.error("Failed to fetch track:",j),g("Failed to load track. Please try again.")}finally{c(!1)}}},P=k=>{k.preventDefault(),k.stopPropagation(),n(),i(""),g(null),h(!1),setTimeout(()=>{var j;const N=(j=v.current)==null?void 0:j.querySelector("input");N&&N.focus()},0)},C=k=>{k.key==="Enter"&&(k.preventDefault(),k.stopPropagation())};return r?t.jsxs("div",{className:"mt-3 p-3 bg-gray-50 rounded-lg flex items-center gap-4 group relative",children:[t.jsx("img",{src:(D=r.album.images[r.album.images.length-1])==null?void 0:D.url,alt:r.album.name,className:"w-16 h-16 object-cover rounded-md"}),t.jsxs("div",{className:"flex-1",children:[t.jsx("h3",{className:"font-medium text-gray-900",children:r.name}),t.jsx("p",{className:"text-sm text-gray-600",children:r.artists.map(k=>k.name).join(", ")}),t.jsx("p",{className:"text-xs text-gray-500",children:r.album.name})]}),t.jsx("button",{onClick:P,className:"absolute top-2 right-2 p-1 rounded-full bg-gray-200 hover:bg-gray-300 transition-colors","aria-label":"Clear selection",children:t.jsx(we,{className:"w-4 h-4 text-gray-600"})})]}):t.jsxs("div",{ref:v,className:"relative",children:[t.jsxs("div",{className:"relative",children:[t.jsx(ps,{className:"absolute left-3 top-1/2 transform -translate-y-1/2 text-gray-400 w-5 h-5"}),t.jsx("input",{type:"text",placeholder:"Search for your track or paste Spotify URL...",value:a,onChange:k=>w(k.target.value),onFocus:()=>h(!0),onKeyDown:C,className:"w-full pl-10 pr-4 py-2 border border-gray-300 rounded-lg focus:ring-2 focus:ring-green-500 focus:border-transparent"}),d&&t.jsx(me,{className:"absolute right-3 top-1/2 transform -translate-y-1/2 text-gray-400 w-5 h-5 animate-spin"})]}),f&&t.jsxs("div",{className:"mt-2 text-sm text-red-600 flex items-center gap-1",children:[t.jsx(fe,{className:"w-4 h-4"}),f]}),u&&(o.length>0||d)&&t.jsxs("div",{className:"absolute z-50 w-full mt-1 bg-white rounded-lg shadow-lg border border-gray-200 max-h-80 overflow-y-auto",children:[o.map(k=>{var N;return t.jsxs("button",{onClick:j=>{j.preventDefault(),y(k)},className:"w-full p-3 hover:bg-gray-50 flex items-center gap-3 border-b border-gray-100 last:border-0",children:[t.jsx("img",{src:(N=k.album.images[k.album.images.length-1])==null?void 0:N.url,alt:k.album.name,className:"w-10 h-10 object-cover rounded"}),t.jsxs("div",{className:"flex-1 text-left",children:[t.jsx("p",{className:"font-medium text-gray-900 line-clamp-1",children:k.name}),t.jsx("p",{className:"text-sm text-gray-500 line-clamp-1",children:k.artists.map(j=>j.name).join(", ")})]})]},k.id)}),d&&t.jsxs("div",{className:"p-4 text-center text-gray-500",children:[t.jsx(me,{className:"w-6 h-6 animate-spin mx-auto"}),t.jsx("p",{className:"mt-2",children:"Searching tracks..."})]})]})]})}const Xt={async submit(s){const{data:e,error:r}=await W.from("submissions").insert({playlist_id:s.playlistId,track_id:s.trackId,track_name:s.trackName,track_url:s.trackUrl,artist_name:s.artistName,email:s.email,message:s.message,status:"pending",created_at:new Date().toISOString(),updated_at:new Date().toISOString()}).select(` *, playlist:playlists ( name ) `).single();if(r)throw console.error("Failed to create submission:",r),r;return e},async getAll(){const{data:s,error:e}=await W.from("submission_details").select("*").order("created_at",{ascending:!1});if(e)throw console.error("Failed to fetch submissions:",e),e;return s.map(r=>({...r,playlist:{name:r.playlist_name}}))},async getHistory(s){const{data:e,error:r}=await W.from("submission_details").select("*").eq("email",s).order("created_at",{ascending:!1});if(r)throw console.error("Failed to fetch submission history:",r),r;return e.map(n=>({...n,playlist:{name:n.playlist_name}}))},async getForPlaylist(s){const{data:e,error:r}=await W.from("submission_details").select("*").eq("playlist_id",s).order("created_at",{ascending:!1});if(r)throw console.error("Failed to fetch playlist submissions:",r),r;return e.map(n=>({...n,playlist:{name:n.playlist_name}}))},async updateStatus(s,e){const{data:r,error:n}=await W.from("submissions").update({status:e,reviewed_at:e==="pending"?null:new Date().toISOString(),updated_at:new Date().toISOString()}).eq("id",s).select(` *, playlist:playlists ( name ) `).single();if(n)throw console.error("Failed to update submission status:",n),n;return r}};function St({playlist:s,onClose:e,onSubmit:r}){const[n,a]=b.useState(()=>{var P;const w=vt();return{spotifyUrl:((P=w==null?void 0:w.lastTrack)==null?void 0:P.external_urls.spotify)||"",artistName:(w==null?void 0:w.artistName)||"",email:(w==null?void 0:w.email)||"",message:""}}),[i,o]=b.useState(()=>{const w=vt();return(w==null?void 0:w.lastTrack)||null}),[l,d]=b.useState({}),[c,u]=b.useState({allowed:!0,remainingSubmissions:as,timeUntilReset:null,totalSubmissions:0,alreadySubmittedToPlaylist:!1}),[h,f]=b.useState("");b.useEffect(()=>{const w=C=>{const D=document.querySelector(".modal-content");D&&!D.contains(C.target)&&e()},P=C=>{C.key==="Escape"&&e()};return document.addEventListener("mousedown",w),document.addEventListener("keydown",P),()=>{document.removeEventListener("mousedown",w),document.removeEventListener("keydown",P)}},[e]),b.useEffect(()=>{if(n.spotifyUrl){const w=zl(n.spotifyUrl,s.id);u(w)}},[n.spotifyUrl,s.id]),b.useEffect(()=>{let w;const P=()=>{if(c.timeUntilReset){const C=Math.floor(c.timeUntilReset/36e5),D=Math.floor(c.timeUntilReset%(1e3*60*60)/(1e3*60)),k=Math.floor(c.timeUntilReset%(1e3*60)/1e3);f(`${C}h ${D}m ${k}s`)}};return c.timeUntilReset&&(P(),w=setInterval(()=>{const C=c.timeUntilReset-1e3;C<=0?(clearInterval(w),u(D=>({...D,timeUntilReset:null,allowed:!0}))):(u(D=>({...D,timeUntilReset:C})),P())},1e3)),()=>{w&&clearInterval(w)}},[c.timeUntilReset]);const g=()=>{const w={};return i||(w.spotifyUrl="Please select a track"),n.artistName.trim()||(w.artistName="Artist name is required"),/^[^\s@]+@[^\s@]+\.[^\s@]+$/.test(n.email)||(w.email="Please enter a valid email address"),d(w),Object.keys(w).length===0},x=async w=>{if(w.preventDefault(),!(!c.allowed||c.alreadySubmittedToPlaylist)&&g())try{const P=jt(n.spotifyUrl,"track");if(!P||!i)throw new Error("Invalid track selection");await Xt.submit({playlistId:s.id,trackId:P,trackName:i.name,trackUrl:n.spotifyUrl,artistName:n.artistName,email:n.email,message:n.message}),Mn({artistName:n.artistName,email:n.email,track:i}),Wl(n.spotifyUrl,s.id),ql(s.id,n.spotifyUrl),r(n)}catch(P){console.error("Failed to submit track:",P),d(C=>({...C,submit:"Failed to submit track. Please try again."}))}},v=w=>{o(w),a(P=>{var C;return{...P,spotifyUrl:w.external_urls.spotify,artistName:((C=w.artists[0])==null?void 0:C.name)||P.artistName}}),d(P=>({...P,spotifyUrl:void 0}))},y=()=>{o(null),a(w=>({...w,spotifyUrl:"",artistName:w.artistName})),d(w=>({...w,spotifyUrl:void 0}))};return t.jsx("div",{className:"fixed inset-0 bg-black bg-opacity-50 flex items-center justify-center p-4 z-50",children:t.jsxs("div",{className:"modal-content bg-white rounded-xl max-w-lg w-full max-h-[90vh] overflow-y-auto",children:[t.jsxs("div",{className:"p-6 border-b border-gray-200",children:[t.jsxs("div",{className:"flex justify-between items-center",children:[t.jsx("h2",{className:"text-xl font-bold text-gray-900",children:"Submit Your Track"}),t.jsx("button",{onClick:e,className:"text-gray-400 hover:text-gray-500 transition-colors",children:t.jsx(we,{className:"w-6 h-6"})})]}),t.jsxs("p",{className:"mt-2 text-gray-600",children:["Submitting to: ",s.name]}),i&&t.jsx("div",{className:"mt-3 flex flex-col gap-2 text-sm",children:t.jsx("div",{className:`px-3 py-2 rounded-lg ${c.alreadySubmittedToPlaylist?"bg-yellow-100 text-yellow-800":c.allowed?"bg-green-100 text-green-800":"bg-red-100 text-red-800"}`,children:c.alreadySubmittedToPlaylist?t.jsxs("div",{className:"flex items-center gap-1",children:[t.jsx(fe,{className:"w-4 h-4"}),"Already submitted to this playlist"]}):c.allowed?t.jsxs("span",{children:[c.remainingSubmissions,"/",as," Submissions Remaining Today"]}):t.jsxs(t.Fragment,{children:[t.jsxs("div",{className:"flex items-center gap-1",children:[t.jsx(fe,{className:"w-4 h-4"}),"Each track can be submitted to up to 10 playlists per day."]}),h&&t.jsxs("div",{className:"text-sm mt-1",children:["(Resets in ",h,")"]})]})})})]}),t.jsxs("form",{onSubmit:x,className:"p-6 space-y-4",children:[t.jsxs("div",{children:[t.jsxs("label",{className:"flex gap-2 text-sm font-medium text-gray-700 mb-1",children:[t.jsx(Hs,{className:"w-4 h-4"}),"Search and Select Your Track"]}),t.jsx(Kn,{onTrackSelect:v,selectedTrack:i,onClearTrack:y}),l.spotifyUrl&&t.jsx("p",{className:"mt-1 text-sm text-red-600",children:l.spotifyUrl})]}),t.jsxs("div",{children:[t.jsxs("label",{className:"flex gap-2 text-sm font-medium text-gray-700 mb-1",children:[t.jsx(Ft,{className:"w-4 h-4"}),"Artist Name"]}),t.jsx("input",{type:"text",placeholder:"Your artist name",value:n.artistName,onChange:w=>a(P=>({...P,artistName:w.target.value})),className:"w-full p-2 border border-gray-300 rounded-lg focus:ring-2 focus:ring-green-500 focus:border-transparent",disabled:!c.allowed||c.alreadySubmittedToPlaylist}),l.artistName&&t.jsx("p",{className:"mt-1 text-sm text-red-600",children:l.artistName})]}),t.jsxs("div",{children:[t.jsxs("label",{className:"flex gap-2 text-sm font-medium text-gray-700 mb-1",children:[t.jsx(Ln,{className:"w-4 h-4"}),"Email"]}),t.jsx("input",{type:"email",placeholder:"your@email.com",value:n.email,onChange:w=>a(P=>({...P,email:w.target.value})),className:"w-full p-2 border border-gray-300 rounded-lg focus:ring-2 focus:ring-green-500 focus:border-transparent",disabled:!c.allowed||c.alreadySubmittedToPlaylist}),l.email&&t.jsx("p",{className:"mt-1 text-sm text-red-600",children:l.email})]}),t.jsxs("div",{children:[t.jsxs("label",{className:"flex gap-2 text-sm font-medium text-gray-700 mb-1",children:[t.jsx(Rn,{className:"w-4 h-4"}),"Message (Optional)"]}),t.jsx("textarea",{placeholder:"Tell the curator about your track...",value:n.message,onChange:w=>a(P=>({...P,message:w.target.value})),rows:4,className:"w-full p-2 border border-gray-300 rounded-lg focus:ring-2 focus:ring-green-500 focus:border-transparent",disabled:!c.allowed||c.alreadySubmittedToPlaylist})]}),l.submit&&t.jsxs("div",{className:"flex items-center gap-2 text-red-600 text-sm",children:[t.jsx(fe,{className:"w-4 h-4"}),t.jsx("p",{children:l.submit})]}),t.jsxs("div",{className:"flex justify-end gap-3 pt-4",children:[t.jsx("button",{type:"button",onClick:e,className:"px-4 py-2 text-gray-700 hover:bg-gray-100 rounded-lg transition-colors",children:"Cancel"}),t.jsxs("button",{type:"submit",disabled:!c.allowed||c.alreadySubmittedToPlaylist,className:`px-4 py-2 rounded-lg flex items-center gap-2 transition-colors ${!c.allowed||c.alreadySubmittedToPlaylist?"bg-gray-300 text-gray-500 cursor-not-allowed":"bg-green-500 text-white hover:bg-green-600"}`,children:[t.jsx(ve,{className:"w-4 h-4"}),"Submit Track"]})]})]})]})})}const oc=Object.freeze(Object.defineProperty({__proto__:null,SubmissionModal:St},Symbol.toStringTag,{value:"Module"}));function lc({message:s,type:e,onClose:r}){const[n,a]=b.useState(!1);b.useEffect(()=>{const l=setTimeout(()=>{a(!0)},4700);return()=>clearTimeout(l)},[]),b.useEffect(()=>{if(n){const l=setTimeout(()=>{r()},300);return()=>clearTimeout(l)}},[n,r]);const i={success:"bg-green-500",error:"bg-red-500",info:"bg-blue-500"}[e],o={success:Gs,error:fe,info:fe}[e];return t.jsxs("div",{className:` fixed bottom-4 right-4 ${i} text-white px-4 py-3 rounded-lg shadow-lg flex items-center gap-3 max-w-md transition-all duration-300 ${n?"opacity-0 translate-y-2":"opacity-100 translate-y-0"} `,children:[t.jsx(o,{className:"w-5 h-5 flex-shrink-0"}),t.jsx("p",{className:"flex-1",children:s}),t.jsx("button",{onClick:()=>a(!0),className:"p-1 hover:bg-white/20 rounded-full transition-colors",children:t.jsx(we,{className:"w-4 h-4"})})]})}function qe(s){const[e]=b.useState(()=>{let r=document.getElementById("toast-container");return r||(r=document.createElement("div"),r.id="toast-container",document.body.appendChild(r)),r});return Vr.createPortal(t.jsx(lc,{...s}),e)}function cc({playlist:s,baseUrl:e}){var n;const r={"@context":"https://schema.org","@type":"MusicPlaylist",name:s.name,description:`Get your music featured on ${s.name}, a Spotify playlist curated by ${s.curator_name} with ${s.followers.toLocaleString()} followers. No account needed! Access thousands of playlists and connect with curators on PlaylistPartner.com.`,numTracks:s.track_count,url:`${e}/playlist/${s.spotify_id}`,sameAs:[`https://open.spotify.com/playlist/${s.spotify_id}`],dateModified:s.updated_at,image:s.image_url,author:{"@type":"Person",name:s.curator_name,url:s.curator_profile_url},genre:[s.genre,...((n=s.sub_genres)==null?void 0:n.slice(0,2))||[]].filter(Boolean),interactionStatistic:{"@type":"InteractionCounter",interactionType:"https://schema.org/FollowAction",userInteractionCount:s.followers},isPartOf:{"@id":e}};return t.jsx("script",{type:"application/ld+json",children:JSON.stringify(r)})}function dc(){var k;const{slug:s}=os(),e=Xe(),r=it(),[n,a]=b.useState(!1),[i,o]=b.useState(null),[l,d]=b.useState(0),{playlist:c,loading:u,error:h,relatedPlaylists:f,isNotFound:g}=Fl(s||""),[x,v]=b.useState(!1);b.useEffect(()=>{v(!1)},[s]),b.useEffect(()=>{!u&&c&&!h&&!g&&typeof window<"u"&&window.prerenderReady!==void 0&&(window.prerenderReady=!0)},[u,c,h,g]),b.useEffect(()=>{async function N(){if(c!=null&&c.genre){const{count:j}=await W.from("playlist_details").select("*",{count:"exact",head:!0}).eq("genre",c.genre);d(j||0)}}c&&N()},[c]);const y=vt(),w=c&&(y==null?void 0:y.lastTrack)&&Fn(c.id,y.lastTrack.external_urls.spotify),P=()=>{var j;const N=(j=r.state)==null?void 0:j.from;e(N==="genre"?-1:"/")},C=async N=>{try{a(!1),o({type:"success",message:`Track submitted to ${c==null?void 0:c.name}! Watch your inbox for feedback from the curator.`})}catch(j){console.error("Failed to submit track:",j),o({type:"error",message:"Failed to submit track. Please try again."})}};if(u)return t.jsx("div",{className:"container mx-auto px-4 py-8",children:t.jsxs("div",{className:"animate-pulse",children:[t.jsx("div",{className:"h-8 w-48 bg-gray-200 rounded mb-6"}),t.jsx("div",{className:"bg-white shadow-lg",children:t.jsxs("div",{className:"grid md:grid-cols-2",children:[t.jsx("div",{className:"aspect-square bg-gray-200"}),t.jsxs("div",{className:"p-6",children:[t.jsx("div",{className:"h-8 w-3/4 bg-gray-200 rounded mb-4"}),t.jsx("div",{className:"h-4 w-1/2 bg-gray-200 rounded mb-4"}),t.jsx("div",{className:"h-20 bg-gray-200 rounded mb-4"})]})]})})]})});if(g||!c)return t.jsx("div",{className:"container mx-auto px-4 py-8",children:t.jsxs("div",{className:"text-center",children:[t.jsxs("div",{className:"flex items-center justify-center gap-2 text-red-600 mb-4",children:[t.jsx(fe,{className:"w-6 h-6"}),t.jsx("h2",{className:"text-2xl font-bold",children:"Playlist Not Found"})]}),t.jsx("p",{className:"text-gray-600 mb-6",children:"The playlist you're looking for doesn't exist or may have been removed."}),t.jsxs("button",{onClick:P,className:"text-green-600 hover:text-green-700 flex items-center gap-2 mx-auto",children:[t.jsx(We,{className:"w-4 h-4"}),"Back to Playlists"]})]})});if(h)return t.jsx("div",{className:"container mx-auto px-4 py-8",children:t.jsxs("div",{className:"text-center",children:[t.jsxs("div",{className:"flex items-center justify-center gap-2 text-red-600 mb-4",children:[t.jsx(fe,{className:"w-6 h-6"}),t.jsx("h2",{className:"text-2xl font-bold",children:"Error Loading Playlist"})]}),t.jsx("p",{className:"text-gray-600 mb-6",children:h.message||"Something went wrong. Please try again."}),t.jsxs("button",{onClick:P,className:"text-green-600 hover:text-green-700 flex items-center gap-2 mx-auto",children:[t.jsx(We,{className:"w-4 h-4"}),"Back to Playlists"]})]})});const D=`Get your music featured on ${c.name}, a Spotify playlist curated by ${c.curator_name||"Independent Curator"}. No account needed! Access ${l} ${c.genre} playlists and connect with curators on PlaylistPartner.com.`;return t.jsxs(t.Fragment,{children:[t.jsx(Fe,{title:c==null?void 0:c.name,description:D,image:c==null?void 0:c.image_url,playlist:c?{name:c.name,curator_name:c.curator_name,followers:c.followers,updated_at:c.updated_at,genre:c.genre,genre_count:l}:void 0}),c&&t.jsx(cc,{playlist:c,baseUrl:window.location.origin}),t.jsxs("main",{className:"container mx-auto px-4 py-8",children:[t.jsxs("button",{onClick:P,className:"inline-flex items-center gap-2 text-green-600 hover:text-green-700 mb-6",children:[t.jsx(We,{className:"w-4 h-4"}),"Back to Playlists"]}),t.jsx("div",{className:"bg-white shadow-lg",children:t.jsxs("div",{className:"grid md:grid-cols-2",children:[t.jsx("div",{className:"relative aspect-square bg-gray-100",children:!c.image_url||x?t.jsx("div",{className:"absolute inset-0 flex items-center justify-center bg-gradient-to-br from-gray-100 to-gray-200",children:t.jsxs("div",{className:"text-center",children:[t.jsx(On,{className:"w-16 h-16 text-gray-400 mx-auto mb-3"}),t.jsx("div",{className:"text-base text-gray-500 font-medium px-4 truncate max-w-[300px]",children:c.name})]})}):t.jsx("img",{src:c.image_url,alt:c.name,className:"w-full h-full object-cover",onError:()=>v(!0)})}),t.jsxs("div",{className:"p-6 flex flex-col justify-between",children:[t.jsxs("div",{children:[t.jsxs("div",{className:"flex items-start justify-between gap-4 mb-2",children:[t.jsx("h1",{className:"text-3xl md:text-4xl font-bold",children:c.name}),t.jsxs("div",{className:"flex gap-2 flex-shrink-0",children:[c.featured&&t.jsxs("div",{className:"bg-yellow-400 text-yellow-900 px-3 py-1.5 rounded-full text-sm font-medium flex items-center gap-1.5",children:[t.jsx(ar,{className:"w-4 h-4"}),"Featured"]}),(()=>{const N=Gn(c.published_at);if(!N)return null;const m={today:{text:"Added Today",bg:"bg-green-500",textColor:"text-white"},yesterday:{text:"Added Yesterday",bg:"bg-blue-500",textColor:"text-white"},"this-week":{text:"Added This Week",bg:"bg-purple-500",textColor:"text-white"}}[N];return t.jsxs("div",{className:`${m.bg} ${m.textColor} px-3 py-1.5 rounded-full text-sm font-medium flex items-center gap-1.5`,children:[t.jsx(ss,{className:"w-4 h-4"}),m.text]})})()]})]}),t.jsxs("div",{className:"flex items-center gap-2 text-gray-600 mb-4",children:[t.jsx(Ft,{className:"w-5 h-5"}),t.jsx("span",{className:"text-lg",children:"Curated by "}),c.curator_profile_url?t.jsx("a",{href:c.curator_profile_url,target:"_blank",rel:"noopener noreferrer",className:"text-lg hover:text-green-600 transition-colors",children:c.curator_name}):t.jsx("span",{className:"text-lg",children:c.curator_name||"Independent Curator"})]}),t.jsx("p",{className:"text-gray-600 text-lg mb-4",children:c.description}),t.jsxs("div",{className:"flex flex-wrap gap-6 mb-4",children:[t.jsxs(ee,{to:`/genre/${c.genre_slug}`,className:"flex items-center text-gray-700 hover:text-green-600 transition-colors",children:[t.jsx(ve,{className:"w-5 h-5 mr-2"}),t.jsx("span",{className:"text-lg",children:c.genre})]}),t.jsxs("div",{className:"flex items-center text-gray-700",children:[t.jsx(qt,{className:"w-5 h-5 mr-2"}),t.jsxs("span",{className:"text-lg",children:[c.followers.toLocaleString()," followers"]})]})]}),((k=c.sub_genres)==null?void 0:k.length)>0&&t.jsx("div",{className:"flex flex-wrap gap-2 mb-6",children:c.sub_genres.map(N=>t.jsx(ee,{to:`/genre/${c.genre_slug}/${N.toLowerCase().replace(/\s+/g,"-")}`,className:"px-3 py-1 bg-gray-100 text-gray-700 rounded-full text-sm hover:bg-gray-200 transition-colors",children:N},N))})]}),w?t.jsxs("div",{className:"w-full sm:w-auto flex items-center justify-center gap-2 bg-gray-100 text-gray-500 px-6 py-3 font-medium",children:[t.jsx(An,{className:"w-5 h-5"}),"Track Submitted"]}):t.jsxs("button",{onClick:()=>a(!0),className:"w-full sm:w-auto flex items-center justify-center gap-2 bg-green-500 text-white px-6 py-3 hover:bg-green-600 transition-colors text-lg font-medium",children:[t.jsx(Dn,{className:"w-5 h-5"}),"Submit Your Track"]})]})]})}),f.length>0&&t.jsxs("div",{className:"mt-12",children:[t.jsx("h2",{className:"text-2xl font-bold mb-6",children:"Related Playlists"}),t.jsx("div",{className:"grid grid-cols-1 md:grid-cols-2 lg:grid-cols-3 xl:grid-cols-4 gap-6",children:f.map(N=>t.jsx(lr,{playlist:N,onSubmit:()=>a(!0),isRelated:!0,hideSubmit:!0},N.id))})]}),n&&c&&t.jsx(St,{playlist:c,onClose:()=>a(!1),onSubmit:C}),i&&t.jsx(qe,{message:i.message,type:i.type,onClose:()=>o(null)})]})]})}function uc({filters:s,onFilterChange:e,hideGenreFilter:r}){const{genres:n,loading:a}=Be(),i=n.find(o=>o.name===s.genre);return t.jsx("div",{className:"bg-white shadow-sm -mx-4 px-4",children:t.jsx("div",{className:"max-w-[1400px] mx-auto",children:t.jsxs("div",{className:`grid ${r?"grid-cols-2":"grid-cols-1 md:grid-cols-2 lg:grid-cols-4"} gap-4 py-4`,children:[t.jsxs("div",{className:"relative",children:[t.jsx(ps,{className:"absolute left-3 top-1/2 transform -translate-y-1/2 text-gray-400 w-5 h-5"}),t.jsx("input",{type:"text",placeholder:"Search playlists...",value:s.search,onChange:o=>e({...s,search:o.target.value}),className:"w-full pl-10 pr-4 py-2 border border-gray-300 rounded-lg focus:ring-2 focus:ring-green-500 focus:border-transparent"})]}),!r&&t.jsxs("div",{className:"relative",children:[t.jsx(ve,{className:"absolute left-3 top-1/2 transform -translate-y-1/2 text-gray-400 w-5 h-5"}),t.jsxs("select",{value:s.genre,onChange:o=>e({...s,genre:o.target.value,subGenre:""}),className:"w-full pl-10 pr-4 py-2 border border-gray-300 rounded-lg appearance-none focus:ring-2 focus:ring-green-500 focus:border-transparent disabled:bg-gray-50 disabled:text-gray-500",disabled:a,children:[t.jsx("option",{value:"",children:"All Genres"}),n.map(o=>t.jsx("option",{value:o.name,children:o.name},o.id))]})]}),t.jsx("div",{className:"relative",children:t.jsxs("select",{value:s.subGenre||"",onChange:o=>e({...s,subGenre:o.target.value}),className:`w-full px-4 py-2 border border-gray-300 rounded-lg appearance-none transition-colors ${i?"focus:ring-2 focus:ring-green-500 focus:border-transparent":"bg-gray-50 text-gray-400 cursor-not-allowed"}`,disabled:!i,children:[t.jsx("option",{value:"",children:i?"All Sub-genres":"-- Select a genre first --"}),i==null?void 0:i.subGenres.map(o=>t.jsx("option",{value:o.name,children:o.name},o.id))]})}),t.jsx("div",{className:"relative",children:t.jsxs("select",{value:s.sortBy,onChange:o=>e({...s,sortBy:o.target.value}),className:"w-full px-4 py-2 border border-gray-300 rounded-lg appearance-none focus:ring-2 focus:ring-green-500 focus:border-transparent",children:[t.jsx("option",{value:"default",children:"Default (Most Recent)"}),t.jsx("option",{value:"followers-high",children:"Most Followers"}),t.jsx("option",{value:"followers-low",children:"Least Followers"})]})})]})})})}const At="playlist_state";function Gt(s){const[e,r]=b.useState(()=>{try{const v=sessionStorage.getItem(At);if(v){const y=JSON.parse(v);if(JSON.stringify(y.filters)===JSON.stringify(s))return y.playlists}return[]}catch{return[]}}),[n,a]=b.useState(!0),[i,o]=b.useState(null),[l,d]=b.useState(!0),[c,u]=b.useState(()=>{try{const v=sessionStorage.getItem(At);if(v){const y=JSON.parse(v);if(JSON.stringify(y.filters)===JSON.stringify(s))return y.currentPage}return 1}catch{return 1}}),[h,f]=b.useState(0),g=12;return b.useEffect(()=>{!n&&h>0&&typeof window<"u"&&window.prerenderReady!==void 0&&(window.prerenderReady=!0)},[n,h]),b.useEffect(()=>{(()=>{const y=sessionStorage.getItem(At);if(y){const w=JSON.parse(y);return JSON.stringify(w.filters)!==JSON.stringify(s)}return!0})()&&(r([]),u(1),d(!0),sessionStorage.removeItem(At))},[s==null?void 0:s.genre,s==null?void 0:s.subGenre,s==null?void 0:s.search,s==null?void 0:s.sortBy]),b.useEffect(()=>{if(e.length>0){const v={playlists:e,currentPage:c,filters:s||{}};sessionStorage.setItem(At,JSON.stringify(v))}},[e,c,s]),b.useEffect(()=>{async function v(){try{a(!0),o(null);let y=W.from("playlist_details").select("*",{count:"exact"});if(s!=null&&s.genre&&(y=y.eq("genre",s.genre)),s!=null&&s.subGenre&&(y=y.contains("sub_genres",[s.subGenre])),s!=null&&s.search){const k=`%${s.search}%`;y=y.or(`name.ilike.${k},description.ilike.${k}`)}switch(s==null?void 0:s.sortBy){case"followers-high":y=y.order("followers",{ascending:!1});break;case"followers-low":y=y.order("followers",{ascending:!0});break;default:if(!(s!=null&&s.genre)&&!(s!=null&&s.subGenre)){let k=W.from("playlist_details").select("*").eq("featured",!0).order("created_at",{ascending:!1}).limit(4);if(s!=null&&s.search){const T=`%${s.search}%`;k=k.or(`name.ilike.${T},description.ilike.${T}`)}const{data:N}=await k,j=(c-1)*g;let m=W.from("playlist_details").select("*",{count:"exact"}).eq("featured",!1).order("created_at",{ascending:!1});if(s!=null&&s.search){const T=`%${s.search}%`;m=m.or(`name.ilike.${T},description.ilike.${T}`)}const{data:p,count:_}=await m.range(j,j+g-1);if(c===1){const T=[...N||[],...p||[]];r(T)}else r(T=>{const I=new Set(T.map(H=>H.id)),L=(p||[]).filter(H=>!I.has(H.id));return[...T,...L]});f((_||0)+((N==null?void 0:N.length)||0)),d(j+g<(_||0)),a(!1);return}else{let k=W.from("playlist_details").select("*").eq("featured",!0).eq("genre",s.genre).order("created_at",{ascending:!1}).limit(4);if(s!=null&&s.subGenre&&(k=k.contains("sub_genres",[s.subGenre])),s!=null&&s.search){const T=`%${s.search}%`;k=k.or(`name.ilike.${T},description.ilike.${T}`)}const{data:N}=await k,j=(c-1)*g;let m=W.from("playlist_details").select("*",{count:"exact"}).eq("featured",!1).eq("genre",s.genre).order("created_at",{ascending:!1});if(s!=null&&s.subGenre&&(m=m.contains("sub_genres",[s.subGenre])),s!=null&&s.search){const T=`%${s.search}%`;m=m.or(`name.ilike.${T},description.ilike.${T}`)}const{data:p,count:_}=await m.range(j,j+g-1);if(c===1){const T=[...N||[],...p||[]];r(T)}else r(T=>{const I=new Set(T.map(H=>H.id)),L=(p||[]).filter(H=>!I.has(H.id));return[...T,...L]});f((_||0)+((N==null?void 0:N.length)||0)),d(j+g<(_||0)),a(!1);return}}const w=(c-1)*g;y=y.range(w,w+g-1);const{data:P,error:C,count:D}=await y;if(C)throw C;f(D||0),r(k=>{const N=P||[];if(c===1)return N;const j=new Set(k.map(p=>p.id)),m=N.filter(p=>!j.has(p.id));return[...k,...m]}),d(w+g<(D||0))}catch(y){console.error("Failed to fetch playlists:",y),o(y instanceof Error?y:new Error("Failed to fetch playlists"))}finally{a(!1)}}v()},[c,s==null?void 0:s.genre,s==null?void 0:s.subGenre,s==null?void 0:s.search,s==null?void 0:s.sortBy]),{playlists:e,loading:n,error:i,hasMore:l,loadMore:()=>{!n&&l&&u(v=>v+1)},currentPage:c,totalCount:h,itemsPerPage:g}}function hc(){var N,j;const s=it(),[e,r]=Jr(),[n,a]=b.useState(()=>{var _;const m=(_=s.state)==null?void 0:_.filters,p=sessionStorage.getItem("playlist_filters");return p&&!(m!=null&&m.fromSubmission)?JSON.parse(p):m?(window.history.replaceState({},""),{search:"",genre:m.genre||"",subGenre:m.subGenre||"",sortBy:"default"}):{search:"",genre:"",subGenre:"",sortBy:"default"}});b.useEffect(()=>{window.scrollTo(0,0)},[]);const{playlists:i,loading:o,error:l,hasMore:d,loadMore:c,currentPage:u,totalCount:h,itemsPerPage:f}=Gt({...n,genre:n.genre||void 0,subGenre:n.subGenre||void 0}),[g,x]=b.useState(null),[v,y]=b.useState(null),w=vt(),[P,C]=b.useState(!0);b.useEffect(()=>{var m;if(!o&&i.length>0&&P){const p=(m=s.state)==null?void 0:m.filters;p!=null&&p.fromSubmission?window.scrollTo(0,0):qn.restorePosition(s.pathname,r),C(!1)}},[o,i.length,s.pathname,s.state,r,P]),b.useEffect(()=>{sessionStorage.setItem("playlist_filters",JSON.stringify(n))},[n]);const D=(u-1)*f+1,k=Math.min(u*f,h);return t.jsxs(t.Fragment,{children:[t.jsx(Fe,{}),t.jsxs("main",{children:[t.jsxs("div",{className:"container mx-auto px-4 pb-12",children:[t.jsx(uc,{filters:n,onFilterChange:a}),(w==null?void 0:w.lastTrack)&&t.jsxs("div",{className:"mb-6 flex items-center justify-between bg-white p-4 shadow-sm rounded-lg max-w-[1400px] mx-auto",children:[t.jsxs("div",{className:"flex items-center gap-4",children:[t.jsx("img",{src:(N=w.lastTrack.album.images[2])==null?void 0:N.url,alt:w.lastTrack.name,className:"w-12 h-12 object-cover rounded-md"}),t.jsxs("div",{children:[t.jsx("p",{className:"font-medium",children:w.lastTrack.name}),t.jsx("p",{className:"text-sm text-gray-600",children:(j=w.lastTrack.artists[0])==null?void 0:j.name})]})]}),t.jsx("button",{onClick:()=>{Bn(),window.location.reload()},className:"p-2 hover:bg-gray-100 rounded-full transition-colors",title:"Clear selected track",children:t.jsx(we,{className:"w-5 h-5 text-gray-500"})})]}),t.jsxs("div",{className:"max-w-[1400px] mx-auto",style:{minHeight:"800px"},children:[i.length>0&&t.jsxs("div",{className:"text-sm text-gray-600 mb-6 mt-6",children:["Showing ",D,"-",k," of ",h," playlists"]}),t.jsx("div",{className:"grid grid-cols-1 sm:grid-cols-2 lg:grid-cols-3 xl:grid-cols-4 gap-4",children:i.map((m,p)=>t.jsx(lr,{playlist:m,onSubmit:_=>x(i.find(T=>T.id===_)||null),priority:p<4},`${m.id}-${p}`))}),o&&t.jsx("div",{className:"flex items-center justify-center py-12",children:t.jsx(me,{className:"w-8 h-8 text-green-500 animate-spin"})}),l&&t.jsx("div",{className:"text-center py-12",children:t.jsx("p",{className:"text-red-500",children:"Failed to load playlists. Please try again."})}),!o&&!l&&i.length===0&&t.jsx("div",{className:"text-center py-12",children:t.jsx("p",{className:"text-gray-500 text-lg",children:"No playlists found matching your criteria."})}),d&&!o&&t.jsx("div",{className:"text-center mt-8",children:t.jsx("button",{onClick:c,className:"px-6 py-3 bg-green-500 text-white rounded-lg hover:bg-green-600 transition-colors",children:"Load More Playlists"})})]})]}),g&&t.jsx(St,{playlist:g,onClose:()=>x(null),onSubmit:()=>{x(null),y({type:"success",message:`Track submitted to ${g.name}! Watch your inbox for feedback from the curator.`})}}),v&&t.jsx(qe,{message:v.message,type:v.type,onClose:()=>y(null)})]})]})}function fc(){const s=Xe(),[e,r]=b.useState(null);b.useEffect(()=>{typeof window<"u"&&window.prerenderReady!==void 0&&(window.prerenderReady=!0)},[]);const n=a=>{var i;Mn({artistName:((i=a.artists[0])==null?void 0:i.name)||"",email:"",track:a}),s("/submit/genre",{state:{selectedTrack:a}})};return t.jsxs("div",{className:"container mx-auto px-4 py-8 max-w-2xl",children:[t.jsxs("button",{onClick:()=>s("/playlists"),className:"flex items-center gap-2 text-gray-600 hover:text-gray-800 transition-colors mb-6",children:[t.jsx(We,{className:"w-5 h-5"}),"Back to Playlists"]}),t.jsxs("div",{className:"space-y-6",children:[t.jsxs("div",{className:"text-center",children:[t.jsx("h1",{className:"text-3xl font-bold mb-2",children:"Submit Your Track"}),t.jsx("p",{className:"text-gray-600",children:"Search for your track on Spotify to get started"})]}),t.jsx("div",{className:"bg-white p-6 rounded-xl shadow-lg",children:t.jsx(Kn,{onTrackSelect:n,selectedTrack:e,onClearTrack:()=>r(null)})}),e&&t.jsxs("button",{onClick:()=>n(e),className:"w-full flex items-center justify-center gap-2 bg-green-500 text-white p-4 rounded-lg hover:bg-green-600 transition-colors",children:["Continue to Genre Selection",t.jsx(Ut,{className:"w-5 h-5"})]})]})]})}function mc(){const s=Xe(),{genres:e}=Be(),[r,n]=b.useState(""),[a,i]=b.useState(""),o=e.find(u=>u.id===r),l=(o==null?void 0:o.subGenres)||[],d=u=>{i(u)},c=u=>{if(!r||!o)return;const h=a?l.find(f=>f.id===a):null;window.scrollTo(0,0),s("/playlists",{state:{filters:{genre:o.name,subGenre:(h==null?void 0:h.name)||"",fromSubmission:!0}},replace:!0})};return t.jsx("div",{className:"container mx-auto px-4 py-8 max-w-4xl",children:t.jsxs("div",{className:"space-y-8",children:[t.jsxs("div",{className:"text-center",children:[t.jsx("h1",{className:"text-3xl font-bold mb-2",children:"Select Your Genre"}),t.jsx("p",{className:"text-gray-600",children:"Choose the main category that best fits your track"})]}),t.jsxs("div",{children:[t.jsx("h2",{className:"text-lg font-medium mb-3",children:"Main Genre"}),t.jsx("div",{className:"grid grid-cols-2 sm:grid-cols-3 md:grid-cols-4 gap-3",children:e.map(u=>t.jsxs("button",{onClick:()=>{n(u.id),i("")},className:`p-4 text-center border-2 rounded-lg transition-colors ${r===u.id?"border-green-500 bg-green-50":"border-gray-200 hover:border-green-500 hover:bg-green-50"}`,children:[t.jsx(ve,{className:"w-6 h-6 mx-auto mb-2 text-gray-600"}),t.jsx("span",{className:"font-medium",children:u.name})]},u.id))})]}),r&&l.length>0&&t.jsxs("div",{children:[t.jsx("h2",{className:"text-lg font-medium mb-3",children:"Sub-genre (Optional)"}),t.jsx("div",{className:"grid grid-cols-2 sm:grid-cols-3 md:grid-cols-4 gap-3",children:l.map(u=>t.jsx("button",{onClick:()=>d(u.id),className:`p-3 text-center border-2 rounded-lg transition-colors ${a===u.id?"border-green-500 bg-green-50":"border-gray-200 hover:border-green-500 hover:bg-green-50"}`,children:t.jsx("span",{className:"font-medium",children:u.name})},u.id))})]}),t.jsxs("div",{className:"flex justify-between items-center",children:[t.jsxs("button",{onClick:()=>s("/submit"),className:"flex items-center gap-2 text-gray-600 hover:text-gray-800 transition-colors",children:[t.jsx(We,{className:"w-5 h-5"}),"Back to Track Selection"]}),t.jsxs("button",{onClick:()=>c(),disabled:!r,className:`flex items-center gap-2 px-6 py-3 rounded-lg font-medium transition-colors ${r?"bg-green-500 text-white hover:bg-green-600":"bg-gray-200 text-gray-500 cursor-not-allowed"}`,children:["Continue to Playlists",t.jsx(Ut,{className:"w-5 h-5"})]})]})]})})}function gc(s=4,e,r){const[n,a]=b.useState([]),[i,o]=b.useState(!0),[l,d]=b.useState(null);return b.useEffect(()=>{!i&&n.length>0&&typeof window<"u"&&window.prerenderReady!==void 0&&(window.prerenderReady=!0)},[i,n.length]),b.useEffect(()=>{async function c(){try{o(!0),d(null);let u=W.from("playlist_details").select("*").eq("featured",!0);e&&(u=u.eq("genre",e)),r&&(u=u.contains("sub_genres",[r]));const{data:h,error:f}=await u;if(f)throw f;const g=h||[];if(g.length>=s){const N=Ur(),j=[...g].sort((m,p)=>{const _=mt(`${N}-${m.id}`),T=mt(`${N}-${p.id}`);return _-T});a(j.slice(0,s));return}const x=s-g.length;let v=W.from("playlist_details").select("*").eq("featured",!1);e&&(v=v.eq("genre",e)),r&&(v=v.contains("sub_genres",[r]));const{data:y,error:w}=await v;if(w)throw w;const P=Ur(),C=[...g].sort((N,j)=>{const m=mt(`${P}-featured-${N.id}`),p=mt(`${P}-featured-${j.id}`);return m-p}),D=[...y||[]].sort((N,j)=>{const m=mt(`${P}-nonfeatured-${N.id}`),p=mt(`${P}-nonfeatured-${j.id}`);return m-p}),k=[...C,...D.slice(0,x)];a(k)}catch(u){console.error("Failed to fetch playlists:",u),d(u instanceof Error?u:new Error("Failed to fetch playlists"))}finally{o(!1)}}c()},[s,e,r]),{playlists:n,loading:i,error:l}}function zn({genre:s,subGenre:e,totalCount:r,onViewAll:n}){const{playlists:a,loading:i}=gc(8,s,e),[o,l]=b.useState(null),[d,c]=b.useState(null);if(i||a.length===0)return null;const h=new Date().toLocaleDateString("en-US",{weekday:"long",month:"long",day:"numeric"}),f=e?`Today's Featured ${e} ${s} Playlists - ${h}`:`Today's Featured ${s} Playlists - ${h}`,g=new URLSearchParams;return g.set("genre",s),e&&g.set("subGenre",e),t.jsxs(t.Fragment,{children:[t.jsxs("div",{className:"border-l-4 border-green-500 pl-6 mb-8",children:[t.jsx("h2",{className:"text-2xl font-semibold text-gray-900 mb-6",children:f}),t.jsx("div",{className:"grid grid-cols-1 sm:grid-cols-2 lg:grid-cols-3 xl:grid-cols-4 gap-4",children:a.map(x=>t.jsx(lr,{playlist:x,onSubmit:v=>l(a.find(y=>y.id===v)||null),priority:!0},x.id))})]}),t.jsx("div",{className:"text-center mb-12",children:t.jsxs("button",{onClick:n,className:"inline-block px-8 py-4 bg-green-500 text-white text-lg font-semibold rounded-lg hover:bg-green-600 transition-all transform hover:scale-105 shadow-lg hover:shadow-xl",children:["View All ",r.toLocaleString()," ",e?`${e} ${s}`:s," Playlists"]})}),o&&t.jsx(St,{playlist:o,onClose:()=>l(null),onSubmit:()=>{l(null),c({type:"success",message:`Track submitted to ${o.name}! Watch your inbox for feedback from the curator.`})}}),d&&t.jsx(qe,{message:d.message,type:d.type,onClose:()=>c(null)})]})}const pc="https://ftwlzdhkzqfuosdorgjt.supabase.co/storage/v1/object/public/playlistpartner%20public/playlistpartner%20og%20image.png";function yc(){const{genre:s}=os(),e=s?decodeURIComponent(s):"",{genres:r,loading:n}=Be(),a=r.find(w=>w.slug===e),[i,o]=b.useState(null),[l,d]=b.useState(!1),[c,u]=b.useState(null),h=Xe(),{totalCount:f}=Gt({genre:a==null?void 0:a.name}),g=()=>{a&&(window.scrollTo(0,0),h("/playlists",{state:{filters:{genre:a.name,fromSubmission:!0}},replace:!0}))};if(n)return t.jsx("div",{className:"container mx-auto px-4 py-8",children:t.jsx("div",{className:"flex items-center justify-center min-h-[400px]",children:t.jsx(me,{className:"w-8 h-8 text-green-500 animate-spin"})})});if(!n&&!a)return t.jsxs("div",{className:"container mx-auto px-4 py-8",children:[t.jsx("h1",{className:"text-2xl font-bold mb-4",children:"Genre Not Found"}),t.jsx(ee,{to:"/",className:"text-green-600 hover:text-green-700",children:"Return to Home"})]});const x=`Free ${a.name} Spotify Playlist Submission - No Signup`,v=`Submit your ${a.name} tracks to ${f} Spotify playlists for free. Connect with independent curators and grow your audience — no signup needed.`,y=async w=>{try{d(!1),u({type:"success",message:`Track submitted to ${i==null?void 0:i.name}! Watch your inbox for feedback from the curator.`})}catch(P){console.error("Failed to submit track:",P),u({type:"error",message:"Failed to submit track. Please try again."})}};return t.jsxs(t.Fragment,{children:[t.jsx(Fe,{title:x,description:v,image:pc,url:`${window.location.origin}/genre/${a.slug}`,type:"website"}),t.jsxs("main",{className:"container mx-auto px-4 py-8",children:[t.jsxs(ee,{to:"/",className:"inline-flex items-center gap-2 text-green-600 hover:text-green-700 mb-6",children:[t.jsx(We,{className:"w-4 h-4"}),"Back to All Genres"]}),t.jsx("div",{className:"bg-white p-6 rounded-lg shadow-sm mb-8",children:t.jsxs("div",{className:"flex items-start gap-4",children:[t.jsx("div",{className:"p-3 bg-green-50 rounded-lg",children:t.jsx(ve,{className:"w-8 h-8 text-green-600"})}),t.jsxs("div",{children:[t.jsxs("h1",{className:"text-3xl font-bold mb-2",children:[a.name," Spotify Playlist Submission"]}),t.jsx("p",{className:"text-gray-600 mb-4",children:a.description}),t.jsx("div",{className:"flex gap-4 text-sm text-gray-600",children:t.jsxs("span",{children:[f," Playlists"]})})]})]})}),t.jsx(zn,{genre:a.name,totalCount:f,onViewAll:g}),l&&i&&t.jsx(St,{playlist:i,onClose:()=>{d(!1),o(null)},onSubmit:y}),c&&t.jsx(qe,{message:c.message,type:c.type,onClose:()=>u(null)})]})]})}const xc="https://ftwlzdhkzqfuosdorgjt.supabase.co/storage/v1/object/public/playlistpartner%20public/playlistpartner%20og%20image.png";function bc(){const{genre:s,subGenre:e}=os(),r=s?decodeURIComponent(s):"",n=e?decodeURIComponent(e):"",{genres:a,loading:i}=Be(),o=a.find(D=>D.slug===r),l=o==null?void 0:o.subGenres.find(D=>Me(D.name)===n),[d,c]=b.useState(null),[u,h]=b.useState(!1),[f,g]=b.useState(null),x=Xe(),{totalCount:v}=Gt({genre:o==null?void 0:o.name,subGenre:l==null?void 0:l.name}),y=()=>{!o||!l||(window.scrollTo(0,0),x("/playlists",{state:{filters:{genre:o.name,subGenre:l.name,fromSubmission:!0}},replace:!0}))};if(i)return t.jsx("div",{className:"container mx-auto px-4 py-8",children:t.jsx("div",{className:"flex items-center justify-center min-h-[400px]",children:t.jsx(me,{className:"w-8 h-8 text-green-500 animate-spin"})})});if(!i&&(!o||!l))return t.jsxs("div",{className:"container mx-auto px-4 py-8",children:[t.jsx("h1",{className:"text-2xl font-bold mb-4",children:"Sub-Genre Not Found"}),t.jsx(ee,{to:"/",className:"text-green-600 hover:text-green-700",children:"Return to Home"})]});const w=`Free ${l.name} Spotify Playlist Submission - No Signup`,P=`Submit your ${l.name} tracks to ${v} Spotify playlists for free. Connect with independent curators and grow your audience — no signup needed.`,C=async D=>{try{h(!1),g({type:"success",message:`Track submitted to ${d==null?void 0:d.name}! Watch your inbox for feedback from the curator.`})}catch(k){console.error("Failed to submit track:",k),g({type:"error",message:"Failed to submit track. Please try again."})}};return t.jsxs(t.Fragment,{children:[t.jsx(Fe,{title:w,description:P,image:xc,url:`${window.location.origin}/genre/${o.slug}/${l.slug}`,type:"website"}),t.jsxs("main",{className:"container mx-auto px-4 py-8",children:[t.jsxs(ee,{to:`/genre/${encodeURIComponent(o.slug)}`,className:"inline-flex items-center gap-2 text-green-600 hover:text-green-700 mb-6",children:[t.jsx(We,{className:"w-4 h-4"}),"Back to ",o.name," Playlists"]}),t.jsx("div",{className:"bg-white p-6 rounded-lg shadow-sm mb-8",children:t.jsxs("div",{className:"flex items-start gap-4",children:[t.jsx("div",{className:"p-3 bg-green-50 rounded-lg",children:t.jsx(ve,{className:"w-8 h-8 text-green-600"})}),t.jsxs("div",{children:[t.jsxs("h1",{className:"text-3xl font-bold mb-2",children:[l.name," Spotify Playlist Submission"]}),t.jsx("p",{className:"text-gray-600 mb-4",children:l.description||`Discover curated playlists specializing in ${l.name} ${o.name} music. Submit your tracks to playlist curators who understand and appreciate your specific style.`}),t.jsx("div",{className:"flex gap-4 text-sm text-gray-600",children:t.jsxs("span",{children:[v," Playlists"]})})]})]})}),t.jsx(zn,{genre:o.name,subGenre:l.name,totalCount:v,onViewAll:y}),u&&d&&t.jsx(St,{playlist:d,onClose:()=>{h(!1),c(null)},onSubmit:C}),f&&t.jsx(qe,{message:f.message,type:f.type,onClose:()=>g(null)})]})]})}function wc(){const{genres:s,loading:e}=Be();return b.useEffect(()=>{!e&&s.length>0&&typeof window<"u"&&window.prerenderReady!==void 0&&(window.prerenderReady=!0)},[e,s]),t.jsxs(t.Fragment,{children:[t.jsx(Fe,{title:"Browse Spotify Playlist Genres - Free Music Submission | PlaylistPartner",description:"Discover Spotify playlists in every genre and sub-genre. Submit your music directly to curators for free - from hip-hop to classical, find the perfect playlists for your sound.",image:"https://ftwlzdhkzqfuosdorgjt.supabase.co/storage/v1/object/public/playlistpartner%20public/playlistpartner%20og%20image.png",url:`${window.location.origin}/genres`,type:"website"}),t.jsxs("main",{className:"container mx-auto px-4 py-8 max-w-5xl",children:[t.jsxs(ee,{to:"/",className:"inline-flex items-center gap-2 text-green-600 hover:text-green-700 mb-6",children:[t.jsx(We,{className:"w-4 h-4"}),"Back to Home"]}),t.jsxs("div",{className:"bg-white rounded-lg shadow-sm p-6 mb-8",children:[t.jsx("h1",{className:"text-3xl font-bold text-gray-900 mb-2",children:"Spotify Playlist Genres"}),t.jsx("p",{className:"text-gray-600",children:"Discover Spotify playlists in every genre and sub-genre. Submit your music directly to curators for free - from hip-hop to classical, find the perfect playlists for your sound."})]}),e?t.jsx("div",{className:"grid grid-cols-1 md:grid-cols-2 lg:grid-cols-3 gap-6",children:[...Array(6)].map((r,n)=>t.jsxs("div",{className:"bg-white p-6 rounded-lg shadow-sm animate-pulse",children:[t.jsx("div",{className:"h-6 w-1/3 bg-gray-200 rounded mb-4"}),t.jsx("div",{className:"space-y-2",children:[...Array(4)].map((a,i)=>t.jsx("div",{className:"h-4 bg-gray-100 rounded w-2/3"},i))})]},n))}):t.jsx("div",{className:"grid grid-cols-1 md:grid-cols-2 lg:grid-cols-3 gap-6",children:s.map(r=>t.jsxs("div",{className:"bg-white p-6 rounded-lg shadow-sm",children:[t.jsxs(ee,{to:`/genre/${Me(r.name)}`,className:"group flex items-center gap-3 mb-4",children:[t.jsx("div",{className:"p-2 bg-gray-50 rounded-lg group-hover:bg-green-50 transition-colors",children:t.jsx(ve,{className:"w-5 h-5 text-gray-500 group-hover:text-green-600"})}),t.jsx("h2",{className:"text-xl font-semibold text-gray-900 group-hover:text-green-600 transition-colors",children:r.name})]}),r.subGenres.length>0&&t.jsx("div",{className:"space-y-1",children:r.subGenres.map(n=>t.jsxs(ee,{to:`/genre/${Me(r.name)}/${Me(n.name)}`,className:"block text-gray-600 hover:text-green-600 transition-colors pl-11",children:[n.name,n.description&&t.jsx("p",{className:"text-sm text-gray-500 mt-0.5",children:n.description})]},n.id))})]},r.id))})]})]})}function vc(){const{totalCount:s}=Gt({});return t.jsxs(t.Fragment,{children:[t.jsx(Fe,{title:"About PlaylistPartner - Free Spotify Playlist Submission Platform",description:"Learn about PlaylistPartner, your free platform for submitting music to Spotify playlist curators. No signup required, direct curator connections."}),t.jsx("div",{className:"bg-gradient-to-b from-green-50 to-white",children:t.jsxs("div",{className:"container mx-auto px-4 py-16 md:py-24",children:[t.jsxs("div",{className:"max-w-3xl mx-auto text-center mb-16",children:[t.jsx(gs,{className:"w-12 h-12 text-green-600 mx-auto mb-6"}),t.jsx("h1",{className:"text-4xl font-bold text-gray-900 mb-6",children:"Music Promotion Made Simple"}),t.jsx("p",{className:"text-xl text-gray-600",children:"Submit your music directly to Spotify playlist curators without the typical barriers. No signups, no fees, and no waiting around. Only on PlaylistPartner."})]}),t.jsxs("div",{className:"max-w-5xl mx-auto grid md:grid-cols-3 gap-8 mb-24",children:[t.jsxs("div",{className:"bg-white p-6 rounded-lg shadow-sm text-center",children:[t.jsx(gl,{className:"w-8 h-8 text-green-600 mx-auto mb-4"}),t.jsx("h3",{className:"text-lg font-semibold mb-2",children:"Always Free"}),t.jsx("p",{className:"text-gray-600",children:"No hidden fees or premium features. Submit your music to 10 playlists daily – it's that simple."})]}),t.jsxs("div",{className:"bg-white p-6 rounded-lg shadow-sm text-center",children:[t.jsx(Tl,{className:"w-8 h-8 text-green-600 mx-auto mb-4"}),t.jsx("h3",{className:"text-lg font-semibold mb-2",children:"No Sign Up"}),t.jsx("p",{className:"text-gray-600",children:"Start submitting your music immediately. No account creation required."})]}),t.jsxs("div",{className:"bg-white p-6 rounded-lg shadow-sm text-center",children:[t.jsx(qt,{className:"w-8 h-8 text-green-600 mx-auto mb-4"}),t.jsx("h3",{className:"text-lg font-semibold mb-2",children:"Direct Connection"}),t.jsx("p",{className:"text-gray-600",children:"Connect directly with curators in your genre and style. Filter playlists by genre, sub-genre, or search."})]})]}),t.jsxs("div",{className:"max-w-4xl mx-auto mb-24",children:[t.jsx("h2",{className:"text-3xl font-bold text-center mb-12",children:"How It Works"}),t.jsxs("div",{className:"space-y-12",children:[t.jsxs("div",{className:"flex items-start gap-6",children:[t.jsx("div",{className:"w-10 h-10 rounded-full bg-green-100 flex-shrink-0 flex items-center justify-center",children:t.jsx("span",{className:"text-green-600 font-bold",children:"1"})}),t.jsxs("div",{children:[t.jsx("h3",{className:"text-xl font-semibold mb-2",children:"Find Your Playlists"}),t.jsx("p",{className:"text-gray-600",children:"Browse our curated collection of Spotify playlists by genre, sub genre or follower count."})]})]}),t.jsxs("div",{className:"flex items-start gap-6",children:[t.jsx("div",{className:"w-10 h-10 rounded-full bg-green-100 flex-shrink-0 flex items-center justify-center",children:t.jsx("span",{className:"text-green-600 font-bold",children:"2"})}),t.jsxs("div",{children:[t.jsx("h3",{className:"text-xl font-semibold mb-2",children:"Submit Your Track"}),t.jsx("p",{className:"text-gray-600",children:"Select your track from Spotify and submit it to any playlist that matches your style. Add a personal message to the curator to increase your chances."})]})]}),t.jsxs("div",{className:"flex items-start gap-6",children:[t.jsx("div",{className:"w-10 h-10 rounded-full bg-green-100 flex-shrink-0 flex items-center justify-center",children:t.jsx("span",{className:"text-green-600 font-bold",children:"3"})}),t.jsxs("div",{children:[t.jsx("h3",{className:"text-xl font-semibold mb-2",children:"Get Featured"}),t.jsx("p",{className:"text-gray-600",children:"Curators review your submission and add tracks that fit their playlist. Build relationships with curators and grow your audience organically."})]})]})]})]}),t.jsx("div",{className:"max-w-4xl mx-auto border-t border-gray-200 pt-16",children:t.jsxs("div",{className:"grid grid-cols-2 md:grid-cols-4 gap-8",children:[t.jsxs("div",{className:"text-center",children:[t.jsxs("div",{className:"text-3xl font-bold text-green-600 mb-1",children:[s.toLocaleString(),"+"]}),t.jsx("div",{className:"text-sm text-gray-600",children:"Active Playlists"})]}),t.jsxs("div",{className:"text-center",children:[t.jsx("div",{className:"text-3xl font-bold text-green-600 mb-1",children:"15K+"}),t.jsx("div",{className:"text-sm text-gray-600",children:"Monthly Submissions"})]}),t.jsxs("div",{className:"text-center",children:[t.jsx("div",{className:"text-3xl font-bold text-green-600 mb-1",children:"2000+"}),t.jsx("div",{className:"text-sm text-gray-600",children:"Curators"})]}),t.jsxs("div",{className:"text-center",children:[t.jsx("div",{className:"text-3xl font-bold text-green-600 mb-1",children:"100%"}),t.jsx("div",{className:"text-sm text-gray-600",children:"Free"})]})]})}),t.jsxs("div",{className:"max-w-xl mx-auto text-center mt-24",children:[t.jsx("h2",{className:"text-2xl font-bold mb-6",children:"Ready to Share Your Music?"}),t.jsxs("div",{className:"flex flex-col sm:flex-row gap-4 justify-center",children:[t.jsx("a",{href:"/submit",className:"inline-flex items-center justify-center bg-green-500 text-white px-8 py-3 rounded-lg hover:bg-green-600 transition-colors font-medium",children:"Submit Your Music"}),t.jsx("a",{href:"/playlists",className:"inline-flex items-center justify-center bg-white text-gray-700 px-8 py-3 rounded-lg hover:bg-gray-100 transition-colors font-medium border border-gray-200",children:"Browse Playlists"})]})]})]})})]})}function jc(){const[s,e]=b.useState({name:"",email:"",playlistUrl:""}),[r,n]=b.useState(!1),[a,i]=b.useState(null),[o,l]=b.useState(!1);b.useEffect(()=>{typeof window<"u"&&window.prerenderReady!==void 0&&(window.prerenderReady=!0)},[]);const d=u=>{const h=jt(u,"playlist");if(!h)throw new Error("Please enter a valid Spotify playlist URL");return h},c=async u=>{u.preventDefault(),i(null),n(!0);try{if(!/^[^\s@]+@[^\s@]+\.[^\s@]+$/.test(s.email))throw new Error("Please enter a valid email address");const h=d(s.playlistUrl),{error:f}=await W.from("curator_applications").insert({name:s.name,email:s.email,playlist_url:s.playlistUrl,playlist_id:h});if(f)throw f;l(!0),e({name:"",email:"",playlistUrl:""})}catch(h){console.error("Application submission failed:",h),i(h instanceof Error?h.message:"Failed to submit application")}finally{n(!1)}};return t.jsxs(t.Fragment,{children:[t.jsx(Fe,{title:"Become a Curator - PlaylistPartner",description:"Join our network of Spotify playlist curators. Apply to list your playlists and connect with artists in your genre."}),t.jsx("div",{className:"bg-gradient-to-b from-green-50 to-white",children:t.jsx("div",{className:"container mx-auto px-4 py-16 md:py-24",children:t.jsxs("div",{className:"max-w-4xl mx-auto",children:[t.jsxs("div",{className:"text-center mb-16",children:[t.jsx(gs,{className:"w-12 h-12 text-green-600 mx-auto mb-6"}),t.jsx("h1",{className:"text-4xl font-bold text-gray-900 mb-12",children:"Join Our Curator Network"}),t.jsxs("div",{className:"grid md:grid-cols-2 gap-8",children:[t.jsxs("div",{className:"bg-white p-8 rounded-xl shadow-sm",children:[t.jsx("div",{className:"p-3 bg-green-50 rounded-lg w-12 h-12 flex items-center justify-center mx-auto mb-4",children:t.jsx(hl,{className:"w-6 h-6 text-green-600"})}),t.jsx("h2",{className:"text-xl font-bold mb-4",children:"For Music Curators"}),t.jsx("p",{className:"text-gray-600",children:"Love discovering and sharing new music? Add your playlists to PlaylistPartner to receive fresh submissions from independent artists, grow your following, and strengthen your reputation as a tastemaker in your genre."})]}),t.jsxs("div",{className:"bg-white p-8 rounded-xl shadow-sm",children:[t.jsx("div",{className:"p-3 bg-green-50 rounded-lg w-12 h-12 flex items-center justify-center mx-auto mb-4",children:t.jsx(qt,{className:"w-6 h-6 text-green-600"})}),t.jsx("h2",{className:"text-xl font-bold mb-4",children:"For Artists"}),t.jsx("p",{className:"text-gray-600",children:"Already making music? List your artist playlists to connect with other independent artists in your genre, expand your network, and build meaningful relationships within your music community."})]})]})]}),t.jsxs("div",{className:"bg-white p-8 rounded-xl shadow-sm mb-12",children:[t.jsx("h2",{className:"text-2xl font-bold mb-6",children:"What We Look For"}),t.jsx("p",{className:"text-gray-600 mb-4",children:"Our curator network maintains high standards to ensure quality. We look for:"}),t.jsxs("ul",{className:"space-y-3 text-gray-600",children:[t.jsxs("li",{className:"flex items-center gap-2",children:[t.jsx(nt,{className:"w-5 h-5 text-green-500 flex-shrink-0"}),"Consistent playlist activity with regular updates"]}),t.jsxs("li",{className:"flex items-center gap-2",children:[t.jsx(nt,{className:"w-5 h-5 text-green-500 flex-shrink-0"}),"Genuine follower engagement"]}),t.jsxs("li",{className:"flex items-center gap-2",children:[t.jsx(nt,{className:"w-5 h-5 text-green-500 flex-shrink-0"}),"Clear genre focus and curation style"]}),t.jsxs("li",{className:"flex items-center gap-2",children:[t.jsx(nt,{className:"w-5 h-5 text-green-500 flex-shrink-0"}),"Professional playlist presentation"]})]})]}),t.jsx("div",{className:"bg-white p-8 rounded-xl shadow-sm",children:o?t.jsxs("div",{className:"text-center py-8",children:[t.jsx(nt,{className:"w-16 h-16 text-green-500 mx-auto mb-4"}),t.jsx("h2",{className:"text-2xl font-bold text-gray-900 mb-4",children:"Application Received!"}),t.jsx("p",{className:"text-gray-600 mb-6",children:"Thank you for your interest in joining PlaylistPartner. We'll review your application and get back to you as soon as possible."}),t.jsx("button",{onClick:()=>l(!1),className:"text-green-600 hover:text-green-700 font-medium",children:"Submit Another Application"})]}):t.jsxs(t.Fragment,{children:[t.jsx("h2",{className:"text-2xl font-bold mb-6",children:"Apply to Join"}),t.jsxs("form",{onSubmit:c,className:"space-y-6",children:[t.jsxs("div",{children:[t.jsx("label",{htmlFor:"name",className:"block text-sm font-medium text-gray-700 mb-1",children:"Your Name"}),t.jsx("input",{type:"text",id:"name",value:s.name,onChange:u=>e(h=>({...h,name:u.target.value})),className:"w-full p-3 border border-gray-300 rounded-lg focus:ring-2 focus:ring-green-500 focus:border-transparent",placeholder:"Enter your name",required:!0,disabled:r})]}),t.jsxs("div",{children:[t.jsx("label",{htmlFor:"email",className:"block text-sm font-medium text-gray-700 mb-1",children:"Email Address"}),t.jsx("input",{type:"email",id:"email",value:s.email,onChange:u=>e(h=>({...h,email:u.target.value})),className:"w-full p-3 border border-gray-300 rounded-lg focus:ring-2 focus:ring-green-500 focus:border-transparent",placeholder:"you@example.com",required:!0,disabled:r})]}),t.jsxs("div",{children:[t.jsx("label",{htmlFor:"playlistUrl",className:"block text-sm font-medium text-gray-700 mb-1",children:"Your Best Playlist"}),t.jsx("input",{type:"url",id:"playlistUrl",value:s.playlistUrl,onChange:u=>e(h=>({...h,playlistUrl:u.target.value})),className:"w-full p-3 border border-gray-300 rounded-lg focus:ring-2 focus:ring-green-500 focus:border-transparent",placeholder:"https://open.spotify.com/playlist/...",required:!0,disabled:r}),t.jsx("p",{className:"mt-1 text-sm text-gray-500",children:"Please provide the Spotify URL of your best performing playlist"})]}),a&&t.jsxs("div",{className:"flex items-center gap-2 text-red-600 bg-red-50 p-3 rounded-lg",children:[t.jsx(fe,{className:"w-5 h-5 flex-shrink-0"}),t.jsx("p",{children:a})]}),t.jsx("button",{type:"submit",disabled:r,className:"w-full flex items-center justify-center gap-2 bg-green-500 text-white p-3 rounded-lg hover:bg-green-600 transition-colors disabled:bg-gray-400 disabled:cursor-not-allowed font-medium",children:r?t.jsxs(t.Fragment,{children:[t.jsx(me,{className:"w-5 h-5 animate-spin"}),"Submitting..."]}):"Submit Application"})]})]})}),t.jsxs("div",{className:"mt-12 bg-white p-8 rounded-xl shadow-sm",children:[t.jsx("h2",{className:"text-2xl font-bold mb-6",children:"What Happens Next?"}),t.jsxs("div",{className:"space-y-6",children:[t.jsxs("div",{className:"flex items-start gap-4",children:[t.jsx("div",{className:"w-8 h-8 bg-green-100 rounded-full flex items-center justify-center flex-shrink-0",children:t.jsx("span",{className:"text-green-600 font-bold",children:"1"})}),t.jsx("div",{children:t.jsx("p",{className:"text-gray-600",children:"Submit your application with links to your playlists"})})]}),t.jsxs("div",{className:"flex items-start gap-4",children:[t.jsx("div",{className:"w-8 h-8 bg-green-100 rounded-full flex items-center justify-center flex-shrink-0",children:t.jsx("span",{className:"text-green-600 font-bold",children:"2"})}),t.jsx("div",{children:t.jsx("p",{className:"text-gray-600",children:"Our team reviews your submission against our quality criteria"})})]}),t.jsxs("div",{className:"flex items-start gap-4",children:[t.jsx("div",{className:"w-8 h-8 bg-green-100 rounded-full flex items-center justify-center flex-shrink-0",children:t.jsx("span",{className:"text-green-600 font-bold",children:"3"})}),t.jsx("div",{children:t.jsx("p",{className:"text-gray-600",children:"If approved, you'll receive instructions for adding your playlists"})})]}),t.jsxs("div",{className:"flex items-start gap-4",children:[t.jsx("div",{className:"w-8 h-8 bg-green-100 rounded-full flex items-center justify-center flex-shrink-0",children:t.jsx("span",{className:"text-green-600 font-bold",children:"4"})}),t.jsx("div",{children:t.jsx("p",{className:"text-gray-600",children:"Start connecting with artists and growing your network"})})]})]})]})]})})})]})}function _c(){const[s,e]=b.useState(1),r=9,n=or,a=n.length,i=Math.ceil(a/r),o=(s-1)*r,l=o+r,d=n.slice(o,l);function c(h){return new Date(h).toLocaleDateString("en-US",{year:"numeric",month:"long",day:"numeric"})}function u(h){return h.startsWith("//")?`https:${h}`:h}return t.jsxs(t.Fragment,{children:[t.jsx(Fe,{title:"Blog / News | PlaylistPartner",description:"Stay updated with the latest news, features, and improvements from PlaylistPartner. Plus practical music marketing tips.",type:"website",structuredData:{"@context":"https://schema.org","@type":"Blog",name:"Playlist Partner Blog",description:"Stay updated with the latest news, features, and improvements from Playlist Partner. Plus practical music marketing tips.",url:window.location.href,inLanguage:"en-US",publisher:{"@type":"Organization",name:"Playlist Partner",logo:{"@type":"ImageObject",url:"https://ftwlzdhkzqfuosdorgjt.supabase.co/storage/v1/object/public/playlistpartner%20public//playlist%20partner%20logo%20square.png",width:"500",height:"500"}}}}),t.jsx("div",{className:"bg-gradient-to-b from-green-50 to-white",children:t.jsxs("section",{className:"max-w-7xl mx-auto px-4 sm:px-6 lg:px-8 py-12 md:py-20",children:[t.jsxs("div",{className:"text-center mb-12",children:[t.jsx("h1",{className:"text-4xl md:text-5xl font-bold text-gray-900 mb-4",children:"Playlist Partner Blog"}),t.jsx("p",{className:"text-xl text-gray-600 max-w-3xl mx-auto",children:"Stay updated with the latest news, features, and improvements from Playlist Partner. Plus, coming soon: practical music marketing tips to boost your career."})]}),d.length===0&&t.jsx("div",{className:"text-center py-12",children:t.jsx("p",{className:"text-gray-600",children:"No blog posts available yet. Check back soon!"})}),d.length>0&&t.jsxs(t.Fragment,{children:[t.jsx("div",{className:"grid grid-cols-1 md:grid-cols-2 lg:grid-cols-3 gap-8 mb-12",children:d.map(h=>{var f,g,x;return t.jsxs("article",{className:"bg-white rounded-lg shadow-md overflow-hidden hover:shadow-lg transition-shadow",children:[((f=h.featuredImage)==null?void 0:f.url)&&t.jsx(ee,{to:`/blog/${((g=h.category)==null?void 0:g.toLowerCase())||"news"}/${h.slug}`,children:t.jsx("img",{src:u(h.featuredImage.url),alt:h.featuredImage.title||h.title,className:"w-full aspect-[3/2] object-cover"})}),t.jsxs("div",{className:"p-6",children:[t.jsx(ee,{to:`/blog/${((x=h.category)==null?void 0:x.toLowerCase())||"news"}/${h.slug}`,children:t.jsx("h2",{className:"text-xl font-semibold text-gray-900 mb-2 hover:text-green-600 transition-colors",children:h.title})}),h.excerpt&&t.jsx("p",{className:"text-gray-600 mb-4 line-clamp-3",children:h.excerpt}),t.jsxs("div",{className:"flex flex-wrap items-center gap-4 text-sm text-gray-500",children:[t.jsxs("div",{className:"flex items-center gap-1",children:[t.jsx(rr,{className:"w-4 h-4"}),t.jsx("span",{children:c(h.publishDate)})]}),h.category&&t.jsxs("div",{className:"flex items-center gap-1",children:[t.jsx(Ks,{className:"w-4 h-4"}),t.jsx("span",{children:h.category})]})]})]})]},h.id)})}),i>1&&t.jsxs("div",{className:"flex justify-center gap-2",children:[t.jsx("button",{onClick:()=>e(s-1),disabled:s===1,className:"px-4 py-2 border border-gray-300 rounded-md text-gray-700 hover:bg-gray-50 disabled:opacity-50 disabled:cursor-not-allowed",children:"Previous"}),t.jsx("div",{className:"flex items-center gap-2",children:Array.from({length:i},(h,f)=>f+1).map(h=>t.jsx("button",{onClick:()=>e(h),className:`px-3 py-1 rounded-md ${h===s?"bg-green-600 text-white":"text-gray-700 hover:bg-gray-50"}`,children:h},h))}),t.jsx("button",{onClick:()=>e(s+1),disabled:s===i,className:"px-4 py-2 border border-gray-300 rounded-md text-gray-700 hover:bg-gray-50 disabled:opacity-50 disabled:cursor-not-allowed",children:"Next"})]})]})]})})]})}var Te={},Nc=s=>{if(Object.prototype.toString.call(s)!=="[object Object]")return!1;const e=Object.getPrototypeOf(s);return e===null||e===Object.prototype};(function(s){var e=Nc;s.BLOCKS=void 0,function(S){S.DOCUMENT="document",S.PARAGRAPH="paragraph",S.HEADING_1="heading-1",S.HEADING_2="heading-2",S.HEADING_3="heading-3",S.HEADING_4="heading-4",S.HEADING_5="heading-5",S.HEADING_6="heading-6",S.OL_LIST="ordered-list",S.UL_LIST="unordered-list",S.LIST_ITEM="list-item",S.HR="hr",S.QUOTE="blockquote",S.EMBEDDED_ENTRY="embedded-entry-block",S.EMBEDDED_ASSET="embedded-asset-block",S.EMBEDDED_RESOURCE="embedded-resource-block",S.TABLE="table",S.TABLE_ROW="table-row",S.TABLE_CELL="table-cell",S.TABLE_HEADER_CELL="table-header-cell"}(s.BLOCKS||(s.BLOCKS={})),s.INLINES=void 0,function(S){S.ASSET_HYPERLINK="asset-hyperlink",S.EMBEDDED_ENTRY="embedded-entry-inline",S.EMBEDDED_RESOURCE="embedded-resource-inline",S.ENTRY_HYPERLINK="entry-hyperlink",S.HYPERLINK="hyperlink",S.RESOURCE_HYPERLINK="resource-hyperlink"}(s.INLINES||(s.INLINES={})),s.MARKS=void 0,function(S){S.BOLD="bold",S.ITALIC="italic",S.UNDERLINE="underline",S.CODE="code",S.SUPERSCRIPT="superscript",S.SUBSCRIPT="subscript",S.STRIKETHROUGH="strikethrough"}(s.MARKS||(s.MARKS={}));var r=function(S,O){return r=Object.setPrototypeOf||{__proto__:[]}instanceof Array&&function(R,E){R.__proto__=E}||function(R,E){for(var A in E)Object.prototype.hasOwnProperty.call(E,A)&&(R[A]=E[A])},r(S,O)};function n(S,O){if(typeof O!="function"&&O!==null)throw new TypeError("Class extends value "+String(O)+" is not a constructor or null");r(S,O);function R(){this.constructor=S}S.prototype=O===null?Object.create(O):(R.prototype=O.prototype,new R)}function a(S,O,R){if(R||arguments.length===2)for(var E=0,A=O.length,$;E<A;E++)($||!(E in O))&&($||($=Array.prototype.slice.call(O,0,E)),$[E]=O[E]);return S.concat($||Array.prototype.slice.call(O))}typeof SuppressedError=="function"&&SuppressedError;var i,o=[s.BLOCKS.PARAGRAPH,s.BLOCKS.HEADING_1,s.BLOCKS.HEADING_2,s.BLOCKS.HEADING_3,s.BLOCKS.HEADING_4,s.BLOCKS.HEADING_5,s.BLOCKS.HEADING_6,s.BLOCKS.OL_LIST,s.BLOCKS.UL_LIST,s.BLOCKS.HR,s.BLOCKS.QUOTE,s.BLOCKS.EMBEDDED_ENTRY,s.BLOCKS.EMBEDDED_ASSET,s.BLOCKS.EMBEDDED_RESOURCE,s.BLOCKS.TABLE],l=[s.BLOCKS.PARAGRAPH,s.BLOCKS.HEADING_1,s.BLOCKS.HEADING_2,s.BLOCKS.HEADING_3,s.BLOCKS.HEADING_4,s.BLOCKS.HEADING_5,s.BLOCKS.HEADING_6,s.BLOCKS.OL_LIST,s.BLOCKS.UL_LIST,s.BLOCKS.HR,s.BLOCKS.QUOTE,s.BLOCKS.EMBEDDED_ENTRY,s.BLOCKS.EMBEDDED_ASSET,s.BLOCKS.EMBEDDED_RESOURCE],d=[s.BLOCKS.TABLE,s.BLOCKS.TABLE_ROW,s.BLOCKS.TABLE_CELL,s.BLOCKS.TABLE_HEADER_CELL],c=[s.BLOCKS.HR,s.BLOCKS.EMBEDDED_ENTRY,s.BLOCKS.EMBEDDED_ASSET,s.BLOCKS.EMBEDDED_RESOURCE],u=(i={},i[s.BLOCKS.OL_LIST]=[s.BLOCKS.LIST_ITEM],i[s.BLOCKS.UL_LIST]=[s.BLOCKS.LIST_ITEM],i[s.BLOCKS.LIST_ITEM]=l,i[s.BLOCKS.QUOTE]=[s.BLOCKS.PARAGRAPH],i[s.BLOCKS.TABLE]=[s.BLOCKS.TABLE_ROW],i[s.BLOCKS.TABLE_ROW]=[s.BLOCKS.TABLE_CELL,s.BLOCKS.TABLE_HEADER_CELL],i[s.BLOCKS.TABLE_CELL]=[s.BLOCKS.PARAGRAPH,s.BLOCKS.UL_LIST,s.BLOCKS.OL_LIST],i[s.BLOCKS.TABLE_HEADER_CELL]=[s.BLOCKS.PARAGRAPH],i),h=[s.BLOCKS.HEADING_1,s.BLOCKS.HEADING_2,s.BLOCKS.HEADING_3,s.BLOCKS.HEADING_4,s.BLOCKS.HEADING_5,s.BLOCKS.HEADING_6],f=a([s.BLOCKS.PARAGRAPH],h,!0),g=[s.BLOCKS.DOCUMENT,s.BLOCKS.PARAGRAPH,s.BLOCKS.HEADING_1,s.BLOCKS.HEADING_2,s.BLOCKS.HEADING_3,s.BLOCKS.HEADING_4,s.BLOCKS.HEADING_5,s.BLOCKS.HEADING_6,s.BLOCKS.OL_LIST,s.BLOCKS.UL_LIST,s.BLOCKS.LIST_ITEM,s.BLOCKS.HR,s.BLOCKS.QUOTE,s.BLOCKS.EMBEDDED_ENTRY,s.BLOCKS.EMBEDDED_ASSET,s.INLINES.HYPERLINK,s.INLINES.ENTRY_HYPERLINK,s.INLINES.ASSET_HYPERLINK,s.INLINES.EMBEDDED_ENTRY,"text"],x=[s.MARKS.BOLD,s.MARKS.CODE,s.MARKS.ITALIC,s.MARKS.UNDERLINE],v={nodeType:s.BLOCKS.DOCUMENT,data:{},content:[{nodeType:s.BLOCKS.PARAGRAPH,data:{},content:[{nodeType:"text",value:"",marks:[],data:{}}]}]};function y(S,O){for(var R=0,E=Object.keys(S);R<E.length;R++){var A=E[R];if(O===S[A])return!0}return!1}function w(S){return y(s.INLINES,S.nodeType)}function P(S){return y(s.BLOCKS,S.nodeType)}function C(S){return S.nodeType==="text"}var D=Object.freeze({__proto__:null,isBlock:P,isInline:w,isText:C}),k=function(S){var O=S.path,R=S.property,E=S.typeName,A=S.value;return{details:'The type of "'.concat(R,'" is incorrect, expected type: ').concat(E),name:"type",path:O.toArray(),type:E,value:A}},N=function(S){var O=S.min,R=S.value,E=S.path;return{name:"size",min:O,path:E.toArray(),details:"Size must be at least ".concat(O),value:R}},j=function(S){var O=S.max,R=S.value,E=S.path;return{name:"size",max:O,path:E.toArray(),details:"Size must be at most ".concat(O),value:R}},m=function(S){var O=S.expected,R=S.value,E=S.path;return{details:"Value must be one of expected values",name:"in",expected:a([],O,!0).sort(),path:E.toArray(),value:R}},p=function(S){var O=S.property,R=S.path;return{details:'The property "'.concat(O,'" is not expected'),name:"unexpected",path:R.toArray()}},_=function(S){var O=S.property,R=S.path;return{details:'The property "'.concat(O,'" is required here'),name:"required",path:R.toArray()}},T=function(){function S(O,R){var E=this;this.obj=O,this.path=R,this._errors=[],this.catch=function(){for(var A,$=[],M=0;M<arguments.length;M++)$[M]=arguments[M];(A=E._errors).push.apply(A,$)},this.exists=function(A){return A in E.obj?!0:(E.catch(_({property:A,path:E.path.of(A)})),!1)},this.object=function(A){var $,M=A?E.obj[A]:E.obj;if(A&&!E.exists(A))return!1;if(e(M))return!0;var Q=A?E.path.of(A):E.path,G=($=A??E.path.last())!==null&&$!==void 0?$:"value";return E.catch(k({typeName:"Object",property:G,path:Q,value:M})),!1},this.string=function(A){var $=E.obj[A];return A&&!E.exists(A)?!1:typeof $=="string"?!0:(E.catch(k({typeName:"String",property:A,path:E.path.of(A),value:$})),!1)},this.number=function(A,$){var M=E.obj[A];return $&&!(A in E.obj)?!0:E.exists(A)?typeof M=="number"&&!Number.isNaN(M)?!0:(E.catch(k({typeName:"Number",property:A,path:E.path.of(A),value:M})),!1):!1},this.array=function(A){var $=E.obj[A];return A&&!E.exists(A)?!1:Array.isArray($)?!0:(E.catch(k({typeName:"Array",property:A,path:E.path.of(A),value:$})),!1)},this.enum=function(A,$){var M=E.obj[A];return typeof M=="string"&&$.includes(M)?!0:(E.catch(m({expected:$,value:M,path:E.path.of(A)})),!1)},this.empty=function(A){if(!E.array(A))return!1;var $=E.obj[A];return $.length===0?!0:(E.catch(j({max:0,value:$,path:E.path.of(A)})),!1)},this.minLength=function(A,$){if(!E.array(A))return!1;var M=E.obj[A];return M.length>=$?!0:(E.catch(N({min:$,value:M,path:E.path.of(A)})),!1)},this.noAdditionalProperties=function(A){var $=Object.keys(E.obj).sort().filter(function(M){return!A.includes(M)});return $.forEach(function(M){return E.catch(p({property:M,path:E.path.of(M)}))}),$.length===0},this.each=function(A,$){if(E.array(A)){var M=E.obj[A],Q=!1;M.forEach(function(G,ye){if(!Q){var V=$(G,E.path.of(A).of(ye));V.length>0&&(Q=!0),E.catch.apply(E,V)}})}}}return Object.defineProperty(S.prototype,"errors",{get:function(){var O=this,R=function(E){return JSON.stringify({details:E.details,path:E.path})};return this._errors.filter(function(E,A){return O._errors.findIndex(function($){return R(E)===R($)})===A})},enumerable:!1,configurable:!0}),S}(),I=[],L=function(){function S(O,R){this.contentRule=O,this.validateData=R}return S.prototype.assert=function(O,R){var E,A,$=new T(O,R);if(!$.object())return $.errors;$.noAdditionalProperties(["nodeType","data","content"]);var M=Array.isArray(this.contentRule)?{nodeTypes:this.contentRule}:this.contentRule(O,R),Q=M.nodeTypes,G=M.min,ye=G===void 0?0:G;if(Q.length===0&&ye>0)throw new Error("Invalid content rule. Cannot have enforce a 'min' of ".concat(ye," with no nodeTypes"));if($.minLength("content",ye),Q.length===0?$.empty("content"):$.each("content",function(de,Re){var Pe=new T(de,Re);return Pe.object()&&Pe.enum("nodeType",Q),Pe.errors}),$.object("data")){var V=(A=(E=this.validateData)===null||E===void 0?void 0:E.call(this,O.data,R.of("data")))!==null&&A!==void 0?A:[];$.catch.apply($,V)}return $.errors},S}(),H=function(S){n(O,S);function O(R,E){var A=S.call(this,E,function($,M){return A.assertLink($,M)})||this;return A.linkType=R,A.assertLink=function($,M){var Q=new T($,M);if(Q.object("target")){var G=new T($.target.sys,M.of("target").of("sys"));G.object()&&(G.enum("type",[A.type]),G.enum("linkType",[A.linkType]),A.type==="Link"?(G.string("id"),G.noAdditionalProperties(["type","linkType","id"])):A.type==="ResourceLink"&&(G.string("urn"),G.noAdditionalProperties(["type","linkType","urn"]))),Q.catch.apply(Q,G.errors)}return Q.noAdditionalProperties(["target"]),Q.errors},A.type=A.linkType.startsWith("Contentful:")?"ResourceLink":"Link",A}return O}(L),Z=function(S){n(O,S);function O(){var R=S.call(this,["text"],function(E,A){return R.assertLink(E,A)})||this;return R.assertLink=function(E,A){var $=new T(E,A);return $.string("uri"),$.noAdditionalProperties(["uri"]),$.errors},R}return O}(L),re=function(S,O){return new L(S,O)},F=function(S,O){return new H(S,O)},ne=function(){function S(O){O===void 0&&(O=[]);var R=this;this.path=O,this.of=function(E){return new S(a(a([],R.path,!0),[E],!1))},this.isRoot=function(){return R.path.length===0},this.last=function(){return R.path[R.path.length-1]},this.toArray=function(){return R.path}}return S}();function K(S,O){var R=new T(S,O);return R.object()&&(R.noAdditionalProperties(["nodeType","data","value","marks"]),R.object("data"),R.each("marks",function(E,A){var $=new T(E,A);return $.object()&&$.string("type"),$.errors}),R.string("value")),R.errors}var U,q=re(a(a([],Object.values(s.INLINES),!0),["text"],!1).sort()),Y=re([s.BLOCKS.LIST_ITEM]),B=F("Entry",I),le=re(function(){return{nodeTypes:[s.BLOCKS.PARAGRAPH],min:1}},function(S,O){var R=new T(S,O);return R.noAdditionalProperties(["colspan","rowspan"]),R.number("colspan",!0),R.number("rowspan",!0),R.errors}),ce=(U={},U[s.BLOCKS.DOCUMENT]=re(o),U[s.BLOCKS.PARAGRAPH]=q,U[s.BLOCKS.HEADING_1]=q,U[s.BLOCKS.HEADING_2]=q,U[s.BLOCKS.HEADING_3]=q,U[s.BLOCKS.HEADING_4]=q,U[s.BLOCKS.HEADING_5]=q,U[s.BLOCKS.HEADING_6]=q,U[s.BLOCKS.QUOTE]=re(u[s.BLOCKS.QUOTE]),U[s.BLOCKS.EMBEDDED_ENTRY]=B,U[s.BLOCKS.EMBEDDED_ASSET]=F("Asset",I),U[s.BLOCKS.EMBEDDED_RESOURCE]=F("Contentful:Entry",I),U[s.BLOCKS.HR]=re(I),U[s.BLOCKS.OL_LIST]=Y,U[s.BLOCKS.UL_LIST]=Y,U[s.BLOCKS.LIST_ITEM]=re(a([],l,!0).sort()),U[s.BLOCKS.TABLE]=re(function(){return{nodeTypes:[s.BLOCKS.TABLE_ROW],min:1}}),U[s.BLOCKS.TABLE_ROW]=re(function(){return{nodeTypes:[s.BLOCKS.TABLE_CELL,s.BLOCKS.TABLE_HEADER_CELL],min:1}}),U[s.BLOCKS.TABLE_CELL]=le,U[s.BLOCKS.TABLE_HEADER_CELL]=le,U[s.INLINES.HYPERLINK]=new Z,U[s.INLINES.EMBEDDED_ENTRY]=B,U[s.INLINES.EMBEDDED_RESOURCE]=F("Contentful:Entry",I),U[s.INLINES.ENTRY_HYPERLINK]=F("Entry",["text"]),U[s.INLINES.ASSET_HYPERLINK]=F("Asset",["text"]),U[s.INLINES.RESOURCE_HYPERLINK]=F("Contentful:Entry",["text"]),U);function ue(S,O){if(S.nodeType==="text")return K(S,O);var R=ce[S.nodeType].assert(S,O);if(R.length>0)return R;var E=new T(S,O);return E.each("content",function(A,$){return ue(A,$)}),E.errors}var ae=function(S){var O=new ne,R=new T(S,O);return R.object()&&R.enum("nodeType",[s.BLOCKS.DOCUMENT]),R.errors.length>0?R.errors:ue(S,O)};s.CONTAINERS=u,s.EMPTY_DOCUMENT=v,s.HEADINGS=h,s.LIST_ITEM_BLOCKS=l,s.TABLE_BLOCKS=d,s.TEXT_CONTAINERS=f,s.TOP_LEVEL_BLOCKS=o,s.V1_MARKS=x,s.V1_NODE_TYPES=g,s.VOID_BLOCKS=c,s.helpers=D,s.validateRichTextDocument=ae})(Te);var se=b,X=Te,pt=function(){return pt=Object.assign||function(e){for(var r,n=1,a=arguments.length;n<a;n++){r=arguments[n];for(var i in r)Object.prototype.hasOwnProperty.call(r,i)&&(e[i]=r[i])}return e},pt.apply(this,arguments)};function Sc(s,e){return se.isValidElement(s)&&s.key===null?se.cloneElement(s,{key:e}):s}function kc(s,e){return s.map(function(r,n){return Sc(Wn(r,e),n)})}function Wn(s,e){var r=e.renderNode,n=e.renderMark,a=e.renderText,i=e.preserveWhitespace;if(X.helpers.isText(s)){var o=a?a(s.value):s.value;if(i&&!a){o=o.replace(/ {2,}/g,function(u){return" ".repeat(u.length)});var l=o.split(` `),d=[];l.forEach(function(u,h){d.push(u),h!==l.length-1&&d.push(se.createElement("br",null))}),o=d}return s.marks.reduce(function(u,h){return n[h.type]?n[h.type](u):u},o)}else{var c=kc(s.content,e);return!s.nodeType||!r[s.nodeType]?se.createElement(se.Fragment,null,c):r[s.nodeType](s,c)}}var ie,He,Ec=(ie={},ie[X.BLOCKS.DOCUMENT]=function(s,e){return e},ie[X.BLOCKS.PARAGRAPH]=function(s,e){return se.createElement("p",null,e)},ie[X.BLOCKS.HEADING_1]=function(s,e){return se.createElement("h1",null,e)},ie[X.BLOCKS.HEADING_2]=function(s,e){return se.createElement("h2",null,e)},ie[X.BLOCKS.HEADING_3]=function(s,e){return se.createElement("h3",null,e)},ie[X.BLOCKS.HEADING_4]=function(s,e){return se.createElement("h4",null,e)},ie[X.BLOCKS.HEADING_5]=function(s,e){return se.createElement("h5",null,e)},ie[X.BLOCKS.HEADING_6]=function(s,e){return se.createElement("h6",null,e)},ie[X.BLOCKS.EMBEDDED_ENTRY]=function(s,e){return se.createElement("div",null,e)},ie[X.BLOCKS.EMBEDDED_RESOURCE]=function(s,e){return se.createElement("div",null,e)},ie[X.BLOCKS.UL_LIST]=function(s,e){return se.createElement("ul",null,e)},ie[X.BLOCKS.OL_LIST]=function(s,e){return se.createElement("ol",null,e)},ie[X.BLOCKS.LIST_ITEM]=function(s,e){return se.createElement("li",null,e)},ie[X.BLOCKS.QUOTE]=function(s,e){return se.createElement("blockquote",null,e)},ie[X.BLOCKS.HR]=function(){return se.createElement("hr",null)},ie[X.BLOCKS.TABLE]=function(s,e){return se.createElement("table",null,se.createElement("tbody",null,e))},ie[X.BLOCKS.TABLE_ROW]=function(s,e){return se.createElement("tr",null,e)},ie[X.BLOCKS.TABLE_HEADER_CELL]=function(s,e){return se.createElement("th",null,e)},ie[X.BLOCKS.TABLE_CELL]=function(s,e){return se.createElement("td",null,e)},ie[X.INLINES.ASSET_HYPERLINK]=function(s){return Cs(X.INLINES.ASSET_HYPERLINK,s)},ie[X.INLINES.ENTRY_HYPERLINK]=function(s){return Cs(X.INLINES.ENTRY_HYPERLINK,s)},ie[X.INLINES.RESOURCE_HYPERLINK]=function(s){return Hr(X.INLINES.RESOURCE_HYPERLINK,s)},ie[X.INLINES.EMBEDDED_ENTRY]=function(s){return Cs(X.INLINES.EMBEDDED_ENTRY,s)},ie[X.INLINES.EMBEDDED_RESOURCE]=function(s,e){return Hr(X.INLINES.EMBEDDED_RESOURCE,s)},ie[X.INLINES.HYPERLINK]=function(s,e){return se.createElement("a",{href:s.data.uri},e)},ie),Tc=(He={},He[X.MARKS.BOLD]=function(s){return se.createElement("b",null,s)},He[X.MARKS.ITALIC]=function(s){return se.createElement("i",null,s)},He[X.MARKS.UNDERLINE]=function(s){return se.createElement("u",null,s)},He[X.MARKS.CODE]=function(s){return se.createElement("code",null,s)},He[X.MARKS.SUPERSCRIPT]=function(s){return se.createElement("sup",null,s)},He[X.MARKS.SUBSCRIPT]=function(s){return se.createElement("sub",null,s)},He[X.MARKS.STRIKETHROUGH]=function(s){return se.createElement("s",null,s)},He);function Cs(s,e){return se.createElement("span",{key:e.data.target.sys.id},"type: ",e.nodeType," id: ",e.data.target.sys.id)}function Hr(s,e){return se.createElement("span",{key:e.data.target.sys.urn},"type: ",e.nodeType," urn: ",e.data.target.sys.urn)}function Cc(s,e){return e===void 0&&(e={}),s?Wn(s,{renderNode:pt(pt({},Ec),e.renderNode),renderMark:pt(pt({},Tc),e.renderMark),renderText:e.renderText,preserveWhitespace:e.preserveWhitespace}):null}var Pc=Cc;function Ac(){var u,h;const{category:s,slug:e}=os(),r=or,n=r.find(f=>f.slug===e),a=n?r.filter(f=>f.category===n.category&&f.slug!==e).slice(0,2):[];function i(f){return new Date(f).toLocaleDateString("en-US",{year:"numeric",month:"long",day:"numeric"})}function o(f){return f.startsWith("//")?`https:${f}`:f}const l={renderNode:{[Te.BLOCKS.PARAGRAPH]:(f,g)=>t.jsx("p",{className:"mb-6 text-gray-700 leading-relaxed",children:g}),[Te.BLOCKS.HEADING_1]:(f,g)=>t.jsx("h1",{className:"text-3xl font-bold mb-6 text-gray-900",children:g}),[Te.BLOCKS.HEADING_2]:(f,g)=>t.jsx("h2",{className:"text-2xl font-semibold mb-4 text-gray-900",children:g}),[Te.BLOCKS.HEADING_3]:(f,g)=>t.jsx("h3",{className:"text-xl font-semibold mb-3 text-gray-900",children:g}),[Te.BLOCKS.UL_LIST]:(f,g)=>t.jsx("ul",{className:"list-disc pl-6 mb-6 space-y-2",children:g}),[Te.BLOCKS.OL_LIST]:(f,g)=>t.jsx("ol",{className:"list-decimal pl-6 mb-6 space-y-2",children:g}),[Te.BLOCKS.LIST_ITEM]:(f,g)=>t.jsx("li",{className:"text-gray-700 leading-relaxed",children:g}),[Te.BLOCKS.QUOTE]:(f,g)=>t.jsx("blockquote",{className:"border-l-4 border-green-600 pl-4 italic my-6 text-gray-600",children:g}),[Te.BLOCKS.EMBEDDED_ASSET]:f=>{var v,y;if(!((y=(v=f.data.target)==null?void 0:v.fields)!=null&&y.file))return null;const{file:g,title:x}=f.data.target.fields;return t.jsx("img",{src:o(g.url),alt:x||"",className:"w-full rounded-lg my-6"})},[Te.INLINES.HYPERLINK]:(f,g)=>t.jsx("a",{href:f.data.uri,target:"_blank",rel:"noopener noreferrer",className:"text-green-600 hover:text-green-700 underline",children:g})}};if(!n)return t.jsxs("div",{className:"min-h-screen flex flex-col justify-center items-center",children:[t.jsx("p",{className:"text-red-600 mb-4",children:"Post not found"}),t.jsx(ee,{to:"/blog",className:"text-green-600 hover:text-green-700",children:"Back to Blog"})]});const d=(u=n.featuredImage)!=null&&u.url?o(n.featuredImage.url):void 0,c=[{"@context":"https://schema.org","@type":"BlogPosting",headline:n.title,description:n.excerpt||"",image:d||"https://ftwlzdhkzqfuosdorgjt.supabase.co/storage/v1/object/public/playlistpartner%20public/playlistpartner%20og%20image.png",datePublished:n.publishDate||n.createdAt,dateModified:n.updatedAt||n.publishDate||n.createdAt,author:{"@type":"Organization",name:"Playlist Partner",url:window.location.origin},publisher:{"@type":"Organization",name:"Playlist Partner",logo:{"@type":"ImageObject",url:"https://ftwlzdhkzqfuosdorgjt.supabase.co/storage/v1/object/public/playlistpartner%20public//playlist%20partner%20logo%20square.png",width:"500",height:"500"}},mainEntityOfPage:{"@type":"WebPage","@id":window.location.href},articleSection:n.category||"News",inLanguage:"en-US"},{"@context":"https://schema.org","@type":"BreadcrumbList",itemListElement:[{"@type":"ListItem",position:1,name:"Home",item:window.location.origin},{"@type":"ListItem",position:2,name:"Blog",item:`${window.location.origin}/blog`},{"@type":"ListItem",position:3,name:n.title,item:window.location.href}]}];return t.jsxs(t.Fragment,{children:[t.jsx(Fe,{title:`${n.title} | PlaylistPartner`,description:n.excerpt||`Read ${n.title} on the PlaylistPartner blog`,image:d,type:"article",article:{publishedTime:n.publishDate||n.createdAt,modifiedTime:n.updatedAt||n.publishDate||n.createdAt,author:"Playlist Partner",section:n.category||"News"},structuredData:c}),t.jsxs("article",{className:"bg-white",children:[t.jsxs("div",{className:"max-w-4xl mx-auto px-4 sm:px-6 lg:px-8 py-12",children:[t.jsxs(ee,{to:"/blog",className:"inline-flex items-center gap-2 text-green-600 hover:text-green-700 mb-8",children:[t.jsx(We,{className:"w-4 h-4"}),"Back to Blog"]}),((h=n.featuredImage)==null?void 0:h.url)&&t.jsx("img",{src:o(n.featuredImage.url),alt:n.featuredImage.title||n.title,className:"w-full aspect-[3/2] object-cover rounded-lg mb-8"}),t.jsxs("header",{className:"mb-8",children:[t.jsx("h1",{className:"text-4xl md:text-5xl font-bold text-gray-900 mb-4",children:n.title}),t.jsxs("div",{className:"flex flex-wrap items-center gap-6 text-gray-600",children:[t.jsxs("div",{className:"flex items-center gap-2",children:[t.jsx(rr,{className:"w-5 h-5"}),t.jsx("span",{children:i(n.publishDate||n.createdAt)})]}),t.jsxs("div",{className:"flex items-center gap-2",children:[t.jsx(Ft,{className:"w-5 h-5"}),t.jsxs("span",{children:["By ",t.jsx(ee,{to:"/",className:"hover:text-green-600 transition-colors",children:"Playlist Partner"})]})]}),n.category&&t.jsxs("div",{className:"inline-flex items-center gap-1 px-3 py-1 bg-green-100 text-green-800 text-sm font-medium rounded-full",children:[t.jsx(Ks,{className:"w-3 h-3"}),n.category]})]})]}),t.jsx("div",{className:"prose prose-lg max-w-none mt-8 prose-ul:list-disc prose-ol:list-decimal prose-li:marker:text-gray-700",children:n.body?Pc(n.body,l):t.jsx("div",{className:"bg-gray-50 p-6 rounded-lg",children:t.jsx("p",{className:"text-gray-600",children:"No content available for this post."})})}),t.jsx("div",{className:"mt-12 pt-8 border-t border-gray-200",children:t.jsxs("div",{className:"flex items-center gap-2 text-sm text-gray-600",children:[t.jsx("span",{children:"Filed under:"}),t.jsxs("div",{className:"inline-flex items-center gap-1 px-3 py-1 bg-gray-100 rounded-full",children:[t.jsx(Ks,{className:"w-3 h-3"}),n.category||"News"]})]})})]}),a.length>0&&t.jsxs("div",{className:"max-w-4xl mx-auto px-4 sm:px-6 lg:px-8 mt-8",children:[t.jsxs("div",{className:"flex items-center gap-3 mb-8",children:[t.jsx(_l,{className:"w-6 h-6 text-gray-700"}),t.jsx("h2",{className:"text-2xl font-semibold text-gray-900",children:"Related News & Guides"})]}),t.jsx("div",{className:"grid md:grid-cols-2 gap-6 mb-16",children:a.map(f=>{var g,x;return t.jsxs(ee,{to:`/blog/${((g=f.category)==null?void 0:g.toLowerCase())||"news"}/${f.slug}`,className:"bg-white border border-gray-200 rounded-lg shadow-sm hover:shadow-md transition-shadow overflow-hidden group",children:[((x=f.featuredImage)==null?void 0:x.url)&&t.jsx("div",{className:"aspect-[3/2] overflow-hidden",children:t.jsx("img",{src:o(f.featuredImage.url),alt:f.featuredImage.title||f.title,className:"w-full h-full object-cover group-hover:scale-105 transition-transform duration-300"})}),t.jsxs("div",{className:"p-6",children:[t.jsx("h3",{className:"font-semibold text-gray-900 group-hover:text-green-600 transition-colors line-clamp-2",children:f.title}),f.excerpt&&t.jsx("p",{className:"text-sm text-gray-600 mt-2 line-clamp-2",children:f.excerpt})]})]},f.id)})})]}),t.jsx("section",{className:"bg-gradient-to-r from-green-600 to-green-700 py-12",children:t.jsxs("div",{className:"max-w-4xl mx-auto px-4 sm:px-6 lg:px-8 text-center",children:[t.jsx("h2",{className:"text-3xl font-bold text-white mb-2",children:"Ready to Submit Your Music?"}),t.jsx("p",{className:"text-xl text-green-100 mb-8",children:"Browse 10,000+ curated playlists"}),t.jsxs("div",{className:"flex flex-col sm:flex-row gap-4 justify-center",children:[t.jsx(ee,{to:"/playlists",className:"inline-flex items-center justify-center px-6 py-3 bg-white text-green-700 font-semibold rounded-lg hover:bg-gray-100 transition-colors",children:"Browse Playlists"}),t.jsxs(ee,{to:"/submit",className:"inline-flex items-center justify-center px-6 py-3 bg-green-800 text-white font-semibold rounded-lg hover:bg-green-900 transition-colors",children:["Submit Track",t.jsx(Ut,{className:"w-5 h-5 ml-2"})]})]})]})})]})]})}function Oc({children:s}){const{user:e,isAdmin:r,loading:n}=sr(),a=it();return n?t.jsx("div",{className:"min-h-screen flex items-center justify-center",children:t.jsx(me,{className:"w-8 h-8 text-green-500 animate-spin"})}):!e||!r?t.jsx(Yr,{to:"/admin/login",state:{from:a},replace:!0}):t.jsx(t.Fragment,{children:s})}function Ic(){const s=it(),e=Xe(),{signOut:r}=sr(),n=[{path:"/admin",icon:xl,label:"Dashboard"},{path:"/admin/playlists",icon:ve,label:"Playlists"},{path:"/admin/submissions",icon:yl,label:"Submissions"},{path:"/admin/genres",icon:bl,label:"Genres"},{path:"/admin/import",icon:rs,label:"Import"},{path:"/admin/settings",icon:kl,label:"Settings"}],a=async()=>{try{await r(),e("/admin/login")}catch(i){console.error("Failed to log out:",i)}};return t.jsx(Oc,{children:t.jsx("div",{className:"min-h-screen bg-gray-100",children:t.jsxs("div",{className:"flex h-screen",children:[t.jsx("div",{className:"w-64 bg-white shadow-lg",children:t.jsxs("div",{className:"h-full flex flex-col",children:[t.jsx("div",{className:"flex items-center justify-center h-16 px-4 border-b",children:t.jsx("h1",{className:"text-xl font-bold text-gray-900",children:"Admin Panel"})}),t.jsx("nav",{className:"flex-1 px-2 py-4 space-y-1",children:n.map(({path:i,icon:o,label:l})=>t.jsxs(ee,{to:i,className:`flex items-center px-4 py-2 text-sm rounded-lg ${s.pathname===i?"bg-green-50 text-green-700":"text-gray-600 hover:bg-gray-50"}`,children:[t.jsx(o,{className:"w-5 h-5 mr-3"}),l]},i))}),t.jsx("div",{className:"p-4 border-t",children:t.jsxs("button",{onClick:a,className:"flex items-center w-full px-4 py-2 text-sm text-red-600 hover:bg-red-50 rounded-lg transition-colors",children:[t.jsx(vl,{className:"w-5 h-5 mr-3"}),"Logout"]})})]})}),t.jsx("div",{className:"flex-1 overflow-auto",children:t.jsx("div",{className:"p-8",children:t.jsx(da,{})})})]})})})}function Lc({stats:s}){const e=[{label:"Total Playlists",value:(s==null?void 0:s.totalPlaylists.toLocaleString())||"0",icon:ve}];return t.jsx("div",{className:"grid grid-cols-1 gap-6",children:e.map(r=>{const n=r.icon;return t.jsx("div",{className:"bg-white p-6 rounded-lg shadow-sm",children:t.jsxs("div",{className:"flex items-center",children:[t.jsx("div",{className:"p-2 bg-green-50 rounded-lg",children:t.jsx(n,{className:"h-6 w-6 text-green-600"})}),t.jsxs("div",{className:"ml-4",children:[t.jsx("p",{className:"text-sm font-medium text-gray-600",children:r.label}),t.jsx("p",{className:"text-2xl font-semibold text-gray-900",children:r.value})]})]})},r.label)})})}function Rc(){const{totalCount:s}=Gt({}),e={totalPlaylists:s};return t.jsxs("div",{children:[t.jsx("h1",{className:"text-2xl font-bold text-gray-900 mb-8",children:"Dashboard"}),t.jsx(Lc,{stats:e})]})}function Dc({playlist:s,onClose:e,onSuccess:r}){const{genres:n,loading:a}=Be(),[i,o]=b.useState({spotifyUrl:s?`https://open.spotify.com/playlist/${s.spotify_id}`:"",name:(s==null?void 0:s.name)||"",description:(s==null?void 0:s.description)||"",imageUrl:(s==null?void 0:s.image_url)||"",genre:(s==null?void 0:s.genre_id)||"",subGenres:(s==null?void 0:s.sub_genre_ids)||[],followers:(s==null?void 0:s.followers)||0,curatorName:(s==null?void 0:s.curator_name)||"",curatorProfileUrl:(s==null?void 0:s.curator_profile_url)||"",featured:(s==null?void 0:s.featured)||!1}),[l,d]=b.useState(!1),[c,u]=b.useState(null),[h,f]=b.useState(!1),g=n.find(y=>y.id===i.genre),x=async y=>{if(o(w=>({...w,spotifyUrl:y})),!(!y||s)){d(!0),u(null);try{const w=jt(y,"playlist");if(!w)throw new Error("Invalid Spotify playlist URL");const P=await ur(w);if(!P)throw new Error("Playlist not found on Spotify");o(C=>{var D,k,N,j,m;return{...C,name:P.name,description:P.description||C.description,imageUrl:((D=P.images[0])==null?void 0:D.url)||C.imageUrl,followers:((k=P.followers)==null?void 0:k.total)||0,curatorName:((N=P.owner)==null?void 0:N.display_name)||C.curatorName,curatorProfileUrl:((m=(j=P.owner)==null?void 0:j.external_urls)==null?void 0:m.spotify)||C.curatorProfileUrl}})}catch(w){console.error("Failed to fetch Spotify data:",w),u(w instanceof Error?w.message:"Failed to fetch playlist data from Spotify")}finally{d(!1)}}},v=async y=>{y.preventDefault(),f(!0),u(null);try{if(!i.spotifyUrl||!i.name||!i.genre)throw new Error("Please fill in all required fields");if(!i.genre.match(/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/))throw new Error("Invalid genre selected");const w=jt(i.spotifyUrl,"playlist");if(!w)throw new Error("Invalid Spotify playlist URL");const P={spotify_id:w,name:i.name,description:i.description,image_url:i.imageUrl,genre_id:i.genre,sub_genre_ids:i.subGenres,followers:i.followers,curator_name:i.curatorName||null,curator_profile_url:i.curatorProfileUrl||null,featured:i.featured};r(P)}catch(w){console.error("Failed to save playlist:",w),u(w instanceof Error?w.message:"Failed to save playlist"),f(!1)}};return t.jsx("div",{className:"fixed inset-0 bg-black bg-opacity-50 flex items-center justify-center p-4 z-50",children:t.jsxs("div",{className:"bg-white rounded-xl max-w-2xl w-full max-h-[90vh] overflow-y-auto",children:[t.jsx("div",{className:"p-6 border-b border-gray-200",children:t.jsxs("div",{className:"flex justify-between items-center",children:[t.jsx("h2",{className:"text-xl font-bold text-gray-900",children:s?"Edit Playlist":"Add New Playlist"}),t.jsx("button",{onClick:e,className:"text-gray-400 hover:text-gray-500 transition-colors",children:t.jsx(we,{className:"w-6 h-6"})})]})}),t.jsxs("form",{onSubmit:v,className:"p-6 space-y-4",children:[t.jsxs("div",{children:[t.jsxs("label",{className:"flex gap-2 text-sm font-medium text-gray-700 mb-1",children:[t.jsx(Hs,{className:"w-4 h-4"}),"Spotify Playlist URL"]}),s?t.jsx("input",{type:"text",value:i.spotifyUrl,readOnly:!0,className:"w-full p-2 border border-gray-300 rounded-lg bg-gray-50 text-gray-500"}):t.jsx("input",{type:"text",value:i.spotifyUrl,onChange:y=>x(y.target.value),placeholder:"https://open.spotify.com/playlist/...",className:"w-full p-2 border border-gray-300 rounded-lg focus:ring-2 focus:ring-green-500 focus:border-transparent",required:!0})]}),t.jsxs("div",{className:"grid grid-cols-2 gap-4",children:[t.jsxs("div",{children:[t.jsxs("label",{className:"flex gap-2 text-sm font-medium text-gray-700 mb-1",children:[t.jsx(ve,{className:"w-4 h-4"}),"Name"]}),t.jsx("input",{type:"text",value:i.name,onChange:y=>o(w=>({...w,name:y.target.value})),className:"w-full p-2 border border-gray-300 rounded-lg focus:ring-2 focus:ring-green-500 focus:border-transparent",required:!0})]}),t.jsxs("div",{children:[t.jsxs("label",{className:"flex gap-2 text-sm font-medium text-gray-700 mb-1",children:[t.jsx(qt,{className:"w-4 h-4"}),"Followers"]}),t.jsx("input",{type:"number",value:i.followers,onChange:y=>o(w=>({...w,followers:parseInt(y.target.value)||0})),className:"w-full p-2 border border-gray-300 rounded-lg focus:ring-2 focus:ring-green-500 focus:border-transparent",required:!0})]})]}),t.jsxs("div",{children:[t.jsx("label",{className:"block text-sm font-medium text-gray-700 mb-1",children:"Description"}),t.jsx("textarea",{value:i.description,onChange:y=>o(w=>({...w,description:y.target.value})),rows:3,className:"w-full p-2 border border-gray-300 rounded-lg focus:ring-2 focus:ring-green-500 focus:border-transparent",required:!0})]}),t.jsxs("div",{children:[t.jsx("label",{className:"block text-sm font-medium text-gray-700 mb-1",children:"Genre"}),t.jsxs("select",{value:i.genre,onChange:y=>o(w=>({...w,genre:y.target.value,subGenres:[]})),className:"w-full p-2 border border-gray-300 rounded-lg focus:ring-2 focus:ring-green-500 focus:border-transparent",required:!0,disabled:a,children:[t.jsx("option",{value:"",children:"Select a genre"}),n.map(y=>t.jsx("option",{value:y.id,children:y.name},y.id))]})]}),g&&g.subGenres.length>0&&t.jsxs("div",{children:[t.jsx("label",{className:"block text-sm font-medium text-gray-700 mb-1",children:"Sub-genres"}),t.jsx("div",{className:"space-y-2",children:g.subGenres.map(y=>t.jsxs("label",{className:"flex items-center gap-2",children:[t.jsx("input",{type:"checkbox",checked:i.subGenres.includes(y.id),onChange:w=>{w.target.checked?o(P=>({...P,subGenres:[...P.subGenres,y.id]})):o(P=>({...P,subGenres:P.subGenres.filter(C=>C!==y.id)}))},className:"rounded border-gray-300 text-green-600 focus:ring-green-500"}),t.jsx("span",{className:"text-sm text-gray-700",children:y.name})]},y.id))})]}),t.jsxs("div",{className:"grid grid-cols-2 gap-4",children:[t.jsxs("div",{children:[t.jsxs("label",{className:"flex gap-2 text-sm font-medium text-gray-700 mb-1",children:[t.jsx(Ft,{className:"w-4 h-4"}),"Curator Name"]}),t.jsx("input",{type:"text",value:i.curatorName,onChange:y=>o(w=>({...w,curatorName:y.target.value})),className:"w-full p-2 border border-gray-300 rounded-lg focus:ring-2 focus:ring-green-500 focus:border-transparent"})]}),t.jsxs("div",{children:[t.jsxs("label",{className:"flex gap-2 text-sm font-medium text-gray-700 mb-1",children:[t.jsx(Hs,{className:"w-4 h-4"}),"Curator Profile URL"]}),t.jsx("input",{type:"text",value:i.curatorProfileUrl,onChange:y=>o(w=>({...w,curatorProfileUrl:y.target.value})),className:"w-full p-2 border border-gray-300 rounded-lg focus:ring-2 focus:ring-green-500 focus:border-transparent"})]})]}),t.jsxs("div",{children:[t.jsxs("label",{className:"flex items-center gap-2",children:[t.jsx("input",{type:"checkbox",checked:i.featured,onChange:y=>o(w=>({...w,featured:y.target.checked})),className:"rounded border-gray-300 text-green-600 focus:ring-green-500"}),t.jsx("span",{className:"text-sm font-medium text-gray-700",children:"Featured Playlist"})]}),t.jsx("p",{className:"text-sm text-gray-500 mt-1",children:"Featured playlists appear first in the default sort order"})]}),c&&t.jsxs("div",{className:"flex items-center gap-2 text-red-600 text-sm",children:[t.jsx(fe,{className:"w-4 h-4 flex-shrink-0"}),t.jsx("p",{children:c})]}),t.jsxs("div",{className:"flex justify-end gap-3 pt-4",children:[t.jsx("button",{type:"button",onClick:e,className:"px-4 py-2 text-gray-700 hover:bg-gray-100 rounded-lg transition-colors",children:"Cancel"}),t.jsxs("button",{type:"submit",disabled:h||l,className:"px-4 py-2 bg-green-500 text-white rounded-lg hover:bg-green-600 disabled:bg-gray-400 disabled:cursor-not-allowed flex items-center gap-2",children:[(h||l)&&t.jsx(me,{className:"w-5 h-5 animate-spin"}),h?"Saving...":"Save Playlist"]})]})]})]})})}function $c({isOpen:s,onClose:e,onComplete:r}){const[n,a]=b.useState(!1),[i,o]=b.useState(null),[l,d]=b.useState(null),c=b.useRef(null),u=async()=>{var f;a(!0),o(null),c.current=new AbortController;try{const{data:g,error:x}=await W.from("playlists").select("id, spotify_id").order("created_at",{ascending:!1});if(x)throw x;if(!g||g.length===0)throw new Error("No playlists found to sync");d({current:0,total:g.length,updated:0,failed:0});const v=10;for(let y=0;y<g.length;y+=v){if((f=c.current)!=null&&f.signal.aborted)throw new Error("Sync cancelled");const w=g.slice(y,Math.min(y+v,g.length)),P=await Promise.allSettled(w.map(async k=>{var N,j,m,p,_,T;try{const I=await ur(k.spotify_id);if(!I)throw new Error("Playlist not found on Spotify");return{id:k.id,name:I.name,description:I.description||"",image_url:((N=I.images[0])==null?void 0:N.url)||"",followers:((j=I.followers)==null?void 0:j.total)||0,track_count:((m=I.tracks)==null?void 0:m.total)||0,curator_name:((p=I.owner)==null?void 0:p.display_name)||null,curator_profile_url:((T=(_=I.owner)==null?void 0:_.external_urls)==null?void 0:T.spotify)||null,updated_at:new Date().toISOString()}}catch(I){throw console.error(`Failed to fetch playlist ${k.spotify_id}:`,I),I}}));let C=0,D=0;for(const k of P)if(k.status==="fulfilled"){const{error:N}=await W.from("playlists").update(k.value).eq("id",k.value.id);N?(console.error("Failed to update playlist:",N),D++):C++}else D++;d(k=>k?{...k,current:Math.min(y+v,g.length),updated:k.updated+C,failed:k.failed+D}:null),y+v<g.length&&await new Promise(k=>setTimeout(k,1e3))}r()}catch(g){console.error("Sync failed:",g),g instanceof Error&&g.message==="Sync cancelled"?o("Sync cancelled"):o(g instanceof Error?g.message:"Failed to sync playlists")}finally{a(!1),c.current=null}},h=()=>{var f;n?(f=c.current)==null||f.abort():e()};return s?t.jsx("div",{className:"fixed inset-0 bg-black bg-opacity-50 flex items-center justify-center p-4 z-50",children:t.jsxs("div",{className:"bg-white rounded-xl max-w-lg w-full",children:[t.jsx("div",{className:"p-6 border-b border-gray-200",children:t.jsxs("div",{className:"flex justify-between items-center",children:[t.jsx("h2",{className:"text-xl font-bold text-gray-900",children:"Sync Playlists"}),t.jsx("button",{onClick:h,className:"text-gray-400 hover:text-gray-500 transition-colors",children:t.jsx(we,{className:"w-6 h-6"})})]})}),t.jsxs("div",{className:"p-6 space-y-4",children:[!n&&!i&&t.jsx("p",{className:"text-gray-600",children:"This will update playlist metadata including artwork, description, curator details, follower count, and track count from Spotify."}),l&&t.jsxs("div",{className:"space-y-3",children:[t.jsxs("div",{className:"flex items-center justify-between text-sm text-gray-600",children:[t.jsx("span",{children:"Processing playlists..."}),t.jsxs("span",{children:[l.current," of ",l.total]})]}),t.jsx("div",{className:"w-full h-2 bg-gray-100 rounded-full overflow-hidden",children:t.jsx("div",{className:"h-full bg-green-500 transition-all duration-300",style:{width:`${l.current/l.total*100}%`}})}),t.jsxs("div",{className:"flex gap-4 text-sm",children:[t.jsxs("span",{className:"flex items-center gap-1 text-green-600",children:[t.jsx(nt,{className:"w-4 h-4"}),l.updated," updated"]}),l.failed>0&&t.jsxs("span",{className:"flex items-center gap-1 text-red-600",children:[t.jsx(fe,{className:"w-4 h-4"}),l.failed," failed"]})]})]}),i&&t.jsxs("div",{className:"flex items-center gap-2 text-red-600 bg-red-50 p-3 rounded-lg",children:[t.jsx(fe,{className:"w-5 h-5 flex-shrink-0"}),t.jsx("p",{children:i})]}),t.jsxs("div",{className:"flex justify-end gap-3 pt-4",children:[t.jsx("button",{onClick:h,className:"px-4 py-2 text-gray-700 hover:bg-gray-100 rounded-lg transition-colors",children:n?"Cancel":"Close"}),!n&&t.jsxs("button",{onClick:u,className:"flex items-center gap-2 px-4 py-2 bg-green-500 text-white rounded-lg hover:bg-green-600 transition-colors",children:[t.jsx(wt,{className:"w-5 h-5"}),"Start Sync"]})]})]})]})}):null}function Uc(){const[s,e]=b.useState([]),[r,n]=b.useState(!0),[a,i]=b.useState(null),o=async h=>{try{n(!0),i(null);let f=W.from("playlists").select(` *, genres ( id, name, slug ) `);switch(h==null?void 0:h.sortBy){case"followers_asc":f=f.order("followers",{ascending:!0});break;case"followers_desc":f=f.order("followers",{ascending:!1});break;case"featured_desc":f=f.order("featured",{ascending:!1}).order("followers",{ascending:!1});break;default:f=f.order("created_at",{ascending:!1})}const{data:g,error:x}=await f;if(x)throw x;const{data:v,error:y}=await W.from("sub_genres").select("*");if(y)throw y;const w=g.map(P=>({...P,sub_genres:P.sub_genre_ids?P.sub_genre_ids.map(C=>{var D;return(D=v.find(k=>k.id===C))==null?void 0:D.name}).filter(Boolean):[]}));e(w)}catch(f){console.error("Failed to fetch playlists:",f),i(f instanceof Error?f:new Error("Failed to fetch playlists"))}finally{n(!1)}};return b.useEffect(()=>{o()},[]),{playlists:s,loading:r,error:a,refresh:o,createPlaylist:async h=>{try{const{data:f,error:g}=await W.from("playlists").insert([{spotify_id:h.spotify_id,name:h.name,description:h.description,image_url:h.image_url,genre_id:h.genre_id,sub_genre_ids:h.sub_genre_ids||[],followers:h.followers,curator_name:h.curator_name||null,curator_profile_url:h.curator_profile_url||null,created_at:new Date().toISOString(),updated_at:new Date().toISOString()}]).select(` *, genres ( id, name, slug ) `).single();if(g)throw g;const{data:x}=await W.from("sub_genres").select("*").in("id",h.sub_genre_ids||[]),v={...f,sub_genres:(x==null?void 0:x.map(y=>y.name))||[]};return e(y=>[v,...y]),v}catch(f){throw console.error("Failed to create playlist:",f),f}},updatePlaylist:async(h,f)=>{try{const{data:g,error:x}=await W.from("playlists").update({...f,updated_at:new Date().toISOString()}).eq("id",h).select(` *, genres ( id, name, slug ) `).single();if(x)throw x;let v=[];if(f.sub_genre_ids){const{data:w}=await W.from("sub_genres").select("*").in("id",f.sub_genre_ids);v=(w==null?void 0:w.map(P=>P.name))||[]}const y={...g,sub_genres:v};return e(w=>w.map(P=>P.id===h?y:P)),y}catch(g){throw console.error("Failed to update playlist:",g),g}},deletePlaylist:async h=>{try{const{error:f}=await W.from("playlists").delete().eq("id",h);if(f)throw f;e(g=>g.filter(x=>x.id!==h))}catch(f){throw console.error("Failed to delete playlist:",f),f}},toggleFeatured:async(h,f)=>{try{const{error:g}=await W.from("playlists").update({featured:f}).eq("id",h);if(g)throw g;e(x=>x.map(v=>v.id===h?{...v,featured:f}:v))}catch(g){throw console.error("Failed to update featured status:",g),g}}}}function Mc(){const[s,e]=b.useState(!1),[r,n]=b.useState(!1),[a,i]=b.useState(null),[o,l]=b.useState(null),[d,c]=b.useState({search:"",genre:"",status:"",sortBy:"created_at_desc"}),{playlists:u,loading:h,error:f,refresh:g,createPlaylist:x,updatePlaylist:v,deletePlaylist:y,toggleFeatured:w}=Uc(),P=()=>{n(!1),l({type:"success",message:"Playlists synced successfully"}),g()},C=async j=>{try{a?(await v(a.id,j),l({type:"success",message:"Playlist updated successfully"})):(await x(j),l({type:"success",message:"Playlist created successfully"})),e(!1),i(null),g()}catch(m){l({type:"error",message:m instanceof Error?m.message:"Failed to save playlist"})}},D=async(j,m)=>{if(window.confirm(`Are you sure you want to delete "${m}"?`))try{await y(j),l({type:"success",message:`${m} has been deleted`}),g()}catch{l({type:"error",message:"Failed to delete playlist"})}},k=async(j,m)=>{try{await w(j,!m),l({type:"success",message:`Playlist ${m?"removed from":"added to"} featured list`})}catch{l({type:"error",message:"Failed to update featured status"})}},N=u.filter(j=>!(d.search&&!j.name.toLowerCase().includes(d.search.toLowerCase())||d.genre&&j.genre_id!==d.genre||d.status==="claimed"&&!j.claimed||d.status==="unclaimed"&&j.claimed));return f?t.jsx("div",{className:"p-8 text-center",children:t.jsxs("div",{className:"flex items-center justify-center gap-2 text-red-600",children:[t.jsx(fe,{className:"w-5 h-5"}),t.jsx("p",{children:"Failed to load playlists"})]})}):t.jsxs("div",{className:"container mx-auto px-4 py-8",children:[t.jsxs("div",{className:"flex justify-between items-center mb-6",children:[t.jsx("h1",{className:"text-2xl font-bold",children:"Playlists"}),t.jsxs("div",{className:"flex gap-3",children:[t.jsxs("button",{onClick:()=>n(!0),className:"flex items-center gap-2 bg-blue-500 text-white px-4 py-2 rounded-lg hover:bg-blue-600",children:[t.jsx(wt,{className:"w-5 h-5"}),"Sync"]}),t.jsxs("button",{onClick:()=>e(!0),className:"flex items-center gap-2 bg-green-500 text-white px-4 py-2 rounded-lg hover:bg-green-600",children:[t.jsx(nr,{className:"w-5 h-5"}),"Add Playlist"]})]})]}),t.jsx("div",{className:"bg-white p-4 rounded-lg shadow-sm mb-6",children:t.jsxs("div",{className:"grid grid-cols-1 md:grid-cols-4 gap-4",children:[t.jsxs("div",{className:"relative",children:[t.jsx(ps,{className:"absolute left-3 top-1/2 transform -translate-y-1/2 text-gray-400 w-5 h-5"}),t.jsx("input",{type:"text",placeholder:"Search playlists...",value:d.search,onChange:j=>c({...d,search:j.target.value}),className:"w-full pl-10 pr-4 py-2 border border-gray-300 rounded-lg"})]}),t.jsxs("select",{value:d.genre,onChange:j=>c({...d,genre:j.target.value}),className:"border border-gray-300 rounded-lg px-4 py-2",children:[t.jsx("option",{value:"",children:"All Genres"}),Array.from(new Set(u.map(j=>j.genre_id))).map(j=>{var p;const m=(p=u.find(_=>_.genre_id===j))==null?void 0:p.genres;return m?t.jsx("option",{value:m.id,children:m.name},m.id):null})]}),t.jsxs("select",{value:d.status,onChange:j=>c({...d,status:j.target.value}),className:"border border-gray-300 rounded-lg px-4 py-2",children:[t.jsx("option",{value:"",children:"Claimed / Unclaimed"}),t.jsx("option",{value:"claimed",children:"Claimed"}),t.jsx("option",{value:"unclaimed",children:"Unclaimed"})]}),t.jsxs("select",{value:d.sortBy,onChange:j=>{c({...d,sortBy:j.target.value}),g({...d,sortBy:j.target.value})},className:"border border-gray-300 rounded-lg px-4 py-2",children:[t.jsx("option",{value:"created_at_desc",children:"Latest First"}),t.jsx("option",{value:"featured_desc",children:"Featured First"}),t.jsx("option",{value:"followers_desc",children:"Most Followers"}),t.jsx("option",{value:"followers_asc",children:"Least Followers"})]})]})}),t.jsx("div",{className:"bg-white rounded-lg shadow-sm overflow-hidden",children:t.jsxs("table",{className:"w-full",children:[t.jsx("thead",{children:t.jsxs("tr",{className:"bg-gray-50",children:[t.jsx("th",{className:"px-6 py-3 text-left text-sm font-medium text-gray-500",children:"Name"}),t.jsx("th",{className:"px-6 py-3 text-left text-sm font-medium text-gray-500",children:"Genre"}),t.jsx("th",{className:"px-6 py-3 text-left text-sm font-medium text-gray-500",children:"Sub-genres"}),t.jsx("th",{className:"px-6 py-3 text-left text-sm font-medium text-gray-500",children:"Curator"}),t.jsx("th",{className:"px-6 py-3 text-left text-sm font-medium text-gray-500",children:"Followers"}),t.jsx("th",{className:"px-6 py-3 text-left text-sm font-medium text-gray-500",children:"Claimed"}),t.jsx("th",{className:"px-6 py-3 text-left text-sm font-medium text-gray-500",children:"Actions"})]})}),t.jsx("tbody",{className:"divide-y divide-gray-200",children:h?t.jsx("tr",{children:t.jsx("td",{colSpan:7,className:"px-6 py-8 text-center",children:t.jsx(me,{className:"w-6 h-6 text-green-500 animate-spin mx-auto"})})}):N.length===0?t.jsx("tr",{children:t.jsx("td",{colSpan:7,className:"px-6 py-8 text-center text-gray-500",children:"No playlists found"})}):N.map(j=>{var m,p;return t.jsxs("tr",{className:"hover:bg-gray-50",children:[t.jsx("td",{className:"px-6 py-4",children:t.jsxs("div",{className:"flex items-center",children:[t.jsx("img",{src:j.image_url,alt:j.name,className:"w-10 h-10 rounded-sm object-cover mr-3"}),t.jsx("span",{className:"font-medium",children:j.name})]})}),t.jsx("td",{className:"px-6 py-4",children:(m=j.genres)==null?void 0:m.name}),t.jsx("td",{className:"px-6 py-4",children:(p=j.sub_genres)==null?void 0:p.map(_=>t.jsx("span",{className:"inline-block px-2 py-1 bg-gray-100 text-gray-700 text-xs rounded-full mr-1 mb-1",children:_},_))}),t.jsx("td",{className:"px-6 py-4",children:j.curator_name||"Unclaimed"}),t.jsx("td",{className:"px-6 py-4",children:Cl(j.followers)}),t.jsx("td",{className:"px-6 py-4",children:t.jsx("span",{className:`inline-flex items-center px-2.5 py-0.5 rounded-full text-xs font-medium ${j.claimed?"bg-green-100 text-green-800":"bg-yellow-100 text-yellow-800"}`,children:j.claimed?"Claimed":"Unclaimed"})}),t.jsx("td",{className:"px-6 py-4",children:t.jsxs("div",{className:"flex items-center gap-2",children:[t.jsx("button",{onClick:()=>k(j.id,j.featured),className:"p-1 hover:bg-gray-100 rounded",title:j.featured?"Remove from featured":"Add to featured",children:t.jsx(ar,{className:`w-4 h-4 ${j.featured?"text-yellow-400 fill-yellow-400":"text-gray-400"}`})}),t.jsx("button",{onClick:()=>i(j),className:"p-1 hover:bg-gray-100 rounded",children:t.jsx($n,{className:"w-4 h-4 text-gray-500"})}),t.jsx("button",{onClick:()=>D(j.id,j.name),className:"p-1 hover:bg-gray-100 rounded",children:t.jsx(ir,{className:"w-4 h-4 text-red-500"})})]})})]},j.id)})})]})}),(s||a)&&t.jsx(Dc,{playlist:a,onClose:()=>{e(!1),i(null)},onSuccess:C}),r&&t.jsx($c,{isOpen:r,onClose:()=>n(!1),onComplete:P}),o&&t.jsx(qe,{message:o.message,type:o.type,onClose:()=>l(null)})]})}function Bc(s){const[e,r]=b.useState([]),[n,a]=b.useState(0),[i,o]=b.useState(!0),[l,d]=b.useState(null);return b.useEffect(()=>{async function u(){try{o(!0),d(null);const h=s?await Xt.getForPlaylist(s):await Xt.getAll();r(h),a(h.length)}catch(h){console.error("Failed to fetch submissions:",h),d(h instanceof Error?h:new Error("Failed to fetch submissions"))}finally{o(!1)}}u()},[s]),{submissions:e,totalCount:n,loading:i,error:l,updateStatus:async(u,h)=>{try{const f=await Xt.updateStatus(u,h);return r(g=>g.map(x=>x.id===u?{...x,...f}:x)),f}catch(f){throw console.error("Failed to update submission status:",f),f}}}}function Fc({submission:s,onClose:e}){var r;return t.jsx("div",{className:"fixed inset-0 bg-black bg-opacity-50 flex items-center justify-center p-4 z-50",children:t.jsxs("div",{className:"bg-white rounded-lg max-w-2xl w-full p-6",children:[t.jsxs("div",{className:"flex justify-between items-center mb-6",children:[t.jsx("h3",{className:"text-xl font-semibold",children:"Submission Details"}),t.jsx("button",{onClick:e,className:"text-gray-500 hover:text-gray-700",children:t.jsx(we,{className:"w-5 h-5"})})]}),t.jsxs("div",{className:"space-y-6",children:[t.jsxs("div",{children:[t.jsx("h4",{className:"text-sm font-medium text-gray-500 mb-2",children:"Track Information"}),t.jsxs("div",{className:"bg-gray-50 p-4 rounded-lg space-y-3",children:[t.jsxs("div",{className:"flex items-center gap-2",children:[t.jsx(ve,{className:"w-4 h-4 text-gray-400"}),t.jsx("span",{className:"font-medium",children:s.track_name})]}),t.jsx("div",{className:"flex items-center gap-2",children:t.jsxs("a",{href:s.track_url,target:"_blank",rel:"noopener noreferrer",className:"text-green-600 hover:text-green-700 flex items-center gap-1",children:[t.jsx(fl,{className:"w-4 h-4"}),"Open in Spotify"]})})]})]}),t.jsxs("div",{children:[t.jsx("h4",{className:"text-sm font-medium text-gray-500 mb-2",children:"Artist & Contact"}),t.jsxs("div",{className:"bg-gray-50 p-4 rounded-lg space-y-3",children:[t.jsxs("p",{children:[t.jsx("span",{className:"font-medium",children:"Artist Name:"})," ",s.artist_name]}),t.jsxs("div",{className:"flex items-center gap-2",children:[t.jsx(Ln,{className:"w-4 h-4 text-gray-400"}),t.jsx("a",{href:`mailto:${s.email}`,className:"text-green-600 hover:text-green-700",children:s.email})]})]})]}),t.jsxs("div",{children:[t.jsx("h4",{className:"text-sm font-medium text-gray-500 mb-2",children:"Playlist"}),t.jsx("div",{className:"bg-gray-50 p-4 rounded-lg",children:t.jsxs("div",{className:"flex items-center gap-2",children:[t.jsx(In,{className:"w-4 h-4 text-gray-400"}),t.jsx("span",{className:"font-medium",children:(r=s.playlist)==null?void 0:r.name})]})})]}),s.message&&t.jsxs("div",{children:[t.jsx("h4",{className:"text-sm font-medium text-gray-500 mb-2",children:"Message"}),t.jsx("div",{className:"bg-gray-50 p-4 rounded-lg",children:t.jsx("p",{className:"text-gray-700 whitespace-pre-wrap",children:s.message})})]}),t.jsxs("div",{children:[t.jsx("h4",{className:"text-sm font-medium text-gray-500 mb-2",children:"Timestamps"}),t.jsxs("div",{className:"bg-gray-50 p-4 rounded-lg space-y-2",children:[t.jsxs("div",{className:"flex items-center gap-2",children:[t.jsx(ss,{className:"w-4 h-4 text-gray-400"}),t.jsxs("span",{children:["Submitted: ",new Date(s.created_at).toLocaleString()]})]}),s.reviewed_at&&t.jsxs("div",{className:"flex items-center gap-2",children:[t.jsx(ss,{className:"w-4 h-4 text-gray-400"}),t.jsxs("span",{children:["Reviewed: ",new Date(s.reviewed_at).toLocaleString()]})]})]})]})]})]})})}function qc(){const[s,e]=b.useState(null),[r,n]=b.useState(null),[a,i]=b.useState({search:"",status:"",startDate:"",endDate:""}),{submissions:o,loading:l,error:d,updateStatus:c}=Bc(),u=async(f,g)=>{try{await c(f,g),e({type:"success",message:`Submission marked as ${g}`})}catch(x){console.error("Failed to update status:",x),e({type:"error",message:"Failed to update submission status"})}},h=o.filter(f=>!(a.search&&!f.track_name.toLowerCase().includes(a.search.toLowerCase())&&!f.artist_name.toLowerCase().includes(a.search.toLowerCase())&&!f.email.toLowerCase().includes(a.search.toLowerCase())||a.status&&f.status!==a.status||a.startDate&&new Date(f.created_at)<new Date(a.startDate)||a.endDate&&new Date(f.created_at)>new Date(a.endDate)));return t.jsxs("div",{className:"container mx-auto px-4 py-8",children:[t.jsx("h1",{className:"text-2xl font-bold mb-6",children:"Submissions"}),t.jsx("div",{className:"bg-white p-4 rounded-lg shadow-sm mb-6",children:t.jsxs("div",{className:"grid grid-cols-1 md:grid-cols-2 lg:grid-cols-4 gap-4",children:[t.jsxs("div",{className:"relative",children:[t.jsx(ps,{className:"absolute left-3 top-1/2 transform -translate-y-1/2 text-gray-400 w-5 h-5"}),t.jsx("input",{type:"text",placeholder:"Search submissions...",value:a.search,onChange:f=>i({...a,search:f.target.value}),className:"w-full pl-10 pr-4 py-2 border border-gray-300 rounded-lg"})]}),t.jsxs("select",{value:a.status,onChange:f=>i({...a,status:f.target.value}),className:"border border-gray-300 rounded-lg px-4 py-2",children:[t.jsx("option",{value:"",children:"All Status"}),t.jsx("option",{value:"pending",children:"Pending"}),t.jsx("option",{value:"approved",children:"Approved"}),t.jsx("option",{value:"rejected",children:"Rejected"})]}),t.jsx("input",{type:"date",value:a.startDate,onChange:f=>i({...a,startDate:f.target.value}),className:"border border-gray-300 rounded-lg px-4 py-2",placeholder:"Start Date"}),t.jsx("input",{type:"date",value:a.endDate,onChange:f=>i({...a,endDate:f.target.value}),className:"border border-gray-300 rounded-lg px-4 py-2",placeholder:"End Date"})]})}),t.jsx("div",{className:"bg-white rounded-lg shadow-sm overflow-hidden",children:t.jsxs("table",{className:"w-full",children:[t.jsx("thead",{children:t.jsxs("tr",{className:"bg-gray-50",children:[t.jsx("th",{className:"px-6 py-3 text-left text-sm font-medium text-gray-500",children:"Track"}),t.jsx("th",{className:"px-6 py-3 text-left text-sm font-medium text-gray-500",children:"Artist"}),t.jsx("th",{className:"px-6 py-3 text-left text-sm font-medium text-gray-500",children:"Email"}),t.jsx("th",{className:"px-6 py-3 text-left text-sm font-medium text-gray-500",children:"Playlist"}),t.jsx("th",{className:"px-6 py-3 text-left text-sm font-medium text-gray-500",children:"Status"}),t.jsx("th",{className:"px-6 py-3 text-left text-sm font-medium text-gray-500",children:"Date"}),t.jsx("th",{className:"px-6 py-3 text-left text-sm font-medium text-gray-500",children:"Actions"})]})}),t.jsx("tbody",{className:"divide-y divide-gray-200",children:l?t.jsx("tr",{children:t.jsx("td",{colSpan:7,className:"px-6 py-8 text-center",children:t.jsx(me,{className:"w-6 h-6 text-green-500 animate-spin mx-auto"})})}):d?t.jsx("tr",{children:t.jsx("td",{colSpan:7,className:"px-6 py-8 text-center",children:t.jsxs("div",{className:"flex items-center justify-center gap-2 text-red-600",children:[t.jsx(fe,{className:"w-5 h-5"}),t.jsx("span",{children:"Failed to load submissions"})]})})}):h.length===0?t.jsx("tr",{children:t.jsx("td",{colSpan:7,className:"px-6 py-8 text-center text-gray-500",children:"No submissions found"})}):h.map(f=>{var g;return t.jsxs("tr",{className:"hover:bg-gray-50 cursor-pointer",onClick:()=>n(f),children:[t.jsx("td",{className:"px-6 py-4",children:t.jsx("a",{href:f.track_url,target:"_blank",rel:"noopener noreferrer",className:"text-green-600 hover:text-green-700",onClick:x=>x.stopPropagation(),children:f.track_name})}),t.jsx("td",{className:"px-6 py-4",children:f.artist_name}),t.jsx("td",{className:"px-6 py-4",children:t.jsx("a",{href:`mailto:${f.email}`,className:"text-green-600 hover:text-green-700",onClick:x=>x.stopPropagation(),children:f.email})}),t.jsx("td",{className:"px-6 py-4",children:(g=f.playlist)==null?void 0:g.name}),t.jsx("td",{className:"px-6 py-4",children:t.jsxs("span",{className:`inline-flex items-center gap-1 px-2.5 py-0.5 rounded-full text-xs font-medium ${f.status==="approved"?"bg-green-100 text-green-800":f.status==="rejected"?"bg-red-100 text-red-800":"bg-yellow-100 text-yellow-800"}`,children:[f.status==="approved"&&t.jsx(Gs,{className:"w-3 h-3"}),f.status==="rejected"&&t.jsx($r,{className:"w-3 h-3"}),f.status.charAt(0).toUpperCase()+f.status.slice(1)]})}),t.jsx("td",{className:"px-6 py-4",children:new Date(f.created_at).toLocaleDateString()}),t.jsx("td",{className:"px-6 py-4",onClick:x=>x.stopPropagation(),children:t.jsxs("div",{className:"flex gap-2",children:[f.status==="pending"&&t.jsx("button",{onClick:()=>u(f.id,"approved"),className:"p-1 text-green-600 hover:bg-green-50 rounded",title:"Approve submission",children:t.jsx(Gs,{className:"w-5 h-5"})}),(f.status==="approved"||f.status==="rejected")&&t.jsx("button",{onClick:()=>u(f.id,"pending"),className:"p-1 text-yellow-600 hover:bg-yellow-50 rounded",title:"Return to pending",children:t.jsx(pl,{className:"w-5 h-5"})}),f.status==="pending"&&t.jsx("button",{onClick:()=>u(f.id,"rejected"),className:"p-1 text-red-600 hover:bg-red-50 rounded",title:"Reject submission",children:t.jsx($r,{className:"w-5 h-5"})}),t.jsx("button",{onClick:()=>n(f),className:"p-1 text-blue-600 hover:bg-blue-50 rounded",title:"View details",children:t.jsx(Rn,{className:"w-5 h-5"})})]})})]},f.id)})})]})}),r&&t.jsx(Fc,{submission:r,onClose:()=>n(null)}),s&&t.jsx(qe,{message:s.message,type:s.type,onClose:()=>e(null)})]})}function Gc({genre:s,onClose:e,onSuccess:r}){const[n,a]=b.useState((s==null?void 0:s.name)||""),[i,o]=b.useState((s==null?void 0:s.description)||""),[l,d]=b.useState((s==null?void 0:s.subGenres.map(m=>({name:m.name,description:m.description})))||[]),[c,u]=b.useState({name:"",description:""}),[h,f]=b.useState(null),[g,x]=b.useState(!1),[v,y]=b.useState(null),{createGenre:w,updateGenre:P}=Be(),C=(m,p)=>{if(!m.name.trim())throw new Error("Sub-genre name cannot be empty");if(!m.description.trim())throw new Error("Sub-genre description cannot be empty");const _=Me(m.name);if(l.filter((I,L)=>L!==p).map(I=>Me(I.name)).includes(_))throw new Error("This sub-genre already exists")},D=async m=>{m.preventDefault(),y(null),x(!0);try{if(!n.trim())throw new Error("Genre name is required");if(!i.trim())throw new Error("Genre description is required");if(new Set(l.map(I=>Me(I.name))).size!==l.length)throw new Error("Duplicate sub-genres are not allowed");const _={name:n.trim(),description:i.trim(),subGenres:l.map(I=>({name:I.name.trim(),description:I.description.trim()}))};let T;s?T=await P(s.id,_):T=await w(_),r(T)}catch(p){console.error("Failed to save genre:",p),y(p instanceof Error?p.message:"Failed to save genre")}finally{x(!1)}},k=()=>{try{C(c),d([...l,{...c}]),u({name:"",description:""}),y(null)}catch(m){y(m instanceof Error?m.message:"Invalid sub-genre")}},N=(m,p)=>{try{const _={...l[m],...p};C(_,m);const T=[...l];T[m]=_,d(T),f(null),y(null)}catch(_){y(_ instanceof Error?_.message:"Invalid sub-genre")}},j=m=>{d(l.filter((p,_)=>_!==m)),y(null)};return t.jsx("div",{className:"fixed inset-0 bg-black bg-opacity-50 flex items-center justify-center p-4 z-50",children:t.jsxs("div",{className:"bg-white rounded-xl max-w-lg w-full max-h-[90vh] overflow-y-auto",children:[t.jsx("div",{className:"p-6 border-b border-gray-200",children:t.jsxs("div",{className:"flex justify-between items-center",children:[t.jsx("h2",{className:"text-xl font-bold text-gray-900",children:s?"Edit Genre":"Add New Genre"}),t.jsx("button",{onClick:e,className:"text-gray-400 hover:text-gray-500 transition-colors",children:t.jsx(we,{className:"w-6 h-6"})})]})}),t.jsxs("form",{onSubmit:D,className:"p-6 space-y-4",children:[t.jsxs("div",{children:[t.jsx("label",{className:"block text-sm font-medium text-gray-700 mb-1",children:"Genre Name"}),t.jsx("input",{type:"text",value:n,onChange:m=>a(m.target.value),className:"w-full p-2 border border-gray-300 rounded-lg focus:ring-2 focus:ring-green-500 focus:border-transparent",placeholder:"e.g., Hip Hop",required:!0})]}),t.jsxs("div",{children:[t.jsx("label",{className:"block text-sm font-medium text-gray-700 mb-1",children:"Description"}),t.jsx("textarea",{value:i,onChange:m=>o(m.target.value),className:"w-full p-2 border border-gray-300 rounded-lg focus:ring-2 focus:ring-green-500 focus:border-transparent",placeholder:"Describe this genre...",rows:3,required:!0})]}),t.jsxs("div",{children:[t.jsx("label",{className:"block text-sm font-medium text-gray-700 mb-1",children:"Sub-genres"}),t.jsx("div",{className:"space-y-4 mb-4",children:t.jsxs("div",{className:"grid grid-cols-1 gap-3",children:[t.jsx("input",{type:"text",value:c.name,onChange:m=>u(p=>({...p,name:m.target.value})),className:"w-full p-2 border border-gray-300 rounded-lg focus:ring-2 focus:ring-green-500 focus:border-transparent",placeholder:"Sub-genre name"}),t.jsx("textarea",{value:c.description,onChange:m=>u(p=>({...p,description:m.target.value})),className:"w-full p-2 border border-gray-300 rounded-lg focus:ring-2 focus:ring-green-500 focus:border-transparent",placeholder:"Describe this sub-genre...",rows:2}),t.jsxs("button",{type:"button",onClick:k,className:"w-full px-4 py-2 bg-green-500 text-white rounded-lg hover:bg-green-600 flex items-center justify-center gap-2",children:[t.jsx(nr,{className:"w-5 h-5"}),"Add Sub-genre"]})]})}),t.jsx("div",{className:"space-y-3",children:l.map((m,p)=>t.jsx("div",{className:"bg-gray-50 p-3 rounded-lg space-y-2",children:h===p?t.jsxs("div",{className:"space-y-2",children:[t.jsx("input",{type:"text",value:m.name,onChange:_=>N(p,{name:_.target.value}),className:"w-full p-2 border border-gray-300 rounded-lg focus:ring-2 focus:ring-green-500 focus:border-transparent"}),t.jsx("textarea",{value:m.description,onChange:_=>N(p,{description:_.target.value}),className:"w-full p-2 border border-gray-300 rounded-lg focus:ring-2 focus:ring-green-500 focus:border-transparent",rows:2}),t.jsxs("div",{className:"flex justify-end gap-2",children:[t.jsx("button",{type:"button",onClick:()=>f(null),className:"px-3 py-1 text-sm text-gray-600 hover:bg-gray-200 rounded",children:"Cancel"}),t.jsx("button",{type:"button",onClick:()=>N(p,m),className:"px-3 py-1 text-sm bg-green-500 text-white rounded hover:bg-green-600",children:"Save"})]})]}):t.jsxs("div",{children:[t.jsxs("div",{className:"flex items-center justify-between",children:[t.jsx("h4",{className:"font-medium",children:m.name}),t.jsxs("div",{className:"flex items-center gap-2",children:[t.jsx("button",{type:"button",onClick:()=>f(p),className:"p-1 hover:bg-gray-200 rounded transition-colors",title:"Edit sub-genre",children:t.jsx(Nl,{className:"w-4 h-4 text-gray-600"})}),t.jsx("button",{type:"button",onClick:()=>j(p),className:"p-1 hover:bg-red-100 rounded transition-colors",title:"Remove sub-genre",children:t.jsx(ir,{className:"w-4 h-4 text-red-500"})})]})]}),t.jsx("p",{className:"text-sm text-gray-600",children:m.description})]})},p))})]}),v&&t.jsxs("div",{className:"flex items-center gap-2 text-red-600 text-sm",children:[t.jsx(fe,{className:"w-4 h-4 flex-shrink-0"}),t.jsx("span",{children:v})]}),t.jsxs("div",{className:"flex justify-end gap-3 pt-4",children:[t.jsx("button",{type:"button",onClick:e,className:"px-4 py-2 text-gray-700 hover:bg-gray-100 rounded-lg transition-colors",children:"Cancel"}),t.jsx("button",{type:"submit",disabled:g,className:"px-4 py-2 bg-green-500 text-white rounded-lg hover:bg-green-600 disabled:bg-gray-400 disabled:cursor-not-allowed flex items-center gap-2",children:g?t.jsxs(t.Fragment,{children:[t.jsx(me,{className:"w-5 h-5 animate-spin"}),"Saving..."]}):t.jsx(t.Fragment,{children:"Save Genre"})})]})]})]})})}function Hc({id:s,name:e,description:r,subGenres:n,onEdit:a,onDelete:i}){const{attributes:o,listeners:l,setNodeRef:d,transform:c,transition:u,isDragging:h}=Zn({id:s}),f={transform:Xn.Transform.toString(c),transition:u,zIndex:h?1:void 0,opacity:h?.5:void 0};return t.jsxs("div",{ref:d,style:f,className:`bg-white p-4 rounded-lg shadow-sm ${h?"shadow-lg":""}`,children:[t.jsxs("div",{className:"flex items-center justify-between mb-4",children:[t.jsxs("div",{className:"flex items-center gap-3",children:[t.jsx("button",{className:"p-2 text-gray-400 hover:text-gray-600 cursor-grab active:cursor-grabbing",...o,...l,children:t.jsx(ml,{className:"w-5 h-5"})}),t.jsx("div",{className:"p-2 bg-green-50 rounded-lg",children:t.jsx(ve,{className:"w-5 h-5 text-green-600"})}),t.jsxs("div",{children:[t.jsx("h3",{className:"text-lg font-medium",children:e}),t.jsxs("p",{className:"text-sm text-gray-500",children:[n.length," sub-genres"]})]})]}),t.jsxs("div",{className:"flex items-center gap-2",children:[t.jsx("button",{onClick:a,className:"p-2 hover:bg-gray-100 rounded-lg transition-colors",title:"Edit genre",children:t.jsx($n,{className:"w-5 h-5 text-gray-600"})}),t.jsx("button",{onClick:i,className:"p-2 hover:bg-red-50 rounded-lg transition-colors",title:"Delete genre",children:t.jsx(ir,{className:"w-5 h-5 text-red-600"})})]})]}),t.jsx("p",{className:"text-gray-600 mb-4",children:r}),n.length>0&&t.jsx("div",{className:"ml-12 space-y-2",children:n.map(g=>t.jsxs("div",{className:"flex items-start gap-2 text-gray-600",children:[t.jsx(ul,{className:"w-4 h-4 mt-1 flex-shrink-0"}),t.jsxs("div",{children:[t.jsx("p",{className:"font-medium text-sm",children:g.name}),t.jsx("p",{className:"text-sm text-gray-500",children:g.description})]})]},g.id))})]})}function Kc(){const{genres:s,loading:e,error:r,deleteGenre:n,updateGenreOrder:a}=Be(),[i,o]=b.useState(!1),[l,d]=b.useState(null),[c,u]=b.useState(null),h=ea(mr(oa),mr(ia,{coordinateGetter:aa})),f=async x=>{const{active:v,over:y}=x;if(y&&v.id!==y.id){const w=s.findIndex(C=>C.id===v.id),P=s.findIndex(C=>C.id===y.id);try{await a(w,P),u({type:"success",message:"Genre order updated successfully"})}catch{u({type:"error",message:"Failed to update genre order"})}}},g=async(x,v)=>{if(window.confirm(`Are you sure you want to delete "${v}" and all its sub-genres?`))try{await n(x),u({type:"success",message:`${v} has been deleted`})}catch(y){u({type:"error",message:y instanceof Error?y.message:"Failed to delete genre"})}};return e?t.jsx("div",{className:"flex items-center justify-center min-h-[400px]",children:t.jsx(me,{className:"w-8 h-8 text-green-500 animate-spin"})}):r?t.jsxs("div",{className:"flex items-center justify-center min-h-[400px] text-red-600",children:[t.jsx(fe,{className:"w-6 h-6 mr-2"}),t.jsx("span",{children:"Failed to load genres"})]}):t.jsxs("div",{className:"container mx-auto px-4 py-8",children:[t.jsxs("div",{className:"flex justify-between items-center mb-6",children:[t.jsx("h1",{className:"text-2xl font-bold",children:"Genres & Sub-genres"}),t.jsxs("button",{onClick:()=>o(!0),className:"flex items-center gap-2 bg-green-500 text-white px-4 py-2 rounded-lg hover:bg-green-600",children:[t.jsx(nr,{className:"w-5 h-5"}),"Add Genre"]})]}),t.jsxs("div",{className:"space-y-4",children:[t.jsx(ta,{sensors:h,collisionDetection:sa,onDragEnd:f,children:t.jsx(ra,{items:s.map(x=>x.id),strategy:na,children:s.map(x=>t.jsx(Hc,{id:x.id,name:x.name,subGenres:x.subGenres,onEdit:()=>d({id:x.id,name:x.name,subGenres:x.subGenres}),onDelete:()=>g(x.id,x.name)},x.id))})}),s.length===0&&t.jsxs("div",{className:"text-center py-12 bg-white rounded-lg",children:[t.jsx(ve,{className:"w-12 h-12 text-gray-400 mx-auto mb-4"}),t.jsx("p",{className:"text-gray-500",children:"No genres added yet"})]})]}),(i||l)&&t.jsx(Gc,{genre:l,onClose:()=>{o(!1),d(null)},onSuccess:x=>{o(!1),d(null),u({type:"success",message:`Genre ${l?"updated":"created"} successfully`})}}),c&&t.jsx(qe,{message:c.message,type:c.type,onClose:()=>u(null)})]})}const zc=la,Vn=b.forwardRef(({className:s,...e},r)=>t.jsx(Kr,{ref:r,className:"inline-flex h-10 items-center justify-center rounded-lg bg-gray-100 p-1 text-gray-500 mb-4",...e}));Vn.displayName=Kr.displayName;const Vs=b.forwardRef(({className:s,...e},r)=>t.jsx(zr,{ref:r,className:"inline-flex items-center justify-center whitespace-nowrap rounded-md px-3 py-1.5 text-sm font-medium ring-offset-white transition-all focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-gray-400 focus-visible:ring-offset-2 disabled:pointer-events-none disabled:opacity-50 data-[state=active]:bg-white data-[state=active]:text-gray-950 data-[state=active]:shadow-sm",...e}));Vs.displayName=zr.displayName;const Js=b.forwardRef(({className:s,...e},r)=>t.jsx(Wr,{ref:r,className:"mt-2 ring-offset-white focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-gray-400 focus-visible:ring-offset-2",...e}));Js.displayName=Wr.displayName;function Wc({onSuccess:s}){const[e,r]=b.useState(!1),[n,a]=b.useState(null),[i,o]=b.useState(null),[l,d]=b.useState(null),[c,u]=b.useState(null),h=async()=>{if(!i||!l){a("Please select both genre and sub-genre files");return}r(!0),a(null),u({stage:"Reading files",current:0,total:2});try{const v=(await i.text()).split(` `),y=v[0].split(",").map(L=>L.trim()),P=["Name","Slug","Description"].filter(L=>!y.includes(L));if(P.length>0)throw new Error(`Missing required columns in genres file: ${P.join(", ")}`);const C=[];for(let L=1;L<v.length;L++){if(!v[L].trim())continue;const H=v[L].split(",").map(Z=>Z.trim());C.push({Name:H[y.indexOf("Name")],Slug:H[y.indexOf("Slug")],Description:H[y.indexOf("Description")]})}u({stage:"Processing genres",current:1,total:2});const k=(await l.text()).split(` `),N=k[0].split(",").map(L=>L.trim()),m=["Name","Slug","Description"].filter(L=>!N.includes(L));if(m.length>0)throw new Error(`Missing required columns in sub-genres file: ${m.join(", ")}`);const p=[];for(let L=1;L<k.length;L++){if(!k[L].trim())continue;const H=k[L].split(",").map(Z=>Z.trim());p.push({Name:H[N.indexOf("Name")],Slug:H[N.indexOf("Slug")],Description:H[N.indexOf("Description")]})}u({stage:"Importing data",current:0,total:C.length+p.length});for(const L of C){const{error:H}=await W.from("genres").insert({name:L.Name,slug:L.Slug||Me(L.Name),description:L.Description});if(H&&H.code!=="23505")throw H;u(Z=>Z?{...Z,current:Z.current+1}:null)}const{data:_,error:T}=await W.from("genres").select("id, name, slug");if(T)throw T;const I=new Map(_.map(L=>[L.name.toLowerCase(),L.id]));for(const L of p){const H=_.find(Z=>L.Slug.includes(Z.slug)||L.Name.toLowerCase().includes(Z.name.toLowerCase()));if(H){const{error:Z}=await W.from("sub_genres").insert({name:L.Name,slug:L.Slug||Me(L.Name),description:L.Description,genre_id:H.id});if(Z&&Z.code!=="23505")throw Z}u(Z=>Z?{...Z,current:Z.current+1}:null)}s()}catch(x){console.error("Import failed:",x),a(x instanceof Error?x.message:"Failed to import data")}finally{r(!1),u(null),o(null),d(null)}},f=x=>{if(!x.name.endsWith(".csv")){a("Please select a CSV file");return}o(x),a(null)},g=x=>{if(!x.name.endsWith(".csv")){a("Please select a CSV file");return}d(x),a(null)};return t.jsxs("div",{className:"space-y-6",children:[t.jsxs("div",{className:"grid grid-cols-2 gap-6",children:[t.jsxs("div",{className:"bg-white p-6 rounded-lg shadow-sm",children:[t.jsx("h3",{className:"text-lg font-medium mb-4",children:"Import Genres"}),t.jsx("div",{onDragOver:x=>x.preventDefault(),onDrop:x=>{x.preventDefault();const v=x.dataTransfer.files[0];v&&f(v)},className:` border-2 border-dashed rounded-lg p-6 text-center transition-colors ${e?"opacity-50 cursor-not-allowed":"hover:border-green-500 cursor-pointer"} ${i?"border-green-500 bg-green-50":"border-gray-300"} `,children:i?t.jsxs("div",{className:"flex items-center justify-between",children:[t.jsx("span",{className:"text-sm text-gray-600",children:i.name}),t.jsx("button",{onClick:()=>o(null),className:"p-1 hover:bg-green-100 rounded-full",disabled:e,children:t.jsx(we,{className:"w-4 h-4 text-gray-500"})})]}):t.jsxs(t.Fragment,{children:[t.jsx(rs,{className:"w-8 h-8 text-gray-400 mx-auto mb-2"}),t.jsx("p",{className:"text-sm text-gray-600 mb-2",children:"Drop genres CSV file here"}),t.jsx("input",{type:"file",accept:".csv",onChange:x=>{var y;const v=(y=x.target.files)==null?void 0:y[0];v&&f(v)},className:"hidden",id:"genres-file",disabled:e}),t.jsx("label",{htmlFor:"genres-file",className:"inline-block px-3 py-1 text-sm bg-green-500 text-white rounded hover:bg-green-600 transition-colors cursor-pointer",children:"Select File"})]})})]}),t.jsxs("div",{className:"bg-white p-6 rounded-lg shadow-sm",children:[t.jsx("h3",{className:"text-lg font-medium mb-4",children:"Import Sub-genres"}),t.jsx("div",{onDragOver:x=>x.preventDefault(),onDrop:x=>{x.preventDefault();const v=x.dataTransfer.files[0];v&&g(v)},className:` border-2 border-dashed rounded-lg p-6 text-center transition-colors ${e?"opacity-50 cursor-not-allowed":"hover:border-green-500 cursor-pointer"} ${l?"border-green-500 bg-green-50":"border-gray-300"} `,children:l?t.jsxs("div",{className:"flex items-center justify-between",children:[t.jsx("span",{className:"text-sm text-gray-600",children:l.name}),t.jsx("button",{onClick:()=>d(null),className:"p-1 hover:bg-green-100 rounded-full",disabled:e,children:t.jsx(we,{className:"w-4 h-4 text-gray-500"})})]}):t.jsxs(t.Fragment,{children:[t.jsx(rs,{className:"w-8 h-8 text-gray-400 mx-auto mb-2"}),t.jsx("p",{className:"text-sm text-gray-600 mb-2",children:"Drop sub-genres CSV file here"}),t.jsx("input",{type:"file",accept:".csv",onChange:x=>{var y;const v=(y=x.target.files)==null?void 0:y[0];v&&g(v)},className:"hidden",id:"sub-genres-file",disabled:e}),t.jsx("label",{htmlFor:"sub-genres-file",className:"inline-block px-3 py-1 text-sm bg-green-500 text-white rounded hover:bg-green-600 transition-colors cursor-pointer",children:"Select File"})]})})]})]}),n&&t.jsxs("div",{className:"p-3 bg-red-50 text-red-700 rounded-lg flex items-center gap-2",children:[t.jsx(fe,{className:"w-5 h-5 flex-shrink-0"}),t.jsx("p",{className:"flex-1",children:n}),t.jsx("button",{onClick:()=>a(null),children:t.jsx(we,{className:"w-5 h-5"})})]}),c&&t.jsxs("div",{className:"bg-white p-4 rounded-lg shadow-sm",children:[t.jsxs("div",{className:"flex items-center gap-3 mb-2",children:[t.jsx(me,{className:"w-5 h-5 text-green-500 animate-spin"}),t.jsxs("span",{className:"text-gray-600",children:[c.stage,"..."]})]}),t.jsx("div",{className:"w-full h-2 bg-gray-100 rounded-full",children:t.jsx("div",{className:"h-full bg-green-500 rounded-full transition-all",style:{width:`${c.current/c.total*100}%`}})})]}),t.jsx("button",{onClick:h,disabled:!i||!l||e,className:`w-full py-2 rounded-lg text-white transition-colors ${!i||!l||e?"bg-gray-300 cursor-not-allowed":"bg-green-500 hover:bg-green-600"}`,children:e?"Importing...":"Import Data"}),t.jsxs("div",{className:"text-sm text-gray-500",children:[t.jsx("p",{className:"font-medium mb-2",children:"CSV Format Requirements:"}),t.jsxs("ul",{className:"list-disc list-inside space-y-1",children:[t.jsx("li",{children:"Files must be in CSV format"}),t.jsx("li",{children:"First row must contain headers"}),t.jsx("li",{children:"Required columns: Name, Slug, Description"}),t.jsx("li",{children:"Values containing commas must be enclosed in quotes"})]})]})]})}const Vc={async importPlaylists(s,e){try{if(!Array.isArray(s)||s.length===0)throw new Error("No playlists provided");const r={current:0,total:s.length,processed:0,skipped:0,failed:0,unmatchedCategories:new Set,recentErrors:[],skippedDetails:{genreNotFound:0,duplicates:0,invalidData:0,details:[]}},{data:n,error:a}=await W.from("genres").select("*").order("name");if(a)throw a;if(!(n!=null&&n.length))throw new Error("No genres found. Please set up genres first.");const{data:i,error:o}=await W.from("sub_genres").select("*").order("name");if(o)throw o;const l=50;for(let d=0;d<s.length;d+=l){const c=s.slice(d,Math.min(d+l,s.length)),u=[];for(const h of c)try{const f=n.find(y=>y.name.toLowerCase()===h.Category.toLowerCase()||h.Category.toLowerCase().includes(y.name.toLowerCase()));if(!f){r.skippedDetails.genreNotFound++,r.skippedDetails.details.push({row:d+c.indexOf(h)+1,name:h.Name,reason:"No matching genre found",details:`Category: ${h.Category}`}),r.unmatchedCategories.add(h.Category),r.failed++;continue}const g=h["Sub Genres"].split(";").map(y=>y.trim()).filter(Boolean),x=(i==null?void 0:i.filter(y=>y.genre_id===f.id&&g.some(w=>w.toLowerCase().includes(y.name.toLowerCase())||y.name.toLowerCase().includes(w.toLowerCase()))).map(y=>y.id))||[],{data:v}=await W.from("playlists").select("id").eq("spotify_id",h.URL.split("/").pop()).single();if(v){r.skippedDetails.duplicates++,r.skippedDetails.details.push({row:d+c.indexOf(h)+1,name:h.Name,reason:"Duplicate playlist",details:`Spotify ID: ${h.URL.split("/").pop()}`}),r.skipped++;continue}u.push({spotify_id:h.URL.split("/").pop(),name:h.Name,description:h.Description,image_url:h["Cover URL"],followers:parseInt(h.Followers.replace(/,/g,""),10),track_count:parseInt(h.Tracks.replace(/,/g,""),10),genre_id:f.id,sub_genre_ids:x,curator_name:h.Curator,curator_profile_url:h["Curator URL"],created_at:new Date().toISOString(),updated_at:new Date().toISOString()}),r.processed++}catch(f){r.skippedDetails.invalidData++,r.skippedDetails.details.push({row:d+c.indexOf(h)+1,name:h.Name,reason:"Invalid data",details:f instanceof Error?f.message:"Unknown error"}),r.failed++,r.recentErrors.push({row:d+c.indexOf(h)+1,message:f instanceof Error?f.message:"Failed to process playlist"})}if(u.length>0){const{error:h}=await W.from("playlists").insert(u);h&&(console.error("Failed to insert batch:",h),r.failed+=u.length,r.processed-=u.length)}r.current=d+c.length,e&&e({...r}),d+l<s.length&&await new Promise(h=>setTimeout(h,1e3))}return{successCount:r.processed,skipCount:r.skipped,unmatchedCategories:Array.from(r.unmatchedCategories),errors:r.recentErrors,skippedDetails:r.skippedDetails}}catch(r){throw console.error("Import failed:",r),r instanceof Error?r:new Error("Failed to import playlists")}}};var Jn={exports:{}};/* @license Papa Parse v5.5.3 https://github.com/mholt/PapaParse License: MIT */(function(s,e){((r,n)=>{s.exports=n()})(Se,function r(){var n=typeof self<"u"?self:typeof window<"u"?window:n!==void 0?n:{},a,i=!n.document&&!!n.postMessage,o=n.IS_PAPA_WORKER||!1,l={},d=0,c={};function u(m){this._handle=null,this._finished=!1,this._completed=!1,this._halted=!1,this._input=null,this._baseIndex=0,this._partialLine="",this._rowCount=0,this._start=0,this._nextChunk=null,this.isFirstChunk=!0,this._completeResults={data:[],errors:[],meta:{}},(function(p){var _=k(p);_.chunkSize=parseInt(_.chunkSize),p.step||p.chunk||(_.chunkSize=null),this._handle=new v(_),(this._handle.streamer=this)._config=_}).call(this,m),this.parseChunk=function(p,_){var T=parseInt(this._config.skipFirstNLines)||0;if(this.isFirstChunk&&0<T){let L=this._config.newline;L||(I=this._config.quoteChar||'"',L=this._handle.guessLineEndings(p,I)),p=[...p.split(L).slice(T)].join(L)}this.isFirstChunk&&j(this._config.beforeFirstChunk)&&(I=this._config.beforeFirstChunk(p))!==void 0&&(p=I),this.isFirstChunk=!1,this._halted=!1;var T=this._partialLine+p,I=(this._partialLine="",this._handle.parse(T,this._baseIndex,!this._finished));if(!this._handle.paused()&&!this._handle.aborted()){if(p=I.meta.cursor,T=(this._finished||(this._partialLine=T.substring(p-this._baseIndex),this._baseIndex=p),I&&I.data&&(this._rowCount+=I.data.length),this._finished||this._config.preview&&this._rowCount>=this._config.preview),o)n.postMessage({results:I,workerId:c.WORKER_ID,finished:T});else if(j(this._config.chunk)&&!_){if(this._config.chunk(I,this._handle),this._handle.paused()||this._handle.aborted())return void(this._halted=!0);this._completeResults=I=void 0}return this._config.step||this._config.chunk||(this._completeResults.data=this._completeResults.data.concat(I.data),this._completeResults.errors=this._completeResults.errors.concat(I.errors),this._completeResults.meta=I.meta),this._completed||!T||!j(this._config.complete)||I&&I.meta.aborted||(this._config.complete(this._completeResults,this._input),this._completed=!0),T||I&&I.meta.paused||this._nextChunk(),I}this._halted=!0},this._sendError=function(p){j(this._config.error)?this._config.error(p):o&&this._config.error&&n.postMessage({workerId:c.WORKER_ID,error:p,finished:!1})}}function h(m){var p;(m=m||{}).chunkSize||(m.chunkSize=c.RemoteChunkSize),u.call(this,m),this._nextChunk=i?function(){this._readChunk(),this._chunkLoaded()}:function(){this._readChunk()},this.stream=function(_){this._input=_,this._nextChunk()},this._readChunk=function(){if(this._finished)this._chunkLoaded();else{if(p=new XMLHttpRequest,this._config.withCredentials&&(p.withCredentials=this._config.withCredentials),i||(p.onload=N(this._chunkLoaded,this),p.onerror=N(this._chunkError,this)),p.open(this._config.downloadRequestBody?"POST":"GET",this._input,!i),this._config.downloadRequestHeaders){var _,T=this._config.downloadRequestHeaders;for(_ in T)p.setRequestHeader(_,T[_])}var I;this._config.chunkSize&&(I=this._start+this._config.chunkSize-1,p.setRequestHeader("Range","bytes="+this._start+"-"+I));try{p.send(this._config.downloadRequestBody)}catch(L){this._chunkError(L.message)}i&&p.status===0&&this._chunkError()}},this._chunkLoaded=function(){p.readyState===4&&(p.status<200||400<=p.status?this._chunkError():(this._start+=this._config.chunkSize||p.responseText.length,this._finished=!this._config.chunkSize||this._start>=(_=>(_=_.getResponseHeader("Content-Range"))!==null?parseInt(_.substring(_.lastIndexOf("/")+1)):-1)(p),this.parseChunk(p.responseText)))},this._chunkError=function(_){_=p.statusText||_,this._sendError(new Error(_))}}function f(m){(m=m||{}).chunkSize||(m.chunkSize=c.LocalChunkSize),u.call(this,m);var p,_,T=typeof FileReader<"u";this.stream=function(I){this._input=I,_=I.slice||I.webkitSlice||I.mozSlice,T?((p=new FileReader).onload=N(this._chunkLoaded,this),p.onerror=N(this._chunkError,this)):p=new FileReaderSync,this._nextChunk()},this._nextChunk=function(){this._finished||this._config.preview&&!(this._rowCount<this._config.preview)||this._readChunk()},this._readChunk=function(){var I=this._input,L=(this._config.chunkSize&&(L=Math.min(this._start+this._config.chunkSize,this._input.size),I=_.call(I,this._start,L)),p.readAsText(I,this._config.encoding));T||this._chunkLoaded({target:{result:L}})},this._chunkLoaded=function(I){this._start+=this._config.chunkSize,this._finished=!this._config.chunkSize||this._start>=this._input.size,this.parseChunk(I.target.result)},this._chunkError=function(){this._sendError(p.error)}}function g(m){var p;u.call(this,m=m||{}),this.stream=function(_){return p=_,this._nextChunk()},this._nextChunk=function(){var _,T;if(!this._finished)return _=this._config.chunkSize,p=_?(T=p.substring(0,_),p.substring(_)):(T=p,""),this._finished=!p,this.parseChunk(T)}}function x(m){u.call(this,m=m||{});var p=[],_=!0,T=!1;this.pause=function(){u.prototype.pause.apply(this,arguments),this._input.pause()},this.resume=function(){u.prototype.resume.apply(this,arguments),this._input.resume()},this.stream=function(I){this._input=I,this._input.on("data",this._streamData),this._input.on("end",this._streamEnd),this._input.on("error",this._streamError)},this._checkIsFinished=function(){T&&p.length===1&&(this._finished=!0)},this._nextChunk=function(){this._checkIsFinished(),p.length?this.parseChunk(p.shift()):_=!0},this._streamData=N(function(I){try{p.push(typeof I=="string"?I:I.toString(this._config.encoding)),_&&(_=!1,this._checkIsFinished(),this.parseChunk(p.shift()))}catch(L){this._streamError(L)}},this),this._streamError=N(function(I){this._streamCleanUp(),this._sendError(I)},this),this._streamEnd=N(function(){this._streamCleanUp(),T=!0,this._streamData("")},this),this._streamCleanUp=N(function(){this._input.removeListener("data",this._streamData),this._input.removeListener("end",this._streamEnd),this._input.removeListener("error",this._streamError)},this)}function v(m){var p,_,T,I,L=Math.pow(2,53),H=-L,Z=/^\s*-?(\d+\.?|\.\d+|\d+\.\d+)([eE][-+]?\d+)?\s*$/,re=/^((\d{4}-[01]\d-[0-3]\dT[0-2]\d:[0-5]\d:[0-5]\d\.\d+([+-][0-2]\d:[0-5]\d|Z))|(\d{4}-[01]\d-[0-3]\dT[0-2]\d:[0-5]\d:[0-5]\d([+-][0-2]\d:[0-5]\d|Z))|(\d{4}-[01]\d-[0-3]\dT[0-2]\d:[0-5]\d([+-][0-2]\d:[0-5]\d|Z)))$/,F=this,ne=0,K=0,U=!1,q=!1,Y=[],B={data:[],errors:[],meta:{}};function le(S){return m.skipEmptyLines==="greedy"?S.join("").trim()==="":S.length===1&&S[0].length===0}function ce(){if(B&&T&&(ae("Delimiter","UndetectableDelimiter","Unable to auto-detect delimiting character; defaulted to '"+c.DefaultDelimiter+"'"),T=!1),m.skipEmptyLines&&(B.data=B.data.filter(function(E){return!le(E)})),ue()){let E=function(A,$){j(m.transformHeader)&&(A=m.transformHeader(A,$)),Y.push(A)};if(B)if(Array.isArray(B.data[0])){for(var S=0;ue()&&S<B.data.length;S++)B.data[S].forEach(E);B.data.splice(0,1)}else B.data.forEach(E)}function O(E,A){for(var $=m.header?{}:[],M=0;M<E.length;M++){var Q=M,G=E[M],G=((ye,V)=>(de=>(m.dynamicTypingFunction&&m.dynamicTyping[de]===void 0&&(m.dynamicTyping[de]=m.dynamicTypingFunction(de)),(m.dynamicTyping[de]||m.dynamicTyping)===!0))(ye)?V==="true"||V==="TRUE"||V!=="false"&&V!=="FALSE"&&((de=>{if(Z.test(de)&&(de=parseFloat(de),H<de&&de<L))return 1})(V)?parseFloat(V):re.test(V)?new Date(V):V===""?null:V):V)(Q=m.header?M>=Y.length?"__parsed_extra":Y[M]:Q,G=m.transform?m.transform(G,Q):G);Q==="__parsed_extra"?($[Q]=$[Q]||[],$[Q].push(G)):$[Q]=G}return m.header&&(M>Y.length?ae("FieldMismatch","TooManyFields","Too many fields: expected "+Y.length+" fields but parsed "+M,K+A):M<Y.length&&ae("FieldMismatch","TooFewFields","Too few fields: expected "+Y.length+" fields but parsed "+M,K+A)),$}var R;B&&(m.header||m.dynamicTyping||m.transform)&&(R=1,!B.data.length||Array.isArray(B.data[0])?(B.data=B.data.map(O),R=B.data.length):B.data=O(B.data,0),m.header&&B.meta&&(B.meta.fields=Y),K+=R)}function ue(){return m.header&&Y.length===0}function ae(S,O,R,E){S={type:S,code:O,message:R},E!==void 0&&(S.row=E),B.errors.push(S)}j(m.step)&&(I=m.step,m.step=function(S){B=S,ue()?ce():(ce(),B.data.length!==0&&(ne+=S.data.length,m.preview&&ne>m.preview?_.abort():(B.data=B.data[0],I(B,F))))}),this.parse=function(S,O,R){var E=m.quoteChar||'"',E=(m.newline||(m.newline=this.guessLineEndings(S,E)),T=!1,m.delimiter?j(m.delimiter)&&(m.delimiter=m.delimiter(S),B.meta.delimiter=m.delimiter):((E=((A,$,M,Q,G)=>{var ye,V,de,Re;G=G||[","," ","|",";",c.RECORD_SEP,c.UNIT_SEP];for(var Pe=0;Pe<G.length;Pe++){for(var De,kt=G[Pe],xe=0,$e=0,ge=0,je=(de=void 0,new w({comments:Q,delimiter:kt,newline:$,preview:10}).parse(A)),Ge=0;Ge<je.data.length;Ge++)M&&le(je.data[Ge])?ge++:(De=je.data[Ge].length,$e+=De,de===void 0?de=De:0<De&&(xe+=Math.abs(De-de),de=De));0<je.data.length&&($e/=je.data.length-ge),(V===void 0||xe<=V)&&(Re===void 0||Re<$e)&&1.99<$e&&(V=xe,ye=kt,Re=$e)}return{successful:!!(m.delimiter=ye),bestDelimiter:ye}})(S,m.newline,m.skipEmptyLines,m.comments,m.delimitersToGuess)).successful?m.delimiter=E.bestDelimiter:(T=!0,m.delimiter=c.DefaultDelimiter),B.meta.delimiter=m.delimiter),k(m));return m.preview&&m.header&&E.preview++,p=S,_=new w(E),B=_.parse(p,O,R),ce(),U?{meta:{paused:!0}}:B||{meta:{paused:!1}}},this.paused=function(){return U},this.pause=function(){U=!0,_.abort(),p=j(m.chunk)?"":p.substring(_.getCharIndex())},this.resume=function(){F.streamer._halted?(U=!1,F.streamer.parseChunk(p,!0)):setTimeout(F.resume,3)},this.aborted=function(){return q},this.abort=function(){q=!0,_.abort(),B.meta.aborted=!0,j(m.complete)&&m.complete(B),p=""},this.guessLineEndings=function(A,E){A=A.substring(0,1048576);var E=new RegExp(y(E)+"([^]*?)"+y(E),"gm"),R=(A=A.replace(E,"")).split("\r"),E=A.split(` `),A=1<E.length&&E[0].length<R[0].length;if(R.length===1||A)return` `;for(var $=0,M=0;M<R.length;M++)R[M][0]===` `&&$++;return $>=R.length/2?`\r `:"\r"}}function y(m){return m.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}function w(m){var p=(m=m||{}).delimiter,_=m.newline,T=m.comments,I=m.step,L=m.preview,H=m.fastMode,Z=null,re=!1,F=m.quoteChar==null?'"':m.quoteChar,ne=F;if(m.escapeChar!==void 0&&(ne=m.escapeChar),(typeof p!="string"||-1<c.BAD_DELIMITERS.indexOf(p))&&(p=","),T===p)throw new Error("Comment character same as delimiter");T===!0?T="#":(typeof T!="string"||-1<c.BAD_DELIMITERS.indexOf(T))&&(T=!1),_!==` `&&_!=="\r"&&_!==`\r `&&(_=` `);var K=0,U=!1;this.parse=function(q,Y,B){if(typeof q!="string")throw new Error("Input must be a string");var le=q.length,ce=p.length,ue=_.length,ae=T.length,S=j(I),O=[],R=[],E=[],A=K=0;if(!q)return xe();if(H||H!==!1&&q.indexOf(F)===-1){for(var $=q.split(_),M=0;M<$.length;M++){if(E=$[M],K+=E.length,M!==$.length-1)K+=_.length;else if(B)return xe();if(!T||E.substring(0,ae)!==T){if(S){if(O=[],Re(E.split(p)),$e(),U)return xe()}else Re(E.split(p));if(L&&L<=M)return O=O.slice(0,L),xe(!0)}}return xe()}for(var Q=q.indexOf(p,K),G=q.indexOf(_,K),ye=new RegExp(y(ne)+y(F),"g"),V=q.indexOf(F,K);;)if(q[K]===F)for(V=K,K++;;){if((V=q.indexOf(F,V+1))===-1)return B||R.push({type:"Quotes",code:"MissingQuotes",message:"Quoted field unterminated",row:O.length,index:K}),De();if(V===le-1)return De(q.substring(K,V).replace(ye,F));if(F===ne&&q[V+1]===ne)V++;else if(F===ne||V===0||q[V-1]!==ne){Q!==-1&&Q<V+1&&(Q=q.indexOf(p,V+1));var de=Pe((G=G!==-1&&G<V+1?q.indexOf(_,V+1):G)===-1?Q:Math.min(Q,G));if(q.substr(V+1+de,ce)===p){E.push(q.substring(K,V).replace(ye,F)),q[K=V+1+de+ce]!==F&&(V=q.indexOf(F,K)),Q=q.indexOf(p,K),G=q.indexOf(_,K);break}if(de=Pe(G),q.substring(V+1+de,V+1+de+ue)===_){if(E.push(q.substring(K,V).replace(ye,F)),kt(V+1+de+ue),Q=q.indexOf(p,K),V=q.indexOf(F,K),S&&($e(),U))return xe();if(L&&O.length>=L)return xe(!0);break}R.push({type:"Quotes",code:"InvalidQuotes",message:"Trailing quote on quoted field is malformed",row:O.length,index:K}),V++}}else if(T&&E.length===0&&q.substring(K,K+ae)===T){if(G===-1)return xe();K=G+ue,G=q.indexOf(_,K),Q=q.indexOf(p,K)}else if(Q!==-1&&(Q<G||G===-1))E.push(q.substring(K,Q)),K=Q+ce,Q=q.indexOf(p,K);else{if(G===-1)break;if(E.push(q.substring(K,G)),kt(G+ue),S&&($e(),U))return xe();if(L&&O.length>=L)return xe(!0)}return De();function Re(ge){O.push(ge),A=K}function Pe(ge){var je=0;return je=ge!==-1&&(ge=q.substring(V+1,ge))&&ge.trim()===""?ge.length:je}function De(ge){return B||(ge===void 0&&(ge=q.substring(K)),E.push(ge),K=le,Re(E),S&&$e()),xe()}function kt(ge){K=ge,Re(E),E=[],G=q.indexOf(_,K)}function xe(ge){if(m.header&&!Y&&O.length&&!re){var je=O[0],Ge=Object.create(null),ys=new Set(je);let hr=!1;for(let lt=0;lt<je.length;lt++){let Ue=je[lt];if(Ge[Ue=j(m.transformHeader)?m.transformHeader(Ue,lt):Ue]){let Et,fr=Ge[Ue];for(;Et=Ue+"_"+fr,fr++,ys.has(Et););ys.add(Et),je[lt]=Et,Ge[Ue]++,hr=!0,(Z=Z===null?{}:Z)[Et]=Ue}else Ge[Ue]=1,je[lt]=Ue;ys.add(Ue)}hr&&console.warn("Duplicate headers found and renamed."),re=!0}return{data:O,errors:R,meta:{delimiter:p,linebreak:_,aborted:U,truncated:!!ge,cursor:A+(Y||0),renamedHeaders:Z}}}function $e(){I(xe()),O=[],R=[]}},this.abort=function(){U=!0},this.getCharIndex=function(){return K}}function P(m){var p=m.data,_=l[p.workerId],T=!1;if(p.error)_.userError(p.error,p.file);else if(p.results&&p.results.data){var I={abort:function(){T=!0,C(p.workerId,{data:[],errors:[],meta:{aborted:!0}})},pause:D,resume:D};if(j(_.userStep)){for(var L=0;L<p.results.data.length&&(_.userStep({data:p.results.data[L],errors:p.results.errors,meta:p.results.meta},I),!T);L++);delete p.results}else j(_.userChunk)&&(_.userChunk(p.results,I,p.file),delete p.results)}p.finished&&!T&&C(p.workerId,p.results)}function C(m,p){var _=l[m];j(_.userComplete)&&_.userComplete(p),_.terminate(),delete l[m]}function D(){throw new Error("Not implemented.")}function k(m){if(typeof m!="object"||m===null)return m;var p,_=Array.isArray(m)?[]:{};for(p in m)_[p]=k(m[p]);return _}function N(m,p){return function(){m.apply(p,arguments)}}function j(m){return typeof m=="function"}return c.parse=function(m,p){var _=(p=p||{}).dynamicTyping||!1;if(j(_)&&(p.dynamicTypingFunction=_,_={}),p.dynamicTyping=_,p.transform=!!j(p.transform)&&p.transform,!p.worker||!c.WORKERS_SUPPORTED)return _=null,c.NODE_STREAM_INPUT,typeof m=="string"?(m=(T=>T.charCodeAt(0)!==65279?T:T.slice(1))(m),_=new(p.download?h:g)(p)):m.readable===!0&&j(m.read)&&j(m.on)?_=new x(p):(n.File&&m instanceof File||m instanceof Object)&&(_=new f(p)),_.stream(m);(_=(()=>{var T;return!!c.WORKERS_SUPPORTED&&(T=(()=>{var I=n.URL||n.webkitURL||null,L=r.toString();return c.BLOB_URL||(c.BLOB_URL=I.createObjectURL(new Blob(["var global = (function() { if (typeof self !== 'undefined') { return self; } if (typeof window !== 'undefined') { return window; } if (typeof global !== 'undefined') { return global; } return {}; })(); global.IS_PAPA_WORKER=true; ","(",L,")();"],{type:"text/javascript"})))})(),(T=new n.Worker(T)).onmessage=P,T.id=d++,l[T.id]=T)})()).userStep=p.step,_.userChunk=p.chunk,_.userComplete=p.complete,_.userError=p.error,p.step=j(p.step),p.chunk=j(p.chunk),p.complete=j(p.complete),p.error=j(p.error),delete p.worker,_.postMessage({input:m,config:p,workerId:_.id})},c.unparse=function(m,p){var _=!1,T=!0,I=",",L=`\r `,H='"',Z=H+H,re=!1,F=null,ne=!1,K=((()=>{if(typeof p=="object"){if(typeof p.delimiter!="string"||c.BAD_DELIMITERS.filter(function(Y){return p.delimiter.indexOf(Y)!==-1}).length||(I=p.delimiter),typeof p.quotes!="boolean"&&typeof p.quotes!="function"&&!Array.isArray(p.quotes)||(_=p.quotes),typeof p.skipEmptyLines!="boolean"&&typeof p.skipEmptyLines!="string"||(re=p.skipEmptyLines),typeof p.newline=="string"&&(L=p.newline),typeof p.quoteChar=="string"&&(H=p.quoteChar),typeof p.header=="boolean"&&(T=p.header),Array.isArray(p.columns)){if(p.columns.length===0)throw new Error("Option columns is empty");F=p.columns}p.escapeChar!==void 0&&(Z=p.escapeChar+H),p.escapeFormulae instanceof RegExp?ne=p.escapeFormulae:typeof p.escapeFormulae=="boolean"&&p.escapeFormulae&&(ne=/^[=+\-@\t\r].*$/)}})(),new RegExp(y(H),"g"));if(typeof m=="string"&&(m=JSON.parse(m)),Array.isArray(m)){if(!m.length||Array.isArray(m[0]))return U(null,m,re);if(typeof m[0]=="object")return U(F||Object.keys(m[0]),m,re)}else if(typeof m=="object")return typeof m.data=="string"&&(m.data=JSON.parse(m.data)),Array.isArray(m.data)&&(m.fields||(m.fields=m.meta&&m.meta.fields||F),m.fields||(m.fields=Array.isArray(m.data[0])?m.fields:typeof m.data[0]=="object"?Object.keys(m.data[0]):[]),Array.isArray(m.data[0])||typeof m.data[0]=="object"||(m.data=[m.data])),U(m.fields||[],m.data||[],re);throw new Error("Unable to serialize unrecognized input");function U(Y,B,le){var ce="",ue=(typeof Y=="string"&&(Y=JSON.parse(Y)),typeof B=="string"&&(B=JSON.parse(B)),Array.isArray(Y)&&0<Y.length),ae=!Array.isArray(B[0]);if(ue&&T){for(var S=0;S<Y.length;S++)0<S&&(ce+=I),ce+=q(Y[S],S);0<B.length&&(ce+=L)}for(var O=0;O<B.length;O++){var R=(ue?Y:B[O]).length,E=!1,A=ue?Object.keys(B[O]).length===0:B[O].length===0;if(le&&!ue&&(E=le==="greedy"?B[O].join("").trim()==="":B[O].length===1&&B[O][0].length===0),le==="greedy"&&ue){for(var $=[],M=0;M<R;M++){var Q=ae?Y[M]:M;$.push(B[O][Q])}E=$.join("").trim()===""}if(!E){for(var G=0;G<R;G++){0<G&&!A&&(ce+=I);var ye=ue&&ae?Y[G]:G;ce+=q(B[O][ye],G)}O<B.length-1&&(!le||0<R&&!A)&&(ce+=L)}}return ce}function q(Y,B){var le,ce;return Y==null?"":Y.constructor===Date?JSON.stringify(Y).slice(1,25):(ce=!1,ne&&typeof Y=="string"&&ne.test(Y)&&(Y="'"+Y,ce=!0),le=Y.toString().replace(K,Z),(ce=ce||_===!0||typeof _=="function"&&_(Y,B)||Array.isArray(_)&&_[B]||((ue,ae)=>{for(var S=0;S<ae.length;S++)if(-1<ue.indexOf(ae[S]))return!0;return!1})(le,c.BAD_DELIMITERS)||-1<le.indexOf(I)||le.charAt(0)===" "||le.charAt(le.length-1)===" ")?H+le+H:le)}},c.RECORD_SEP="",c.UNIT_SEP="",c.BYTE_ORDER_MARK="\uFEFF",c.BAD_DELIMITERS=["\r",` `,'"',c.BYTE_ORDER_MARK],c.WORKERS_SUPPORTED=!i&&!!n.Worker,c.NODE_STREAM_INPUT=1,c.LocalChunkSize=10485760,c.RemoteChunkSize=5242880,c.DefaultDelimiter=",",c.Parser=w,c.ParserHandle=v,c.NetworkStreamer=h,c.FileStreamer=f,c.StringStreamer=g,c.ReadableStreamStreamer=x,n.jQuery&&((a=n.jQuery).fn.parse=function(m){var p=m.config||{},_=[];return this.each(function(L){if(!(a(this).prop("tagName").toUpperCase()==="INPUT"&&a(this).attr("type").toLowerCase()==="file"&&n.FileReader)||!this.files||this.files.length===0)return!0;for(var H=0;H<this.files.length;H++)_.push({file:this.files[H],inputElem:this,instanceConfig:a.extend({},p)})}),T(),this;function T(){if(_.length===0)j(m.complete)&&m.complete();else{var L,H,Z,re,F=_[0];if(j(m.before)){var ne=m.before(F.file,F.inputElem);if(typeof ne=="object"){if(ne.action==="abort")return L="AbortError",H=F.file,Z=F.inputElem,re=ne.reason,void(j(m.error)&&m.error({name:L},H,Z,re));if(ne.action==="skip")return void I();typeof ne.config=="object"&&(F.instanceConfig=a.extend(F.instanceConfig,ne.config))}else if(ne==="skip")return void I()}var K=F.instanceConfig.complete;F.instanceConfig.complete=function(U){j(K)&&K(U,F.file,F.inputElem),I()},c.parse(F.file,F.instanceConfig)}}function I(){_.splice(0,1),T()}}),o&&(n.onmessage=function(m){m=m.data,c.WORKER_ID===void 0&&m&&(c.WORKER_ID=m.workerId),typeof m.input=="string"?n.postMessage({workerId:c.WORKER_ID,results:c.parse(m.input,m.config),finished:!0}):(n.File&&m.input instanceof File||m.input instanceof Object)&&(m=c.parse(m.input,m.config))&&n.postMessage({workerId:c.WORKER_ID,results:m,finished:!0})}),(h.prototype=Object.create(u.prototype)).constructor=h,(f.prototype=Object.create(u.prototype)).constructor=f,(g.prototype=Object.create(g.prototype)).constructor=g,(x.prototype=Object.create(u.prototype)).constructor=x,c})})(Jn);var Jc=Jn.exports;const Yc=is(Jc),Qc=({onSuccess:s})=>{const[e,r]=b.useState(!1),[n,a]=b.useState(null),[i,o]=b.useState([]),[l,d]=b.useState(!1),[c,u]=b.useState(null),[h,f]=b.useState(!1),[g,x]=b.useState(null),v=async()=>{try{r(!0),a(null),x(null);const k=await Vc.importPlaylists(i,N=>{u({total:N.total,processed:N.processed,successCount:N.processed-N.failed,skipCount:N.skipped,unmatchedCategories:Array.from(N.unmatchedCategories),errors:N.recentErrors.map(j=>({row:j.row,error:j.message}))})});x(k),k.successCount>0&&s()}catch(k){a("Error importing playlists"),console.error("Import error:",k)}finally{r(!1)}},y=async k=>{try{if(r(!0),a(null),u(null),!k.name.endsWith(".csv")){a("Please upload a CSV file");return}const N=new FileReader;N.onload=async j=>{var T;const m=(T=j.target)==null?void 0:T.result,{data:p,errors:_}=Yc.parse(m,{header:!0,skipEmptyLines:!0});if(_.length>0){a("Error parsing CSV file");return}o(p),d(!0)},N.readAsText(k)}catch{a("Error processing file")}finally{r(!1)}},w=b.useCallback(k=>{k.preventDefault(),k.stopPropagation(),f(!0)},[]),P=b.useCallback(k=>{k.preventDefault(),k.stopPropagation(),f(!1)},[]),C=b.useCallback(k=>{k.preventDefault(),k.stopPropagation(),f(!1);const N=k.dataTransfer.files[0];N&&y(N)},[]),D=k=>{var j;const N=(j=k.target.files)==null?void 0:j[0];N&&y(N),k.target.value=""};return t.jsxs("div",{className:"space-y-4",children:[t.jsx("div",{onDragOver:w,onDragLeave:P,onDrop:C,className:` border-2 border-dashed rounded-lg p-8 text-center transition-colors ${h?"border-green-500 bg-green-50":"border-gray-300 hover:border-green-500"} ${e?"opacity-50 cursor-not-allowed":"cursor-pointer"} `,children:e?t.jsxs("div",{className:"space-y-4",children:[t.jsx(me,{className:"w-8 h-8 text-green-500 animate-spin mx-auto"}),c&&t.jsxs("div",{className:"text-sm text-gray-600",children:["Processing ",c.processed," of ",c.total," playlists...",c.successCount>0&&t.jsxs("div",{className:"text-green-600",children:[c.successCount," playlists imported successfully"]}),c.skipCount>0&&t.jsxs("div",{className:"text-yellow-600",children:[c.skipCount," playlists skipped"]})]})]}):t.jsxs(t.Fragment,{children:[t.jsx(rs,{className:"w-8 h-8 text-gray-400 mx-auto mb-3"}),t.jsx("p",{className:"text-gray-600 mb-2",children:"Drag and drop your CSV file here, or click to select"}),t.jsx("input",{type:"file",accept:".csv",onChange:D,className:"hidden",id:"file-upload",disabled:e}),t.jsx("label",{htmlFor:"file-upload",className:"inline-block px-4 py-2 bg-green-500 text-white rounded-lg hover:bg-green-600 transition-colors cursor-pointer",children:"Select File"})]})}),n&&t.jsxs("div",{className:"mt-4 p-3 rounded-lg bg-red-50 text-red-700 flex items-center gap-2",children:[t.jsx(fe,{className:"w-5 h-5 flex-shrink-0"}),t.jsx("p",{className:"flex-1",children:n}),t.jsx("button",{onClick:()=>a(null),children:t.jsx(we,{className:"w-5 h-5"})})]}),l&&i.length>0&&t.jsxs("div",{className:"mt-4",children:[t.jsxs("div",{className:"flex justify-between items-center mb-4",children:[t.jsxs("h3",{className:"text-lg font-medium",children:["Preview (",i.length," playlists)"]}),t.jsx("button",{onClick:v,disabled:e,className:` px-4 py-2 rounded-lg text-white ${e?"bg-gray-400 cursor-not-allowed":"bg-green-500 hover:bg-green-600 transition-colors"} `,children:e?"Importing...":"Import Playlists"})]}),t.jsx("div",{className:"bg-white rounded-lg shadow overflow-hidden",children:t.jsxs("table",{className:"min-w-full divide-y divide-gray-200",children:[t.jsx("thead",{className:"bg-gray-50",children:t.jsxs("tr",{children:[t.jsx("th",{className:"px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider",children:"Name"}),t.jsx("th",{className:"px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider",children:"Genre"}),t.jsx("th",{className:"px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider",children:"Curator"})]})}),t.jsxs("tbody",{className:"bg-white divide-y divide-gray-200",children:[i.slice(0,5).map((k,N)=>t.jsxs("tr",{children:[t.jsx("td",{className:"px-6 py-4 whitespace-nowrap text-sm text-gray-900",children:k.Name}),t.jsx("td",{className:"px-6 py-4 whitespace-nowrap text-sm text-gray-500",children:k.Category}),t.jsx("td",{className:"px-6 py-4 whitespace-nowrap text-sm text-gray-500",children:k.Curator})]},N)),i.length>5&&t.jsx("tr",{children:t.jsxs("td",{colSpan:3,className:"px-6 py-4 text-sm text-gray-500 text-center",children:["+ ",i.length-5," more playlists"]})})]})]})})]}),g&&!e&&t.jsx(Zc,{result:g})]})},Zc=({result:s})=>t.jsx("div",{className:"mt-4",children:t.jsxs("div",{className:"bg-white rounded-lg shadow-sm p-4 border border-gray-200",children:[t.jsx("h3",{className:"text-lg font-medium mb-4",children:"Import Results"}),t.jsxs("div",{className:"grid grid-cols-3 gap-4 mb-4",children:[t.jsxs("div",{className:"bg-green-50 p-3 rounded-lg",children:[t.jsx("div",{className:"text-2xl font-semibold text-green-600",children:s.successCount}),t.jsx("div",{className:"text-sm text-green-700",children:"Successfully imported"})]}),t.jsxs("div",{className:"bg-yellow-50 p-3 rounded-lg",children:[t.jsx("div",{className:"text-2xl font-semibold text-yellow-600",children:s.skipCount}),t.jsx("div",{className:"text-sm text-yellow-700",children:"Skipped"})]}),t.jsxs("div",{className:"bg-blue-50 p-3 rounded-lg",children:[t.jsx("div",{className:"text-2xl font-semibold text-blue-600",children:s.unmatchedCategories.length}),t.jsx("div",{className:"text-sm text-blue-700",children:"Unmatched categories"})]})]}),s.unmatchedCategories.length>0&&t.jsxs("div",{className:"mb-4",children:[t.jsx("h4",{className:"font-medium mb-2 text-sm text-gray-700",children:"Unmatched Categories:"}),t.jsx("div",{className:"flex flex-wrap gap-2",children:s.unmatchedCategories.map((e,r)=>t.jsx("span",{className:"inline-flex items-center px-2 py-1 rounded-full text-xs font-medium bg-blue-100 text-blue-800",children:e},r))})]}),s.errors.length>0&&t.jsxs("div",{children:[t.jsx("h4",{className:"font-medium mb-2 text-sm text-gray-700",children:"Errors:"}),t.jsx("div",{className:"max-h-60 overflow-y-auto rounded-lg border border-gray-200",children:t.jsxs("table",{className:"min-w-full divide-y divide-gray-200",children:[t.jsx("thead",{className:"bg-gray-50",children:t.jsxs("tr",{children:[t.jsx("th",{className:"px-4 py-2 text-left text-xs font-medium text-gray-500",children:"Row"}),t.jsx("th",{className:"px-4 py-2 text-left text-xs font-medium text-gray-500",children:"Error"})]})}),t.jsx("tbody",{className:"bg-white divide-y divide-gray-200",children:s.errors.map((e,r)=>t.jsxs("tr",{children:[t.jsxs("td",{className:"px-4 py-2 whitespace-nowrap text-sm text-gray-500",children:["Row ",e.row]}),t.jsx("td",{className:"px-4 py-2 text-sm text-gray-500",children:e.error})]},r))})]})})]})]})});function Xc({onClose:s,onComplete:e}){const[r,n]=b.useState(!1),[a,i]=b.useState(!1),[o,l]=b.useState(null),[d,c]=b.useState(null),u=b.useRef(null),h=async()=>{var x,v;console.log("Starting sync process..."),i(!0),l(null),u.current=new AbortController;try{console.log("Fetching playlist count...");const y=new Date(Date.now()-96*60*60*1e3).toISOString(),{count:w,error:P}=await W.from("playlists").select("*",{count:"exact",head:!0}).or(`last_synced_at.is.null,last_synced_at.lt.${y}`);if(P)throw console.error("Error getting playlist count:",P),P;if(!w||w===0)throw new Error("No playlists need syncing");console.log(`Total playlists to sync: ${w}`),c({current:0,total:w,updated:0,failed:0});const C=1e3,D=5,k=1e3,N=3e4;let j=k,m=0,p=null;for(;m<w;){if((x=u.current)!=null&&x.signal.aborted)throw new Error("Sync cancelled");console.log(`Fetching page of playlists${p?` after ID ${p}`:""}...`);let _=W.from("playlists").select("id, spotify_id, last_synced_at").or(`last_synced_at.is.null,last_synced_at.lt.${y}`).order("last_synced_at",{ascending:!0,nullsFirst:!0}).limit(C);p&&(_=_.gt("id",p));const{data:T,error:I}=await _;if(I)throw console.error("Error fetching playlists:",I),I;if(!T||T.length===0){console.log("No more playlists to process");break}console.log(`Processing page of ${T.length} playlists${p?` after ID ${p}`:""}`),p=T[T.length-1].id;for(let L=0;L<T.length;L+=D){if((v=u.current)!=null&&v.signal.aborted)throw new Error("Sync cancelled");const H=T.slice(L,Math.min(L+D,T.length)),Z=Math.floor((m+L)/D)+1,re=Math.ceil(w/D);console.log(`Processing batch ${Z} of ${re}`);try{const F=await Promise.allSettled(H.map(async U=>{var q,Y,B,le,ce,ue;try{console.log(`Fetching details for playlist ${U.spotify_id}`);const ae=await ur(U.spotify_id);if(!ae)throw console.error(`No data returned for playlist ${U.spotify_id}`),new Error("Playlist not found on Spotify");return console.log(`Successfully fetched details for playlist ${U.spotify_id}`),{id:U.id,name:ae.name,description:ae.description||"",image_url:((q=ae.images[0])==null?void 0:q.url)||"",followers:((Y=ae.followers)==null?void 0:Y.total)||0,track_count:((B=ae.tracks)==null?void 0:B.total)||0,curator_name:((le=ae.owner)==null?void 0:le.display_name)||null,curator_profile_url:((ue=(ce=ae.owner)==null?void 0:ce.external_urls)==null?void 0:ue.spotify)||null,curator_email:ae.curator_email||null,last_synced_at:new Date().toISOString(),updated_at:new Date().toISOString()}}catch(ae){throw console.error(`Failed to fetch playlist ${U.spotify_id}:`,ae),ae}}));j=k;let ne=0,K=0;for(const U of F)if(U.status==="fulfilled"){const{error:q}=await W.from("playlists").update(U.value).eq("id",U.value.id);q?(console.error("Failed to update playlist:",q),K++):(console.log(`Successfully updated playlist ${U.value.id}`),ne++)}else{console.error("Batch update failed:",U.reason);const q=U.reason instanceof Error?U.reason.message:"Unknown error";console.error("Detailed error:",{message:q,fullError:U.reason}),K++}c(U=>({current:m+L+H.length,updated:((U==null?void 0:U.updated)||0)+ne,failed:((U==null?void 0:U.failed)||0)+K,total:w}))}catch(F){if(F instanceof Error&&F.message.includes("rate limit")){console.log(`Rate limit hit. Waiting ${j/1e3} seconds before retrying...`),await new Promise(ne=>setTimeout(ne,j)),j=Math.min(j*2,N),L-=D;continue}throw F}await new Promise(F=>setTimeout(F,j))}m+=T.length}e(),n(!1)}catch(y){console.error("Sync failed:",y);const w=y instanceof Error?y.message:"Failed to sync playlists";console.error("Detailed error:",{error:y,message:w}),l(w)}finally{i(!1),u.current=null}},f=()=>{var x;a?(x=u.current)==null||x.abort():(n(!1),s==null||s())},g=()=>{n(!0),setTimeout(()=>{h()},100)};return t.jsxs(t.Fragment,{children:[t.jsx("div",{className:"bg-white p-6 rounded-lg shadow-sm",children:t.jsxs("div",{className:"flex justify-between items-center mb-4",children:[t.jsxs("div",{children:[t.jsx("h2",{className:"text-lg font-semibold",children:"Sync with Spotify"}),t.jsx("p",{className:"text-sm text-gray-600",children:"Update playlist metadata from Spotify including artwork, description, curator details, and follower counts."})]}),t.jsxs("button",{onClick:g,className:"flex items-center gap-2 bg-blue-500 text-white px-4 py-2 rounded-lg hover:bg-blue-600 transition-colors",children:[t.jsx(wt,{className:"w-5 h-5"}),"Start Sync"]})]})}),r&&t.jsx("div",{className:"fixed inset-0 bg-black bg-opacity-50 flex items-center justify-center p-4 z-50",children:t.jsxs("div",{className:"bg-white rounded-xl max-w-lg w-full",children:[t.jsx("div",{className:"p-6 border-b border-gray-200",children:t.jsxs("div",{className:"flex justify-between items-center",children:[t.jsx("h2",{className:"text-xl font-bold text-gray-900",children:"Sync Playlists"}),t.jsx("button",{onClick:f,className:"text-gray-400 hover:text-gray-500 transition-colors",children:t.jsx(we,{className:"w-6 h-6"})})]})}),t.jsxs("div",{className:"p-6 space-y-4",children:[!a&&!o&&t.jsx("p",{className:"text-gray-600",children:"This will update playlist metadata including artwork, description, curator details, follower count, and track count from Spotify."}),d&&t.jsxs("div",{className:"space-y-3",children:[t.jsxs("div",{className:"flex items-center justify-between text-sm text-gray-600",children:[t.jsx("span",{children:"Processing playlists..."}),t.jsxs("span",{children:[d.current," of ",d.total," (",Math.round(d.current/d.total*100),"%)"]})]}),t.jsx("div",{className:"w-full h-2 bg-gray-100 rounded-full overflow-hidden",children:t.jsx("div",{className:"h-full bg-green-500 transition-all duration-300",style:{width:`${d.current/d.total*100}%`}})}),t.jsxs("div",{className:"flex gap-4 text-sm",children:[t.jsxs("span",{className:"flex items-center gap-1 text-green-600",children:[t.jsx(nt,{className:"w-4 h-4"}),d.updated," updated (",Math.round(d.updated/d.total*100),"%)"]}),d.failed>0&&t.jsxs("span",{className:"flex items-center gap-1 text-red-600",children:[t.jsx(fe,{className:"w-4 h-4"}),d.failed," failed (",Math.round(d.failed/d.total*100),"%)"]})]})]}),o&&t.jsxs("div",{className:"flex items-center gap-2 text-red-600 bg-red-50 p-3 rounded-lg",children:[t.jsx(fe,{className:"w-5 h-5 flex-shrink-0"}),t.jsx("p",{children:o})]}),t.jsxs("div",{className:"flex justify-end gap-3 pt-4",children:[t.jsx("button",{onClick:f,className:"px-4 py-2 text-gray-700 hover:bg-gray-100 rounded-lg transition-colors",children:a?"Cancel":"Close"}),!a&&!o&&t.jsxs("button",{onClick:h,className:"flex items-center gap-2 px-4 py-2 bg-green-500 text-white rounded-lg hover:bg-green-600 transition-colors",children:[t.jsx(wt,{className:"w-5 h-5"}),"Start Sync"]})]})]})]})})]})}function ed(){const[s,e]=b.useState(null);return t.jsxs("div",{className:"container mx-auto px-4 py-8",children:[t.jsx("h1",{className:"text-2xl font-bold mb-6",children:"Import & Sync Data"}),t.jsxs("div",{className:"space-y-6",children:[t.jsx(Xc,{onComplete:()=>e({type:"success",message:"Successfully synced playlists with Spotify"})}),t.jsxs(zc,{defaultValue:"playlists",className:"space-y-6",children:[t.jsxs(Vn,{children:[t.jsx(Vs,{value:"playlists",children:"Playlists"}),t.jsx(Vs,{value:"genres",children:"Genres & Sub-genres"})]}),t.jsx(Js,{value:"playlists",children:t.jsx(Qc,{onSuccess:()=>e({type:"success",message:"Successfully imported playlists"})})}),t.jsx(Js,{value:"genres",children:t.jsx(Wc,{onSuccess:()=>e({type:"success",message:"Successfully imported genres and sub-genres"})})})]})]}),s&&t.jsx(qe,{message:s.message,type:s.type,onClose:()=>e(null)})]})}function td({isOpen:s,onClose:e,onConfirm:r,isCleaning:n,progress:a}){if(!s)return null;const i=a?Math.round(a.processed/a.total*100):0;return t.jsx("div",{className:"fixed inset-0 bg-black bg-opacity-50 flex items-center justify-center z-50",children:t.jsxs("div",{className:"bg-white rounded-lg p-6 max-w-md w-full mx-4",children:[t.jsxs("div",{className:"flex justify-between items-center mb-4",children:[t.jsx("h2",{className:"text-xl font-semibold",children:n?"Cleaning Descriptions":"Confirm Clean Descriptions"}),t.jsx("button",{onClick:e,className:"text-gray-500 hover:text-gray-700",disabled:n,children:t.jsx(we,{className:"w-5 h-5"})})]}),n?t.jsxs("div",{className:"space-y-4",children:[t.jsxs("div",{className:"space-y-2",children:[t.jsxs("div",{className:"flex justify-between text-sm",children:[t.jsx("span",{children:"Progress"}),t.jsxs("span",{children:[i,"%"]})]}),t.jsx("div",{className:"w-full bg-gray-200 rounded-full h-2.5",children:t.jsx("div",{className:"bg-blue-500 h-2.5 rounded-full transition-all duration-300",style:{width:`${i}%`}})})]}),t.jsxs("div",{className:"grid grid-cols-2 gap-4 text-sm",children:[t.jsxs("div",{children:[t.jsx("span",{className:"text-gray-500",children:"Processed:"}),t.jsx("span",{className:"ml-2 font-medium",children:(a==null?void 0:a.processed)||0})]}),t.jsxs("div",{children:[t.jsx("span",{className:"text-gray-500",children:"Updated:"}),t.jsx("span",{className:"ml-2 font-medium",children:(a==null?void 0:a.updated)||0})]}),t.jsxs("div",{children:[t.jsx("span",{className:"text-gray-500",children:"Total:"}),t.jsx("span",{className:"ml-2 font-medium",children:(a==null?void 0:a.total)||0})]})]}),t.jsxs("div",{className:"flex items-center justify-center text-blue-500",children:[t.jsx(me,{className:"w-6 h-6 animate-spin"}),t.jsx("span",{className:"ml-2",children:"Cleaning in progress..."})]})]}):t.jsxs("div",{className:"space-y-4",children:[t.jsx("p",{className:"text-gray-600",children:"This will clean all playlist descriptions by removing HTML, URLs, and extracting curator emails. Existing emails will be preserved unless new ones are found."}),t.jsxs("div",{className:"flex justify-end gap-3",children:[t.jsx("button",{onClick:e,className:"px-4 py-2 text-gray-600 hover:text-gray-800",children:"Cancel"}),t.jsx("button",{onClick:r,className:"px-4 py-2 bg-blue-500 text-white rounded-lg hover:bg-blue-600",children:"Start Cleaning"})]})]})]})})}async function sd(){return{success:!0}}function rd(){const[s,e]=b.useState(""),[r,n]=b.useState(""),[a,i]=b.useState(""),[o,l]=b.useState(!1),[d,c]=b.useState(!1),[u,h]=b.useState(!1),[f,g]=b.useState(!1),[x,v]=b.useState(null),[y,w]=b.useState(null),P=async N=>{if(N.preventDefault(),r!==a){v({type:"error",message:"New passwords do not match"});return}l(!0);try{v({type:"success",message:"Password updated successfully"}),e(""),n(""),i("")}catch(j){console.error("Failed to update password:",j),v({type:"error",message:"Failed to update password"})}finally{l(!1)}},C=async()=>{c(!0);try{await sd(),v({type:"success",message:"Genres and sub-genres have been set up successfully"})}catch(N){console.error("Failed to setup genres:",N),v({type:"error",message:"Failed to setup genres and sub-genres"})}finally{c(!1)}},D=async()=>{g(!0)},k=async()=>{h(!0),g(!0);try{const{count:N,error:j}=await W.from("playlists").select("*",{count:"exact",head:!0});if(j)throw j;if(!N)throw new Error("No playlists found");w({total:N,processed:0,updated:0});let m=!0,p=0;const _=50;for(;m;){const{data:T,error:I}=await W.from("playlists").select("id, description").range(p,p+_-1);if(I)throw I;if(!T||T.length===0){m=!1;break}for(const L of T){const{description:H,extractedEmail:Z}=Hn(L.description);if(H!==L.description||Z){const{error:re}=await W.from("playlists").update({description:H,curator_email:Z,updated_at:new Date().toISOString()}).eq("id",L.id);if(re){console.error(`Failed to update playlist ${L.id}:`,re);continue}w(F=>F?{...F,updated:F.updated+1}:null)}w(re=>re?{...re,processed:re.processed+1}:null)}p+=_}v({type:"success",message:`Processed ${y==null?void 0:y.processed} playlists, updated ${y==null?void 0:y.updated} descriptions`})}catch(N){console.error("Failed to clean descriptions:",N),v({type:"error",message:N instanceof Error?N.message:"Failed to clean descriptions"})}finally{h(!1),g(!1),w(null)}};return t.jsxs("div",{className:"container mx-auto px-4 py-8",children:[t.jsx("h1",{className:"text-2xl font-bold mb-6",children:"Settings"}),t.jsxs("div",{className:"space-y-6 max-w-md",children:[t.jsxs("div",{className:"bg-white p-6 rounded-lg shadow-sm",children:[t.jsx("h2",{className:"text-lg font-medium mb-4",children:"Genre Management"}),t.jsxs("button",{onClick:C,disabled:d,className:"flex items-center gap-2 bg-green-500 text-white px-4 py-2 rounded-lg hover:bg-green-600 disabled:bg-gray-400 disabled:cursor-not-allowed",children:[d?t.jsx(me,{className:"w-5 h-5 animate-spin"}):t.jsx(wt,{className:"w-5 h-5"}),d?"Setting up...":"Setup Genres & Sub-genres"]}),t.jsx("p",{className:"mt-2 text-sm text-gray-600",children:"This will create or update all genres and their associated sub-genres."})]}),t.jsxs("div",{className:"bg-white p-6 rounded-lg shadow-sm",children:[t.jsx("h2",{className:"text-lg font-medium mb-4",children:"Clean Playlist Descriptions"}),t.jsxs("button",{onClick:D,disabled:u,className:"flex items-center gap-2 bg-blue-500 text-white px-4 py-2 rounded-lg hover:bg-blue-600 disabled:bg-gray-400 disabled:cursor-not-allowed",children:[u?t.jsx(me,{className:"w-5 h-5 animate-spin"}):t.jsx(El,{className:"w-5 h-5"}),u?"Cleaning...":"Clean All Descriptions"]}),t.jsx("p",{className:"mt-2 text-sm text-gray-600",children:"This will clean all playlist descriptions by removing HTML, URLs, and extracting curator emails."})]}),t.jsxs("div",{className:"bg-white p-6 rounded-lg shadow-sm",children:[t.jsx("h2",{className:"text-lg font-medium mb-4",children:"Change Password"}),t.jsxs("form",{onSubmit:P,className:"space-y-4",children:[t.jsxs("div",{children:[t.jsx("label",{htmlFor:"currentPassword",className:"block text-sm font-medium text-gray-700 mb-1",children:"Current Password"}),t.jsx("input",{type:"password",id:"currentPassword",value:s,onChange:N=>e(N.target.value),required:!0,className:"w-full px-3 py-2 border border-gray-300 rounded-lg focus:ring-2 focus:ring-green-500 focus:border-transparent"})]}),t.jsxs("div",{children:[t.jsx("label",{htmlFor:"newPassword",className:"block text-sm font-medium text-gray-700 mb-1",children:"New Password"}),t.jsx("input",{type:"password",id:"newPassword",value:r,onChange:N=>n(N.target.value),required:!0,className:"w-full px-3 py-2 border border-gray-300 rounded-lg focus:ring-2 focus:ring-green-500 focus:border-transparent"})]}),t.jsxs("div",{children:[t.jsx("label",{htmlFor:"confirmPassword",className:"block text-sm font-medium text-gray-700 mb-1",children:"Confirm New Password"}),t.jsx("input",{type:"password",id:"confirmPassword",value:a,onChange:N=>i(N.target.value),required:!0,className:"w-full px-3 py-2 border border-gray-300 rounded-lg focus:ring-2 focus:ring-green-500 focus:border-transparent"})]}),t.jsxs("button",{type:"submit",disabled:o,className:"w-full flex items-center justify-center gap-2 bg-green-500 text-white px-4 py-2 rounded-lg hover:bg-green-600 disabled:bg-gray-400",children:[o?t.jsx(me,{className:"w-5 h-5 animate-spin"}):t.jsx(Sl,{className:"w-5 h-5"}),o?"Updating...":"Update Password"]})]})]})]}),t.jsx(td,{isOpen:f,onClose:()=>g(!1),onConfirm:k,isCleaning:u,progress:y}),x&&t.jsx(qe,{message:x.message,type:x.type,onClose:()=>v(null)})]})}function nd(){var g,x;const[s,e]=b.useState(""),[r,n]=b.useState(""),[a,i]=b.useState(""),[o,l]=b.useState(!1),d=Xe(),c=it(),{signIn:u}=sr(),h=((x=(g=c.state)==null?void 0:g.from)==null?void 0:x.pathname)||"/admin",f=async v=>{v.preventDefault(),i(""),l(!0);try{await u(s.trim(),r),d(h,{replace:!0})}catch(y){console.error("Login failed:",y),i("Invalid email or password"),n("")}finally{l(!1)}};return t.jsx("div",{className:"min-h-screen bg-gray-100 flex items-center justify-center p-4",children:t.jsxs("div",{className:"max-w-md w-full space-y-8 bg-white p-8 rounded-lg shadow-md",children:[t.jsxs("div",{className:"text-center",children:[t.jsx("div",{className:"mx-auto h-12 w-12 rounded-full bg-green-100 flex items-center justify-center",children:t.jsx(wl,{className:"h-6 w-6 text-green-600"})}),t.jsx("h2",{className:"mt-6 text-3xl font-extrabold text-gray-900",children:"Admin Login"}),t.jsx("p",{className:"mt-2 text-sm text-gray-600",children:"Sign in to access the admin dashboard"})]}),t.jsxs("form",{className:"mt-8 space-y-6",onSubmit:f,children:[t.jsxs("div",{className:"space-y-4",children:[t.jsxs("div",{children:[t.jsx("label",{htmlFor:"email",className:"block text-sm font-medium text-gray-700",children:"Email"}),t.jsx("input",{id:"email",type:"email",required:!0,value:s,onChange:v=>e(v.target.value),className:"mt-1 block w-full px-3 py-2 border border-gray-300 rounded-lg shadow-sm focus:ring-green-500 focus:border-green-500",placeholder:"admin@example.com",disabled:o})]}),t.jsxs("div",{children:[t.jsx("label",{htmlFor:"password",className:"block text-sm font-medium text-gray-700",children:"Password"}),t.jsx("input",{id:"password",type:"password",required:!0,value:r,onChange:v=>n(v.target.value),className:"mt-1 block w-full px-3 py-2 border border-gray-300 rounded-lg shadow-sm focus:ring-green-500 focus:border-green-500",placeholder:"Enter your password",disabled:o})]})]}),a&&t.jsxs("div",{className:"flex items-center gap-2 text-red-600 text-sm",children:[t.jsx(fe,{className:"w-4 h-4"}),a]}),t.jsx("button",{type:"submit",disabled:o,className:"w-full flex justify-center py-2 px-4 border border-transparent rounded-lg shadow-sm text-sm font-medium text-white bg-green-600 hover:bg-green-700 focus:outline-none focus:ring-2 focus:ring-offset-2 focus:ring-green-500 disabled:opacity-50 disabled:cursor-not-allowed",children:o?t.jsx(me,{className:"w-5 h-5 animate-spin"}):"Sign in"})]})]})})}function ad(){return t.jsx(Un,{children:t.jsx("div",{className:"min-h-screen flex flex-col",children:t.jsxs(ua,{children:[t.jsx(he,{path:"/",element:t.jsxs(t.Fragment,{children:[t.jsx(ke,{}),t.jsx(Ul,{}),t.jsx(Ee,{})]})}),t.jsx(he,{path:"/playlists",element:t.jsxs(t.Fragment,{children:[t.jsx(ke,{}),t.jsx(hc,{}),t.jsx(Ee,{})]})}),t.jsx(he,{path:"/submit",element:t.jsxs(t.Fragment,{children:[t.jsx(ke,{}),t.jsx(fc,{}),t.jsx(Ee,{})]})}),t.jsx(he,{path:"/submit/genre",element:t.jsxs(t.Fragment,{children:[t.jsx(ke,{}),t.jsx(mc,{}),t.jsx(Ee,{})]})}),t.jsx(he,{path:"/playlist/:slug/*",element:t.jsxs(t.Fragment,{children:[t.jsx(ke,{}),t.jsx(dc,{}),t.jsx(Ee,{})]})}),t.jsx(he,{path:"/genres",element:t.jsxs(t.Fragment,{children:[t.jsx(ke,{}),t.jsx(wc,{}),t.jsx(Ee,{})]})}),t.jsx(he,{path:"/genre/:genre",element:t.jsxs(t.Fragment,{children:[t.jsx(ke,{}),t.jsx(yc,{}),t.jsx(Ee,{})]})}),t.jsx(he,{path:"/genre/:genre/:subGenre",element:t.jsxs(t.Fragment,{children:[t.jsx(ke,{}),t.jsx(bc,{}),t.jsx(Ee,{})]})}),t.jsx(he,{path:"/about",element:t.jsxs(t.Fragment,{children:[t.jsx(ke,{}),t.jsx(vc,{}),t.jsx(Ee,{})]})}),t.jsx(he,{path:"/for-curators",element:t.jsxs(t.Fragment,{children:[t.jsx(ke,{}),t.jsx(jc,{}),t.jsx(Ee,{})]})}),t.jsx(he,{path:"/blog",element:t.jsxs(t.Fragment,{children:[t.jsx(ke,{}),t.jsx(_c,{}),t.jsx(Ee,{})]})}),t.jsx(he,{path:"/blog/:category/:slug",element:t.jsxs(t.Fragment,{children:[t.jsx(ke,{}),t.jsx(Ac,{}),t.jsx(Ee,{})]})}),t.jsx(he,{path:"/admin/login",element:t.jsx(nd,{})}),t.jsxs(he,{path:"/admin",element:t.jsx(Ic,{}),children:[t.jsx(he,{index:!0,element:t.jsx(Rc,{})}),t.jsx(he,{path:"playlists",element:t.jsx(Mc,{})}),t.jsx(he,{path:"submissions",element:t.jsx(qc,{})}),t.jsx(he,{path:"genres",element:t.jsx(Kc,{})}),t.jsx(he,{path:"import",element:t.jsx(ed,{})}),t.jsx(he,{path:"settings",element:t.jsx(rd,{})})]}),t.jsx(he,{path:"*",element:t.jsx(Yr,{to:"/",replace:!0})})]})})})}const id={};Qr(document.getElementById("root")).render(t.jsx(b.StrictMode,{children:t.jsx(nn,{context:id,children:t.jsx(ha,{children:t.jsx(ol,{children:t.jsx(Un,{children:t.jsx(ad,{})})})})})}));export{me as L,lr as P,St as S,qe as T,gc as u}; //# sourceMappingURL=index-DmpArtWK.js.map