const __vite__mapDeps=(i,m=__vite__mapDeps,d=(m.f||(m.f=["assets/browser-Bb8gMH3P.js","assets/react-vendor-DqtKxO-G.js","assets/FeaturedPlaylists-CGac0gns.js","assets/ui-vendor-C3vDQktR.js","assets/FAQSection-DqnOdgPP.js","assets/AdditionalInfoSection-jTLY8rfk.js"])))=>i.map(i=>d[i]); var Tn=Object.defineProperty;var Pn=(r,e,s)=>e in r?Tn(r,e,{enumerable:!0,configurable:!0,writable:!0,value:s}):r[e]=s;var Ne=(r,e,s)=>Pn(r,typeof e!="symbol"?e+"":e,s);import{j as t,u as An,C as On,a as $n,b as Ws,D as Rn,c as In,S as Dn,v as Ln,s as Fn,K as Un,P as Mn,L as Sr,T as kr,d as Er,R as qn}from"./ui-vendor-C3vDQktR.js";import{a as Cr,g as Jt,R as Be,r as y,c as Gn,d as ve,L as X,u as Qe,e as He,f as Tr,h as Os,N as Pr,O as Bn,i as zn,j as ue,B as Hn}from"./react-vendor-DqtKxO-G.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 s(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=s(a);fetch(a.href,i)}})();var Ar,Vs=Cr;Ar=Vs.createRoot,Vs.hydrateRoot;var Jn=typeof Element<"u",Kn=typeof Map=="function",Wn=typeof Set=="function",Vn=typeof ArrayBuffer=="function"&&!!ArrayBuffer.isView;function Ft(r,e){if(r===e)return!0;if(r&&e&&typeof r=="object"&&typeof e=="object"){if(r.constructor!==e.constructor)return!1;var s,n,a;if(Array.isArray(r)){if(s=r.length,s!=e.length)return!1;for(n=s;n--!==0;)if(!Ft(r[n],e[n]))return!1;return!0}var i;if(Kn&&r instanceof Map&&e instanceof Map){if(r.size!==e.size)return!1;for(i=r.entries();!(n=i.next()).done;)if(!e.has(n.value[0]))return!1;for(i=r.entries();!(n=i.next()).done;)if(!Ft(n.value[1],e.get(n.value[0])))return!1;return!0}if(Wn&&r instanceof Set&&e instanceof Set){if(r.size!==e.size)return!1;for(i=r.entries();!(n=i.next()).done;)if(!e.has(n.value[0]))return!1;return!0}if(Vn&&ArrayBuffer.isView(r)&&ArrayBuffer.isView(e)){if(s=r.length,s!=e.length)return!1;for(n=s;n--!==0;)if(r[n]!==e[n])return!1;return!0}if(r.constructor===RegExp)return r.source===e.source&&r.flags===e.flags;if(r.valueOf!==Object.prototype.valueOf&&typeof r.valueOf=="function"&&typeof e.valueOf=="function")return r.valueOf()===e.valueOf();if(r.toString!==Object.prototype.toString&&typeof r.toString=="function"&&typeof e.toString=="function")return r.toString()===e.toString();if(a=Object.keys(r),s=a.length,s!==Object.keys(e).length)return!1;for(n=s;n--!==0;)if(!Object.prototype.hasOwnProperty.call(e,a[n]))return!1;if(Jn&&r instanceof Element)return!1;for(n=s;n--!==0;)if(!((a[n]==="_owner"||a[n]==="__v"||a[n]==="__o")&&r.$$typeof)&&!Ft(r[a[n]],e[a[n]]))return!1;return!0}return r!==r&&e!==e}var Yn=function(e,s){try{return Ft(e,s)}catch(n){if((n.message||"").match(/stack|recursion/i))return console.warn("react-fast-compare cannot handle circular refs"),!1;throw n}};const Zn=Jt(Yn);var Qn=function(r,e,s,n,a,i,o,l){if(!r){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=[s,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}},Xn=Qn;const Ys=Jt(Xn);var ea=function(e,s,n,a){var i=n?n.call(a,e,s):void 0;if(i!==void 0)return!!i;if(e===s)return!0;if(typeof e!="object"||!e||typeof s!="object"||!s)return!1;var o=Object.keys(e),l=Object.keys(s);if(o.length!==l.length)return!1;for(var d=Object.prototype.hasOwnProperty.bind(s),c=0;c<o.length;c++){var u=o[c];if(!d(u))return!1;var h=e[u],f=s[u];if(i=n?n.call(a,h,f,u):void 0,i===!1||i===void 0&&h!==f)return!1}return!0};const ta=Jt(ea);var Or=(r=>(r.BASE="base",r.BODY="body",r.HEAD="head",r.HTML="html",r.LINK="link",r.META="meta",r.NOSCRIPT="noscript",r.SCRIPT="script",r.STYLE="style",r.TITLE="title",r.FRAGMENT="Symbol(react.fragment)",r))(Or||{}),ns={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"]}},Zs=Object.values(Or),$s={accesskey:"accessKey",charset:"charSet",class:"className",contenteditable:"contentEditable",contextmenu:"contextMenu","http-equiv":"httpEquiv",itemprop:"itemProp",tabindex:"tabIndex"},sa=Object.entries($s).reduce((r,[e,s])=>(r[s]=e,r),{}),Ee="data-rh",ot={DEFAULT_TITLE:"defaultTitle",DEFER:"defer",ENCODE_SPECIAL_CHARACTERS:"encodeSpecialCharacters",ON_CHANGE_CLIENT_STATE:"onChangeClientState",TITLE_TEMPLATE:"titleTemplate",PRIORITIZE_SEO_TAGS:"prioritizeSeoTags"},lt=(r,e)=>{for(let s=r.length-1;s>=0;s-=1){const n=r[s];if(Object.prototype.hasOwnProperty.call(n,e))return n[e]}return null},ra=r=>{let e=lt(r,"title");const s=lt(r,ot.TITLE_TEMPLATE);if(Array.isArray(e)&&(e=e.join("")),s&&e)return s.replace(/%s/g,()=>e);const n=lt(r,ot.DEFAULT_TITLE);return e||n||void 0},na=r=>lt(r,ot.ON_CHANGE_CLIENT_STATE)||(()=>{}),as=(r,e)=>e.filter(s=>typeof s[r]<"u").map(s=>s[r]).reduce((s,n)=>({...s,...n}),{}),aa=(r,e)=>e.filter(s=>typeof s.base<"u").map(s=>s.base).reverse().reduce((s,n)=>{if(!s.length){const a=Object.keys(n);for(let i=0;i<a.length;i+=1){const l=a[i].toLowerCase();if(r.indexOf(l)!==-1&&n[l])return s.concat(n)}}return s},[]),ia=r=>console&&typeof console.warn=="function"&&console.warn(r),bt=(r,e,s)=>{const n={};return s.filter(a=>Array.isArray(a[r])?!0:(typeof a[r]<"u"&&ia(`Helmet: ${r} should be of type "Array". Instead found type "${typeof a[r]}"`),!1)).map(a=>a[r]).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 p=u[f],b=p.toLowerCase();e.indexOf(b)!==-1&&!(c==="rel"&&d[c].toLowerCase()==="canonical")&&!(b==="rel"&&d[b].toLowerCase()==="stylesheet")&&(c=b),e.indexOf(p)!==-1&&(p==="innerHTML"||p==="cssText"||p==="itemprop")&&(c=p)}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()},oa=(r,e)=>{if(Array.isArray(r)&&r.length){for(let s=0;s<r.length;s+=1)if(r[s][e])return!0}return!1},la=r=>({baseTag:aa(["href"],r),bodyAttributes:as("bodyAttributes",r),defer:lt(r,ot.DEFER),encode:lt(r,ot.ENCODE_SPECIAL_CHARACTERS),htmlAttributes:as("htmlAttributes",r),linkTags:bt("link",["rel","href"],r),metaTags:bt("meta",["name","charset","http-equiv","property","itemprop"],r),noscriptTags:bt("noscript",["innerHTML"],r),onChangeClientState:na(r),scriptTags:bt("script",["src","innerHTML"],r),styleTags:bt("style",["cssText"],r),title:ra(r),titleAttributes:as("titleAttributes",r),prioritizeSeoTags:oa(r,ot.PRIORITIZE_SEO_TAGS)}),$r=r=>Array.isArray(r)?r.join(""):r,ca=(r,e)=>{const s=Object.keys(r);for(let n=0;n<s.length;n+=1)if(e[s[n]]&&e[s[n]].includes(r[s[n]]))return!0;return!1},is=(r,e)=>Array.isArray(r)?r.reduce((s,n)=>(ca(n,e)?s.priority.push(n):s.default.push(n),s),{priority:[],default:[]}):{default:r,priority:[]},Qs=(r,e)=>({...r,[e]:void 0}),da=["noscript","script","style"],gs=(r,e=!0)=>e===!1?String(r):String(r).replace(/&/g,"&").replace(/</g,"<").replace(/>/g,">").replace(/"/g,""").replace(/'/g,"'"),Rr=r=>Object.keys(r).reduce((e,s)=>{const n=typeof r[s]<"u"?`${s}="${r[s]}"`:`${s}`;return e?`${e} ${n}`:n},""),ua=(r,e,s,n)=>{const a=Rr(s),i=$r(e);return a?`<${r} ${Ee}="true" ${a}>${gs(i,n)}</${r}>`:`<${r} ${Ee}="true">${gs(i,n)}</${r}>`},ha=(r,e,s=!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}="${gs(i[u],s)}"`;return c?`${c} ${h}`:h},""),l=i.innerHTML||i.cssText||"",d=da.indexOf(r)===-1;return`${n}<${r} ${Ee}="true" ${o}${d?"/>":`>${l}</${r}>`}`},""),Ir=(r,e={})=>Object.keys(r).reduce((s,n)=>{const a=$s[n];return s[a||n]=r[n],s},e),fa=(r,e,s)=>{const n={key:e,[Ee]:!0},a=Ir(s,n);return[Be.createElement("title",a,e)]},Ut=(r,e)=>e.map((s,n)=>{const a={key:n,[Ee]:!0};return Object.keys(s).forEach(i=>{const l=$s[i]||i;if(l==="innerHTML"||l==="cssText"){const d=s.innerHTML||s.cssText;a.dangerouslySetInnerHTML={__html:d}}else a[l]=s[i]}),Be.createElement(r,a)}),je=(r,e,s=!0)=>{switch(r){case"title":return{toComponent:()=>fa(r,e.title,e.titleAttributes),toString:()=>ua(r,e.title,e.titleAttributes,s)};case"bodyAttributes":case"htmlAttributes":return{toComponent:()=>Ir(e),toString:()=>Rr(e)};default:return{toComponent:()=>Ut(r,e),toString:()=>ha(r,e,s)}}},ma=({metaTags:r,linkTags:e,scriptTags:s,encode:n})=>{const a=is(r,ns.meta),i=is(e,ns.link),o=is(s,ns.script);return{priorityMethods:{toComponent:()=>[...Ut("meta",a.priority),...Ut("link",i.priority),...Ut("script",o.priority)],toString:()=>`${je("meta",a.priority,n)} ${je("link",i.priority,n)} ${je("script",o.priority,n)}`},metaTags:a.default,linkTags:i.default,scriptTags:o.default}},ga=r=>{const{baseTag:e,bodyAttributes:s,encode:n=!0,htmlAttributes:a,noscriptTags:i,styleTags:o,title:l="",titleAttributes:d,prioritizeSeoTags:c}=r;let{linkTags:u,metaTags:h,scriptTags:f}=r,p={toComponent:()=>{},toString:()=>""};return c&&({priorityMethods:p,linkTags:u,metaTags:h,scriptTags:f}=ma(r)),{priority:p,base:je("base",e,n),bodyAttributes:je("bodyAttributes",s,n),htmlAttributes:je("htmlAttributes",a,n),link:je("link",u,n),meta:je("meta",h,n),noscript:je("noscript",i,n),script:je("script",f,n),style:je("style",o,n),title:je("title",{title:l,titleAttributes:d},n)}},ps=ga,Ot=[],Dr=!!(typeof window<"u"&&window.document&&window.document.createElement),xs=class{constructor(r,e){Ne(this,"instances",[]);Ne(this,"canUseDOM",Dr);Ne(this,"context");Ne(this,"value",{setHelmet:r=>{this.context.helmet=r},helmetInstances:{get:()=>this.canUseDOM?Ot:this.instances,add:r=>{(this.canUseDOM?Ot:this.instances).push(r)},remove:r=>{const e=(this.canUseDOM?Ot:this.instances).indexOf(r);(this.canUseDOM?Ot:this.instances).splice(e,1)}}});this.context=r,this.canUseDOM=e||!1,e||(r.helmet=ps({baseTag:[],bodyAttributes:{},encodeSpecialCharacters:!0,htmlAttributes:{},linkTags:[],metaTags:[],noscriptTags:[],scriptTags:[],styleTags:[],title:"",titleAttributes:{}}))}},pa={},Lr=Be.createContext(pa),Ze,Fr=(Ze=class extends y.Component{constructor(s){super(s);Ne(this,"helmetData");this.helmetData=new xs(this.props.context||{},Ze.canUseDOM)}render(){return Be.createElement(Lr.Provider,{value:this.helmetData.value},this.props.children)}},Ne(Ze,"canUseDOM",Dr),Ze),rt=(r,e)=>{const s=document.head||document.querySelector("head"),n=s.querySelectorAll(`${r}[${Ee}]`),a=[].slice.call(n),i=[];let o;return e&&e.length&&e.forEach(l=>{const d=document.createElement(r);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(Ee,"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=>s.appendChild(l)),{oldTags:a,newTags:i}},ys=(r,e)=>{const s=document.getElementsByTagName(r)[0];if(!s)return;const n=s.getAttribute(Ee),a=n?n.split(","):[],i=[...a],o=Object.keys(e);for(const l of o){const d=e[l]||"";s.getAttribute(l)!==d&&s.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)s.removeAttribute(i[l]);a.length===i.length?s.removeAttribute(Ee):s.getAttribute(Ee)!==o.join(",")&&s.setAttribute(Ee,o.join(","))},xa=(r,e)=>{typeof r<"u"&&document.title!==r&&(document.title=$r(r)),ys("title",e)},Xs=(r,e)=>{const{baseTag:s,bodyAttributes:n,htmlAttributes:a,linkTags:i,metaTags:o,noscriptTags:l,onChangeClientState:d,scriptTags:c,styleTags:u,title:h,titleAttributes:f}=r;ys("body",n),ys("html",a),xa(h,f);const p={baseTag:rt("base",s),linkTags:rt("link",i),metaTags:rt("meta",o),noscriptTags:rt("noscript",l),scriptTags:rt("script",c),styleTags:rt("style",u)},b={},j={};Object.keys(p).forEach(x=>{const{newTags:w,oldTags:k}=p[x];w.length&&(b[x]=w),k.length&&(j[x]=p[x].oldTags)}),e&&e(),d(r,b,j)},wt=null,ya=r=>{wt&&cancelAnimationFrame(wt),r.defer?wt=requestAnimationFrame(()=>{Xs(r,()=>{wt=null})}):(Xs(r),wt=null)},ba=ya,er=class extends y.Component{constructor(){super(...arguments);Ne(this,"rendered",!1)}shouldComponentUpdate(e){return!ta(e,this.props)}componentDidUpdate(){this.emitChange()}componentWillUnmount(){const{helmetInstances:e}=this.props.context;e.remove(this),this.emitChange()}emitChange(){const{helmetInstances:e,setHelmet:s}=this.props.context;let n=null;const a=la(e.get().map(i=>{const o={...i.props};return delete o.context,o}));Fr.canUseDOM?ba(a):ps&&(n=ps(a)),s(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}},ms,wa=(ms=class extends y.Component{shouldComponentUpdate(r){return!Zn(Qs(this.props,"helmetData"),Qs(r,"helmetData"))}mapNestedChildrenToProps(r,e){if(!e)return null;switch(r.type){case"script":case"noscript":return{innerHTML:e};case"style":return{cssText:e};default:throw new Error(`<${r.type} /> elements are self-closing and can not contain children. Refer to our API for more information.`)}}flattenArrayTypeChildren(r,e,s,n){return{...e,[r.type]:[...e[r.type]||[],{...s,...this.mapNestedChildrenToProps(r,n)}]}}mapObjectTypeChildren(r,e,s,n){switch(r.type){case"title":return{...e,[r.type]:n,titleAttributes:{...s}};case"body":return{...e,bodyAttributes:{...s}};case"html":return{...e,htmlAttributes:{...s}};default:return{...e,[r.type]:{...s}}}}mapArrayTypeChildrenToProps(r,e){let s={...e};return Object.keys(r).forEach(n=>{s={...s,[n]:r[n]}}),s}warnOnInvalidChildren(r,e){return Ys(Zs.some(s=>r.type===s),typeof r.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 ${Zs.join(", ")} are allowed. Helmet does not support rendering <${r.type}> elements. Refer to our API for more information.`),Ys(!e||typeof e=="string"||Array.isArray(e)&&!e.some(s=>typeof s!="string"),`Helmet expects a string as a child of <${r.type}>. Did you forget to wrap your children in braces? ( <${r.type}>{\`\`}</${r.type}> ) Refer to our API for more information.`),!0}mapChildrenToProps(r,e){let s={};return Be.Children.forEach(r,n=>{if(!n||!n.props)return;const{children:a,...i}=n.props,o=Object.keys(i).reduce((d,c)=>(d[sa[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":s=this.flattenArrayTypeChildren(n,s,o,a);break;default:e=this.mapObjectTypeChildren(n,e,o,a);break}}),this.mapArrayTypeChildrenToProps(s,e)}render(){const{children:r,...e}=this.props;let s={...e},{helmetData:n}=e;if(r&&(s=this.mapChildrenToProps(r,s)),n&&!(n instanceof xs)){const a=n;n=new xs(a.context,!0),delete s.helmetData}return n?Be.createElement(er,{...s,context:n.value}):Be.createElement(Lr.Consumer,null,a=>Be.createElement(er,{...s,context:a}))}},Ne(ms,"defaultProps",{defer:!0,encodeSpecialCharacters:!0,prioritizeSeoTags:!1}),ms);const va="modulepreload",ja=function(r){return"/"+r},tr={},Re=function(e,s,n){let a=Promise.resolve();if(s&&s.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(s.map(d=>{if(d=ja(d),d in tr)return;tr[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":va,c||(h.as="script"),h.crossOrigin="",h.href=d,l&&h.setAttribute("nonce",l),document.head.appendChild(h),c)return new Promise((f,p)=>{h.addEventListener("load",f),h.addEventListener("error",()=>p(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)})},_a=r=>{let e;return r?e=r:typeof fetch>"u"?e=(...s)=>Re(async()=>{const{default:n}=await Promise.resolve().then(()=>mt);return{default:n}},void 0).then(({default:n})=>n(...s)):e=fetch,(...s)=>e(...s)};class Rs extends Error{constructor(e,s="FunctionsError",n){super(e),this.name=s,this.context=n}}class Na extends Rs{constructor(e){super("Failed to send a request to the Edge Function","FunctionsFetchError",e)}}class Sa extends Rs{constructor(e){super("Relay Error invoking the Edge Function","FunctionsRelayError",e)}}class ka extends Rs{constructor(e){super("Edge Function returned a non-2xx status code","FunctionsHttpError",e)}}var bs;(function(r){r.Any="any",r.ApNortheast1="ap-northeast-1",r.ApNortheast2="ap-northeast-2",r.ApSouth1="ap-south-1",r.ApSoutheast1="ap-southeast-1",r.ApSoutheast2="ap-southeast-2",r.CaCentral1="ca-central-1",r.EuCentral1="eu-central-1",r.EuWest1="eu-west-1",r.EuWest2="eu-west-2",r.EuWest3="eu-west-3",r.SaEast1="sa-east-1",r.UsEast1="us-east-1",r.UsWest1="us-west-1",r.UsWest2="us-west-2"})(bs||(bs={}));var Ea=function(r,e,s,n){function a(i){return i instanceof s?i:new s(function(o){o(i)})}return new(s||(s=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(r,e||[])).next())})};class Ca{constructor(e,{headers:s={},customFetch:n,region:a=bs.Any}={}){this.url=e,this.headers=s,this.region=a,this.fetch=_a(n)}setAuth(e){this.headers.Authorization=`Bearer ${e}`}invoke(e,s={}){var n;return Ea(this,void 0,void 0,function*(){try{const{headers:a,method:i,body:o}=s;let l={},{region:d}=s;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(b=>{throw new Na(b)}),h=u.headers.get("x-relay-error");if(h&&h==="true")throw new Sa(u);if(!u.ok)throw new ka(u);let f=((n=u.headers.get("Content-Type"))!==null&&n!==void 0?n:"text/plain").split(";")[0].trim(),p;return f==="application/json"?p=yield u.json():f==="application/octet-stream"?p=yield u.blob():f==="text/event-stream"?p=u:f==="multipart/form-data"?p=yield u.formData():p=yield u.text(),{data:p,error:null}}catch(a){return{data:null,error:a}}})}}var be={},Is={},Kt={},Ct={},Wt={},Vt={},Ta=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")},dt=Ta();const Pa=dt.fetch,Ur=dt.fetch.bind(dt),Mr=dt.Headers,Aa=dt.Request,Oa=dt.Response,mt=Object.freeze(Object.defineProperty({__proto__:null,Headers:Mr,Request:Aa,Response:Oa,default:Ur,fetch:Pa},Symbol.toStringTag,{value:"Module"})),$a=Gn(mt);var Yt={};Object.defineProperty(Yt,"__esModule",{value:!0});class Ra extends Error{constructor(e){super(e.message),this.name="PostgrestError",this.details=e.details,this.hint=e.hint,this.code=e.code}}Yt.default=Ra;var qr=ve&&ve.__importDefault||function(r){return r&&r.__esModule?r:{default:r}};Object.defineProperty(Vt,"__esModule",{value:!0});const Ia=qr($a),Da=qr(Yt);let La=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=Ia.default:this.fetch=fetch}throwOnError(){return this.shouldThrowOnError=!0,this}setHeader(e,s){return this.headers=Object.assign({},this.headers),this.headers[e]=s,this}then(e,s){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,p=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 j=(o=this.headers.Prefer)===null||o===void 0?void 0:o.match(/count=(exact|planned|estimated)/),x=(l=i.headers.get("content-range"))===null||l===void 0?void 0:l.split("/");j&&x&&x.length>1&&(h=parseInt(x[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,p="Not Acceptable"):u.length===1?u=u[0]:u=null)}else{const j=await i.text();try{c=JSON.parse(j),Array.isArray(c)&&i.status===404&&(u=[],c=null,f=200,p="OK")}catch{i.status===404&&j===""?(f=204,p="No Content"):c={message:j}}if(c&&this.isMaybeSingle&&(!((d=c==null?void 0:c.details)===null||d===void 0)&&d.includes("0 rows"))&&(c=null,f=200,p="OK"),c&&this.shouldThrowOnError)throw new Da.default(c)}return{error:c,data:u,count:h,status:f,statusText:p}});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,s)}};Vt.default=La;var Fa=ve&&ve.__importDefault||function(r){return r&&r.__esModule?r:{default:r}};Object.defineProperty(Wt,"__esModule",{value:!0});const Ua=Fa(Vt);let Ma=class extends Ua.default{select(e){let s=!1;const n=(e??"*").split("").map(a=>/\s/.test(a)&&!s?"":(a==='"'&&(s=!s),a)).join("");return this.url.searchParams.set("select",n),this.headers.Prefer&&(this.headers.Prefer+=","),this.headers.Prefer+="return=representation",this}order(e,{ascending:s=!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}.${s?"asc":"desc"}${n===void 0?"":n?".nullsfirst":".nullslast"}`),this}limit(e,{foreignTable:s,referencedTable:n=s}={}){const a=typeof n>"u"?"limit":`${n}.limit`;return this.url.searchParams.set(a,`${e}`),this}range(e,s,{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,`${s-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:s=!1,settings:n=!1,buffers:a=!1,wal:i=!1,format:o="text"}={}){var l;const d=[e?"analyze":null,s?"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}};Wt.default=Ma;var qa=ve&&ve.__importDefault||function(r){return r&&r.__esModule?r:{default:r}};Object.defineProperty(Ct,"__esModule",{value:!0});const Ga=qa(Wt);let Ba=class extends Ga.default{eq(e,s){return this.url.searchParams.append(e,`eq.${s}`),this}neq(e,s){return this.url.searchParams.append(e,`neq.${s}`),this}gt(e,s){return this.url.searchParams.append(e,`gt.${s}`),this}gte(e,s){return this.url.searchParams.append(e,`gte.${s}`),this}lt(e,s){return this.url.searchParams.append(e,`lt.${s}`),this}lte(e,s){return this.url.searchParams.append(e,`lte.${s}`),this}like(e,s){return this.url.searchParams.append(e,`like.${s}`),this}likeAllOf(e,s){return this.url.searchParams.append(e,`like(all).{${s.join(",")}}`),this}likeAnyOf(e,s){return this.url.searchParams.append(e,`like(any).{${s.join(",")}}`),this}ilike(e,s){return this.url.searchParams.append(e,`ilike.${s}`),this}ilikeAllOf(e,s){return this.url.searchParams.append(e,`ilike(all).{${s.join(",")}}`),this}ilikeAnyOf(e,s){return this.url.searchParams.append(e,`ilike(any).{${s.join(",")}}`),this}is(e,s){return this.url.searchParams.append(e,`is.${s}`),this}in(e,s){const n=Array.from(new Set(s)).map(a=>typeof a=="string"&&new RegExp("[,()]").test(a)?`"${a}"`:`${a}`).join(",");return this.url.searchParams.append(e,`in.(${n})`),this}contains(e,s){return typeof s=="string"?this.url.searchParams.append(e,`cs.${s}`):Array.isArray(s)?this.url.searchParams.append(e,`cs.{${s.join(",")}}`):this.url.searchParams.append(e,`cs.${JSON.stringify(s)}`),this}containedBy(e,s){return typeof s=="string"?this.url.searchParams.append(e,`cd.${s}`):Array.isArray(s)?this.url.searchParams.append(e,`cd.{${s.join(",")}}`):this.url.searchParams.append(e,`cd.${JSON.stringify(s)}`),this}rangeGt(e,s){return this.url.searchParams.append(e,`sr.${s}`),this}rangeGte(e,s){return this.url.searchParams.append(e,`nxl.${s}`),this}rangeLt(e,s){return this.url.searchParams.append(e,`sl.${s}`),this}rangeLte(e,s){return this.url.searchParams.append(e,`nxr.${s}`),this}rangeAdjacent(e,s){return this.url.searchParams.append(e,`adj.${s}`),this}overlaps(e,s){return typeof s=="string"?this.url.searchParams.append(e,`ov.${s}`):this.url.searchParams.append(e,`ov.{${s.join(",")}}`),this}textSearch(e,s,{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}.${s}`),this}match(e){return Object.entries(e).forEach(([s,n])=>{this.url.searchParams.append(s,`eq.${n}`)}),this}not(e,s,n){return this.url.searchParams.append(e,`not.${s}.${n}`),this}or(e,{foreignTable:s,referencedTable:n=s}={}){const a=n?`${n}.or`:"or";return this.url.searchParams.append(a,`(${e})`),this}filter(e,s,n){return this.url.searchParams.append(e,`${s}.${n}`),this}};Ct.default=Ba;var za=ve&&ve.__importDefault||function(r){return r&&r.__esModule?r:{default:r}};Object.defineProperty(Kt,"__esModule",{value:!0});const vt=za(Ct);let Ha=class{constructor(e,{headers:s={},schema:n,fetch:a}){this.url=e,this.headers=s,this.schema=n,this.fetch=a}select(e,{head:s=!1,count:n}={}){const a=s?"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 vt.default({method:a,url:this.url,headers:this.headers,schema:this.schema,fetch:this.fetch,allowEmpty:!1})}insert(e,{count:s,defaultToNull:n=!0}={}){const a="POST",i=[];if(this.headers.Prefer&&i.push(this.headers.Prefer),s&&i.push(`count=${s}`),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 vt.default({method:a,url:this.url,headers:this.headers,schema:this.schema,body:e,fetch:this.fetch,allowEmpty:!1})}upsert(e,{onConflict:s,ignoreDuplicates:n=!1,count:a,defaultToNull:i=!0}={}){const o="POST",l=[`resolution=${n?"ignore":"merge"}-duplicates`];if(s!==void 0&&this.url.searchParams.set("on_conflict",s),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 vt.default({method:o,url:this.url,headers:this.headers,schema:this.schema,body:e,fetch:this.fetch,allowEmpty:!1})}update(e,{count:s}={}){const n="PATCH",a=[];return this.headers.Prefer&&a.push(this.headers.Prefer),s&&a.push(`count=${s}`),this.headers.Prefer=a.join(","),new vt.default({method:n,url:this.url,headers:this.headers,schema:this.schema,body:e,fetch:this.fetch,allowEmpty:!1})}delete({count:e}={}){const s="DELETE",n=[];return e&&n.push(`count=${e}`),this.headers.Prefer&&n.unshift(this.headers.Prefer),this.headers.Prefer=n.join(","),new vt.default({method:s,url:this.url,headers:this.headers,schema:this.schema,fetch:this.fetch,allowEmpty:!1})}};Kt.default=Ha;var Zt={},Qt={};Object.defineProperty(Qt,"__esModule",{value:!0});Qt.version=void 0;Qt.version="0.0.0-automated";Object.defineProperty(Zt,"__esModule",{value:!0});Zt.DEFAULT_HEADERS=void 0;const Ja=Qt;Zt.DEFAULT_HEADERS={"X-Client-Info":`postgrest-js/${Ja.version}`};var Gr=ve&&ve.__importDefault||function(r){return r&&r.__esModule?r:{default:r}};Object.defineProperty(Is,"__esModule",{value:!0});const Ka=Gr(Kt),Wa=Gr(Ct),Va=Zt;let Ya=class Br{constructor(e,{headers:s={},schema:n,fetch:a}={}){this.url=e,this.headers=Object.assign(Object.assign({},Va.DEFAULT_HEADERS),s),this.schemaName=n,this.fetch=a}from(e){const s=new URL(`${this.url}/${e}`);return new Ka.default(s,{headers:Object.assign({},this.headers),schema:this.schemaName,fetch:this.fetch})}schema(e){return new Br(this.url,{headers:this.headers,schema:e,fetch:this.fetch})}rpc(e,s={},{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(s).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=s);const c=Object.assign({},this.headers);return i&&(c.Prefer=`count=${i}`),new Wa.default({method:o,url:l,headers:c,schema:this.schemaName,body:d,fetch:this.fetch,allowEmpty:!1})}};Is.default=Ya;var gt=ve&&ve.__importDefault||function(r){return r&&r.__esModule?r:{default:r}};Object.defineProperty(be,"__esModule",{value:!0});be.PostgrestError=be.PostgrestBuilder=be.PostgrestTransformBuilder=be.PostgrestFilterBuilder=be.PostgrestQueryBuilder=be.PostgrestClient=void 0;const zr=gt(Is);be.PostgrestClient=zr.default;const Hr=gt(Kt);be.PostgrestQueryBuilder=Hr.default;const Jr=gt(Ct);be.PostgrestFilterBuilder=Jr.default;const Kr=gt(Wt);be.PostgrestTransformBuilder=Kr.default;const Wr=gt(Vt);be.PostgrestBuilder=Wr.default;const Vr=gt(Yt);be.PostgrestError=Vr.default;var Za=be.default={PostgrestClient:zr.default,PostgrestQueryBuilder:Hr.default,PostgrestFilterBuilder:Jr.default,PostgrestTransformBuilder:Kr.default,PostgrestBuilder:Wr.default,PostgrestError:Vr.default};const{PostgrestClient:Qa,PostgrestQueryBuilder:Sc,PostgrestFilterBuilder:kc,PostgrestTransformBuilder:Ec,PostgrestBuilder:Cc}=Za,Xa="2.10.7",ei={"X-Client-Info":`realtime-js/${Xa}`},ti="1.0.0",Yr=1e4,si=1e3;var ct;(function(r){r[r.connecting=0]="connecting",r[r.open=1]="open",r[r.closing=2]="closing",r[r.closed=3]="closed"})(ct||(ct={}));var we;(function(r){r.closed="closed",r.errored="errored",r.joined="joined",r.joining="joining",r.leaving="leaving"})(we||(we={}));var ke;(function(r){r.close="phx_close",r.error="phx_error",r.join="phx_join",r.reply="phx_reply",r.leave="phx_leave",r.access_token="access_token"})(ke||(ke={}));var ws;(function(r){r.websocket="websocket"})(ws||(ws={}));var Ve;(function(r){r.Connecting="connecting",r.Open="open",r.Closing="closing",r.Closed="closed"})(Ve||(Ve={}));class ri{constructor(){this.HEADER_LENGTH=1}decode(e,s){return e.constructor===ArrayBuffer?s(this._binaryDecode(e)):s(typeof e=="string"?JSON.parse(e):{})}_binaryDecode(e){const s=new DataView(e),n=new TextDecoder;return this._decodeBroadcast(e,s,n)}_decodeBroadcast(e,s,n){const a=s.getUint8(1),i=s.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 Zr{constructor(e,s){this.callback=e,this.timerCalc=s,this.timer=void 0,this.tries=0,this.callback=e,this.timerCalc=s}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 Q;(function(r){r.abstime="abstime",r.bool="bool",r.date="date",r.daterange="daterange",r.float4="float4",r.float8="float8",r.int2="int2",r.int4="int4",r.int4range="int4range",r.int8="int8",r.int8range="int8range",r.json="json",r.jsonb="jsonb",r.money="money",r.numeric="numeric",r.oid="oid",r.reltime="reltime",r.text="text",r.time="time",r.timestamp="timestamp",r.timestamptz="timestamptz",r.timetz="timetz",r.tsrange="tsrange",r.tstzrange="tstzrange"})(Q||(Q={}));const sr=(r,e,s={})=>{var n;const a=(n=s.skipTypes)!==null&&n!==void 0?n:[];return Object.keys(e).reduce((i,o)=>(i[o]=ni(o,r,e,a),i),{})},ni=(r,e,s,n)=>{const a=e.find(l=>l.name===r),i=a==null?void 0:a.type,o=s[r];return i&&!n.includes(i)?Qr(i,o):vs(o)},Qr=(r,e)=>{if(r.charAt(0)==="_"){const s=r.slice(1,r.length);return li(e,s)}switch(r){case Q.bool:return ai(e);case Q.float4:case Q.float8:case Q.int2:case Q.int4:case Q.int8:case Q.numeric:case Q.oid:return ii(e);case Q.json:case Q.jsonb:return oi(e);case Q.timestamp:return ci(e);case Q.abstime:case Q.date:case Q.daterange:case Q.int4range:case Q.int8range:case Q.money:case Q.reltime:case Q.text:case Q.time:case Q.timestamptz:case Q.timetz:case Q.tsrange:case Q.tstzrange:return vs(e);default:return vs(e)}},vs=r=>r,ai=r=>{switch(r){case"t":return!0;case"f":return!1;default:return r}},ii=r=>{if(typeof r=="string"){const e=parseFloat(r);if(!Number.isNaN(e))return e}return r},oi=r=>{if(typeof r=="string")try{return JSON.parse(r)}catch(e){return console.log(`JSON parse error: ${e}`),r}return r},li=(r,e)=>{if(typeof r!="string")return r;const s=r.length-1,n=r[s];if(r[0]==="{"&&n==="}"){let i;const o=r.slice(1,s);try{i=JSON.parse("["+o+"]")}catch{i=o?o.split(","):[]}return i.map(l=>Qr(e,l))}return r},ci=r=>typeof r=="string"?r.replace(" ","T"):r,Xr=r=>{let e=r;return e=e.replace(/^ws/i,"http"),e=e.replace(/(\/socket\/websocket|\/socket|\/websocket)\/?$/i,""),e.replace(/\/+$/,"")};class os{constructor(e,s,n={},a=Yr){this.channel=e,this.event=s,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,s){var n;return this._hasReceived(e)&&s((n=this.receivedResp)===null||n===void 0?void 0:n.response),this.recHooks.push({status:e,callback:s}),this}startTimeout(){if(this.timeoutTimer)return;this.ref=this.channel.socket._makeRef(),this.refEvent=this.channel._replyEventName(this.ref);const e=s=>{this._cancelRefEvent(),this._cancelTimeout(),this.receivedResp=s,this._matchReceive(s)};this.channel._on(this.refEvent,{},e),this.timeoutTimer=setTimeout(()=>{this.trigger("timeout",{})},this.timeout)}trigger(e,s){this.refEvent&&this.channel._trigger(this.refEvent,{status:e,response:s})}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:s}){this.recHooks.filter(n=>n.status===e).forEach(n=>n.callback(s))}_hasReceived(e){return this.receivedResp&&this.receivedResp.status===e}}var rr;(function(r){r.SYNC="sync",r.JOIN="join",r.LEAVE="leave"})(rr||(rr={}));class St{constructor(e,s){this.channel=e,this.state={},this.pendingDiffs=[],this.joinRef=null,this.caller={onJoin:()=>{},onLeave:()=>{},onSync:()=>{}};const n=(s==null?void 0:s.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=St.syncState(this.state,a,i,o),this.pendingDiffs.forEach(d=>{this.state=St.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=St.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,s,n,a){const i=this.cloneDeep(e),o=this.transformState(s),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(x=>x.presence_ref),p=h.map(x=>x.presence_ref),b=u.filter(x=>p.indexOf(x.presence_ref)<0),j=h.filter(x=>f.indexOf(x.presence_ref)<0);b.length>0&&(l[c]=b),j.length>0&&(d[c]=j)}else l[c]=u}),this.syncDiff(i,{joins:l,leaves:d},n,a)}static syncDiff(e,s,n,a){const{joins:i,leaves:o}={joins:this.transformState(s.joins),leaves:this.transformState(s.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(p=>p.presence_ref),f=u.filter(p=>h.indexOf(p.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,s){return Object.getOwnPropertyNames(e).map(n=>s(n,e[n]))}static transformState(e){return e=this.cloneDeep(e),Object.getOwnPropertyNames(e).reduce((s,n)=>{const a=e[n];return"metas"in a?s[n]=a.metas.map(i=>(i.presence_ref=i.phx_ref,delete i.phx_ref,delete i.phx_ref_prev,i)):s[n]=a,s},{})}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(r){r.ALL="*",r.INSERT="INSERT",r.UPDATE="UPDATE",r.DELETE="DELETE"})(nr||(nr={}));var ar;(function(r){r.BROADCAST="broadcast",r.PRESENCE="presence",r.POSTGRES_CHANGES="postgres_changes",r.SYSTEM="system"})(ar||(ar={}));var ir;(function(r){r.SUBSCRIBED="SUBSCRIBED",r.TIMED_OUT="TIMED_OUT",r.CLOSED="CLOSED",r.CHANNEL_ERROR="CHANNEL_ERROR"})(ir||(ir={}));class Ds{constructor(e,s={config:{}},n){this.topic=e,this.params=s,this.socket=n,this.bindings={},this.state=we.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},s.config),this.timeout=this.socket.timeout,this.joinPush=new os(this,ke.join,this.params,this.timeout),this.rejoinTimer=new Zr(()=>this._rejoinUntilConnected(),this.socket.reconnectAfterMs),this.joinPush.receive("ok",()=>{this.state=we.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=we.closed,this.socket._remove(this)}),this._onError(a=>{this._isLeaving()||this._isClosed()||(this.socket.log("channel",`error ${this.topic}`,a),this.state=we.errored,this.rejoinTimer.scheduleTimeout())}),this.joinPush.receive("timeout",()=>{this._isJoining()&&(this.socket.log("channel",`timeout ${this.topic}`,this.joinPush.timeout),this.state=we.errored,this.rejoinTimer.scheduleTimeout())}),this._on(ke.reply,{},(a,i)=>{this._trigger(this._replyEventName(i),a)}),this.presence=new St(this),this.broadcastEndpointURL=Xr(this.socket.endPoint)+"/api/broadcast",this.private=this.params.config.private||!1}subscribe(e,s=this.timeout){var n,a;if(this.socket.isConnected()||this.socket.connect(),this.joinedOnce)throw"tried to subscribe multiple times. 'subscribe' can only be called a single time per channel instance";{const{config:{broadcast:i,presence:o,private:l}}=this.params;this._onError(u=>e&&e("CHANNEL_ERROR",u)),this._onClose(()=>e&&e("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.accessToken&&(d.access_token=this.socket.accessToken),this.updateJoinPayload(Object.assign({config:c},d)),this.joinedOnce=!0,this._rejoin(s),this.joinPush.receive("ok",({postgres_changes:u})=>{var h;if(this.socket.accessToken&&this.socket.setAuth(this.socket.accessToken),u===void 0){e&&e("SUBSCRIBED");return}else{const f=this.bindings.postgres_changes,p=(h=f==null?void 0:f.length)!==null&&h!==void 0?h:0,b=[];for(let j=0;j<p;j++){const x=f[j],{filter:{event:w,schema:k,table:P,filter:A}}=x,N=u&&u[j];if(N&&N.event===w&&N.schema===k&&N.table===P&&N.filter===A)b.push(Object.assign(Object.assign({},x),{id:N.id}));else{this.unsubscribe(),e&&e("CHANNEL_ERROR",new Error("mismatch between server and client bindings for postgres changes"));return}}this.bindings.postgres_changes=b,e&&e("SUBSCRIBED");return}}).receive("error",u=>{e&&e("CHANNEL_ERROR",new Error(JSON.stringify(Object.values(u).join(", ")||"error")))}).receive("timeout",()=>{e&&e("TIMED_OUT")})}return this}presenceState(){return this.presence.state}async track(e,s={}){return await this.send({type:"presence",event:"track",payload:e},s.timeout||this.timeout)}async untrack(e={}){return await this.send({type:"presence",event:"untrack"},e)}on(e,s,n){return this._on(e,s,n)}async send(e,s={}){var n,a;if(!this._canPush()&&e.type==="broadcast"){const{event:i,payload:o}=e,l={method:"POST",headers:{Authorization:this.socket.accessToken?`Bearer ${this.socket.accessToken}`:"",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 d=await this._fetchWithTimeout(this.broadcastEndpointURL,l,(n=s.timeout)!==null&&n!==void 0?n:this.timeout);return await((a=d.body)===null||a===void 0?void 0:a.cancel()),d.ok?"ok":"error"}catch(d){return d.name==="AbortError"?"timed out":"error"}}else return new Promise(i=>{var o,l,d;const c=this._push(e.type,e,s.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=we.leaving;const s=()=>{this.socket.log("channel",`leave ${this.topic}`),this._trigger(ke.close,"leave",this._joinRef())};return this.rejoinTimer.reset(),this.joinPush.destroy(),new Promise(n=>{const a=new os(this,ke.leave,{},e);a.receive("ok",()=>{s(),n("ok")}).receive("timeout",()=>{s(),n("timed out")}).receive("error",()=>{n("error")}),a.send(),this._canPush()||a.trigger("ok",{})})}async _fetchWithTimeout(e,s,n){const a=new AbortController,i=setTimeout(()=>a.abort(),n),o=await this.socket.fetch(e,Object.assign(Object.assign({},s),{signal:a.signal}));return clearTimeout(i),o}_push(e,s,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 os(this,e,s,n);return this._canPush()?a.send():(a.startTimeout(),this.pushBuffer.push(a)),a}_onMessage(e,s,n){return s}_isMember(e){return this.topic===e}_joinRef(){return this.joinPush.ref}_trigger(e,s,n){var a,i;const o=e.toLocaleLowerCase(),{close:l,error:d,leave:c,join:u}=ke;if(n&&[l,d,c,u].indexOf(o)>=0&&n!==this._joinRef())return;let f=this._onMessage(o,s,n);if(s&&!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(p=>{var b,j,x;return((b=p.filter)===null||b===void 0?void 0:b.event)==="*"||((x=(j=p.filter)===null||j===void 0?void 0:j.event)===null||x===void 0?void 0:x.toLocaleLowerCase())===o}).map(p=>p.callback(f,n)):(i=this.bindings[o])===null||i===void 0||i.filter(p=>{var b,j,x,w,k,P;if(["broadcast","presence","postgres_changes"].includes(o))if("id"in p){const A=p.id,N=(b=p.filter)===null||b===void 0?void 0:b.event;return A&&((j=s.ids)===null||j===void 0?void 0:j.includes(A))&&(N==="*"||(N==null?void 0:N.toLocaleLowerCase())===((x=s.data)===null||x===void 0?void 0:x.type.toLocaleLowerCase()))}else{const A=(k=(w=p==null?void 0:p.filter)===null||w===void 0?void 0:w.event)===null||k===void 0?void 0:k.toLocaleLowerCase();return A==="*"||A===((P=s==null?void 0:s.event)===null||P===void 0?void 0:P.toLocaleLowerCase())}else return p.type.toLocaleLowerCase()===o}).map(p=>{if(typeof f=="object"&&"ids"in f){const b=f.data,{schema:j,table:x,commit_timestamp:w,type:k,errors:P}=b;f=Object.assign(Object.assign({},{schema:j,table:x,commit_timestamp:w,eventType:k,new:{},old:{},errors:P}),this._getPayloadRecords(b))}p.callback(f,n)})}_isClosed(){return this.state===we.closed}_isJoined(){return this.state===we.joined}_isJoining(){return this.state===we.joining}_isLeaving(){return this.state===we.leaving}_replyEventName(e){return`chan_reply_${e}`}_on(e,s,n){const a=e.toLocaleLowerCase(),i={type:a,filter:s,callback:n};return this.bindings[a]?this.bindings[a].push(i):this.bindings[a]=[i],this}_off(e,s){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&&Ds.isEqual(a.filter,s))}),this}static isEqual(e,s){if(Object.keys(e).length!==Object.keys(s).length)return!1;for(const n in e)if(e[n]!==s[n])return!1;return!0}_rejoinUntilConnected(){this.rejoinTimer.scheduleTimeout(),this.socket.isConnected()&&this._rejoin()}_onClose(e){this._on(ke.close,{},e)}_onError(e){this._on(ke.error,{},s=>e(s))}_canPush(){return this.socket.isConnected()&&this._isJoined()}_rejoin(e=this.timeout){this._isLeaving()||(this.socket._leaveOpenTopic(this.topic),this.state=we.joining,this.joinPush.resend(e))}_getPayloadRecords(e){const s={new:{},old:{}};return(e.type==="INSERT"||e.type==="UPDATE")&&(s.new=sr(e.columns,e.record)),(e.type==="UPDATE"||e.type==="DELETE")&&(s.old=sr(e.columns,e.old_record)),s}}const di=()=>{},ui=typeof WebSocket<"u",hi=` addEventListener("message", (e) => { if (e.data.event === "start") { setInterval(() => postMessage({ event: "keepAlive" }), e.data.interval); } });`;class fi{constructor(e,s){var n;this.accessToken=null,this.apiKey=null,this.channels=[],this.endPoint="",this.httpEndpoint="",this.headers=ei,this.params={},this.timeout=Yr,this.heartbeatIntervalMs=3e4,this.heartbeatTimer=void 0,this.pendingHeartbeatRef=null,this.ref=0,this.logger=di,this.conn=null,this.sendBuffer=[],this.serializer=new ri,this.stateChangeCallbacks={open:[],close:[],error:[],message:[]},this._resolveFetch=i=>{let o;return i?o=i:typeof fetch>"u"?o=(...l)=>Re(async()=>{const{default:d}=await Promise.resolve().then(()=>mt);return{default:d}},void 0).then(({default:d})=>d(...l)):o=fetch,(...l)=>o(...l)},this.endPoint=`${e}/${ws.websocket}`,this.httpEndpoint=Xr(e),s!=null&&s.transport?this.transport=s.transport:this.transport=null,s!=null&&s.params&&(this.params=s.params),s!=null&&s.headers&&(this.headers=Object.assign(Object.assign({},this.headers),s.headers)),s!=null&&s.timeout&&(this.timeout=s.timeout),s!=null&&s.logger&&(this.logger=s.logger),s!=null&&s.heartbeatIntervalMs&&(this.heartbeatIntervalMs=s.heartbeatIntervalMs);const a=(n=s==null?void 0:s.params)===null||n===void 0?void 0:n.apikey;if(a&&(this.accessToken=a,this.apiKey=a),this.reconnectAfterMs=s!=null&&s.reconnectAfterMs?s.reconnectAfterMs:i=>[1e3,2e3,5e3,1e4][i-1]||1e4,this.encode=s!=null&&s.encode?s.encode:(i,o)=>o(JSON.stringify(i)),this.decode=s!=null&&s.decode?s.decode:this.serializer.decode.bind(this.serializer),this.reconnectTimer=new Zr(async()=>{this.disconnect(),this.connect()},this.reconnectAfterMs),this.fetch=this._resolveFetch(s==null?void 0:s.fetch),s!=null&&s.worker){if(typeof window<"u"&&!window.Worker)throw new Error("Web Worker is not supported");this.worker=(s==null?void 0:s.worker)||!1,this.workerUrl=s==null?void 0:s.workerUrl}}connect(){if(!this.conn){if(this.transport){this.conn=new this.transport(this._endPointURL(),void 0,{headers:this.headers});return}if(ui){this.conn=new WebSocket(this._endPointURL()),this.setupConnection();return}this.conn=new mi(this._endPointURL(),void 0,{close:()=>{this.conn=null}}),Re(async()=>{const{default:e}=await import("./browser-Bb8gMH3P.js").then(s=>s.b);return{default:e}},__vite__mapDeps([0,1])).then(({default:e})=>{this.conn=new e(this._endPointURL(),void 0,{headers:this.headers}),this.setupConnection()})}}disconnect(e,s){this.conn&&(this.conn.onclose=function(){},e?this.conn.close(e,s??""):this.conn.close(),this.conn=null,this.heartbeatTimer&&clearInterval(this.heartbeatTimer),this.reconnectTimer.reset())}getChannels(){return this.channels}async removeChannel(e){const s=await e.unsubscribe();return this.channels.length===0&&this.disconnect(),s}async removeAllChannels(){const e=await Promise.all(this.channels.map(s=>s.unsubscribe()));return this.disconnect(),e}log(e,s,n){this.logger(e,s,n)}connectionState(){switch(this.conn&&this.conn.readyState){case ct.connecting:return Ve.Connecting;case ct.open:return Ve.Open;case ct.closing:return Ve.Closing;default:return Ve.Closed}}isConnected(){return this.connectionState()===Ve.Open}channel(e,s={config:{}}){const n=new Ds(`realtime:${e}`,s,this);return this.channels.push(n),n}push(e){const{topic:s,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",`${s} ${n} (${i})`,a),this.isConnected()?o():this.sendBuffer.push(o)}setAuth(e){this.accessToken=e,this.channels.forEach(s=>{e&&s.updateJoinPayload({access_token:e}),s.joinedOnce&&s._isJoined()&&s._push(ke.access_token,{access_token:e})})}_makeRef(){let e=this.ref+1;return e===this.ref?this.ref=0:this.ref=e,this.ref.toString()}_leaveOpenTopic(e){let s=this.channels.find(n=>n.topic===e&&(n._isJoined()||n._isJoining()));s&&(this.log("transport",`leaving duplicate topic "${e}"`),s.unsubscribe())}_remove(e){this.channels=this.channels.filter(s=>s._joinRef()!==e._joinRef())}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))}_endPointURL(){return this._appendParams(this.endPoint,Object.assign({},this.params,{vsn:ti}))}_onConnMessage(e){this.decode(e.data,s=>{let{topic:n,event:a,payload:i,ref:o}=s;(o&&o===this.pendingHeartbeatRef||a===(i==null?void 0:i.type))&&(this.pendingHeartbeatRef=null),this.log("receive",`${i.status||""} ${n} ${a} ${o&&"("+o+")"||""}`,i),this.channels.filter(l=>l._isMember(n)).forEach(l=>l._trigger(a,i,o)),this.stateChangeCallbacks.message.forEach(l=>l(s))})}async _onConnOpen(){if(this.log("transport",`connected to ${this._endPointURL()}`),this._flushSendBuffer(),this.reconnectTimer.reset(),!this.worker)this.heartbeatTimer&&clearInterval(this.heartbeatTimer),this.heartbeatTimer=setInterval(()=>this._sendHeartbeat(),this.heartbeatIntervalMs);else{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=s=>{this.log("worker","worker error",s.message),this.workerRef.terminate()},this.workerRef.onmessage=s=>{s.data.event==="keepAlive"&&this._sendHeartbeat()},this.workerRef.postMessage({event:"start",interval:this.heartbeatIntervalMs})}this.stateChangeCallbacks.open.forEach(e=>e())}_onConnClose(e){this.log("transport","close",e),this._triggerChanError(),this.heartbeatTimer&&clearInterval(this.heartbeatTimer),this.reconnectTimer.scheduleTimeout(),this.stateChangeCallbacks.close.forEach(s=>s(e))}_onConnError(e){this.log("transport",e.message),this._triggerChanError(),this.stateChangeCallbacks.error.forEach(s=>s(e))}_triggerChanError(){this.channels.forEach(e=>e._trigger(ke.error))}_appendParams(e,s){if(Object.keys(s).length===0)return e;const n=e.match(/\?/)?"&":"?",a=new URLSearchParams(s);return`${e}${n}${a}`}_flushSendBuffer(){this.isConnected()&&this.sendBuffer.length>0&&(this.sendBuffer.forEach(e=>e()),this.sendBuffer=[])}_sendHeartbeat(){var e;if(this.isConnected()){if(this.pendingHeartbeatRef){this.pendingHeartbeatRef=null,this.log("transport","heartbeat timeout. Attempting to re-establish connection"),(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.setAuth(this.accessToken)}}_workerObjectUrl(e){let s;if(e)s=e;else{const n=new Blob([hi],{type:"application/javascript"});s=URL.createObjectURL(n)}return s}}class mi{constructor(e,s,n){this.binaryType="arraybuffer",this.onclose=()=>{},this.onerror=()=>{},this.onmessage=()=>{},this.onopen=()=>{},this.readyState=ct.connecting,this.send=()=>{},this.url=null,this.url=e,this.close=n.close}}class Ls extends Error{constructor(e){super(e),this.__isStorageError=!0,this.name="StorageError"}}function fe(r){return typeof r=="object"&&r!==null&&"__isStorageError"in r}class gi extends Ls{constructor(e,s){super(e),this.name="StorageApiError",this.status=s}toJSON(){return{name:this.name,message:this.message,status:this.status}}}class js extends Ls{constructor(e,s){super(e),this.name="StorageUnknownError",this.originalError=s}}var pi=function(r,e,s,n){function a(i){return i instanceof s?i:new s(function(o){o(i)})}return new(s||(s=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(r,e||[])).next())})};const en=r=>{let e;return r?e=r:typeof fetch>"u"?e=(...s)=>Re(async()=>{const{default:n}=await Promise.resolve().then(()=>mt);return{default:n}},void 0).then(({default:n})=>n(...s)):e=fetch,(...s)=>e(...s)},xi=()=>pi(void 0,void 0,void 0,function*(){return typeof Response>"u"?(yield Re(()=>Promise.resolve().then(()=>mt),void 0)).Response:Response}),_s=r=>{if(Array.isArray(r))return r.map(s=>_s(s));if(typeof r=="function"||r!==Object(r))return r;const e={};return Object.entries(r).forEach(([s,n])=>{const a=s.replace(/([-_][a-z])/gi,i=>i.toUpperCase().replace(/[-_]/g,""));e[a]=_s(n)}),e};var Xe=function(r,e,s,n){function a(i){return i instanceof s?i:new s(function(o){o(i)})}return new(s||(s=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(r,e||[])).next())})};const ls=r=>r.msg||r.message||r.error_description||r.error||JSON.stringify(r),yi=(r,e,s)=>Xe(void 0,void 0,void 0,function*(){const n=yield xi();r instanceof n&&!(s!=null&&s.noResolveJson)?r.json().then(a=>{e(new gi(ls(a),r.status||500))}).catch(a=>{e(new js(ls(a),a))}):e(new js(ls(r),r))}),bi=(r,e,s,n)=>{const a={method:r,headers:(e==null?void 0:e.headers)||{}};return r==="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),s))};function Tt(r,e,s,n,a,i){return Xe(this,void 0,void 0,function*(){return new Promise((o,l)=>{r(s,bi(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=>yi(d,l,n))})})}function Gt(r,e,s,n){return Xe(this,void 0,void 0,function*(){return Tt(r,"GET",e,s,n)})}function qe(r,e,s,n,a){return Xe(this,void 0,void 0,function*(){return Tt(r,"POST",e,n,a,s)})}function wi(r,e,s,n,a){return Xe(this,void 0,void 0,function*(){return Tt(r,"PUT",e,n,a,s)})}function vi(r,e,s,n){return Xe(this,void 0,void 0,function*(){return Tt(r,"HEAD",e,Object.assign(Object.assign({},s),{noResolveJson:!0}),n)})}function tn(r,e,s,n,a){return Xe(this,void 0,void 0,function*(){return Tt(r,"DELETE",e,n,a,s)})}var ye=function(r,e,s,n){function a(i){return i instanceof s?i:new s(function(o){o(i)})}return new(s||(s=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(r,e||[])).next())})};const ji={limit:100,offset:0,sortBy:{column:"name",order:"asc"}},or={cacheControl:"3600",contentType:"text/plain;charset=UTF-8",upsert:!1};class _i{constructor(e,s={},n,a){this.url=e,this.headers=s,this.bucketId=n,this.fetch=en(a)}uploadOrUpdate(e,s,n,a){return ye(this,void 0,void 0,function*(){try{let i;const o=Object.assign(Object.assign({},or),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(s),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(fe(i))return{data:null,error:i};throw i}})}upload(e,s,n){return ye(this,void 0,void 0,function*(){return this.uploadOrUpdate("POST",e,s,n)})}uploadToSignedUrl(e,s,n,a){return ye(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",s);try{let d;const c=Object.assign({upsert:or.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(fe(d))return{data:null,error:d};throw d}})}createSignedUploadUrl(e,s){return ye(this,void 0,void 0,function*(){try{let n=this._getFinalPath(e);const a=Object.assign({},this.headers);s!=null&&s.upsert&&(a["x-upsert"]="true");const i=yield qe(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 Ls("No token returned by API");return{data:{signedUrl:o.toString(),path:e,token:l},error:null}}catch(n){if(fe(n))return{data:null,error:n};throw n}})}update(e,s,n){return ye(this,void 0,void 0,function*(){return this.uploadOrUpdate("PUT",e,s,n)})}move(e,s,n){return ye(this,void 0,void 0,function*(){try{return{data:yield qe(this.fetch,`${this.url}/object/move`,{bucketId:this.bucketId,sourceKey:e,destinationKey:s,destinationBucket:n==null?void 0:n.destinationBucket},{headers:this.headers}),error:null}}catch(a){if(fe(a))return{data:null,error:a};throw a}})}copy(e,s,n){return ye(this,void 0,void 0,function*(){try{return{data:{path:(yield qe(this.fetch,`${this.url}/object/copy`,{bucketId:this.bucketId,sourceKey:e,destinationKey:s,destinationBucket:n==null?void 0:n.destinationBucket},{headers:this.headers})).Key},error:null}}catch(a){if(fe(a))return{data:null,error:a};throw a}})}createSignedUrl(e,s,n){return ye(this,void 0,void 0,function*(){try{let a=this._getFinalPath(e),i=yield qe(this.fetch,`${this.url}/object/sign/${a}`,Object.assign({expiresIn:s},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(fe(a))return{data:null,error:a};throw a}})}createSignedUrls(e,s,n){return ye(this,void 0,void 0,function*(){try{const a=yield qe(this.fetch,`${this.url}/object/sign/${this.bucketId}`,{expiresIn:s,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(fe(a))return{data:null,error:a};throw a}})}download(e,s){return ye(this,void 0,void 0,function*(){const a=typeof(s==null?void 0:s.transform)<"u"?"render/image/authenticated":"object",i=this.transformOptsToQueryString((s==null?void 0:s.transform)||{}),o=i?`?${i}`:"";try{const l=this._getFinalPath(e);return{data:yield(yield Gt(this.fetch,`${this.url}/${a}/${l}${o}`,{headers:this.headers,noResolveJson:!0})).blob(),error:null}}catch(l){if(fe(l))return{data:null,error:l};throw l}})}info(e){return ye(this,void 0,void 0,function*(){const s=this._getFinalPath(e);try{const n=yield Gt(this.fetch,`${this.url}/object/info/${s}`,{headers:this.headers});return{data:_s(n),error:null}}catch(n){if(fe(n))return{data:null,error:n};throw n}})}exists(e){return ye(this,void 0,void 0,function*(){const s=this._getFinalPath(e);try{return yield vi(this.fetch,`${this.url}/object/${s}`,{headers:this.headers}),{data:!0,error:null}}catch(n){if(fe(n)&&n instanceof js){const a=n.originalError;if([400,404].includes(a==null?void 0:a.status))return{data:!1,error:n}}throw n}})}getPublicUrl(e,s){const n=this._getFinalPath(e),a=[],i=s!=null&&s.download?`download=${s.download===!0?"":s.download}`:"";i!==""&&a.push(i);const l=typeof(s==null?void 0:s.transform)<"u"?"render/image":"object",d=this.transformOptsToQueryString((s==null?void 0:s.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 ye(this,void 0,void 0,function*(){try{return{data:yield tn(this.fetch,`${this.url}/object/${this.bucketId}`,{prefixes:e},{headers:this.headers}),error:null}}catch(s){if(fe(s))return{data:null,error:s};throw s}})}list(e,s,n){return ye(this,void 0,void 0,function*(){try{const a=Object.assign(Object.assign(Object.assign({},ji),s),{prefix:e||""});return{data:yield qe(this.fetch,`${this.url}/object/list/${this.bucketId}`,a,{headers:this.headers},n),error:null}}catch(a){if(fe(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 s=[];return e.width&&s.push(`width=${e.width}`),e.height&&s.push(`height=${e.height}`),e.resize&&s.push(`resize=${e.resize}`),e.format&&s.push(`format=${e.format}`),e.quality&&s.push(`quality=${e.quality}`),s.join("&")}}const Ni="2.7.1",Si={"X-Client-Info":`storage-js/${Ni}`};var nt=function(r,e,s,n){function a(i){return i instanceof s?i:new s(function(o){o(i)})}return new(s||(s=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(r,e||[])).next())})};class ki{constructor(e,s={},n){this.url=e,this.headers=Object.assign(Object.assign({},Si),s),this.fetch=en(n)}listBuckets(){return nt(this,void 0,void 0,function*(){try{return{data:yield Gt(this.fetch,`${this.url}/bucket`,{headers:this.headers}),error:null}}catch(e){if(fe(e))return{data:null,error:e};throw e}})}getBucket(e){return nt(this,void 0,void 0,function*(){try{return{data:yield Gt(this.fetch,`${this.url}/bucket/${e}`,{headers:this.headers}),error:null}}catch(s){if(fe(s))return{data:null,error:s};throw s}})}createBucket(e,s={public:!1}){return nt(this,void 0,void 0,function*(){try{return{data:yield qe(this.fetch,`${this.url}/bucket`,{id:e,name:e,public:s.public,file_size_limit:s.fileSizeLimit,allowed_mime_types:s.allowedMimeTypes},{headers:this.headers}),error:null}}catch(n){if(fe(n))return{data:null,error:n};throw n}})}updateBucket(e,s){return nt(this,void 0,void 0,function*(){try{return{data:yield wi(this.fetch,`${this.url}/bucket/${e}`,{id:e,name:e,public:s.public,file_size_limit:s.fileSizeLimit,allowed_mime_types:s.allowedMimeTypes},{headers:this.headers}),error:null}}catch(n){if(fe(n))return{data:null,error:n};throw n}})}emptyBucket(e){return nt(this,void 0,void 0,function*(){try{return{data:yield qe(this.fetch,`${this.url}/bucket/${e}/empty`,{},{headers:this.headers}),error:null}}catch(s){if(fe(s))return{data:null,error:s};throw s}})}deleteBucket(e){return nt(this,void 0,void 0,function*(){try{return{data:yield tn(this.fetch,`${this.url}/bucket/${e}`,{},{headers:this.headers}),error:null}}catch(s){if(fe(s))return{data:null,error:s};throw s}})}}class Ei extends ki{constructor(e,s={},n){super(e,s,n)}from(e){return new _i(this.url,this.headers,e,this.fetch)}}const Ci="2.46.1";let Nt="";typeof Deno<"u"?Nt="deno":typeof document<"u"?Nt="web":typeof navigator<"u"&&navigator.product==="ReactNative"?Nt="react-native":Nt="node";const Ti={"X-Client-Info":`supabase-js-${Nt}/${Ci}`},Pi={headers:Ti},Ai={schema:"public"},Oi={autoRefreshToken:!0,persistSession:!0,detectSessionInUrl:!0,flowType:"implicit"},$i={};var Ri=function(r,e,s,n){function a(i){return i instanceof s?i:new s(function(o){o(i)})}return new(s||(s=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(r,e||[])).next())})};const Ii=r=>{let e;return r?e=r:typeof fetch>"u"?e=Ur:e=fetch,(...s)=>e(...s)},Di=()=>typeof Headers>"u"?Mr:Headers,Li=(r,e,s)=>{const n=Ii(s),a=Di();return(i,o)=>Ri(void 0,void 0,void 0,function*(){var l;const d=(l=yield e())!==null&&l!==void 0?l:r;let c=new a(o==null?void 0:o.headers);return c.has("apikey")||c.set("apikey",r),c.has("Authorization")||c.set("Authorization",`Bearer ${d}`),n(i,Object.assign(Object.assign({},o),{headers:c}))})};var Fi=function(r,e,s,n){function a(i){return i instanceof s?i:new s(function(o){o(i)})}return new(s||(s=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(r,e||[])).next())})};function Ui(r){return r.replace(/\/$/,"")}function Mi(r,e){const{db:s,auth:n,realtime:a,global:i}=r,{db:o,auth:l,realtime:d,global:c}=e,u={db:Object.assign(Object.assign({},o),s),auth:Object.assign(Object.assign({},l),n),realtime:Object.assign(Object.assign({},d),a),global:Object.assign(Object.assign({},c),i),accessToken:()=>Fi(this,void 0,void 0,function*(){return""})};return r.accessToken?u.accessToken=r.accessToken:delete u.accessToken,u}const sn="2.65.1",qi="http://localhost:9999",Gi="supabase.auth.token",Bi={"X-Client-Info":`gotrue-js/${sn}`},lr=10,Ns="X-Supabase-Api-Version",rn={"2024-01-01":{timestamp:Date.parse("2024-01-01T00:00:00.0Z"),name:"2024-01-01"}};function zi(r){return Math.round(Date.now()/1e3)+r}function Hi(){return"xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx".replace(/[xy]/g,function(r){const e=Math.random()*16|0;return(r=="x"?e:e&3|8).toString(16)})}const Se=()=>typeof document<"u",Ke={tested:!1,writable:!1},kt=()=>{if(!Se())return!1;try{if(typeof globalThis.localStorage!="object")return!1}catch{return!1}if(Ke.tested)return Ke.writable;const r=`lswt-${Math.random()}${Math.random()}`;try{globalThis.localStorage.setItem(r,r),globalThis.localStorage.removeItem(r),Ke.tested=!0,Ke.writable=!0}catch{Ke.tested=!0,Ke.writable=!1}return Ke.writable};function cs(r){const e={},s=new URL(r);if(s.hash&&s.hash[0]==="#")try{new URLSearchParams(s.hash.substring(1)).forEach((a,i)=>{e[i]=a})}catch{}return s.searchParams.forEach((n,a)=>{e[a]=n}),e}const nn=r=>{let e;return r?e=r:typeof fetch>"u"?e=(...s)=>Re(async()=>{const{default:n}=await Promise.resolve().then(()=>mt);return{default:n}},void 0).then(({default:n})=>n(...s)):e=fetch,(...s)=>e(...s)},Ji=r=>typeof r=="object"&&r!==null&&"status"in r&&"ok"in r&&"json"in r&&typeof r.json=="function",an=async(r,e,s)=>{await r.setItem(e,JSON.stringify(s))},$t=async(r,e)=>{const s=await r.getItem(e);if(!s)return null;try{return JSON.parse(s)}catch{return s}},Rt=async(r,e)=>{await r.removeItem(e)};function Ki(r){const e="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=";let s="",n,a,i,o,l,d,c,u=0;for(r=r.replace("-","+").replace("_","/");u<r.length;)o=e.indexOf(r.charAt(u++)),l=e.indexOf(r.charAt(u++)),d=e.indexOf(r.charAt(u++)),c=e.indexOf(r.charAt(u++)),n=o<<2|l>>4,a=(l&15)<<4|d>>2,i=(d&3)<<6|c,s=s+String.fromCharCode(n),d!=64&&a!=0&&(s=s+String.fromCharCode(a)),c!=64&&i!=0&&(s=s+String.fromCharCode(i));return s}class Xt{constructor(){this.promise=new Xt.promiseConstructor((e,s)=>{this.resolve=e,this.reject=s})}}Xt.promiseConstructor=Promise;function cr(r){const e=/^([a-z0-9_-]{4})*($|[a-z0-9_-]{3}=?$|[a-z0-9_-]{2}(==)?$)$/i,s=r.split(".");if(s.length!==3)throw new Error("JWT is not valid: not a JWT structure");if(!e.test(s[1]))throw new Error("JWT is not valid: payload is not in base64url format");const n=s[1];return JSON.parse(Ki(n))}async function Wi(r){return await new Promise(e=>{setTimeout(()=>e(null),r)})}function Vi(r,e){return new Promise((n,a)=>{(async()=>{for(let i=0;i<1/0;i++)try{const o=await r(i);if(!e(i,null,o)){n(o);return}}catch(o){if(!e(i,o)){a(o);return}}})()})}function Yi(r){return("0"+r.toString(16)).substr(-2)}function Zi(){const e=new Uint32Array(56);if(typeof crypto>"u"){const s="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-._~",n=s.length;let a="";for(let i=0;i<56;i++)a+=s.charAt(Math.floor(Math.random()*n));return a}return crypto.getRandomValues(e),Array.from(e,Yi).join("")}async function Qi(r){const s=new TextEncoder().encode(r),n=await crypto.subtle.digest("SHA-256",s),a=new Uint8Array(n);return Array.from(a).map(i=>String.fromCharCode(i)).join("")}function Xi(r){return btoa(r).replace(/\+/g,"-").replace(/\//g,"_").replace(/=+$/,"")}async function eo(r){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."),r;const s=await Qi(r);return Xi(s)}async function at(r,e,s=!1){const n=Zi();let a=n;s&&(a+="/PASSWORD_RECOVERY"),await an(r,`${e}-code-verifier`,a);const i=await eo(n);return[i,n===i?"plain":"s256"]}const to=/^2[0-9]{3}-(0[1-9]|1[0-2])-(0[1-9]|1[0-9]|2[0-9]|3[0-1])$/i;function so(r){const e=r.headers.get(Ns);if(!e||!e.match(to))return null;try{return new Date(`${e}T00:00:00.0Z`)}catch{return null}}class Fs extends Error{constructor(e,s,n){super(e),this.__isAuthError=!0,this.name="AuthError",this.status=s,this.code=n}}function G(r){return typeof r=="object"&&r!==null&&"__isAuthError"in r}class ro extends Fs{constructor(e,s,n){super(e,s,n),this.name="AuthApiError",this.status=s,this.code=n}}function no(r){return G(r)&&r.name==="AuthApiError"}class on extends Fs{constructor(e,s){super(e),this.name="AuthUnknownError",this.originalError=s}}class et extends Fs{constructor(e,s,n,a){super(e,n,a),this.name=s,this.status=n}}class Ue extends et{constructor(){super("Auth session missing!","AuthSessionMissingError",400,void 0)}}function ao(r){return G(r)&&r.name==="AuthSessionMissingError"}class ds extends et{constructor(){super("Auth session or user missing","AuthInvalidTokenResponseError",500,void 0)}}class It extends et{constructor(e){super(e,"AuthInvalidCredentialsError",400,void 0)}}class Dt extends et{constructor(e,s=null){super(e,"AuthImplicitGrantRedirectError",500,void 0),this.details=null,this.details=s}toJSON(){return{name:this.name,message:this.message,status:this.status,details:this.details}}}class dr extends et{constructor(e,s=null){super(e,"AuthPKCEGrantCodeExchangeError",500,void 0),this.details=null,this.details=s}toJSON(){return{name:this.name,message:this.message,status:this.status,details:this.details}}}class Ss extends et{constructor(e,s){super(e,"AuthRetryableFetchError",s,void 0)}}function us(r){return G(r)&&r.name==="AuthRetryableFetchError"}class ur extends et{constructor(e,s,n){super(e,"AuthWeakPasswordError",s,"weak_password"),this.reasons=n}}var io=function(r,e){var s={};for(var n in r)Object.prototype.hasOwnProperty.call(r,n)&&e.indexOf(n)<0&&(s[n]=r[n]);if(r!=null&&typeof Object.getOwnPropertySymbols=="function")for(var a=0,n=Object.getOwnPropertySymbols(r);a<n.length;a++)e.indexOf(n[a])<0&&Object.prototype.propertyIsEnumerable.call(r,n[a])&&(s[n[a]]=r[n[a]]);return s};const We=r=>r.msg||r.message||r.error_description||r.error||JSON.stringify(r),oo=[502,503,504];async function hr(r){var e;if(!Ji(r))throw new Ss(We(r),0);if(oo.includes(r.status))throw new Ss(We(r),r.status);let s;try{s=await r.json()}catch(i){throw new on(We(i),i)}let n;const a=so(r);if(a&&a.getTime()>=rn["2024-01-01"].timestamp&&typeof s=="object"&&s&&typeof s.code=="string"?n=s.code:typeof s=="object"&&s&&typeof s.error_code=="string"&&(n=s.error_code),n){if(n==="weak_password")throw new ur(We(s),r.status,((e=s.weak_password)===null||e===void 0?void 0:e.reasons)||[]);if(n==="session_not_found")throw new Ue}else if(typeof s=="object"&&s&&typeof s.weak_password=="object"&&s.weak_password&&Array.isArray(s.weak_password.reasons)&&s.weak_password.reasons.length&&s.weak_password.reasons.reduce((i,o)=>i&&typeof o=="string",!0))throw new ur(We(s),r.status,s.weak_password.reasons);throw new ro(We(s),r.status||500,n)}const lo=(r,e,s,n)=>{const a={method:r,headers:(e==null?void 0:e.headers)||{}};return r==="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),s))};async function K(r,e,s,n){var a;const i=Object.assign({},n==null?void 0:n.headers);i[Ns]||(i[Ns]=rn["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 co(r,e,s+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 co(r,e,s,n,a,i){const o=lo(e,n,a,i);let l;try{l=await r(s,Object.assign({},o))}catch(d){throw console.error(d),new Ss(We(d),0)}if(l.ok||await hr(l),n!=null&&n.noResolveJson)return l;try{return await l.json()}catch(d){await hr(d)}}function Me(r){var e;let s=null;mo(r)&&(s=Object.assign({},r),r.expires_at||(s.expires_at=zi(r.expires_in)));const n=(e=r.user)!==null&&e!==void 0?e:r;return{data:{session:s,user:n},error:null}}function fr(r){const e=Me(r);return!e.error&&r.weak_password&&typeof r.weak_password=="object"&&Array.isArray(r.weak_password.reasons)&&r.weak_password.reasons.length&&r.weak_password.message&&typeof r.weak_password.message=="string"&&r.weak_password.reasons.reduce((s,n)=>s&&typeof n=="string",!0)&&(e.data.weak_password=r.weak_password),e}function Ge(r){var e;return{data:{user:(e=r.user)!==null&&e!==void 0?e:r},error:null}}function uo(r){return{data:r,error:null}}function ho(r){const{action_link:e,email_otp:s,hashed_token:n,redirect_to:a,verification_type:i}=r,o=io(r,["action_link","email_otp","hashed_token","redirect_to","verification_type"]),l={action_link:e,email_otp:s,hashed_token:n,redirect_to:a,verification_type:i},d=Object.assign({},o);return{data:{properties:l,user:d},error:null}}function fo(r){return r}function mo(r){return r.access_token&&r.refresh_token&&r.expires_in}var go=function(r,e){var s={};for(var n in r)Object.prototype.hasOwnProperty.call(r,n)&&e.indexOf(n)<0&&(s[n]=r[n]);if(r!=null&&typeof Object.getOwnPropertySymbols=="function")for(var a=0,n=Object.getOwnPropertySymbols(r);a<n.length;a++)e.indexOf(n[a])<0&&Object.prototype.propertyIsEnumerable.call(r,n[a])&&(s[n[a]]=r[n[a]]);return s};class po{constructor({url:e="",headers:s={},fetch:n}){this.url=e,this.headers=s,this.fetch=nn(n),this.mfa={listFactors:this._listFactors.bind(this),deleteFactor:this._deleteFactor.bind(this)}}async signOut(e,s="global"){try{return await K(this.fetch,"POST",`${this.url}/logout?scope=${s}`,{headers:this.headers,jwt:e,noResolveJson:!0}),{data:null,error:null}}catch(n){if(G(n))return{data:null,error:n};throw n}}async inviteUserByEmail(e,s={}){try{return await K(this.fetch,"POST",`${this.url}/invite`,{body:{email:e,data:s.data},headers:this.headers,redirectTo:s.redirectTo,xform:Ge})}catch(n){if(G(n))return{data:{user:null},error:n};throw n}}async generateLink(e){try{const{options:s}=e,n=go(e,["options"]),a=Object.assign(Object.assign({},n),s);return"newEmail"in n&&(a.new_email=n==null?void 0:n.newEmail,delete a.newEmail),await K(this.fetch,"POST",`${this.url}/admin/generate_link`,{body:a,headers:this.headers,xform:ho,redirectTo:s==null?void 0:s.redirectTo})}catch(s){if(G(s))return{data:{properties:null,user:null},error:s};throw s}}async createUser(e){try{return await K(this.fetch,"POST",`${this.url}/admin/users`,{body:e,headers:this.headers,xform:Ge})}catch(s){if(G(s))return{data:{user:null},error:s};throw s}}async listUsers(e){var s,n,a,i,o,l,d;try{const c={nextPage:null,lastPage:0,total:0},u=await K(this.fetch,"GET",`${this.url}/admin/users`,{headers:this.headers,noResolveJson:!0,query:{page:(n=(s=e==null?void 0:e.page)===null||s===void 0?void 0:s.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:fo});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,p=(d=(l=u.headers.get("link"))===null||l===void 0?void 0:l.split(","))!==null&&d!==void 0?d:[];return p.length>0&&(p.forEach(b=>{const j=parseInt(b.split(";")[0].split("=")[1].substring(0,1)),x=JSON.parse(b.split(";")[1].split("=")[1]);c[`${x}Page`]=j}),c.total=parseInt(f)),{data:Object.assign(Object.assign({},h),c),error:null}}catch(c){if(G(c))return{data:{users:[]},error:c};throw c}}async getUserById(e){try{return await K(this.fetch,"GET",`${this.url}/admin/users/${e}`,{headers:this.headers,xform:Ge})}catch(s){if(G(s))return{data:{user:null},error:s};throw s}}async updateUserById(e,s){try{return await K(this.fetch,"PUT",`${this.url}/admin/users/${e}`,{body:s,headers:this.headers,xform:Ge})}catch(n){if(G(n))return{data:{user:null},error:n};throw n}}async deleteUser(e,s=!1){try{return await K(this.fetch,"DELETE",`${this.url}/admin/users/${e}`,{headers:this.headers,body:{should_soft_delete:s},xform:Ge})}catch(n){if(G(n))return{data:{user:null},error:n};throw n}}async _listFactors(e){try{const{data:s,error:n}=await K(this.fetch,"GET",`${this.url}/admin/users/${e.userId}/factors`,{headers:this.headers,xform:a=>({data:{factors:a},error:null})});return{data:s,error:n}}catch(s){if(G(s))return{data:null,error:s};throw s}}async _deleteFactor(e){try{return{data:await K(this.fetch,"DELETE",`${this.url}/admin/users/${e.userId}/factors/${e.id}`,{headers:this.headers}),error:null}}catch(s){if(G(s))return{data:null,error:s};throw s}}}const xo={getItem:r=>kt()?globalThis.localStorage.getItem(r):null,setItem:(r,e)=>{kt()&&globalThis.localStorage.setItem(r,e)},removeItem:r=>{kt()&&globalThis.localStorage.removeItem(r)}};function mr(r={}){return{getItem:e=>r[e]||null,setItem:(e,s)=>{r[e]=s},removeItem:e=>{delete r[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 it={debug:!!(globalThis&&kt()&&globalThis.localStorage&&globalThis.localStorage.getItem("supabase.gotrue-js.locks.debug")==="true")};class ln extends Error{constructor(e){super(e),this.isAcquireTimeout=!0}}class bo extends ln{}async function wo(r,e,s){it.debug&&console.log("@supabase/gotrue-js: navigatorLock: acquire lock",r,e);const n=new globalThis.AbortController;return e>0&&setTimeout(()=>{n.abort(),it.debug&&console.log("@supabase/gotrue-js: navigatorLock acquire timed out",r)},e),await globalThis.navigator.locks.request(r,e===0?{mode:"exclusive",ifAvailable:!0}:{mode:"exclusive",signal:n.signal},async a=>{if(a){it.debug&&console.log("@supabase/gotrue-js: navigatorLock: acquired",r,a.name);try{return await s()}finally{it.debug&&console.log("@supabase/gotrue-js: navigatorLock: released",r,a.name)}}else{if(e===0)throw it.debug&&console.log("@supabase/gotrue-js: navigatorLock: not immediately available",r),new bo(`Acquiring an exclusive Navigator LockManager lock "${r}" immediately failed`);if(it.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 s()}})}yo();const vo={url:qi,storageKey:Gi,autoRefreshToken:!0,persistSession:!0,detectSessionInUrl:!0,headers:Bi,flowType:"implicit",debug:!1,hasCustomAuthorizationHeader:!1},jt=30*1e3,gr=3;async function pr(r,e,s){return await s()}class Et{constructor(e){var s,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=Et.nextInstanceID,Et.nextInstanceID+=1,this.instanceID>0&&Se()&&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({},vo),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 po({url:a.url,headers:a.headers,fetch:a.fetch}),this.url=a.url,this.headers=a.headers,this.fetch=nn(a.fetch),this.lock=a.lock||pr,this.detectSessionInUrl=a.detectSessionInUrl,this.flowType=a.flowType,this.hasCustomAuthorizationHeader=a.hasCustomAuthorizationHeader,a.lock?this.lock=a.lock:Se()&&(!((s=globalThis==null?void 0:globalThis.navigator)===null||s===void 0)&&s.locks)?this.lock=wo:this.lock=pr,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:kt()?this.storage=xo:(this.memoryStorage={},this.storage=mr(this.memoryStorage)):(this.memoryStorage={},this.storage=mr(this.memoryStorage)),Se()&&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} (${sn}) ${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(){try{const e=Se()?await this._isPKCEFlow():!1;if(this._debug("#_initialize()","begin","is PKCE flow",e),e||this.detectSessionInUrl&&this._isImplicitGrantFlow()){const{data:s,error:n}=await this._getSessionFromURL(e);if(n)return this._debug("#_initialize()","error detecting session from URL",n),(n==null?void 0:n.code)==="identity_already_exists"?{error:n}:(await this._removeSession(),{error:n});const{session:a,redirectType:i}=s;return this._debug("#_initialize()","detected session in URL",a,"redirect type",i),await this._saveSession(a),setTimeout(async()=>{i==="recovery"?await this._notifyAllSubscribers("PASSWORD_RECOVERY",a):await this._notifyAllSubscribers("SIGNED_IN",a)},0),{error:null}}return await this._recoverAndRefresh(),{error:null}}catch(e){return G(e)?{error:e}:{error:new on("Unexpected error during initialization",e)}}finally{await this._handleVisibilityChange(),this._debug("#_initialize()","end")}}async signInAnonymously(e){var s,n,a;try{const i=await K(this.fetch,"POST",`${this.url}/signup`,{headers:this.headers,body:{data:(n=(s=e==null?void 0:e.options)===null||s===void 0?void 0:s.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:Me}),{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(G(i))return{data:{user:null,session:null},error:i};throw i}}async signUp(e){var s,n,a;try{let i;if("email"in e){const{email:u,password:h,options:f}=e;let p=null,b=null;this.flowType==="pkce"&&([p,b]=await at(this.storage,this.storageKey)),i=await K(this.fetch,"POST",`${this.url}/signup`,{headers:this.headers,redirectTo:f==null?void 0:f.emailRedirectTo,body:{email:u,password:h,data:(s=f==null?void 0:f.data)!==null&&s!==void 0?s:{},gotrue_meta_security:{captcha_token:f==null?void 0:f.captchaToken},code_challenge:p,code_challenge_method:b},xform:Me})}else if("phone"in e){const{phone:u,password:h,options:f}=e;i=await K(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:Me})}else throw new It("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(G(i))return{data:{user:null,session:null},error:i};throw i}}async signInWithPassword(e){try{let s;if("email"in e){const{email:i,password:o,options:l}=e;s=await K(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:fr})}else if("phone"in e){const{phone:i,password:o,options:l}=e;s=await K(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:fr})}else throw new It("You must provide either an email or phone number and a password");const{data:n,error:a}=s;return a?{data:{user:null,session:null},error:a}:!n||!n.session||!n.user?{data:{user:null,session:null},error:new ds}:(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(s){if(G(s))return{data:{user:null,session:null},error:s};throw s}}async signInWithOAuth(e){var s,n,a,i;return await this._handleProviderSignIn(e.provider,{redirectTo:(s=e.options)===null||s===void 0?void 0:s.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 _exchangeCodeForSession(e){const s=await $t(this.storage,`${this.storageKey}-code-verifier`),[n,a]=(s??"").split("/");try{const{data:i,error:o}=await K(this.fetch,"POST",`${this.url}/token?grant_type=pkce`,{headers:this.headers,body:{auth_code:e,code_verifier:n},xform:Me});if(await Rt(this.storage,`${this.storageKey}-code-verifier`),o)throw o;return!i||!i.session||!i.user?{data:{user:null,session:null,redirectType:null},error:new ds}:(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(G(i))return{data:{user:null,session:null,redirectType:null},error:i};throw i}}async signInWithIdToken(e){try{const{options:s,provider:n,token:a,access_token:i,nonce:o}=e,l=await K(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:s==null?void 0:s.captchaToken}},xform:Me}),{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 ds}:(d.session&&(await this._saveSession(d.session),await this._notifyAllSubscribers("SIGNED_IN",d.session)),{data:d,error:c})}catch(s){if(G(s))return{data:{user:null,session:null},error:s};throw s}}async signInWithOtp(e){var s,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 at(this.storage,this.storageKey));const{error:h}=await K(this.fetch,"POST",`${this.url}/otp`,{headers:this.headers,body:{email:l,data:(s=d==null?void 0:d.data)!==null&&s!==void 0?s:{},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 K(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 It("You must provide either an email or phone number.")}catch(l){if(G(l))return{data:{user:null,session:null},error:l};throw l}}async verifyOtp(e){var s,n;try{let a,i;"options"in e&&(a=(s=e.options)===null||s===void 0?void 0:s.redirectTo,i=(n=e.options)===null||n===void 0?void 0:n.captchaToken);const{data:o,error:l}=await K(this.fetch,"POST",`${this.url}/verify`,{headers:this.headers,body:Object.assign(Object.assign({},e),{gotrue_meta_security:{captcha_token:i}}),redirectTo:a,xform:Me});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(G(a))return{data:{user:null,session:null},error:a};throw a}}async signInWithSSO(e){var s,n,a;try{let i=null,o=null;return this.flowType==="pkce"&&([i,o]=await at(this.storage,this.storageKey)),await K(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=(s=e.options)===null||s===void 0?void 0:s.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:uo})}catch(i){if(G(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:s},error:n}=e;if(n)throw n;if(!s)throw new Ue;const{error:a}=await K(this.fetch,"GET",`${this.url}/reauthenticate`,{headers:this.headers,jwt:s.access_token});return{data:{user:null,session:null},error:a}})}catch(e){if(G(e))return{data:{user:null,session:null},error:e};throw e}}async resend(e){try{const s=`${this.url}/resend`;if("email"in e){const{email:n,type:a,options:i}=e,{error:o}=await K(this.fetch,"POST",s,{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 K(this.fetch,"POST",s,{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 It("You must provide either an email or phone number and a type")}catch(s){if(G(s))return{data:{user:null,session:null},error:s};throw s}}async getSession(){return await this.initializePromise,await this._acquireLock(-1,async()=>this._useSession(async s=>s))}async _acquireLock(e,s){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 s()))();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=s();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 s=await this.__loadSession();return await e(s)}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 s=await $t(this.storage,this.storageKey);if(this._debug("#getSession()","session from storage",s),s!==null&&(this._isValidSession(s)?e=s:(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<=Date.now()/1e3:!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 many 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 K(this.fetch,"GET",`${this.url}/user`,{headers:this.headers,jwt:e,xform:Ge}):await this._useSession(async s=>{var n,a,i;const{data:o,error:l}=s;if(l)throw l;return!(!((n=o.session)===null||n===void 0)&&n.access_token)&&!this.hasCustomAuthorizationHeader?{data:{user:null},error:new Ue}:await K(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:Ge})})}catch(s){if(G(s))return ao(s)&&(await this._removeSession(),await Rt(this.storage,`${this.storageKey}-code-verifier`)),{data:{user:null},error:s};throw s}}async updateUser(e,s={}){return await this.initializePromise,await this._acquireLock(-1,async()=>await this._updateUser(e,s))}async _updateUser(e,s={}){try{return await this._useSession(async n=>{const{data:a,error:i}=n;if(i)throw i;if(!a.session)throw new Ue;const o=a.session;let l=null,d=null;this.flowType==="pkce"&&e.email!=null&&([l,d]=await at(this.storage,this.storageKey));const{data:c,error:u}=await K(this.fetch,"PUT",`${this.url}/user`,{headers:this.headers,redirectTo:s==null?void 0:s.emailRedirectTo,body:Object.assign(Object.assign({},e),{code_challenge:l,code_challenge_method:d}),jwt:o.access_token,xform:Ge});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(G(n))return{data:{user:null},error:n};throw n}}_decodeJWT(e){return cr(e)}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 Ue;const s=Date.now()/1e3;let n=s,a=!0,i=null;const o=cr(e.access_token);if(o.exp&&(n=o.exp,a=n<=s),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-s,expires_at:n},await this._saveSession(i),await this._notifyAllSubscribers("SIGNED_IN",i)}return{data:{user:i.user,session:i},error:null}}catch(s){if(G(s))return{data:{session:null,user:null},error:s};throw s}}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 s=>{var n;if(!e){const{data:o,error:l}=s;if(l)throw l;e=(n=o.session)!==null&&n!==void 0?n:void 0}if(!(e!=null&&e.refresh_token))throw new Ue;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(s){if(G(s))return{data:{user:null,session:null},error:s};throw s}}async _getSessionFromURL(e){try{if(!Se())throw new Dt("No browser detected.");if(this.flowType==="implicit"&&!this._isImplicitGrantFlow())throw new Dt("Not a valid implicit grant flow url.");if(this.flowType=="pkce"&&!e)throw new dr("Not a valid PKCE flow url.");const s=cs(window.location.href);if(e){if(!s.code)throw new dr("No code detected.");const{data:k,error:P}=await this._exchangeCodeForSession(s.code);if(P)throw P;const A=new URL(window.location.href);return A.searchParams.delete("code"),window.history.replaceState(window.history.state,"",A.toString()),{data:{session:k.session,redirectType:null},error:null}}if(s.error||s.error_description||s.error_code)throw new Dt(s.error_description||"Error in URL with unspecified error_description",{error:s.error||"unspecified_error",code:s.error_code||"unspecified_code"});const{provider_token:n,provider_refresh_token:a,access_token:i,refresh_token:o,expires_in:l,expires_at:d,token_type:c}=s;if(!i||!l||!o||!c)throw new Dt("No session defined in URL");const u=Math.round(Date.now()/1e3),h=parseInt(l);let f=u+h;d&&(f=parseInt(d));const p=f-u;p*1e3<=jt&&console.warn(`@supabase/gotrue-js: Session as retrieved from URL expires in ${p}s, should have been closer to ${h}s`);const b=f-h;u-b>=120?console.warn("@supabase/gotrue-js: Session as retrieved from URL was issued over 120s ago, URL could be stale",b,f,u):u-b<0&&console.warn("@supabase/gotrue-js: Session as retrieved from URL was issued in the future? Check the device clock for skew",b,f,u);const{data:j,error:x}=await this._getUser(i);if(x)throw x;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:j.user};return window.location.hash="",this._debug("#_getSessionFromURL()","clearing window.location.hash"),{data:{session:w,redirectType:s.type},error:null}}catch(s){if(G(s))return{data:{session:null,redirectType:null},error:s};throw s}}_isImplicitGrantFlow(){const e=cs(window.location.href);return!!(Se()&&(e.access_token||e.error_description))}async _isPKCEFlow(){const e=cs(window.location.href),s=await $t(this.storage,`${this.storageKey}-code-verifier`);return!!(e.code&&s)}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 s=>{var n;const{data:a,error:i}=s;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&&!(no(l)&&(l.status===404||l.status===401||l.status===403)))return{error:l}}return e!=="others"&&(await this._removeSession(),await Rt(this.storage,`${this.storageKey}-code-verifier`)),{error:null}})}onAuthStateChange(e){const s=Hi(),n={id:s,callback:e,unsubscribe:()=>{this._debug("#unsubscribe()","state change callback with id removed",s),this.stateChangeEmitters.delete(s)}};return this._debug("#onAuthStateChange()","registered callback with id",s),this.stateChangeEmitters.set(s,n),(async()=>(await this.initializePromise,await this._acquireLock(-1,async()=>{this._emitInitialSession(s)})))(),{data:{subscription:n}}}async _emitInitialSession(e){return await this._useSession(async s=>{var n,a;try{const{data:{session:i},error:o}=s;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,s={}){let n=null,a=null;this.flowType==="pkce"&&([n,a]=await at(this.storage,this.storageKey,!0));try{return await K(this.fetch,"POST",`${this.url}/recover`,{body:{email:e,code_challenge:n,code_challenge_method:a,gotrue_meta_security:{captcha_token:s.captchaToken}},headers:this.headers,redirectTo:s.redirectTo})}catch(i){if(G(i))return{data:null,error:i};throw i}}async getUserIdentities(){var e;try{const{data:s,error:n}=await this.getUser();if(n)throw n;return{data:{identities:(e=s.user.identities)!==null&&e!==void 0?e:[]},error:null}}catch(s){if(G(s))return{data:null,error:s};throw s}}async linkIdentity(e){var s;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 p=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 K(this.fetch,"GET",p,{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 Se()&&!(!((s=e.options)===null||s===void 0)&&s.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(G(n))return{data:{provider:e.provider,url:null},error:n};throw n}}async unlinkIdentity(e){try{return await this._useSession(async s=>{var n,a;const{data:i,error:o}=s;if(o)throw o;return await K(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(s){if(G(s))return{data:null,error:s};throw s}}async _refreshAccessToken(e){const s=`#_refreshAccessToken(${e.substring(0,5)}...)`;this._debug(s,"begin");try{const n=Date.now();return await Vi(async a=>(a>0&&await Wi(200*Math.pow(2,a-1)),this._debug(s,"refreshing attempt",a),await K(this.fetch,"POST",`${this.url}/token?grant_type=refresh_token`,{body:{refresh_token:e},headers:this.headers,xform:Me})),(a,i)=>{const o=200*Math.pow(2,a);return i&&us(i)&&Date.now()+o-n<jt})}catch(n){if(this._debug(s,"error",n),G(n))return{data:{session:null,user:null},error:n};throw n}finally{this._debug(s,"end")}}_isValidSession(e){return typeof e=="object"&&e!==null&&"access_token"in e&&"refresh_token"in e&&"expires_at"in e}async _handleProviderSignIn(e,s){const n=await this._getUrlForProvider(`${this.url}/authorize`,e,{redirectTo:s.redirectTo,scopes:s.scopes,queryParams:s.queryParams});return this._debug("#_handleProviderSignIn()","provider",e,"options",s,"url",n),Se()&&!s.skipBrowserRedirect&&window.location.assign(n),{data:{provider:e,url:n},error:null}}async _recoverAndRefresh(){var e;const s="#_recoverAndRefresh()";this._debug(s,"begin");try{const n=await $t(this.storage,this.storageKey);if(this._debug(s,"session from storage",n),!this._isValidSession(n)){this._debug(s,"session is not valid"),n!==null&&await this._removeSession();return}const a=Math.round(Date.now()/1e3),i=((e=n.expires_at)!==null&&e!==void 0?e:1/0)<a+lr;if(this._debug(s,`session has${i?"":" not"} expired with margin of ${lr}s`),i){if(this.autoRefreshToken&&n.refresh_token){const{error:o}=await this._callRefreshToken(n.refresh_token);o&&(console.error(o),us(o)||(this._debug(s,"refresh failed with a non-retryable error, removing the session",o),await this._removeSession()))}}else await this._notifyAllSubscribers("SIGNED_IN",n)}catch(n){this._debug(s,"error",n),console.error(n);return}finally{this._debug(s,"end")}}async _callRefreshToken(e){var s,n;if(!e)throw new Ue;if(this.refreshingDeferred)return this.refreshingDeferred.promise;const a=`#_callRefreshToken(${e.substring(0,5)}...)`;this._debug(a,"begin");try{this.refreshingDeferred=new Xt;const{data:i,error:o}=await this._refreshAccessToken(e);if(o)throw o;if(!i.session)throw new Ue;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),G(i)){const o={session:null,error:i};return us(i)||await this._removeSession(),(s=this.refreshingDeferred)===null||s===void 0||s.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,s,n=!0){const a=`#_notifyAllSubscribers(${e})`;this._debug(a,"begin",s,`broadcast = ${n}`);try{this.broadcastChannel&&n&&this.broadcastChannel.postMessage({event:e,session:s});const i=[],o=Array.from(this.stateChangeEmitters.values()).map(async l=>{try{await l.callback(e,s)}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 an(this.storage,this.storageKey,e)}async _removeSession(){this._debug("#_removeSession()"),await Rt(this.storage,this.storageKey),await this._notifyAllSubscribers("SIGNED_OUT",null)}_removeVisibilityChangedCallback(){this._debug("#_removeVisibilityChangedCallback()");const e=this.visibilityChangedCallback;this.visibilityChangedCallback=null;try{e&&Se()&&(window!=null&&window.removeEventListener)&&window.removeEventListener("visibilitychange",e)}catch(s){console.error("removing visibilitychange callback failed",s)}}async _startAutoRefresh(){await this._stopAutoRefresh(),this._debug("#_startAutoRefresh()");const e=setInterval(()=>this._autoRefreshTokenTick(),jt);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 s=>{const{data:{session:n}}=s;if(!n||!n.refresh_token||!n.expires_at){this._debug("#_autoRefreshTokenTick()","no session");return}const a=Math.floor((n.expires_at*1e3-e)/jt);this._debug("#_autoRefreshTokenTick()",`access token expires in ${a} ticks, a tick lasts ${jt}ms, refresh threshold is ${gr} ticks`),a<=gr&&await this._callRefreshToken(n.refresh_token)})}catch(s){console.error("Auto refresh tick failed with error. This is likely a transient error.",s)}}finally{this._debug("#_autoRefreshTokenTick()","end")}})}catch(e){if(e.isAcquireTimeout||e instanceof ln)this._debug("auto refresh token tick lock not available");else throw e}}async _handleVisibilityChange(){if(this._debug("#_handleVisibilityChange()"),!Se()||!(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 s=`#_onVisibilityChanged(${e})`;this._debug(s,"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(s,"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,s,n){const a=[`provider=${encodeURIComponent(s)}`];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 at(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 s=>{var n;const{data:a,error:i}=s;return i?{data:null,error:i}:await K(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(s){if(G(s))return{data:null,error:s};throw s}}async _enroll(e){try{return await this._useSession(async s=>{var n,a;const{data:i,error:o}=s;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 K(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(s){if(G(s))return{data:null,error:s};throw s}}async _verify(e){return this._acquireLock(-1,async()=>{try{return await this._useSession(async s=>{var n;const{data:a,error:i}=s;if(i)return{data:null,error:i};const{data:o,error:l}=await K(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(s){if(G(s))return{data:null,error:s};throw s}})}async _challenge(e){return this._acquireLock(-1,async()=>{try{return await this._useSession(async s=>{var n;const{data:a,error:i}=s;return i?{data:null,error:i}:await K(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(s){if(G(s))return{data:null,error:s};throw s}})}async _challengeAndVerify(e){const{data:s,error:n}=await this._challenge({factorId:e.factorId});return n?{data:null,error:n}:await this._verify({factorId:e.factorId,challengeId:s.id,code:e.code})}async _listFactors(){const{data:{user:e},error:s}=await this.getUser();if(s)return{data:null,error:s};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 s,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 o=this._decodeJWT(a.access_token);let l=null;o.aal&&(l=o.aal);let d=l;((n=(s=a.user.factors)===null||s===void 0?void 0:s.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}}))}}Et.nextInstanceID=0;const jo=Et;class _o extends jo{constructor(e){super(e)}}var No=function(r,e,s,n){function a(i){return i instanceof s?i:new s(function(o){o(i)})}return new(s||(s=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(r,e||[])).next())})};class So{constructor(e,s,n){var a,i,o;if(this.supabaseUrl=e,this.supabaseKey=s,!e)throw new Error("supabaseUrl is required.");if(!s)throw new Error("supabaseKey is required.");const l=Ui(e);this.realtimeUrl=`${l}/realtime/v1`.replace(/^http/i,"ws"),this.authUrl=`${l}/auth/v1`,this.storageUrl=`${l}/storage/v1`,this.functionsUrl=`${l}/functions/v1`;const d=`sb-${new URL(this.authUrl).hostname.split(".")[0]}-auth-token`,c={db:Ai,realtime:$i,auth:Object.assign(Object.assign({},Oi),{storageKey:d}),global:Pi},u=Mi(n??{},c);this.storageKey=(a=u.auth.storageKey)!==null&&a!==void 0?a:"",this.headers=(i=u.global.headers)!==null&&i!==void 0?i:{},u.accessToken?(this.accessToken=u.accessToken,this.auth=new Proxy({},{get:(h,f)=>{throw new Error(`@supabase/supabase-js: Supabase Client is configured with the accessToken option, accessing supabase.auth.${String(f)} is not possible`)}})):this.auth=this._initSupabaseAuthClient((o=u.auth)!==null&&o!==void 0?o:{},this.headers,u.global.fetch),this.fetch=Li(s,this._getAccessToken.bind(this),u.global.fetch),this.realtime=this._initRealtimeClient(Object.assign({headers:this.headers},u.realtime)),this.rest=new Qa(`${l}/rest/v1`,{headers:this.headers,schema:u.db.schema,fetch:this.fetch}),u.accessToken||this._listenForAuthEvents()}get functions(){return new Ca(this.functionsUrl,{headers:this.headers,customFetch:this.fetch})}get storage(){return new Ei(this.storageUrl,this.headers,this.fetch)}from(e){return this.rest.from(e)}schema(e){return this.rest.schema(e)}rpc(e,s={},n={}){return this.rest.rpc(e,s,n)}channel(e,s={config:{}}){return this.realtime.channel(e,s)}getChannels(){return this.realtime.getChannels()}removeChannel(e){return this.realtime.removeChannel(e)}removeAllChannels(){return this.realtime.removeAllChannels()}_getAccessToken(){var e,s;return No(this,void 0,void 0,function*(){if(this.accessToken)return yield this.accessToken();const{data:n}=yield this.auth.getSession();return(s=(e=n.session)===null||e===void 0?void 0:e.access_token)!==null&&s!==void 0?s:null})}_initSupabaseAuthClient({autoRefreshToken:e,persistSession:s,detectSessionInUrl:n,storage:a,storageKey:i,flowType:o,lock:l,debug:d},c,u){var h;const f={Authorization:`Bearer ${this.supabaseKey}`,apikey:`${this.supabaseKey}`};return new _o({url:this.authUrl,headers:Object.assign(Object.assign({},f),c),storageKey:i,autoRefreshToken:e,persistSession:s,detectSessionInUrl:n,storage:a,flowType:o,lock:l,debug:d,fetch:u,hasCustomAuthorizationHeader:(h="Authorization"in this.headers)!==null&&h!==void 0?h:!1})}_initRealtimeClient(e){return new fi(this.realtimeUrl,Object.assign(Object.assign({},e),{params:Object.assign({apikey:this.supabaseKey},e==null?void 0:e.params)}))}_listenForAuthEvents(){return this.auth.onAuthStateChange((s,n)=>{this._handleTokenChanged(s,"CLIENT",n==null?void 0:n.access_token)})}_handleTokenChanged(e,s,n){(e==="TOKEN_REFRESHED"||e==="SIGNED_IN")&&this.changedAccessToken!==n?(this.realtime.setAuth(n??null),this.changedAccessToken=n):e==="SIGNED_OUT"&&(this.realtime.setAuth(this.supabaseKey),s=="STORAGE"&&this.auth.signOut(),this.changedAccessToken=void 0)}}const ko=(r,e,s)=>new So(r,e,s),Eo="https://ftwlzdhkzqfuosdorgjt.supabase.co",Co="eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJpc3MiOiJzdXBhYmFzZSIsInJlZiI6ImZ0d2x6ZGhrenFmdW9zZG9yZ2p0Iiwicm9sZSI6ImFub24iLCJpYXQiOjE3MzE1Mjc0MzksImV4cCI6MjA0NzEwMzQzOX0.msaWtaLGNMDiyuxIOFDwULWee0nqcM7p_LAYWB14j1k",D=ko(Eo,Co,{auth:{persistSession:!0,autoRefreshToken:!0,detectSessionInUrl:!0}}),cn=y.createContext({user:null,isAdmin:!1,loading:!0,signIn:async()=>{},signOut:async()=>{}}),hs="ben@phippsmusic.com";function To({children:r}){const[e,s]=y.useState(null),[n,a]=y.useState(!1),[i,o]=y.useState(!0);y.useEffect(()=>{D.auth.getSession().then(({data:{session:u}})=>{u!=null&&u.user&&(s({id:u.user.id,email:u.user.email||""}),a(u.user.email===hs)),o(!1)});const{data:{subscription:c}}=D.auth.onAuthStateChange((u,h)=>{h!=null&&h.user?(s({id:h.user.id,email:h.user.email||""}),a(h.user.email===hs)):(s(null),a(!1)),o(!1)});return()=>{c.unsubscribe()}},[]);const l=async(c,u)=>{o(!0);try{const{data:h,error:f}=await D.auth.signInWithPassword({email:c,password:u});if(f)throw f;if(h.user.email!==hs)throw await D.auth.signOut(),new Error("Unauthorized access");s({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 D.auth.signOut(),s(null),a(!1)}catch(c){throw console.error("Sign out failed:",c),c}};return t.jsx(cn.Provider,{value:{user:e,isAdmin:n,loading:i,signIn:l,signOut:d},children:r})}function Us(){return y.useContext(cn)}/** * @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 Po={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 Ao=r=>r.replace(/([a-z0-9])([A-Z])/g,"$1-$2").toLowerCase().trim(),L=(r,e)=>{const s=y.forwardRef(({color:n="currentColor",size:a=24,strokeWidth:i=2,absoluteStrokeWidth:o,className:l="",children:d,...c},u)=>y.createElement("svg",{ref:u,...Po,width:a,height:a,stroke:n,strokeWidth:o?Number(i)*24/Number(a):i,className:["lucide",`lucide-${Ao(r)}`,l].join(" "),...c},[...e.map(([h,f])=>y.createElement(h,f)),...Array.isArray(d)?d:[d]]));return s.displayName=`${r}`,s};/** * @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 oe=L("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 Oo=L("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 ze=L("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 dn=L("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 ks=L("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 Ye=L("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 un=L("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 $o=L("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 xr=L("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 Ro=L("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 Io=L("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 Do=L("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 Lo=L("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 Fo=L("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 hn=L("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 Uo=L("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 Mo=L("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 Es=L("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 fn=L("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 qo=L("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 ce=L("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 Go=L("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 Bo=L("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 mn=L("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 zo=L("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 gn=L("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 pe=L("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 es=L("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 Ho=L("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 Ms=L("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 ut=L("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 Jo=L("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 ts=L("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 pn=L("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 Ko=L("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 Wo=L("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 xn=L("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 yn=L("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 qs=L("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 Bt=L("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 ss=L("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 Pt=L("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 yr=L("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 ge=L("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 Vo=L("Zap",[["polygon",{points:"13 2 3 14 12 14 11 22 21 10 12 10 13 2",key:"45s27k"}]]);class bn extends y.Component{constructor(){super(...arguments);Ne(this,"state",{hasError:!1,error:null});Ne(this,"handleRetry",()=>{window.location.reload()})}static getDerivedStateFromError(s){return{hasError:!0,error:s}}componentDidCatch(s,n){console.error("Uncaught error:",s,n)}render(){var s,n;if(this.state.hasError){const i=((s=this.state.error)==null?void 0:s.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(Oo,{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(ut,{className:"w-4 h-4"}),"Retry"]})]})})}return this.props.children}}function Ie(){const[r,e]=y.useState([]),[s,n]=y.useState(!0),[a,i]=y.useState(null);return y.useEffect(()=>{async function o(){try{n(!0),i(null);const{data:l,error:d}=await D.from("genres").select("*").order("display_order");if(d)throw d;const{data:c,error:u}=await D.from("sub_genres").select("*").order("name");if(u)throw u;const h=l.map(f=>({...f,subGenres:c.filter(p=>p.genre_id===f.id).map(p=>({id:p.id,name:p.name,description:p.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:r,loading:s,error:a}}function $e(r){return r?r.toLowerCase().includes("r&b")?"rnb-soul":r.toString().toLowerCase().trim().replace(/[^\w\s-]/g,"").replace(/\s+/g,"-").replace(/-+/g,"-").replace(/^-+|-+$/g,""):""}function Yo(r){return r>=1e6?(r/1e6).toFixed(1)+"M":r>=1e3?(r/1e3).toFixed(1)+"K":r.toString()}function br(){const r=new Date;return`${r.getFullYear()}-${r.getMonth()+1}-${r.getDate()}`}function Lt(r){let e=0;for(let s=0;s<r.length;s++){const n=r.charCodeAt(s);e=(e<<5)-e+n,e=e&e}return e}function Zo({onClose:r}){const{genres:e,loading:s}=Ie();if(s)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(X,{to:"/genres",onClick:r,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(fn,{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(X,{to:`/genre/${$e(o.name)}`,onClick:r,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(pe,{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 Ae(){const r=Qe(),[e,s]=y.useState(!1),[n,a]=y.useState(!1),i=y.useRef();y.useRef(null);const o=r.pathname.startsWith("/submit"),l=()=>{i.current&&clearTimeout(i.current),s(!0)},d=()=>{i.current=setTimeout(()=>{s(!1)},300)};return y.useEffect(()=>{a(!1)},[r.pathname]),y.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(X,{to:"/",className:"flex items-center gap-3 hover:opacity-90 transition-opacity",children:[t.jsx(es,{className:"w-8 h-8"}),t.jsx("h1",{className:"text-2xl font-bold whitespace-nowrap",children:"Playlist Partner"})]}),!o&&t.jsx(X,{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(ge,{className:"w-6 h-6"}):t.jsx(zo,{className:"w-6 h-6"})}),t.jsxs("div",{className:"hidden md:flex items-center gap-8",children:[t.jsx(X,{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(X,{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(Zo,{onClose:()=>s(!1)})]})]}),t.jsx(X,{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(X,{to:"/about",className:"flex items-center gap-2 text-white hover:text-white/90 transition-colors py-2 px-3 -ml-3",children:"About"}),!o&&t.jsx(X,{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(X,{to:"/playlists",className:"block px-4 py-2 hover:bg-white/10 rounded-lg",onClick:()=>a(!1),children:"Browse Playlists"}),t.jsx(X,{to:"/genres",className:"block px-4 py-2 hover:bg-white/10 rounded-lg",onClick:()=>a(!1),children:"Browse Genres"}),t.jsx(X,{to:"/for-curators",className:"block px-4 py-2 hover:bg-white/10 rounded-lg",onClick:()=>a(!1),children:"For Curators"}),t.jsx(X,{to:"/about",className:"block px-4 py-2 hover:bg-white/10 rounded-lg",onClick:()=>a(!1),children:"About"})]})})]})})}function Oe(){const{genres:r}=Ie();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(es,{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:r.map(e=>t.jsx(X,{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 Je({title:r,description:e,image:s="https://ftwlzdhkzqfuosdorgjt.supabase.co/storage/v1/object/public/playlistpartner%20public/playlistpartner%20og%20image.png",url:n,type:a="website",noIndex:i=!1,playlist:o}){var f;const l=o?`Submit Music to ${o.name} - Free Spotify Playlist Submission`:r||"Free Spotify Playlist Submission – No Signup | PlaylistPartner",d=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 ${((f=o.genre_count)==null?void 0:f.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.",c=e||d,u=n||window.location.href.split("?")[0],h=window.location.origin;return t.jsxs(wa,{children:[t.jsx("title",{children:l}),t.jsx("meta",{name:"description",content:c,"data-react-helmet":"true"}),t.jsx("link",{rel:"canonical",href:u}),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:l,"data-react-helmet":"true"}),t.jsx("meta",{property:"og:description",content:c,"data-react-helmet":"true"}),t.jsx("meta",{property:"og:type",content:a}),t.jsx("meta",{property:"og:url",content:u}),t.jsx("meta",{property:"og:image",content:s,"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:l,"data-react-helmet":"true"}),t.jsx("meta",{name:"twitter:description",content:c,"data-react-helmet":"true"}),t.jsx("meta",{name:"twitter:image",content:s,"data-react-helmet":"true"}),t.jsx("meta",{name:"twitter:site",content:"@playlistpartner"}),t.jsx("script",{type:"application/ld+json",children:JSON.stringify({"@context":"https://schema.org","@type":"WebSite",name:"PlaylistPartner",url:h,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:u}})})]})}const zt="last_submission_data",Qo=30*24*60*60*1e3;function wn(r){try{const e={artistName:r.artistName,email:r.email,lastTrack:r.track,lastUpdated:Date.now()};localStorage.setItem(zt,JSON.stringify(e))}catch(e){console.error("Failed to save submission data:",e)}}function ht(){try{const r=localStorage.getItem(zt);if(!r)return null;const e=JSON.parse(r);return Date.now()-e.lastUpdated>Qo?(localStorage.removeItem(zt),null):{artistName:e.artistName,email:e.email,lastTrack:e.lastTrack}}catch(r){return console.error("Failed to retrieve submission data:",r),null}}function vn(){try{localStorage.removeItem(zt),localStorage.removeItem("trackSubmissions"),localStorage.removeItem("playlist_submissions"),localStorage.removeItem("spotify_token"),sessionStorage.clear()}catch(r){console.error("Failed to reset storage data:",r)}}const Xo=y.lazy(()=>Re(()=>import("./FeaturedPlaylists-CGac0gns.js"),__vite__mapDeps([2,3,1])).then(r=>({default:r.FeaturedPlaylists}))),el=y.lazy(()=>Re(()=>Promise.resolve().then(()=>El),void 0).then(r=>({default:r.SubmissionModal}))),tl=()=>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."})]})]})]})})}),sl=()=>{var e,s;const r=ht();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"})]}),(r==null?void 0:r.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=r.lastTrack.album.images[2])==null?void 0:e.url,alt:r.lastTrack.name,className:"w-12 h-12 object-cover rounded-md",loading:"lazy"}),t.jsxs("div",{children:[t.jsx("p",{className:"font-medium",children:r.lastTrack.name}),t.jsx("p",{className:"text-sm text-gray-600",children:(s=r.lastTrack.artists[0])==null?void 0:s.name})]})]}),t.jsx("button",{onClick:()=>{vn(),window.location.reload()},className:"p-2 hover:bg-gray-100 rounded-full transition-colors",title:"Clear selected track",children:t.jsx(ge,{className:"w-5 h-5 text-gray-500"})})]}),t.jsx("div",{className:"border-l-4 border-green-500 pl-6",children:t.jsx(y.Suspense,{fallback:t.jsx("div",{className:"h-32 flex items-center justify-center",children:t.jsx(ce,{className:"w-8 h-8 animate-spin"})}),children:t.jsx(Xo,{})})})]})})},rl=()=>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(X,{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 nl(){const[r,e]=y.useState(null);return t.jsxs(t.Fragment,{children:[t.jsx(Je,{}),t.jsxs("main",{children:[t.jsx(tl,{}),t.jsxs("div",{className:"container mx-auto px-4 pb-12",children:[t.jsx(y.Suspense,{fallback:null,children:t.jsx(sl,{})}),t.jsx(rl,{}),t.jsxs(y.Suspense,{fallback:null,children:[t.jsx(al,{}),t.jsx(il,{})]})]}),r&&t.jsx(y.Suspense,{fallback:null,children:t.jsx(el,{playlist:r,onClose:()=>e(null),onSubmit:()=>e(null)})})]})]})}const al=y.lazy(()=>Re(()=>import("./FAQSection-DqnOdgPP.js"),__vite__mapDeps([4,3,1]))),il=y.lazy(()=>Re(()=>import("./AdditionalInfoSection-jTLY8rfk.js"),__vite__mapDeps([5,3,1])));function ol(r){const[e,s]=y.useState(null),[n,a]=y.useState(!0),[i,o]=y.useState(null),[l,d]=y.useState([]);return y.useEffect(()=>{let c=!0;async function u(){if(!r){o(new Error("Invalid playlist URL")),a(!1);return}try{a(!0),o(null);const{data:h,error:f}=await D.from("playlist_details").select("*").eq("slug",r).limit(1);if(f)throw f;if(!h||h.length===0)throw new Error("Playlist not found");const p=h[0];if(c){s(p);const{data:b,error:j}=await D.from("playlist_details").select("*").eq("genre",p.genre).neq("id",p.id).order("followers",{ascending:!1}).limit(4);!j&&b&&d(b)}}catch(h){console.error("Failed to fetch playlist:",h),c&&(o(h instanceof Error?h:new Error("Failed to fetch playlist")),s(null),d([]))}finally{c&&a(!1)}}return u(),()=>{c=!1}},[r]),{playlist:e,loading:n,error:i,relatedPlaylists:l,isNotFound:(i==null?void 0:i.message)==="Playlist not found"}}const Cs="playlist_submissions";function ll(r,e){try{const s=JSON.parse(localStorage.getItem(Cs)||"[]"),n=s.find(a=>a.playlistId===r);n?n.tracks.some(a=>a.spotifyUrl===e)||n.tracks.push({spotifyUrl:e,timestamp:Date.now()}):s.push({playlistId:r,tracks:[{spotifyUrl:e,timestamp:Date.now()}]}),localStorage.setItem(Cs,JSON.stringify(s))}catch(s){console.error("Failed to track submission:",s)}}function jn(r,e){try{const n=JSON.parse(localStorage.getItem(Cs)||"[]").find(a=>a.playlistId===r);return!!(n!=null&&n.tracks.some(a=>a.spotifyUrl===e))}catch(s){return console.error("Failed to check submission status:",s),!1}}const Ts="scrollPositions",cl=5*60*1e3,dl=10,ul=100;function wr(){try{return JSON.parse(sessionStorage.getItem(Ts)||"[]")}catch{return[]}}const _n={savePosition(r,e){try{const s=wr(),n=window.scrollY;if(n>0){s.push({pathname:r,position:n,timestamp:Date.now(),searchParams:e==null?void 0:e.toString()});const a=s.filter(i=>Date.now()-i.timestamp<cl);sessionStorage.setItem(Ts,JSON.stringify(a))}}catch(s){console.error("Failed to save scroll position:",s)}},restorePosition(r,e){try{const s=wr(),n=s.find(a=>a.pathname===r);if(n){const a=s.filter(l=>l!==n);sessionStorage.setItem(Ts,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>=dl){window.scrollTo({top:d,behavior:"instant"});return}i++,setTimeout(o,ul)};setTimeout(o,50)}}catch(s){console.error("Failed to restore scroll position:",s)}}};function Gs({playlist:r,onSubmit:e,isRelated:s,priority:n=!1,hideSubmit:a=!1}){const i=He(),o=Qe(),[l]=Tr(),[d,c]=y.useState(!1),u=ht(),h=(u==null?void 0:u.lastTrack)&&jn(r.id,u.lastTrack.external_urls.spotify),f=p=>{p.preventDefault(),s||_n.savePosition(o.pathname,l);const b=o.pathname.startsWith("/genre/");window.scrollTo({top:0,behavior:"instant"}),i(`/playlist/${r.slug}`,{state:{from:b?"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/${r.slug}`,onClick:f,className:"cursor-pointer no-js-fallback",children:[t.jsxs("div",{className:"relative pb-[100%] bg-gray-100",children:[d||!r.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(hn,{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:r.name})]})}):t.jsx("img",{src:r.image_url,alt:r.name,className:"absolute inset-0 w-full h-full object-cover sm:rounded-[2px] lg:rounded-[4px]",loading:n?"eager":"lazy",onError:()=>c(!0)}),r.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(yn,{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:r.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:r.description}),t.jsxs("div",{className:"space-y-2",children:[t.jsxs("div",{className:"flex items-center gap-4 text-sm",children:[t.jsxs(X,{to:`/genre/${r.genre_slug}`,onClick:p=>p.stopPropagation(),className:"flex items-center text-gray-700 hover:text-green-600 transition-colors",children:[t.jsx(pe,{className:"w-4 h-4 mr-1 flex-shrink-0"}),t.jsx("span",{className:"truncate",children:r.genre})]}),t.jsxs("div",{className:"flex items-center text-gray-700",children:[t.jsx(Pt,{className:"w-4 h-4 mr-1 flex-shrink-0"}),t.jsx("span",{children:r.followers.toLocaleString()})]})]}),r.curator_name&&t.jsxs("div",{className:"flex items-center gap-2 text-sm text-gray-600",children:[t.jsx(ss,{className:"w-4 h-4 flex-shrink-0"}),r.curator_profile_url?t.jsx("a",{href:r.curator_profile_url,target:"_blank",rel:"noopener noreferrer",onClick:p=>p.stopPropagation(),className:"truncate hover:text-green-600 transition-colors",children:r.curator_name}):t.jsx("span",{className:"truncate",children:r.curator_name})]})]})]})]}),!a&&t.jsx("div",{className:"px-4 py-3 border-t border-gray-100 mt-auto",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(un,{className:"w-3.5 h-3.5"}),"Submitted"]}):t.jsxs("button",{onClick:p=>{p.stopPropagation(),e(r.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(pn,{className:"w-3.5 h-3.5"}),"Submit"]})})]})}const Ht=10,fs=24*60*60*1e3;function Mt(r){return ml(r,"track")||r}function hl(r,e){try{if(!r||!e)return{allowed:!1,remainingSubmissions:0,timeUntilReset:null,totalSubmissions:0,alreadySubmittedToPlaylist:!1};const s=JSON.parse(localStorage.getItem("trackSubmissions")||"[]"),n=Date.now(),a=Mt(r),i=s.filter(d=>n-d.timestamp<fs);i.length<s.length&&localStorage.setItem("trackSubmissions",JSON.stringify(i));const o=i.find(d=>Mt(d.spotifyUrl)===a&&d.playlistId===e);if(o)return{allowed:!1,remainingSubmissions:0,timeUntilReset:Math.max(0,fs-(n-o.timestamp)),totalSubmissions:i.length,alreadySubmittedToPlaylist:!0};const l=i.filter(d=>Mt(d.spotifyUrl)===a);if(l.length>=Ht){const d=l.reduce((u,h)=>h.timestamp<u.timestamp?h:u);return{allowed:!1,remainingSubmissions:0,timeUntilReset:Math.max(0,fs-(n-d.timestamp)),totalSubmissions:l.length,alreadySubmittedToPlaylist:!1}}return{allowed:!0,remainingSubmissions:Ht-l.length,timeUntilReset:null,totalSubmissions:l.length,alreadySubmittedToPlaylist:!1}}catch(s){return console.error("Rate limit check failed:",s),{allowed:!1,remainingSubmissions:0,timeUntilReset:null,totalSubmissions:0,alreadySubmittedToPlaylist:!1}}}function fl(r,e){if(!(!r||!e))try{const s=JSON.parse(localStorage.getItem("trackSubmissions")||"[]");s.push({timestamp:Date.now(),spotifyUrl:Mt(r),playlistId:e}),localStorage.setItem("trackSubmissions",JSON.stringify(s))}catch(s){console.error("Failed to record submission:",s)}}function ml(r,e){if(!r)return null;try{const s=[new RegExp(`${e}/([a-zA-Z0-9]+)`),new RegExp(`${e}:([a-zA-Z0-9]+)`)];for(const n of s){const a=r.match(n);if(a&&a[1])return a[1]}return null}catch(s){return console.error("Failed to extract ID:",s),null}}const vr=/([a-zA-Z0-9._-]+@[a-zA-Z0-9._-]+\.[a-zA-Z0-9._-]+)/gi,gl=/(?:e-?mail|email)\s*:*\s*/gi,pl=/(?:https?:\/\/)?(?:(?:www|bit|t|tinyurl)\.[a-z]{2,}|[a-z0-9-]+(?:\.[a-z]{2,})+)(?:\/[^\s]*)?/gi,xl=/(?:https?:\/\/|;to\/|\.com\/|\.co\/|\.ly\/|\.be\/|href=")[^\s]*/gi,yl=/<[^>]*>|<[^>]*$/g,bl=/&([a-z0-9]+|#[0-9]{1,6}|#x[0-9a-fA-F]{1,6});/gi,wl=/(?:@[\w-]+|#[\w-]+)/g;function vl(r){const e=document.createElement("textarea");return r.replace(bl,(s,n)=>(e.innerHTML=s,e.value||s))}function Nn(r){let e=r,s=null;const n=r.match(vr);return n&&(s=n[0].toLowerCase(),e=e.replace(vr,"")),e=e.replace(gl,""),e=e.replace(pl,"").replace(xl,""),e=e.replace(yl,""),e=e.replace(wl,""),e=vl(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:s}}const jl="76b2d4d1d7bf4e8cb8ad64047c0c5851",_l="1c3baa4d0f0044d5a1e3bb830cfe2214",jr=15e3;let _r=0;function Nl(r){try{if(r.startsWith("spotify:")){const s=r.split(":");return`https://open.spotify.com/${s[1]}/${s[2]}`}return`https://open.spotify.com${new URL(r).pathname}`}catch{return r}}function ft(r,e){if(!r)return null;try{const s=Nl(r),n=[new RegExp(`${e}/([a-zA-Z0-9]+)`),new RegExp(`${e}:([a-zA-Z0-9]+)`)];for(const a of n){const i=s.match(a);if(i&&i[1])return i[1]}return null}catch(s){return console.error("Failed to extract ID:",s),null}}async function Bs(){try{const r=localStorage.getItem("spotify_token");if(r){const a=JSON.parse(r);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(`${jl}:${_l}`)}`},body:"grant_type=client_credentials"});if(!e.ok)throw new Error(`Failed to get access token: ${e.status} ${e.statusText}`);const s=await e.json(),n={access_token:s.access_token,expires_at:Date.now()+s.expires_in*1e3};return localStorage.setItem("spotify_token",JSON.stringify(n)),n.access_token}catch(r){throw console.error("Failed to get Spotify access token:",r),new Error("Failed to authenticate with Spotify")}}async function zs(r){const s=Date.now()-_r;return s<jr&&await new Promise(n=>setTimeout(n,jr-s)),_r=Date.now(),r()}async function Hs(r){try{return await zs(async()=>{const e=await Bs(),s=await fetch(`https://api.spotify.com/v1/playlists/${r}?fields=id,name,description,images,followers,owner(id,display_name,external_urls),tracks(total)`,{headers:{Authorization:`Bearer ${e}`}});if(!s.ok){if(s.status===404)return null;throw s.status===429?new Error("Rate limit exceeded. Please try again later."):new Error(`Failed to fetch playlist: ${s.status} ${s.statusText}`)}const n=await s.json(),{description:a,extractedEmail:i}=Nn(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 Sl(r){if(!r.trim())return[];try{return await zs(async()=>{var a;const e=await Bs(),s=await fetch(`https://api.spotify.com/v1/search?q=${encodeURIComponent(r)}&type=track&limit=5`,{headers:{Authorization:`Bearer ${e}`}});if(!s.ok)throw s.status===429?new Error("Rate limit exceeded. Please try again later."):new Error(`Search failed: ${s.status} ${s.statusText}`);const n=await s.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 Nr(r){if(!r)return null;try{return await zs(async()=>{const e=await Bs(),s=await fetch(`https://api.spotify.com/v1/tracks/${encodeURIComponent(r)}`,{headers:{Authorization:`Bearer ${e}`}});if(!s.ok){if(s.status===404)return null;throw s.status===429?new Error("Rate limit exceeded. Please try again later."):new Error(`Failed to fetch track: ${s.status} ${s.statusText}`)}const n=await s.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 kl(r,e){const[s,n]=y.useState(r);return y.useEffect(()=>{const a=setTimeout(()=>{n(r)},e);return()=>{clearTimeout(a)}},[r,e]),s}function Sn({onTrackSelect:r,initialUrl:e,selectedTrack:s,onClearTrack:n}){var A;const[a,i]=y.useState(""),[o,l]=y.useState([]),[d,c]=y.useState(!1),[u,h]=y.useState(!1),[f,p]=y.useState(null),b=kl(a,300),j=y.useRef(null);y.useEffect(()=>{const N=S=>{j.current&&!j.current.contains(S.target)&&h(!1)};return document.addEventListener("mousedown",N),()=>document.removeEventListener("mousedown",N)},[]),y.useEffect(()=>{async function N(){if(!b.trim()){l([]);return}c(!0),p(null);try{const S=await Sl(b);S.length===0&&p("No tracks found"),l(S),h(!0)}catch(S){console.error("Failed to fetch tracks:",S),p("Failed to search tracks. Please try again.")}finally{c(!1)}}N()},[b]),y.useEffect(()=>{async function N(){if(e){const S=ft(e,"track");if(S){c(!0),p(null);try{const _=await Nr(S);_?r(_):p("Track not found")}catch(_){console.error("Failed to fetch initial track:",_),p("Failed to load track. Please try again.")}finally{c(!1)}}}}N()},[e,r]);const x=async N=>{r(N),h(!1),i(""),p(null)},w=async N=>{i(N),p(null);const S=ft(N,"track");if(S){c(!0);try{const _=await Nr(S);_?x(_):p("Invalid Spotify URL or track not found")}catch(_){console.error("Failed to fetch track:",_),p("Failed to load track. Please try again.")}finally{c(!1)}}},k=N=>{N.preventDefault(),N.stopPropagation(),n(),i(""),p(null),h(!1),setTimeout(()=>{var _;const S=(_=j.current)==null?void 0:_.querySelector("input");S&&S.focus()},0)},P=N=>{N.key==="Enter"&&(N.preventDefault(),N.stopPropagation())};return s?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:(A=s.album.images[s.album.images.length-1])==null?void 0:A.url,alt:s.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:s.name}),t.jsx("p",{className:"text-sm text-gray-600",children:s.artists.map(N=>N.name).join(", ")}),t.jsx("p",{className:"text-xs text-gray-500",children:s.album.name})]}),t.jsx("button",{onClick:k,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(ge,{className:"w-4 h-4 text-gray-600"})})]}):t.jsxs("div",{ref:j,className:"relative",children:[t.jsxs("div",{className:"relative",children:[t.jsx(ts,{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:N=>w(N.target.value),onFocus:()=>h(!0),onKeyDown:P,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(ce,{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(oe,{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(N=>{var S;return t.jsxs("button",{onClick:_=>{_.preventDefault(),x(N)},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:(S=N.album.images[N.album.images.length-1])==null?void 0:S.url,alt:N.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:N.name}),t.jsx("p",{className:"text-sm text-gray-500 line-clamp-1",children:N.artists.map(_=>_.name).join(", ")})]})]},N.id)}),d&&t.jsxs("div",{className:"p-4 text-center text-gray-500",children:[t.jsx(ce,{className:"w-6 h-6 animate-spin mx-auto"}),t.jsx("p",{className:"mt-2",children:"Searching tracks..."})]})]})]})}const qt={async submit(r){const{data:e,error:s}=await D.from("submissions").insert({playlist_id:r.playlistId,track_id:r.trackId,track_name:r.trackName,track_url:r.trackUrl,artist_name:r.artistName,email:r.email,message:r.message,status:"pending",created_at:new Date().toISOString(),updated_at:new Date().toISOString()}).select(` *, playlist:playlists ( name ) `).single();if(s)throw console.error("Failed to create submission:",s),s;return e},async getAll(){const{data:r,error:e}=await D.from("submission_details").select("*").order("created_at",{ascending:!1});if(e)throw console.error("Failed to fetch submissions:",e),e;return r.map(s=>({...s,playlist:{name:s.playlist_name}}))},async getHistory(r){const{data:e,error:s}=await D.from("submission_details").select("*").eq("email",r).order("created_at",{ascending:!1});if(s)throw console.error("Failed to fetch submission history:",s),s;return e.map(n=>({...n,playlist:{name:n.playlist_name}}))},async getForPlaylist(r){const{data:e,error:s}=await D.from("submission_details").select("*").eq("playlist_id",r).order("created_at",{ascending:!1});if(s)throw console.error("Failed to fetch playlist submissions:",s),s;return e.map(n=>({...n,playlist:{name:n.playlist_name}}))},async updateStatus(r,e){const{data:s,error:n}=await D.from("submissions").update({status:e,reviewed_at:e==="pending"?null:new Date().toISOString(),updated_at:new Date().toISOString()}).eq("id",r).select(` *, playlist:playlists ( name ) `).single();if(n)throw console.error("Failed to update submission status:",n),n;return s}};function pt({playlist:r,onClose:e,onSubmit:s}){const[n,a]=y.useState(()=>{var k;const w=ht();return{spotifyUrl:((k=w==null?void 0:w.lastTrack)==null?void 0:k.external_urls.spotify)||"",artistName:(w==null?void 0:w.artistName)||"",email:(w==null?void 0:w.email)||"",message:""}}),[i,o]=y.useState(()=>{const w=ht();return(w==null?void 0:w.lastTrack)||null}),[l,d]=y.useState({}),[c,u]=y.useState({allowed:!0,remainingSubmissions:Ht,timeUntilReset:null,totalSubmissions:0,alreadySubmittedToPlaylist:!1}),[h,f]=y.useState("");y.useEffect(()=>{const w=P=>{const A=document.querySelector(".modal-content");A&&!A.contains(P.target)&&e()},k=P=>{P.key==="Escape"&&e()};return document.addEventListener("mousedown",w),document.addEventListener("keydown",k),()=>{document.removeEventListener("mousedown",w),document.removeEventListener("keydown",k)}},[e]),y.useEffect(()=>{if(n.spotifyUrl){const w=hl(n.spotifyUrl,r.id);u(w)}},[n.spotifyUrl,r.id]),y.useEffect(()=>{let w;const k=()=>{if(c.timeUntilReset){const P=Math.floor(c.timeUntilReset/36e5),A=Math.floor(c.timeUntilReset%(1e3*60*60)/(1e3*60)),N=Math.floor(c.timeUntilReset%(1e3*60)/1e3);f(`${P}h ${A}m ${N}s`)}};return c.timeUntilReset&&(k(),w=setInterval(()=>{const P=c.timeUntilReset-1e3;P<=0?(clearInterval(w),u(A=>({...A,timeUntilReset:null,allowed:!0}))):(u(A=>({...A,timeUntilReset:P})),k())},1e3)),()=>{w&&clearInterval(w)}},[c.timeUntilReset]);const p=()=>{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},b=async w=>{if(w.preventDefault(),!(!c.allowed||c.alreadySubmittedToPlaylist)&&p())try{const k=ft(n.spotifyUrl,"track");if(!k||!i)throw new Error("Invalid track selection");await qt.submit({playlistId:r.id,trackId:k,trackName:i.name,trackUrl:n.spotifyUrl,artistName:n.artistName,email:n.email,message:n.message}),wn({artistName:n.artistName,email:n.email,track:i}),fl(n.spotifyUrl,r.id),ll(r.id,n.spotifyUrl),s(n)}catch(k){console.error("Failed to submit track:",k),d(P=>({...P,submit:"Failed to submit track. Please try again."}))}},j=w=>{o(w),a(k=>{var P;return{...k,spotifyUrl:w.external_urls.spotify,artistName:((P=w.artists[0])==null?void 0:P.name)||k.artistName}}),d(k=>({...k,spotifyUrl:void 0}))},x=()=>{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(ge,{className:"w-6 h-6"})})]}),t.jsxs("p",{className:"mt-2 text-gray-600",children:["Submitting to: ",r.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(oe,{className:"w-4 h-4"}),"Already submitted to this playlist"]}):c.allowed?t.jsxs("span",{children:[c.remainingSubmissions,"/",Ht," Submissions Remaining Today"]}):t.jsxs(t.Fragment,{children:[t.jsxs("div",{className:"flex items-center gap-1",children:[t.jsx(oe,{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:b,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(Es,{className:"w-4 h-4"}),"Search and Select Your Track"]}),t.jsx(Sn,{onTrackSelect:j,selectedTrack:i,onClearTrack:x}),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(ss,{className:"w-4 h-4"}),"Artist Name"]}),t.jsx("input",{type:"text",placeholder:"Your artist name",value:n.artistName,onChange:w=>a(k=>({...k,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(mn,{className:"w-4 h-4"}),"Email"]}),t.jsx("input",{type:"email",placeholder:"your@email.com",value:n.email,onChange:w=>a(k=>({...k,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(gn,{className:"w-4 h-4"}),"Message (Optional)"]}),t.jsx("textarea",{placeholder:"Tell the curator about your track...",value:n.message,onChange:w=>a(k=>({...k,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(oe,{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(pe,{className:"w-4 h-4"}),"Submit Track"]})]})]})]})})}const El=Object.freeze(Object.defineProperty({__proto__:null,SubmissionModal:pt},Symbol.toStringTag,{value:"Module"}));function Cl({message:r,type:e,onClose:s}){const[n,a]=y.useState(!1);y.useEffect(()=>{const l=setTimeout(()=>{a(!0)},4700);return()=>clearTimeout(l)},[]),y.useEffect(()=>{if(n){const l=setTimeout(()=>{s()},300);return()=>clearTimeout(l)}},[n,s]);const i={success:"bg-green-500",error:"bg-red-500",info:"bg-blue-500"}[e],o={success:ks,error:oe,info:oe}[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:r}),t.jsx("button",{onClick:()=>a(!0),className:"p-1 hover:bg-white/20 rounded-full transition-colors",children:t.jsx(ge,{className:"w-4 h-4"})})]})}function De(r){const[e]=y.useState(()=>{let s=document.getElementById("toast-container");return s||(s=document.createElement("div"),s.id="toast-container",document.body.appendChild(s)),s});return Cr.createPortal(t.jsx(Cl,{...r}),e)}function Tl({playlist:r,baseUrl:e}){var n;const s={"@context":"https://schema.org","@type":"MusicPlaylist",name:r.name,description:`Get your music featured on ${r.name}, a Spotify playlist curated by ${r.curator_name} with ${r.followers.toLocaleString()} followers. No account needed! Access thousands of playlists and connect with curators on PlaylistPartner.com.`,numTracks:r.track_count,url:`${e}/playlist/${r.spotify_id}`,sameAs:[`https://open.spotify.com/playlist/${r.spotify_id}`],dateModified:r.updated_at,image:r.image_url,author:{"@type":"Person",name:r.curator_name,url:r.curator_profile_url},genre:[r.genre,...((n=r.sub_genres)==null?void 0:n.slice(0,2))||[]].filter(Boolean),interactionStatistic:{"@type":"InteractionCounter",interactionType:"https://schema.org/FollowAction",userInteractionCount:r.followers},isPartOf:{"@id":e}};return t.jsx("script",{type:"application/ld+json",children:JSON.stringify(s)})}function Pl(){var N;const{slug:r}=Os(),e=He(),s=Qe(),[n,a]=y.useState(!1),[i,o]=y.useState(null),[l,d]=y.useState(0),{playlist:c,loading:u,error:h,relatedPlaylists:f,isNotFound:p}=ol(r||""),[b,j]=y.useState(!1);y.useEffect(()=>{!u&&c&&!h&&!p&&typeof window<"u"&&window.prerenderReady!==void 0&&(window.prerenderReady=!0)},[u,c,h,p]),y.useEffect(()=>{async function S(){if(c!=null&&c.genre){const{count:_}=await D.from("playlist_details").select("*",{count:"exact",head:!0}).eq("genre",c.genre);d(_||0)}}c&&S()},[c]);const x=ht(),w=c&&(x==null?void 0:x.lastTrack)&&jn(c.id,x.lastTrack.external_urls.spotify),k=()=>{var _;const S=(_=s.state)==null?void 0:_.from;e(S==="genre"?-1:"/")},P=async S=>{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(_){console.error("Failed to submit track:",_),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(p||!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(oe,{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:k,className:"text-green-600 hover:text-green-700 flex items-center gap-2 mx-auto",children:[t.jsx(ze,{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(oe,{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:k,className:"text-green-600 hover:text-green-700 flex items-center gap-2 mx-auto",children:[t.jsx(ze,{className:"w-4 h-4"}),"Back to Playlists"]})]})});const A=`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(Je,{title:c==null?void 0:c.name,description:A,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(Tl,{playlist:c,baseUrl:window.location.origin}),t.jsxs("main",{className:"container mx-auto px-4 py-8",children:[t.jsxs("button",{onClick:k,className:"inline-flex items-center gap-2 text-green-600 hover:text-green-700 mb-6",children:[t.jsx(ze,{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||b?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(hn,{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:()=>j(!0)})}),t.jsxs("div",{className:"p-6 flex flex-col justify-between",children:[t.jsxs("div",{children:[t.jsx("h1",{className:"text-3xl md:text-4xl font-bold mb-2",children:c.name}),t.jsxs("div",{className:"flex items-center gap-2 text-gray-600 mb-4",children:[t.jsx(ss,{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(X,{to:`/genre/${c.genre_slug}`,className:"flex items-center text-gray-700 hover:text-green-600 transition-colors",children:[t.jsx(pe,{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(Pt,{className:"w-5 h-5 mr-2"}),t.jsxs("span",{className:"text-lg",children:[c.followers.toLocaleString()," followers"]})]})]}),((N=c.sub_genres)==null?void 0:N.length)>0&&t.jsx("div",{className:"flex flex-wrap gap-2 mb-6",children:c.sub_genres.map(S=>t.jsx(X,{to:`/genre/${c.genre_slug}/${S.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:S},S))})]}),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(un,{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(pn,{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(S=>t.jsx(Gs,{playlist:S,onSubmit:()=>a(!0),isRelated:!0,hideSubmit:!0},S.id))})]}),n&&c&&t.jsx(pt,{playlist:c,onClose:()=>a(!1),onSubmit:P}),i&&t.jsx(De,{message:i.message,type:i.type,onClose:()=>o(null)})]})]})}function Al({filters:r,onFilterChange:e,hideGenreFilter:s}){const{genres:n,loading:a}=Ie(),i=n.find(o=>o.name===r.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 ${s?"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(ts,{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:r.search,onChange:o=>e({...r,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"})]}),!s&&t.jsxs("div",{className:"relative",children:[t.jsx(pe,{className:"absolute left-3 top-1/2 transform -translate-y-1/2 text-gray-400 w-5 h-5"}),t.jsxs("select",{value:r.genre,onChange:o=>e({...r,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:r.subGenre||"",onChange:o=>e({...r,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:r.sortBy,onChange:o=>e({...r,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 _t="playlist_state";function At(r){const[e,s]=y.useState(()=>{try{const j=sessionStorage.getItem(_t);if(j){const x=JSON.parse(j);if(JSON.stringify(x.filters)===JSON.stringify(r))return x.playlists}return[]}catch{return[]}}),[n,a]=y.useState(!0),[i,o]=y.useState(null),[l,d]=y.useState(!0),[c,u]=y.useState(()=>{try{const j=sessionStorage.getItem(_t);if(j){const x=JSON.parse(j);if(JSON.stringify(x.filters)===JSON.stringify(r))return x.currentPage}return 1}catch{return 1}}),[h,f]=y.useState(0),p=12;return y.useEffect(()=>{!n&&h>0&&typeof window<"u"&&window.prerenderReady!==void 0&&(window.prerenderReady=!0)},[n,h]),y.useEffect(()=>{(()=>{const x=sessionStorage.getItem(_t);if(x){const w=JSON.parse(x);return JSON.stringify(w.filters)!==JSON.stringify(r)}return!0})()&&(s([]),u(1),d(!0),sessionStorage.removeItem(_t))},[r==null?void 0:r.genre,r==null?void 0:r.subGenre,r==null?void 0:r.search,r==null?void 0:r.sortBy]),y.useEffect(()=>{if(e.length>0){const j={playlists:e,currentPage:c,filters:r||{}};sessionStorage.setItem(_t,JSON.stringify(j))}},[e,c,r]),y.useEffect(()=>{async function j(){try{a(!0),o(null);let x=D.from("playlist_details").select("*",{count:"exact"});if(r!=null&&r.genre&&(x=x.eq("genre",r.genre)),r!=null&&r.subGenre&&(x=x.contains("sub_genres",[r.subGenre])),r!=null&&r.search){const N=`%${r.search}%`;x=x.or(`name.ilike.${N},description.ilike.${N}`)}switch(r==null?void 0:r.sortBy){case"followers-high":x=x.order("followers",{ascending:!1});break;case"followers-low":x=x.order("followers",{ascending:!0});break;default:if(!(r!=null&&r.genre)&&!(r!=null&&r.subGenre)){const{data:N}=await D.from("playlist_details").select("*").eq("featured",!0).order("created_at",{ascending:!1}).limit(4),S=(c-1)*p;let _=D.from("playlist_details").select("*",{count:"exact"}).eq("featured",!1).order("created_at",{ascending:!1});if(r!=null&&r.search){const v=`%${r.search}%`;_=_.or(`name.ilike.${v},description.ilike.${v}`)}const{data:m,count:g}=await _.range(S,S+p-1);if(c===1){const v=[...N||[],...m||[]];s(v)}else s(v=>{const E=new Set(v.map(T=>T.id)),C=(m||[]).filter(T=>!E.has(T.id));return[...v,...C]});f((g||0)+((N==null?void 0:N.length)||0)),d(S+p<(g||0)),a(!1);return}else{const{data:N}=await D.from("playlist_details").select("*").eq("featured",!0).eq("genre",r.genre).order("created_at",{ascending:!1}).limit(4),S=(c-1)*p;let _=D.from("playlist_details").select("*",{count:"exact"}).eq("featured",!1).eq("genre",r.genre).order("created_at",{ascending:!1});if(r!=null&&r.search){const v=`%${r.search}%`;_=_.or(`name.ilike.${v},description.ilike.${v}`)}const{data:m,count:g}=await _.range(S,S+p-1);if(c===1){const v=[...N||[],...m||[]];s(v)}else s(v=>{const E=new Set(v.map(T=>T.id)),C=(m||[]).filter(T=>!E.has(T.id));return[...v,...C]});f((g||0)+((N==null?void 0:N.length)||0)),d(S+p<(g||0)),a(!1);return}}const w=(c-1)*p;x=x.range(w,w+p-1);const{data:k,error:P,count:A}=await x;if(P)throw P;f(A||0),s(N=>{const S=k||[];if(c===1)return S;const _=new Set(N.map(g=>g.id)),m=S.filter(g=>!_.has(g.id));return[...N,...m]}),d(w+p<(A||0))}catch(x){console.error("Failed to fetch playlists:",x),o(x instanceof Error?x:new Error("Failed to fetch playlists"))}finally{a(!1)}}j()},[c,r==null?void 0:r.genre,r==null?void 0:r.subGenre,r==null?void 0:r.search,r==null?void 0:r.sortBy]),{playlists:e,loading:n,error:i,hasMore:l,loadMore:()=>{!n&&l&&u(j=>j+1)},currentPage:c,totalCount:h,itemsPerPage:p}}function Ol(){var S,_;const r=Qe(),[e,s]=Tr(),[n,a]=y.useState(()=>{var v;const m=(v=r.state)==null?void 0:v.filters,g=sessionStorage.getItem("playlist_filters");return g&&!(m!=null&&m.fromSubmission)?JSON.parse(g):m?(window.history.replaceState({},""),{search:"",genre:m.genre||"",subGenre:m.subGenre||"",sortBy:"default"}):{search:"",genre:"",subGenre:"",sortBy:"default"}});y.useEffect(()=>{window.scrollTo(0,0)},[]);const{playlists:i,loading:o,error:l,hasMore:d,loadMore:c,currentPage:u,totalCount:h,itemsPerPage:f}=At({...n,genre:n.genre||void 0,subGenre:n.subGenre||void 0}),[p,b]=y.useState(null),[j,x]=y.useState(null),w=ht(),[k,P]=y.useState(!0);y.useEffect(()=>{var m;if(!o&&i.length>0&&k){const g=(m=r.state)==null?void 0:m.filters;g!=null&&g.fromSubmission?window.scrollTo(0,0):_n.restorePosition(r.pathname,s),P(!1)}},[o,i.length,r.pathname,r.state,s,k]),y.useEffect(()=>{sessionStorage.setItem("playlist_filters",JSON.stringify(n))},[n]);const A=(u-1)*f+1,N=Math.min(u*f,h);return t.jsxs(t.Fragment,{children:[t.jsx(Je,{}),t.jsxs("main",{children:[t.jsxs("div",{className:"container mx-auto px-4 pb-12",children:[t.jsx(Al,{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:(S=w.lastTrack.album.images[2])==null?void 0:S.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:(_=w.lastTrack.artists[0])==null?void 0:_.name})]})]}),t.jsx("button",{onClick:()=>{vn(),window.location.reload()},className:"p-2 hover:bg-gray-100 rounded-full transition-colors",title:"Clear selected track",children:t.jsx(ge,{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 ",A,"-",N," 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,g)=>t.jsx(Gs,{playlist:m,onSubmit:v=>b(i.find(E=>E.id===v)||null),priority:g<4},`${m.id}-${g}`))}),o&&t.jsx("div",{className:"flex items-center justify-center py-12",children:t.jsx(ce,{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"})})]})]}),p&&t.jsx(pt,{playlist:p,onClose:()=>b(null),onSubmit:()=>{b(null),x({type:"success",message:`Track submitted to ${p.name}! Watch your inbox for feedback from the curator.`})}}),j&&t.jsx(De,{message:j.message,type:j.type,onClose:()=>x(null)})]})]})}function $l(){const r=He(),[e,s]=y.useState(null);y.useEffect(()=>{typeof window<"u"&&window.prerenderReady!==void 0&&(window.prerenderReady=!0)},[]);const n=a=>{var i;wn({artistName:((i=a.artists[0])==null?void 0:i.name)||"",email:"",track:a}),r("/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:()=>r("/playlists"),className:"flex items-center gap-2 text-gray-600 hover:text-gray-800 transition-colors mb-6",children:[t.jsx(ze,{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(Sn,{onTrackSelect:n,selectedTrack:e,onClearTrack:()=>s(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(dn,{className:"w-5 h-5"})]})]})]})}function Rl(){const r=He(),{genres:e,loading:s}=Ie(),[n,a]=y.useState(""),[i,o]=y.useState(""),l=e.find(h=>h.id===n),d=(l==null?void 0:l.subGenres)||[],c=h=>{o(h)},u=h=>{if(!n||!l)return;const f=i?d.find(p=>p.id===i):null;window.scrollTo(0,0),r("/playlists",{state:{filters:{genre:l.name,subGenre:(f==null?void 0:f.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(h=>t.jsxs("button",{onClick:()=>{a(h.id),o("")},className:`p-4 text-center border-2 rounded-lg transition-colors ${n===h.id?"border-green-500 bg-green-50":"border-gray-200 hover:border-green-500 hover:bg-green-50"}`,children:[t.jsx(pe,{className:"w-6 h-6 mx-auto mb-2 text-gray-600"}),t.jsx("span",{className:"font-medium",children:h.name})]},h.id))})]}),n&&d.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:d.map(h=>t.jsx("button",{onClick:()=>c(h.id),className:`p-3 text-center border-2 rounded-lg transition-colors ${i===h.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:h.name})},h.id))})]}),t.jsxs("div",{className:"flex justify-between items-center",children:[t.jsxs("button",{onClick:()=>r("/submit"),className:"flex items-center gap-2 text-gray-600 hover:text-gray-800 transition-colors",children:[t.jsx(ze,{className:"w-5 h-5"}),"Back to Track Selection"]}),t.jsxs("button",{onClick:()=>u(),disabled:!n,className:`flex items-center gap-2 px-6 py-3 rounded-lg font-medium transition-colors ${n?"bg-green-500 text-white hover:bg-green-600":"bg-gray-200 text-gray-500 cursor-not-allowed"}`,children:["Continue to Playlists",t.jsx(dn,{className:"w-5 h-5"})]})]})]})})}function Il(r=4,e,s){const[n,a]=y.useState([]),[i,o]=y.useState(!0),[l,d]=y.useState(null);return y.useEffect(()=>{!i&&n.length>0&&typeof window<"u"&&window.prerenderReady!==void 0&&(window.prerenderReady=!0)},[i,n.length]),y.useEffect(()=>{async function c(){try{o(!0),d(null);let u=D.from("playlist_details").select("*").eq("featured",!0);e&&(u=u.eq("genre",e)),s&&(u=u.contains("sub_genres",[s]));const{data:h,error:f}=await u;if(f)throw f;if(h&&h.length>=r){const A=br(),N=[...h].sort((S,_)=>{const m=Lt(`${A}-${S.id}`),g=Lt(`${A}-${_.id}`);return m-g});a(N.slice(0,r));return}let p=D.from("playlist_details").select("*").eq("featured",!1);e&&(p=p.eq("genre",e)),s&&(p=p.contains("sub_genres",[s]));const{data:b,error:j}=await p;if(j)throw j;const w=[...h||[],...b||[]].filter((A,N,S)=>N===S.findIndex(_=>_.id===A.id)),k=br(),P=w.sort((A,N)=>{const S=Lt(`${k}-${A.id}`),_=Lt(`${k}-${N.id}`);return S-_});a(P.slice(0,r))}catch(u){console.error("Failed to fetch playlists:",u),d(u instanceof Error?u:new Error("Failed to fetch playlists"))}finally{o(!1)}}c()},[r,e,s]),{playlists:n,loading:i,error:l}}function kn({genre:r,subGenre:e,totalCount:s,onViewAll:n}){const{playlists:a,loading:i}=Il(8,r,e),[o,l]=y.useState(null),[d,c]=y.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} ${r} Playlists - ${h}`:`Today's Featured ${r} Playlists - ${h}`,p=new URLSearchParams;return p.set("genre",r),e&&p.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(b=>t.jsx(Gs,{playlist:b,onSubmit:j=>l(a.find(x=>x.id===j)||null),priority:!0},b.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 ",s.toLocaleString()," ",e?`${e} ${r}`:r," Playlists"]})}),o&&t.jsx(pt,{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(De,{message:d.message,type:d.type,onClose:()=>c(null)})]})}const Dl="https://ftwlzdhkzqfuosdorgjt.supabase.co/storage/v1/object/public/playlistpartner%20public/playlistpartner%20og%20image.png";function Ll(){const{genre:r}=Os(),e=r?decodeURIComponent(r):"",{genres:s,loading:n}=Ie(),a=s.find(w=>w.slug===e),[i,o]=y.useState(null),[l,d]=y.useState(!1),[c,u]=y.useState(null),h=He(),{totalCount:f}=At({genre:a==null?void 0:a.name}),p=()=>{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(ce,{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(X,{to:"/",className:"text-green-600 hover:text-green-700",children:"Return to Home"})]});const b=`Free ${a.name} Spotify Playlist Submission - No Signup`,j=`Submit your ${a.name} tracks to ${f} Spotify playlists for free. Connect with independent curators and grow your audience — no signup needed.`,x=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(k){console.error("Failed to submit track:",k),u({type:"error",message:"Failed to submit track. Please try again."})}};return t.jsxs(t.Fragment,{children:[t.jsx(Je,{title:b,description:j,image:Dl,url:`${window.location.origin}/genre/${a.slug}`,type:"website"}),t.jsxs("main",{className:"container mx-auto px-4 py-8",children:[t.jsxs(X,{to:"/",className:"inline-flex items-center gap-2 text-green-600 hover:text-green-700 mb-6",children:[t.jsx(ze,{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(pe,{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(kn,{genre:a.name,totalCount:f,onViewAll:p}),l&&i&&t.jsx(pt,{playlist:i,onClose:()=>{d(!1),o(null)},onSubmit:x}),c&&t.jsx(De,{message:c.message,type:c.type,onClose:()=>u(null)})]})]})}const Fl="https://ftwlzdhkzqfuosdorgjt.supabase.co/storage/v1/object/public/playlistpartner%20public/playlistpartner%20og%20image.png";function Ul(){const{genre:r,subGenre:e}=Os(),s=r?decodeURIComponent(r):"",n=e?decodeURIComponent(e):"",{genres:a,loading:i}=Ie(),o=a.find(A=>A.slug===s),l=o==null?void 0:o.subGenres.find(A=>$e(A.name)===n),[d,c]=y.useState(null),[u,h]=y.useState(!1),[f,p]=y.useState(null),b=He(),{totalCount:j}=At({genre:o==null?void 0:o.name,subGenre:l==null?void 0:l.name}),x=()=>{!o||!l||(window.scrollTo(0,0),b("/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(ce,{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(X,{to:"/",className:"text-green-600 hover:text-green-700",children:"Return to Home"})]});const w=`Free ${l.name} Spotify Playlist Submission - No Signup`,k=`Submit your ${l.name} tracks to ${j} Spotify playlists for free. Connect with independent curators and grow your audience — no signup needed.`,P=async A=>{try{h(!1),p({type:"success",message:`Track submitted to ${d==null?void 0:d.name}! Watch your inbox for feedback from the curator.`})}catch(N){console.error("Failed to submit track:",N),p({type:"error",message:"Failed to submit track. Please try again."})}};return t.jsxs(t.Fragment,{children:[t.jsx(Je,{title:w,description:k,image:Fl,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(X,{to:`/genre/${encodeURIComponent(o.slug)}`,className:"inline-flex items-center gap-2 text-green-600 hover:text-green-700 mb-6",children:[t.jsx(ze,{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(pe,{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:[j," Playlists"]})})]})]})}),t.jsx(kn,{genre:o.name,subGenre:l.name,totalCount:j,onViewAll:x}),u&&d&&t.jsx(pt,{playlist:d,onClose:()=>{h(!1),c(null)},onSubmit:P}),f&&t.jsx(De,{message:f.message,type:f.type,onClose:()=>p(null)})]})]})}function Ml(){const{genres:r,loading:e}=Ie();return y.useEffect(()=>{!e&&r.length>0&&typeof window<"u"&&window.prerenderReady!==void 0&&(window.prerenderReady=!0)},[e,r]),t.jsxs(t.Fragment,{children:[t.jsx(Je,{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(X,{to:"/",className:"inline-flex items-center gap-2 text-green-600 hover:text-green-700 mb-6",children:[t.jsx(ze,{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((s,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:r.map(s=>t.jsxs("div",{className:"bg-white p-6 rounded-lg shadow-sm",children:[t.jsxs(X,{to:`/genre/${$e(s.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(pe,{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:s.name})]}),s.subGenres.length>0&&t.jsx("div",{className:"space-y-1",children:s.subGenres.map(n=>t.jsxs(X,{to:`/genre/${$e(s.name)}/${$e(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))})]},s.id))})]})]})}function ql(){const{totalCount:r}=At({});return t.jsxs(t.Fragment,{children:[t.jsx(Je,{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(es,{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(Lo,{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(Vo,{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(Pt,{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:[r.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 Gl(){const[r,e]=y.useState({name:"",email:"",playlistUrl:""}),[s,n]=y.useState(!1),[a,i]=y.useState(null),[o,l]=y.useState(!1);y.useEffect(()=>{typeof window<"u"&&window.prerenderReady!==void 0&&(window.prerenderReady=!0)},[]);const d=u=>{const h=ft(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(r.email))throw new Error("Please enter a valid email address");const h=d(r.playlistUrl),{error:f}=await D.from("curator_applications").insert({name:r.name,email:r.email,playlist_url:r.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(Je,{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(es,{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(Ro,{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(Pt,{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(Ye,{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(Ye,{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(Ye,{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(Ye,{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(Ye,{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:r.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:s})]}),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:r.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:s})]}),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:r.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:s}),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(oe,{className:"w-5 h-5 flex-shrink-0"}),t.jsx("p",{children:a})]}),t.jsx("button",{type:"submit",disabled:s,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:s?t.jsxs(t.Fragment,{children:[t.jsx(ce,{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 Bl({children:r}){const{user:e,isAdmin:s,loading:n}=Us(),a=Qe();return n?t.jsx("div",{className:"min-h-screen flex items-center justify-center",children:t.jsx(ce,{className:"w-8 h-8 text-green-500 animate-spin"})}):!e||!s?t.jsx(Pr,{to:"/admin/login",state:{from:a},replace:!0}):t.jsx(t.Fragment,{children:r})}function zl(){const r=Qe(),e=He(),{signOut:s}=Us(),n=[{path:"/admin",icon:Mo,label:"Dashboard"},{path:"/admin/playlists",icon:pe,label:"Playlists"},{path:"/admin/submissions",icon:Uo,label:"Submissions"},{path:"/admin/genres",icon:qo,label:"Genres"},{path:"/admin/import",icon:Bt,label:"Import"},{path:"/admin/settings",icon:Ko,label:"Settings"}],a=async()=>{try{await s(),e("/admin/login")}catch(i){console.error("Failed to log out:",i)}};return t.jsx(Bl,{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(X,{to:i,className:`flex items-center px-4 py-2 text-sm rounded-lg ${r.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(Bo,{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(Bn,{})})})]})})})}function Hl({stats:r}){const e=[{label:"Total Playlists",value:(r==null?void 0:r.totalPlaylists.toLocaleString())||"0",icon:pe}];return t.jsx("div",{className:"grid grid-cols-1 gap-6",children:e.map(s=>{const n=s.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:s.label}),t.jsx("p",{className:"text-2xl font-semibold text-gray-900",children:s.value})]})]})},s.label)})})}function Jl(){const{totalCount:r}=At({}),e={totalPlaylists:r};return t.jsxs("div",{children:[t.jsx("h1",{className:"text-2xl font-bold text-gray-900 mb-8",children:"Dashboard"}),t.jsx(Hl,{stats:e})]})}function Kl({playlist:r,onClose:e,onSuccess:s}){const{genres:n,loading:a}=Ie(),[i,o]=y.useState({spotifyUrl:r?`https://open.spotify.com/playlist/${r.spotify_id}`:"",name:(r==null?void 0:r.name)||"",description:(r==null?void 0:r.description)||"",imageUrl:(r==null?void 0:r.image_url)||"",genre:(r==null?void 0:r.genre_id)||"",subGenres:(r==null?void 0:r.sub_genre_ids)||[],followers:(r==null?void 0:r.followers)||0,curatorName:(r==null?void 0:r.curator_name)||"",curatorProfileUrl:(r==null?void 0:r.curator_profile_url)||"",featured:(r==null?void 0:r.featured)||!1}),[l,d]=y.useState(!1),[c,u]=y.useState(null),[h,f]=y.useState(!1),p=n.find(x=>x.id===i.genre),b=async x=>{if(o(w=>({...w,spotifyUrl:x})),!(!x||r)){d(!0),u(null);try{const w=ft(x,"playlist");if(!w)throw new Error("Invalid Spotify playlist URL");const k=await Hs(w);if(!k)throw new Error("Playlist not found on Spotify");o(P=>{var A,N,S,_,m;return{...P,name:k.name,description:k.description||P.description,imageUrl:((A=k.images[0])==null?void 0:A.url)||P.imageUrl,followers:((N=k.followers)==null?void 0:N.total)||0,curatorName:((S=k.owner)==null?void 0:S.display_name)||P.curatorName,curatorProfileUrl:((m=(_=k.owner)==null?void 0:_.external_urls)==null?void 0:m.spotify)||P.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)}}},j=async x=>{x.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=ft(i.spotifyUrl,"playlist");if(!w)throw new Error("Invalid Spotify playlist URL");const k={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};s(k)}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:r?"Edit Playlist":"Add New Playlist"}),t.jsx("button",{onClick:e,className:"text-gray-400 hover:text-gray-500 transition-colors",children:t.jsx(ge,{className:"w-6 h-6"})})]})}),t.jsxs("form",{onSubmit:j,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(Es,{className:"w-4 h-4"}),"Spotify Playlist URL"]}),r?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:x=>b(x.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(pe,{className:"w-4 h-4"}),"Name"]}),t.jsx("input",{type:"text",value:i.name,onChange:x=>o(w=>({...w,name:x.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(Pt,{className:"w-4 h-4"}),"Followers"]}),t.jsx("input",{type:"number",value:i.followers,onChange:x=>o(w=>({...w,followers:parseInt(x.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:x=>o(w=>({...w,description:x.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:x=>o(w=>({...w,genre:x.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(x=>t.jsx("option",{value:x.id,children:x.name},x.id))]})]}),p&&p.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:p.subGenres.map(x=>t.jsxs("label",{className:"flex items-center gap-2",children:[t.jsx("input",{type:"checkbox",checked:i.subGenres.includes(x.id),onChange:w=>{w.target.checked?o(k=>({...k,subGenres:[...k.subGenres,x.id]})):o(k=>({...k,subGenres:k.subGenres.filter(P=>P!==x.id)}))},className:"rounded border-gray-300 text-green-600 focus:ring-green-500"}),t.jsx("span",{className:"text-sm text-gray-700",children:x.name})]},x.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(ss,{className:"w-4 h-4"}),"Curator Name"]}),t.jsx("input",{type:"text",value:i.curatorName,onChange:x=>o(w=>({...w,curatorName:x.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(Es,{className:"w-4 h-4"}),"Curator Profile URL"]}),t.jsx("input",{type:"text",value:i.curatorProfileUrl,onChange:x=>o(w=>({...w,curatorProfileUrl:x.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:x=>o(w=>({...w,featured:x.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(oe,{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(ce,{className:"w-5 h-5 animate-spin"}),h?"Saving...":"Save Playlist"]})]})]})]})})}function Wl({isOpen:r,onClose:e,onComplete:s}){const[n,a]=y.useState(!1),[i,o]=y.useState(null),[l,d]=y.useState(null),c=y.useRef(null),u=async()=>{var f;a(!0),o(null),c.current=new AbortController;try{const{data:p,error:b}=await D.from("playlists").select("id, spotify_id").order("created_at",{ascending:!1});if(b)throw b;if(!p||p.length===0)throw new Error("No playlists found to sync");d({current:0,total:p.length,updated:0,failed:0});const j=10;for(let x=0;x<p.length;x+=j){if((f=c.current)!=null&&f.signal.aborted)throw new Error("Sync cancelled");const w=p.slice(x,Math.min(x+j,p.length)),k=await Promise.allSettled(w.map(async N=>{var S,_,m,g,v,E;try{const C=await Hs(N.spotify_id);if(!C)throw new Error("Playlist not found on Spotify");return{id:N.id,name:C.name,description:C.description||"",image_url:((S=C.images[0])==null?void 0:S.url)||"",followers:((_=C.followers)==null?void 0:_.total)||0,track_count:((m=C.tracks)==null?void 0:m.total)||0,curator_name:((g=C.owner)==null?void 0:g.display_name)||null,curator_profile_url:((E=(v=C.owner)==null?void 0:v.external_urls)==null?void 0:E.spotify)||null,updated_at:new Date().toISOString()}}catch(C){throw console.error(`Failed to fetch playlist ${N.spotify_id}:`,C),C}}));let P=0,A=0;for(const N of k)if(N.status==="fulfilled"){const{error:S}=await D.from("playlists").update(N.value).eq("id",N.value.id);S?(console.error("Failed to update playlist:",S),A++):P++}else A++;d(N=>N?{...N,current:Math.min(x+j,p.length),updated:N.updated+P,failed:N.failed+A}:null),x+j<p.length&&await new Promise(N=>setTimeout(N,1e3))}s()}catch(p){console.error("Sync failed:",p),p instanceof Error&&p.message==="Sync cancelled"?o("Sync cancelled"):o(p instanceof Error?p.message:"Failed to sync playlists")}finally{a(!1),c.current=null}},h=()=>{var f;n?(f=c.current)==null||f.abort():e()};return 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:h,className:"text-gray-400 hover:text-gray-500 transition-colors",children:t.jsx(ge,{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(Ye,{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(oe,{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(oe,{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(ut,{className:"w-5 h-5"}),"Start Sync"]})]})]})]})}):null}function Vl(){const[r,e]=y.useState([]),[s,n]=y.useState(!0),[a,i]=y.useState(null),o=async h=>{try{n(!0),i(null);let f=D.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:p,error:b}=await f;if(b)throw b;const{data:j,error:x}=await D.from("sub_genres").select("*");if(x)throw x;const w=p.map(k=>({...k,sub_genres:k.sub_genre_ids?k.sub_genre_ids.map(P=>{var A;return(A=j.find(N=>N.id===P))==null?void 0:A.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 y.useEffect(()=>{o()},[]),{playlists:r,loading:s,error:a,refresh:o,createPlaylist:async h=>{try{const{data:f,error:p}=await D.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(p)throw p;const{data:b}=await D.from("sub_genres").select("*").in("id",h.sub_genre_ids||[]),j={...f,sub_genres:(b==null?void 0:b.map(x=>x.name))||[]};return e(x=>[j,...x]),j}catch(f){throw console.error("Failed to create playlist:",f),f}},updatePlaylist:async(h,f)=>{try{const{data:p,error:b}=await D.from("playlists").update({...f,updated_at:new Date().toISOString()}).eq("id",h).select(` *, genres ( id, name, slug ) `).single();if(b)throw b;let j=[];if(f.sub_genre_ids){const{data:w}=await D.from("sub_genres").select("*").in("id",f.sub_genre_ids);j=(w==null?void 0:w.map(k=>k.name))||[]}const x={...p,sub_genres:j};return e(w=>w.map(k=>k.id===h?x:k)),x}catch(p){throw console.error("Failed to update playlist:",p),p}},deletePlaylist:async h=>{try{const{error:f}=await D.from("playlists").delete().eq("id",h);if(f)throw f;e(p=>p.filter(b=>b.id!==h))}catch(f){throw console.error("Failed to delete playlist:",f),f}},toggleFeatured:async(h,f)=>{try{const{error:p}=await D.from("playlists").update({featured:f}).eq("id",h);if(p)throw p;e(b=>b.map(j=>j.id===h?{...j,featured:f}:j))}catch(p){throw console.error("Failed to update featured status:",p),p}}}}function Yl(){const[r,e]=y.useState(!1),[s,n]=y.useState(!1),[a,i]=y.useState(null),[o,l]=y.useState(null),[d,c]=y.useState({search:"",genre:"",status:"",sortBy:"created_at_desc"}),{playlists:u,loading:h,error:f,refresh:p,createPlaylist:b,updatePlaylist:j,deletePlaylist:x,toggleFeatured:w}=Vl(),k=()=>{n(!1),l({type:"success",message:"Playlists synced successfully"}),p()},P=async _=>{try{a?(await j(a.id,_),l({type:"success",message:"Playlist updated successfully"})):(await b(_),l({type:"success",message:"Playlist created successfully"})),e(!1),i(null),p()}catch(m){l({type:"error",message:m instanceof Error?m.message:"Failed to save playlist"})}},A=async(_,m)=>{if(window.confirm(`Are you sure you want to delete "${m}"?`))try{await x(_),l({type:"success",message:`${m} has been deleted`}),p()}catch{l({type:"error",message:"Failed to delete playlist"})}},N=async(_,m)=>{try{await w(_,!m),l({type:"success",message:`Playlist ${m?"removed from":"added to"} featured list`})}catch{l({type:"error",message:"Failed to update featured status"})}},S=u.filter(_=>!(d.search&&!_.name.toLowerCase().includes(d.search.toLowerCase())||d.genre&&_.genre_id!==d.genre||d.status==="claimed"&&!_.claimed||d.status==="unclaimed"&&_.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(oe,{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(ut,{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(Ms,{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(ts,{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:_=>c({...d,search:_.target.value}),className:"w-full pl-10 pr-4 py-2 border border-gray-300 rounded-lg"})]}),t.jsxs("select",{value:d.genre,onChange:_=>c({...d,genre:_.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(_=>_.genre_id))).map(_=>{var g;const m=(g=u.find(v=>v.genre_id===_))==null?void 0:g.genres;return m?t.jsx("option",{value:m.id,children:m.name},m.id):null})]}),t.jsxs("select",{value:d.status,onChange:_=>c({...d,status:_.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:_=>{c({...d,sortBy:_.target.value}),p({...d,sortBy:_.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(ce,{className:"w-6 h-6 text-green-500 animate-spin mx-auto"})})}):S.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"})}):S.map(_=>{var m,g;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:_.image_url,alt:_.name,className:"w-10 h-10 rounded-sm object-cover mr-3"}),t.jsx("span",{className:"font-medium",children:_.name})]})}),t.jsx("td",{className:"px-6 py-4",children:(m=_.genres)==null?void 0:m.name}),t.jsx("td",{className:"px-6 py-4",children:(g=_.sub_genres)==null?void 0:g.map(v=>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:v},v))}),t.jsx("td",{className:"px-6 py-4",children:_.curator_name||"Unclaimed"}),t.jsx("td",{className:"px-6 py-4",children:Yo(_.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 ${_.claimed?"bg-green-100 text-green-800":"bg-yellow-100 text-yellow-800"}`,children:_.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:()=>N(_.id,_.featured),className:"p-1 hover:bg-gray-100 rounded",title:_.featured?"Remove from featured":"Add to featured",children:t.jsx(yn,{className:`w-4 h-4 ${_.featured?"text-yellow-400 fill-yellow-400":"text-gray-400"}`})}),t.jsx("button",{onClick:()=>i(_),className:"p-1 hover:bg-gray-100 rounded",children:t.jsx(xn,{className:"w-4 h-4 text-gray-500"})}),t.jsx("button",{onClick:()=>A(_.id,_.name),className:"p-1 hover:bg-gray-100 rounded",children:t.jsx(qs,{className:"w-4 h-4 text-red-500"})})]})})]},_.id)})})]})}),(r||a)&&t.jsx(Kl,{playlist:a,onClose:()=>{e(!1),i(null)},onSuccess:P}),s&&t.jsx(Wl,{isOpen:s,onClose:()=>n(!1),onComplete:k}),o&&t.jsx(De,{message:o.message,type:o.type,onClose:()=>l(null)})]})}function Zl(r){const[e,s]=y.useState([]),[n,a]=y.useState(0),[i,o]=y.useState(!0),[l,d]=y.useState(null);return y.useEffect(()=>{async function u(){try{o(!0),d(null);const h=r?await qt.getForPlaylist(r):await qt.getAll();s(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()},[r]),{submissions:e,totalCount:n,loading:i,error:l,updateStatus:async(u,h)=>{try{const f=await qt.updateStatus(u,h);return s(p=>p.map(b=>b.id===u?{...b,...f}:b)),f}catch(f){throw console.error("Failed to update submission status:",f),f}}}}function Ql({submission:r,onClose:e}){var s;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(ge,{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(pe,{className:"w-4 h-4 text-gray-400"}),t.jsx("span",{className:"font-medium",children:r.track_name})]}),t.jsx("div",{className:"flex items-center gap-2",children:t.jsxs("a",{href:r.track_url,target:"_blank",rel:"noopener noreferrer",className:"text-green-600 hover:text-green-700 flex items-center gap-1",children:[t.jsx(Io,{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:"})," ",r.artist_name]}),t.jsxs("div",{className:"flex items-center gap-2",children:[t.jsx(mn,{className:"w-4 h-4 text-gray-400"}),t.jsx("a",{href:`mailto:${r.email}`,className:"text-green-600 hover:text-green-700",children:r.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(fn,{className:"w-4 h-4 text-gray-400"}),t.jsx("span",{className:"font-medium",children:(s=r.playlist)==null?void 0:s.name})]})})]}),r.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:r.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(xr,{className:"w-4 h-4 text-gray-400"}),t.jsxs("span",{children:["Submitted: ",new Date(r.created_at).toLocaleString()]})]}),r.reviewed_at&&t.jsxs("div",{className:"flex items-center gap-2",children:[t.jsx(xr,{className:"w-4 h-4 text-gray-400"}),t.jsxs("span",{children:["Reviewed: ",new Date(r.reviewed_at).toLocaleString()]})]})]})]})]})]})})}function Xl(){const[r,e]=y.useState(null),[s,n]=y.useState(null),[a,i]=y.useState({search:"",status:"",startDate:"",endDate:""}),{submissions:o,loading:l,error:d,updateStatus:c}=Zl(),u=async(f,p)=>{try{await c(f,p),e({type:"success",message:`Submission marked as ${p}`})}catch(b){console.error("Failed to update status:",b),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(ts,{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(ce,{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(oe,{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 p;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:b=>b.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:b=>b.stopPropagation(),children:f.email})}),t.jsx("td",{className:"px-6 py-4",children:(p=f.playlist)==null?void 0:p.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(ks,{className:"w-3 h-3"}),f.status==="rejected"&&t.jsx(yr,{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:b=>b.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(ks,{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(Fo,{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(yr,{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(gn,{className:"w-5 h-5"})})]})})]},f.id)})})]})}),s&&t.jsx(Ql,{submission:s,onClose:()=>n(null)}),r&&t.jsx(De,{message:r.message,type:r.type,onClose:()=>e(null)})]})}function ec({genre:r,onClose:e,onSuccess:s}){const[n,a]=y.useState((r==null?void 0:r.name)||""),[i,o]=y.useState((r==null?void 0:r.description)||""),[l,d]=y.useState((r==null?void 0:r.subGenres.map(m=>({name:m.name,description:m.description})))||[]),[c,u]=y.useState({name:"",description:""}),[h,f]=y.useState(null),[p,b]=y.useState(!1),[j,x]=y.useState(null),{createGenre:w,updateGenre:k}=Ie(),P=(m,g)=>{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 v=$e(m.name);if(l.filter((C,T)=>T!==g).map(C=>$e(C.name)).includes(v))throw new Error("This sub-genre already exists")},A=async m=>{m.preventDefault(),x(null),b(!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(C=>$e(C.name))).size!==l.length)throw new Error("Duplicate sub-genres are not allowed");const v={name:n.trim(),description:i.trim(),subGenres:l.map(C=>({name:C.name.trim(),description:C.description.trim()}))};let E;r?E=await k(r.id,v):E=await w(v),s(E)}catch(g){console.error("Failed to save genre:",g),x(g instanceof Error?g.message:"Failed to save genre")}finally{b(!1)}},N=()=>{try{P(c),d([...l,{...c}]),u({name:"",description:""}),x(null)}catch(m){x(m instanceof Error?m.message:"Invalid sub-genre")}},S=(m,g)=>{try{const v={...l[m],...g};P(v,m);const E=[...l];E[m]=v,d(E),f(null),x(null)}catch(v){x(v instanceof Error?v.message:"Invalid sub-genre")}},_=m=>{d(l.filter((g,v)=>v!==m)),x(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:r?"Edit Genre":"Add New Genre"}),t.jsx("button",{onClick:e,className:"text-gray-400 hover:text-gray-500 transition-colors",children:t.jsx(ge,{className:"w-6 h-6"})})]})}),t.jsxs("form",{onSubmit:A,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(g=>({...g,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(g=>({...g,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:N,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(Ms,{className:"w-5 h-5"}),"Add Sub-genre"]})]})}),t.jsx("div",{className:"space-y-3",children:l.map((m,g)=>t.jsx("div",{className:"bg-gray-50 p-3 rounded-lg space-y-2",children:h===g?t.jsxs("div",{className:"space-y-2",children:[t.jsx("input",{type:"text",value:m.name,onChange:v=>S(g,{name:v.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:v=>S(g,{description:v.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:()=>S(g,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(g),className:"p-1 hover:bg-gray-200 rounded transition-colors",title:"Edit sub-genre",children:t.jsx(Ho,{className:"w-4 h-4 text-gray-600"})}),t.jsx("button",{type:"button",onClick:()=>_(g),className:"p-1 hover:bg-red-100 rounded transition-colors",title:"Remove sub-genre",children:t.jsx(qs,{className:"w-4 h-4 text-red-500"})})]})]}),t.jsx("p",{className:"text-sm text-gray-600",children:m.description})]})},g))})]}),j&&t.jsxs("div",{className:"flex items-center gap-2 text-red-600 text-sm",children:[t.jsx(oe,{className:"w-4 h-4 flex-shrink-0"}),t.jsx("span",{children:j})]}),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:p,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:p?t.jsxs(t.Fragment,{children:[t.jsx(ce,{className:"w-5 h-5 animate-spin"}),"Saving..."]}):t.jsx(t.Fragment,{children:"Save Genre"})})]})]})]})})}function tc({id:r,name:e,description:s,subGenres:n,onEdit:a,onDelete:i}){const{attributes:o,listeners:l,setNodeRef:d,transform:c,transition:u,isDragging:h}=An({id:r}),f={transform:On.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(Do,{className:"w-5 h-5"})}),t.jsx("div",{className:"p-2 bg-green-50 rounded-lg",children:t.jsx(pe,{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(xn,{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(qs,{className:"w-5 h-5 text-red-600"})})]})]}),t.jsx("p",{className:"text-gray-600 mb-4",children:s}),n.length>0&&t.jsx("div",{className:"ml-12 space-y-2",children:n.map(p=>t.jsxs("div",{className:"flex items-start gap-2 text-gray-600",children:[t.jsx($o,{className:"w-4 h-4 mt-1 flex-shrink-0"}),t.jsxs("div",{children:[t.jsx("p",{className:"font-medium text-sm",children:p.name}),t.jsx("p",{className:"text-sm text-gray-500",children:p.description})]})]},p.id))})]})}function sc(){const{genres:r,loading:e,error:s,deleteGenre:n,updateGenreOrder:a}=Ie(),[i,o]=y.useState(!1),[l,d]=y.useState(null),[c,u]=y.useState(null),h=$n(Ws(Mn),Ws(Un,{coordinateGetter:Fn})),f=async b=>{const{active:j,over:x}=b;if(x&&j.id!==x.id){const w=r.findIndex(P=>P.id===j.id),k=r.findIndex(P=>P.id===x.id);try{await a(w,k),u({type:"success",message:"Genre order updated successfully"})}catch{u({type:"error",message:"Failed to update genre order"})}}},p=async(b,j)=>{if(window.confirm(`Are you sure you want to delete "${j}" and all its sub-genres?`))try{await n(b),u({type:"success",message:`${j} has been deleted`})}catch(x){u({type:"error",message:x instanceof Error?x.message:"Failed to delete genre"})}};return e?t.jsx("div",{className:"flex items-center justify-center min-h-[400px]",children:t.jsx(ce,{className:"w-8 h-8 text-green-500 animate-spin"})}):s?t.jsxs("div",{className:"flex items-center justify-center min-h-[400px] text-red-600",children:[t.jsx(oe,{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(Ms,{className:"w-5 h-5"}),"Add Genre"]})]}),t.jsxs("div",{className:"space-y-4",children:[t.jsx(Rn,{sensors:h,collisionDetection:In,onDragEnd:f,children:t.jsx(Dn,{items:r.map(b=>b.id),strategy:Ln,children:r.map(b=>t.jsx(tc,{id:b.id,name:b.name,subGenres:b.subGenres,onEdit:()=>d({id:b.id,name:b.name,subGenres:b.subGenres}),onDelete:()=>p(b.id,b.name)},b.id))})}),r.length===0&&t.jsxs("div",{className:"text-center py-12 bg-white rounded-lg",children:[t.jsx(pe,{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(ec,{genre:l,onClose:()=>{o(!1),d(null)},onSuccess:b=>{o(!1),d(null),u({type:"success",message:`Genre ${l?"updated":"created"} successfully`})}}),c&&t.jsx(De,{message:c.message,type:c.type,onClose:()=>u(null)})]})}const rc=qn,En=y.forwardRef(({className:r,...e},s)=>t.jsx(Sr,{ref:s,className:"inline-flex h-10 items-center justify-center rounded-lg bg-gray-100 p-1 text-gray-500 mb-4",...e}));En.displayName=Sr.displayName;const Ps=y.forwardRef(({className:r,...e},s)=>t.jsx(kr,{ref:s,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}));Ps.displayName=kr.displayName;const As=y.forwardRef(({className:r,...e},s)=>t.jsx(Er,{ref:s,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}));As.displayName=Er.displayName;function nc({onSuccess:r}){const[e,s]=y.useState(!1),[n,a]=y.useState(null),[i,o]=y.useState(null),[l,d]=y.useState(null),[c,u]=y.useState(null),h=async()=>{if(!i||!l){a("Please select both genre and sub-genre files");return}s(!0),a(null),u({stage:"Reading files",current:0,total:2});try{const j=(await i.text()).split(` `),x=j[0].split(",").map(T=>T.trim()),k=["Name","Slug","Description"].filter(T=>!x.includes(T));if(k.length>0)throw new Error(`Missing required columns in genres file: ${k.join(", ")}`);const P=[];for(let T=1;T<j.length;T++){if(!j[T].trim())continue;const U=j[T].split(",").map(z=>z.trim());P.push({Name:U[x.indexOf("Name")],Slug:U[x.indexOf("Slug")],Description:U[x.indexOf("Description")]})}u({stage:"Processing genres",current:1,total:2});const N=(await l.text()).split(` `),S=N[0].split(",").map(T=>T.trim()),m=["Name","Slug","Description"].filter(T=>!S.includes(T));if(m.length>0)throw new Error(`Missing required columns in sub-genres file: ${m.join(", ")}`);const g=[];for(let T=1;T<N.length;T++){if(!N[T].trim())continue;const U=N[T].split(",").map(z=>z.trim());g.push({Name:U[S.indexOf("Name")],Slug:U[S.indexOf("Slug")],Description:U[S.indexOf("Description")]})}u({stage:"Importing data",current:0,total:P.length+g.length});for(const T of P){const{error:U}=await D.from("genres").insert({name:T.Name,slug:T.Slug||$e(T.Name),description:T.Description});if(U&&U.code!=="23505")throw U;u(z=>z?{...z,current:z.current+1}:null)}const{data:v,error:E}=await D.from("genres").select("id, name, slug");if(E)throw E;const C=new Map(v.map(T=>[T.name.toLowerCase(),T.id]));for(const T of g){const U=v.find(z=>T.Slug.includes(z.slug)||T.Name.toLowerCase().includes(z.name.toLowerCase()));if(U){const{error:z}=await D.from("sub_genres").insert({name:T.Name,slug:T.Slug||$e(T.Name),description:T.Description,genre_id:U.id});if(z&&z.code!=="23505")throw z}u(z=>z?{...z,current:z.current+1}:null)}r()}catch(b){console.error("Import failed:",b),a(b instanceof Error?b.message:"Failed to import data")}finally{s(!1),u(null),o(null),d(null)}},f=b=>{if(!b.name.endsWith(".csv")){a("Please select a CSV file");return}o(b),a(null)},p=b=>{if(!b.name.endsWith(".csv")){a("Please select a CSV file");return}d(b),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:b=>b.preventDefault(),onDrop:b=>{b.preventDefault();const j=b.dataTransfer.files[0];j&&f(j)},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(ge,{className:"w-4 h-4 text-gray-500"})})]}):t.jsxs(t.Fragment,{children:[t.jsx(Bt,{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:b=>{var x;const j=(x=b.target.files)==null?void 0:x[0];j&&f(j)},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:b=>b.preventDefault(),onDrop:b=>{b.preventDefault();const j=b.dataTransfer.files[0];j&&p(j)},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(ge,{className:"w-4 h-4 text-gray-500"})})]}):t.jsxs(t.Fragment,{children:[t.jsx(Bt,{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:b=>{var x;const j=(x=b.target.files)==null?void 0:x[0];j&&p(j)},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(oe,{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(ge,{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(ce,{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 ac={async importPlaylists(r,e){try{if(!Array.isArray(r)||r.length===0)throw new Error("No playlists provided");const s={current:0,total:r.length,processed:0,skipped:0,failed:0,unmatchedCategories:new Set,recentErrors:[],skippedDetails:{genreNotFound:0,duplicates:0,invalidData:0,details:[]}},{data:n,error:a}=await D.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 D.from("sub_genres").select("*").order("name");if(o)throw o;const l=50;for(let d=0;d<r.length;d+=l){const c=r.slice(d,Math.min(d+l,r.length)),u=[];for(const h of c)try{const f=n.find(x=>x.name.toLowerCase()===h.Category.toLowerCase()||h.Category.toLowerCase().includes(x.name.toLowerCase()));if(!f){s.skippedDetails.genreNotFound++,s.skippedDetails.details.push({row:d+c.indexOf(h)+1,name:h.Name,reason:"No matching genre found",details:`Category: ${h.Category}`}),s.unmatchedCategories.add(h.Category),s.failed++;continue}const p=h["Sub Genres"].split(";").map(x=>x.trim()).filter(Boolean),b=(i==null?void 0:i.filter(x=>x.genre_id===f.id&&p.some(w=>w.toLowerCase().includes(x.name.toLowerCase())||x.name.toLowerCase().includes(w.toLowerCase()))).map(x=>x.id))||[],{data:j}=await D.from("playlists").select("id").eq("spotify_id",h.URL.split("/").pop()).single();if(j){s.skippedDetails.duplicates++,s.skippedDetails.details.push({row:d+c.indexOf(h)+1,name:h.Name,reason:"Duplicate playlist",details:`Spotify ID: ${h.URL.split("/").pop()}`}),s.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:b,curator_name:h.Curator,curator_profile_url:h["Curator URL"],created_at:new Date().toISOString(),updated_at:new Date().toISOString()}),s.processed++}catch(f){s.skippedDetails.invalidData++,s.skippedDetails.details.push({row:d+c.indexOf(h)+1,name:h.Name,reason:"Invalid data",details:f instanceof Error?f.message:"Unknown error"}),s.failed++,s.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 D.from("playlists").insert(u);h&&(console.error("Failed to insert batch:",h),s.failed+=u.length,s.processed-=u.length)}s.current=d+c.length,e&&e({...s}),d+l<r.length&&await new Promise(h=>setTimeout(h,1e3))}return{successCount:s.processed,skipCount:s.skipped,unmatchedCategories:Array.from(s.unmatchedCategories),errors:s.recentErrors,skippedDetails:s.skippedDetails}}catch(s){throw console.error("Import failed:",s),s instanceof Error?s:new Error("Failed to import playlists")}}};var Cn={exports:{}};/* @license Papa Parse v5.5.2 https://github.com/mholt/PapaParse License: MIT */(function(r,e){((s,n)=>{r.exports=n()})(ve,function s(){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(g){var v=N(g);v.chunkSize=parseInt(v.chunkSize),g.step||g.chunk||(v.chunkSize=null),this._handle=new j(v),(this._handle.streamer=this)._config=v}).call(this,m),this.parseChunk=function(g,v){var E=parseInt(this._config.skipFirstNLines)||0;if(this.isFirstChunk&&0<E){let T=this._config.newline;T||(C=this._config.quoteChar||'"',T=this._handle.guessLineEndings(g,C)),g=[...g.split(T).slice(E)].join(T)}this.isFirstChunk&&_(this._config.beforeFirstChunk)&&(C=this._config.beforeFirstChunk(g))!==void 0&&(g=C),this.isFirstChunk=!1,this._halted=!1;var E=this._partialLine+g,C=(this._partialLine="",this._handle.parse(E,this._baseIndex,!this._finished));if(!this._handle.paused()&&!this._handle.aborted()){if(g=C.meta.cursor,E=(this._finished||(this._partialLine=E.substring(g-this._baseIndex),this._baseIndex=g),C&&C.data&&(this._rowCount+=C.data.length),this._finished||this._config.preview&&this._rowCount>=this._config.preview),o)n.postMessage({results:C,workerId:c.WORKER_ID,finished:E});else if(_(this._config.chunk)&&!v){if(this._config.chunk(C,this._handle),this._handle.paused()||this._handle.aborted())return void(this._halted=!0);this._completeResults=C=void 0}return this._config.step||this._config.chunk||(this._completeResults.data=this._completeResults.data.concat(C.data),this._completeResults.errors=this._completeResults.errors.concat(C.errors),this._completeResults.meta=C.meta),this._completed||!E||!_(this._config.complete)||C&&C.meta.aborted||(this._config.complete(this._completeResults,this._input),this._completed=!0),E||C&&C.meta.paused||this._nextChunk(),C}this._halted=!0},this._sendError=function(g){_(this._config.error)?this._config.error(g):o&&this._config.error&&n.postMessage({workerId:c.WORKER_ID,error:g,finished:!1})}}function h(m){var g;(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(v){this._input=v,this._nextChunk()},this._readChunk=function(){if(this._finished)this._chunkLoaded();else{if(g=new XMLHttpRequest,this._config.withCredentials&&(g.withCredentials=this._config.withCredentials),i||(g.onload=S(this._chunkLoaded,this),g.onerror=S(this._chunkError,this)),g.open(this._config.downloadRequestBody?"POST":"GET",this._input,!i),this._config.downloadRequestHeaders){var v,E=this._config.downloadRequestHeaders;for(v in E)g.setRequestHeader(v,E[v])}var C;this._config.chunkSize&&(C=this._start+this._config.chunkSize-1,g.setRequestHeader("Range","bytes="+this._start+"-"+C));try{g.send(this._config.downloadRequestBody)}catch(T){this._chunkError(T.message)}i&&g.status===0&&this._chunkError()}},this._chunkLoaded=function(){g.readyState===4&&(g.status<200||400<=g.status?this._chunkError():(this._start+=this._config.chunkSize||g.responseText.length,this._finished=!this._config.chunkSize||this._start>=(v=>(v=v.getResponseHeader("Content-Range"))!==null?parseInt(v.substring(v.lastIndexOf("/")+1)):-1)(g),this.parseChunk(g.responseText)))},this._chunkError=function(v){v=g.statusText||v,this._sendError(new Error(v))}}function f(m){(m=m||{}).chunkSize||(m.chunkSize=c.LocalChunkSize),u.call(this,m);var g,v,E=typeof FileReader<"u";this.stream=function(C){this._input=C,v=C.slice||C.webkitSlice||C.mozSlice,E?((g=new FileReader).onload=S(this._chunkLoaded,this),g.onerror=S(this._chunkError,this)):g=new FileReaderSync,this._nextChunk()},this._nextChunk=function(){this._finished||this._config.preview&&!(this._rowCount<this._config.preview)||this._readChunk()},this._readChunk=function(){var C=this._input,T=(this._config.chunkSize&&(T=Math.min(this._start+this._config.chunkSize,this._input.size),C=v.call(C,this._start,T)),g.readAsText(C,this._config.encoding));E||this._chunkLoaded({target:{result:T}})},this._chunkLoaded=function(C){this._start+=this._config.chunkSize,this._finished=!this._config.chunkSize||this._start>=this._input.size,this.parseChunk(C.target.result)},this._chunkError=function(){this._sendError(g.error)}}function p(m){var g;u.call(this,m=m||{}),this.stream=function(v){return g=v,this._nextChunk()},this._nextChunk=function(){var v,E;if(!this._finished)return v=this._config.chunkSize,g=v?(E=g.substring(0,v),g.substring(v)):(E=g,""),this._finished=!g,this.parseChunk(E)}}function b(m){u.call(this,m=m||{});var g=[],v=!0,E=!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(C){this._input=C,this._input.on("data",this._streamData),this._input.on("end",this._streamEnd),this._input.on("error",this._streamError)},this._checkIsFinished=function(){E&&g.length===1&&(this._finished=!0)},this._nextChunk=function(){this._checkIsFinished(),g.length?this.parseChunk(g.shift()):v=!0},this._streamData=S(function(C){try{g.push(typeof C=="string"?C:C.toString(this._config.encoding)),v&&(v=!1,this._checkIsFinished(),this.parseChunk(g.shift()))}catch(T){this._streamError(T)}},this),this._streamError=S(function(C){this._streamCleanUp(),this._sendError(C)},this),this._streamEnd=S(function(){this._streamCleanUp(),E=!0,this._streamData("")},this),this._streamCleanUp=S(function(){this._input.removeListener("data",this._streamData),this._input.removeListener("end",this._streamEnd),this._input.removeListener("error",this._streamError)},this)}function j(m){var g,v,E,C,T=Math.pow(2,53),U=-T,z=/^\s*-?(\d+\.?|\.\d+|\d+\.\d+)([eE][-+]?\d+)?\s*$/,ie=/^((\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)))$/,$=this,V=0,R=0,q=!1,I=!1,B=[],O={data:[],errors:[],meta:{}};function re(H){return m.skipEmptyLines==="greedy"?H.join("").trim()==="":H.length===1&&H[0].length===0}function te(){if(O&&E&&(ee("Delimiter","UndetectableDelimiter","Unable to auto-detect delimiting character; defaulted to '"+c.DefaultDelimiter+"'"),E=!1),m.skipEmptyLines&&(O.data=O.data.filter(function(F){return!re(F)})),le()){let F=function(ae,de){_(m.transformHeader)&&(ae=m.transformHeader(ae,de)),B.push(ae)};if(O)if(Array.isArray(O.data[0])){for(var H=0;le()&&H<O.data.length;H++)O.data[H].forEach(F);O.data.splice(0,1)}else O.data.forEach(F)}function W(F,ae){for(var de=m.header?{}:[],Y=0;Y<F.length;Y++){var Z=Y,J=F[Y],J=((_e,M)=>(se=>(m.dynamicTypingFunction&&m.dynamicTyping[se]===void 0&&(m.dynamicTyping[se]=m.dynamicTypingFunction(se)),(m.dynamicTyping[se]||m.dynamicTyping)===!0))(_e)?M==="true"||M==="TRUE"||M!=="false"&&M!=="FALSE"&&((se=>{if(z.test(se)&&(se=parseFloat(se),U<se&&se<T))return 1})(M)?parseFloat(M):ie.test(M)?new Date(M):M===""?null:M):M)(Z=m.header?Y>=B.length?"__parsed_extra":B[Y]:Z,J=m.transform?m.transform(J,Z):J);Z==="__parsed_extra"?(de[Z]=de[Z]||[],de[Z].push(J)):de[Z]=J}return m.header&&(Y>B.length?ee("FieldMismatch","TooManyFields","Too many fields: expected "+B.length+" fields but parsed "+Y,R+ae):Y<B.length&&ee("FieldMismatch","TooFewFields","Too few fields: expected "+B.length+" fields but parsed "+Y,R+ae)),de}var ne;O&&(m.header||m.dynamicTyping||m.transform)&&(ne=1,!O.data.length||Array.isArray(O.data[0])?(O.data=O.data.map(W),ne=O.data.length):O.data=W(O.data,0),m.header&&O.meta&&(O.meta.fields=B),R+=ne)}function le(){return m.header&&B.length===0}function ee(H,W,ne,F){H={type:H,code:W,message:ne},F!==void 0&&(H.row=F),O.errors.push(H)}_(m.step)&&(C=m.step,m.step=function(H){O=H,le()?te():(te(),O.data.length!==0&&(V+=H.data.length,m.preview&&V>m.preview?v.abort():(O.data=O.data[0],C(O,$))))}),this.parse=function(H,W,ne){var F=m.quoteChar||'"',F=(m.newline||(m.newline=this.guessLineEndings(H,F)),E=!1,m.delimiter?_(m.delimiter)&&(m.delimiter=m.delimiter(H),O.meta.delimiter=m.delimiter):((F=((ae,de,Y,Z,J)=>{var _e,M,se,Fe;J=J||[","," ","|",";",c.RECORD_SEP,c.UNIT_SEP];for(var tt=0;tt<J.length;tt++){for(var Ce,xt=J[tt],me=0,Te=0,he=0,xe=(se=void 0,new w({comments:Z,delimiter:xt,newline:de,preview:10}).parse(ae)),Le=0;Le<xe.data.length;Le++)Y&&re(xe.data[Le])?he++:(Ce=xe.data[Le].length,Te+=Ce,se===void 0?se=Ce:0<Ce&&(me+=Math.abs(Ce-se),se=Ce));0<xe.data.length&&(Te/=xe.data.length-he),(M===void 0||me<=M)&&(Fe===void 0||Fe<Te)&&1.99<Te&&(M=me,_e=xt,Fe=Te)}return{successful:!!(m.delimiter=_e),bestDelimiter:_e}})(H,m.newline,m.skipEmptyLines,m.comments,m.delimitersToGuess)).successful?m.delimiter=F.bestDelimiter:(E=!0,m.delimiter=c.DefaultDelimiter),O.meta.delimiter=m.delimiter),N(m));return m.preview&&m.header&&F.preview++,g=H,v=new w(F),O=v.parse(g,W,ne),te(),q?{meta:{paused:!0}}:O||{meta:{paused:!1}}},this.paused=function(){return q},this.pause=function(){q=!0,v.abort(),g=_(m.chunk)?"":g.substring(v.getCharIndex())},this.resume=function(){$.streamer._halted?(q=!1,$.streamer.parseChunk(g,!0)):setTimeout($.resume,3)},this.aborted=function(){return I},this.abort=function(){I=!0,v.abort(),O.meta.aborted=!0,_(m.complete)&&m.complete(O),g=""},this.guessLineEndings=function(ae,F){ae=ae.substring(0,1048576);var F=new RegExp(x(F)+"([^]*?)"+x(F),"gm"),ne=(ae=ae.replace(F,"")).split("\r"),F=ae.split(` `),ae=1<F.length&&F[0].length<ne[0].length;if(ne.length===1||ae)return` `;for(var de=0,Y=0;Y<ne.length;Y++)ne[Y][0]===` `&&de++;return de>=ne.length/2?`\r `:"\r"}}function x(m){return m.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}function w(m){var g=(m=m||{}).delimiter,v=m.newline,E=m.comments,C=m.step,T=m.preview,U=m.fastMode,z=null,ie=!1,$=m.quoteChar==null?'"':m.quoteChar,V=$;if(m.escapeChar!==void 0&&(V=m.escapeChar),(typeof g!="string"||-1<c.BAD_DELIMITERS.indexOf(g))&&(g=","),E===g)throw new Error("Comment character same as delimiter");E===!0?E="#":(typeof E!="string"||-1<c.BAD_DELIMITERS.indexOf(E))&&(E=!1),v!==` `&&v!=="\r"&&v!==`\r `&&(v=` `);var R=0,q=!1;this.parse=function(I,B,O){if(typeof I!="string")throw new Error("Input must be a string");var re=I.length,te=g.length,le=v.length,ee=E.length,H=_(C),W=[],ne=[],F=[],ae=R=0;if(!I)return me();if(U||U!==!1&&I.indexOf($)===-1){for(var de=I.split(v),Y=0;Y<de.length;Y++){if(F=de[Y],R+=F.length,Y!==de.length-1)R+=v.length;else if(O)return me();if(!E||F.substring(0,ee)!==E){if(H){if(W=[],Fe(F.split(g)),Te(),q)return me()}else Fe(F.split(g));if(T&&T<=Y)return W=W.slice(0,T),me(!0)}}return me()}for(var Z=I.indexOf(g,R),J=I.indexOf(v,R),_e=new RegExp(x(V)+x($),"g"),M=I.indexOf($,R);;)if(I[R]===$)for(M=R,R++;;){if((M=I.indexOf($,M+1))===-1)return O||ne.push({type:"Quotes",code:"MissingQuotes",message:"Quoted field unterminated",row:W.length,index:R}),Ce();if(M===re-1)return Ce(I.substring(R,M).replace(_e,$));if($===V&&I[M+1]===V)M++;else if($===V||M===0||I[M-1]!==V){Z!==-1&&Z<M+1&&(Z=I.indexOf(g,M+1));var se=tt((J=J!==-1&&J<M+1?I.indexOf(v,M+1):J)===-1?Z:Math.min(Z,J));if(I.substr(M+1+se,te)===g){F.push(I.substring(R,M).replace(_e,$)),I[R=M+1+se+te]!==$&&(M=I.indexOf($,R)),Z=I.indexOf(g,R),J=I.indexOf(v,R);break}if(se=tt(J),I.substring(M+1+se,M+1+se+le)===v){if(F.push(I.substring(R,M).replace(_e,$)),xt(M+1+se+le),Z=I.indexOf(g,R),M=I.indexOf($,R),H&&(Te(),q))return me();if(T&&W.length>=T)return me(!0);break}ne.push({type:"Quotes",code:"InvalidQuotes",message:"Trailing quote on quoted field is malformed",row:W.length,index:R}),M++}}else if(E&&F.length===0&&I.substring(R,R+ee)===E){if(J===-1)return me();R=J+le,J=I.indexOf(v,R),Z=I.indexOf(g,R)}else if(Z!==-1&&(Z<J||J===-1))F.push(I.substring(R,Z)),R=Z+te,Z=I.indexOf(g,R);else{if(J===-1)break;if(F.push(I.substring(R,J)),xt(J+le),H&&(Te(),q))return me();if(T&&W.length>=T)return me(!0)}return Ce();function Fe(he){W.push(he),ae=R}function tt(he){var xe=0;return xe=he!==-1&&(he=I.substring(M+1,he))&&he.trim()===""?he.length:xe}function Ce(he){return O||(he===void 0&&(he=I.substring(R)),F.push(he),R=re,Fe(F),H&&Te()),me()}function xt(he){R=he,Fe(F),F=[],J=I.indexOf(v,R)}function me(he){if(m.header&&!B&&W.length&&!ie){var xe=W[0],Le={},rs=new Set(xe);let Js=!1;for(let st=0;st<xe.length;st++){let Pe=xe[st];if(Le[Pe=_(m.transformHeader)?m.transformHeader(Pe,st):Pe]){let yt,Ks=Le[Pe];for(;yt=Pe+"_"+Ks,Ks++,rs.has(yt););rs.add(yt),xe[st]=yt,Le[Pe]++,Js=!0,(z=z===null?{}:z)[yt]=Pe}else Le[Pe]=1,xe[st]=Pe;rs.add(Pe)}Js&&console.warn("Duplicate headers found and renamed."),ie=!0}return{data:W,errors:ne,meta:{delimiter:g,linebreak:v,aborted:q,truncated:!!he,cursor:ae+(B||0),renamedHeaders:z}}}function Te(){C(me()),W=[],ne=[]}},this.abort=function(){q=!0},this.getCharIndex=function(){return R}}function k(m){var g=m.data,v=l[g.workerId],E=!1;if(g.error)v.userError(g.error,g.file);else if(g.results&&g.results.data){var C={abort:function(){E=!0,P(g.workerId,{data:[],errors:[],meta:{aborted:!0}})},pause:A,resume:A};if(_(v.userStep)){for(var T=0;T<g.results.data.length&&(v.userStep({data:g.results.data[T],errors:g.results.errors,meta:g.results.meta},C),!E);T++);delete g.results}else _(v.userChunk)&&(v.userChunk(g.results,C,g.file),delete g.results)}g.finished&&!E&&P(g.workerId,g.results)}function P(m,g){var v=l[m];_(v.userComplete)&&v.userComplete(g),v.terminate(),delete l[m]}function A(){throw new Error("Not implemented.")}function N(m){if(typeof m!="object"||m===null)return m;var g,v=Array.isArray(m)?[]:{};for(g in m)v[g]=N(m[g]);return v}function S(m,g){return function(){m.apply(g,arguments)}}function _(m){return typeof m=="function"}return c.parse=function(m,g){var v=(g=g||{}).dynamicTyping||!1;if(_(v)&&(g.dynamicTypingFunction=v,v={}),g.dynamicTyping=v,g.transform=!!_(g.transform)&&g.transform,!g.worker||!c.WORKERS_SUPPORTED)return v=null,c.NODE_STREAM_INPUT,typeof m=="string"?(m=(E=>E.charCodeAt(0)!==65279?E:E.slice(1))(m),v=new(g.download?h:p)(g)):m.readable===!0&&_(m.read)&&_(m.on)?v=new b(g):(n.File&&m instanceof File||m instanceof Object)&&(v=new f(g)),v.stream(m);(v=(()=>{var E;return!!c.WORKERS_SUPPORTED&&(E=(()=>{var C=n.URL||n.webkitURL||null,T=s.toString();return c.BLOB_URL||(c.BLOB_URL=C.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; ","(",T,")();"],{type:"text/javascript"})))})(),(E=new n.Worker(E)).onmessage=k,E.id=d++,l[E.id]=E)})()).userStep=g.step,v.userChunk=g.chunk,v.userComplete=g.complete,v.userError=g.error,g.step=_(g.step),g.chunk=_(g.chunk),g.complete=_(g.complete),g.error=_(g.error),delete g.worker,v.postMessage({input:m,config:g,workerId:v.id})},c.unparse=function(m,g){var v=!1,E=!0,C=",",T=`\r `,U='"',z=U+U,ie=!1,$=null,V=!1,R=((()=>{if(typeof g=="object"){if(typeof g.delimiter!="string"||c.BAD_DELIMITERS.filter(function(B){return g.delimiter.indexOf(B)!==-1}).length||(C=g.delimiter),typeof g.quotes!="boolean"&&typeof g.quotes!="function"&&!Array.isArray(g.quotes)||(v=g.quotes),typeof g.skipEmptyLines!="boolean"&&typeof g.skipEmptyLines!="string"||(ie=g.skipEmptyLines),typeof g.newline=="string"&&(T=g.newline),typeof g.quoteChar=="string"&&(U=g.quoteChar),typeof g.header=="boolean"&&(E=g.header),Array.isArray(g.columns)){if(g.columns.length===0)throw new Error("Option columns is empty");$=g.columns}g.escapeChar!==void 0&&(z=g.escapeChar+U),g.escapeFormulae instanceof RegExp?V=g.escapeFormulae:typeof g.escapeFormulae=="boolean"&&g.escapeFormulae&&(V=/^[=+\-@\t\r].*$/)}})(),new RegExp(x(U),"g"));if(typeof m=="string"&&(m=JSON.parse(m)),Array.isArray(m)){if(!m.length||Array.isArray(m[0]))return q(null,m,ie);if(typeof m[0]=="object")return q($||Object.keys(m[0]),m,ie)}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||$),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])),q(m.fields||[],m.data||[],ie);throw new Error("Unable to serialize unrecognized input");function q(B,O,re){var te="",le=(typeof B=="string"&&(B=JSON.parse(B)),typeof O=="string"&&(O=JSON.parse(O)),Array.isArray(B)&&0<B.length),ee=!Array.isArray(O[0]);if(le&&E){for(var H=0;H<B.length;H++)0<H&&(te+=C),te+=I(B[H],H);0<O.length&&(te+=T)}for(var W=0;W<O.length;W++){var ne=(le?B:O[W]).length,F=!1,ae=le?Object.keys(O[W]).length===0:O[W].length===0;if(re&&!le&&(F=re==="greedy"?O[W].join("").trim()==="":O[W].length===1&&O[W][0].length===0),re==="greedy"&&le){for(var de=[],Y=0;Y<ne;Y++){var Z=ee?B[Y]:Y;de.push(O[W][Z])}F=de.join("").trim()===""}if(!F){for(var J=0;J<ne;J++){0<J&&!ae&&(te+=C);var _e=le&&ee?B[J]:J;te+=I(O[W][_e],J)}W<O.length-1&&(!re||0<ne&&!ae)&&(te+=T)}}return te}function I(B,O){var re,te;return B==null?"":B.constructor===Date?JSON.stringify(B).slice(1,25):(te=!1,V&&typeof B=="string"&&V.test(B)&&(B="'"+B,te=!0),re=B.toString().replace(R,z),(te=te||v===!0||typeof v=="function"&&v(B,O)||Array.isArray(v)&&v[O]||((le,ee)=>{for(var H=0;H<ee.length;H++)if(-1<le.indexOf(ee[H]))return!0;return!1})(re,c.BAD_DELIMITERS)||-1<re.indexOf(C)||re.charAt(0)===" "||re.charAt(re.length-1)===" ")?U+re+U:re)}},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=j,c.NetworkStreamer=h,c.FileStreamer=f,c.StringStreamer=p,c.ReadableStreamStreamer=b,n.jQuery&&((a=n.jQuery).fn.parse=function(m){var g=m.config||{},v=[];return this.each(function(T){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 U=0;U<this.files.length;U++)v.push({file:this.files[U],inputElem:this,instanceConfig:a.extend({},g)})}),E(),this;function E(){if(v.length===0)_(m.complete)&&m.complete();else{var T,U,z,ie,$=v[0];if(_(m.before)){var V=m.before($.file,$.inputElem);if(typeof V=="object"){if(V.action==="abort")return T="AbortError",U=$.file,z=$.inputElem,ie=V.reason,void(_(m.error)&&m.error({name:T},U,z,ie));if(V.action==="skip")return void C();typeof V.config=="object"&&($.instanceConfig=a.extend($.instanceConfig,V.config))}else if(V==="skip")return void C()}var R=$.instanceConfig.complete;$.instanceConfig.complete=function(q){_(R)&&R(q,$.file,$.inputElem),C()},c.parse($.file,$.instanceConfig)}}function C(){v.splice(0,1),E()}}),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,(p.prototype=Object.create(p.prototype)).constructor=p,(b.prototype=Object.create(u.prototype)).constructor=b,c})})(Cn);var ic=Cn.exports;const oc=Jt(ic),lc=({onSuccess:r})=>{const[e,s]=y.useState(!1),[n,a]=y.useState(null),[i,o]=y.useState([]),[l,d]=y.useState(!1),[c,u]=y.useState(null),[h,f]=y.useState(!1),[p,b]=y.useState(null),j=async()=>{try{s(!0),a(null),b(null);const N=await ac.importPlaylists(i,S=>{u({total:S.total,processed:S.processed,successCount:S.processed-S.failed,skipCount:S.skipped,unmatchedCategories:Array.from(S.unmatchedCategories),errors:S.recentErrors.map(_=>({row:_.row,error:_.message}))})});b(N),N.successCount>0&&r()}catch(N){a("Error importing playlists"),console.error("Import error:",N)}finally{s(!1)}},x=async N=>{try{if(s(!0),a(null),u(null),!N.name.endsWith(".csv")){a("Please upload a CSV file");return}const S=new FileReader;S.onload=async _=>{var E;const m=(E=_.target)==null?void 0:E.result,{data:g,errors:v}=oc.parse(m,{header:!0,skipEmptyLines:!0});if(v.length>0){a("Error parsing CSV file");return}o(g),d(!0)},S.readAsText(N)}catch{a("Error processing file")}finally{s(!1)}},w=y.useCallback(N=>{N.preventDefault(),N.stopPropagation(),f(!0)},[]),k=y.useCallback(N=>{N.preventDefault(),N.stopPropagation(),f(!1)},[]),P=y.useCallback(N=>{N.preventDefault(),N.stopPropagation(),f(!1);const S=N.dataTransfer.files[0];S&&x(S)},[]),A=N=>{var _;const S=(_=N.target.files)==null?void 0:_[0];S&&x(S),N.target.value=""};return t.jsxs("div",{className:"space-y-4",children:[t.jsx("div",{onDragOver:w,onDragLeave:k,onDrop:P,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(ce,{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(Bt,{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:A,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(oe,{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(ge,{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:j,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((N,S)=>t.jsxs("tr",{children:[t.jsx("td",{className:"px-6 py-4 whitespace-nowrap text-sm text-gray-900",children:N.Name}),t.jsx("td",{className:"px-6 py-4 whitespace-nowrap text-sm text-gray-500",children:N.Category}),t.jsx("td",{className:"px-6 py-4 whitespace-nowrap text-sm text-gray-500",children:N.Curator})]},S)),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"]})})]})]})})]}),p&&!e&&t.jsx(cc,{result:p})]})},cc=({result:r})=>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:r.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:r.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:r.unmatchedCategories.length}),t.jsx("div",{className:"text-sm text-blue-700",children:"Unmatched categories"})]})]}),r.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:r.unmatchedCategories.map((e,s)=>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},s))})]}),r.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:r.errors.map((e,s)=>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})]},s))})]})})]})]})});function dc({onClose:r,onComplete:e}){const[s,n]=y.useState(!1),[a,i]=y.useState(!1),[o,l]=y.useState(null),[d,c]=y.useState(null),u=y.useRef(null),h=async()=>{var b,j;console.log("Starting sync process..."),i(!0),l(null),u.current=new AbortController;try{console.log("Fetching playlist count...");const x=new Date(Date.now()-96*60*60*1e3).toISOString(),{count:w,error:k}=await D.from("playlists").select("*",{count:"exact",head:!0}).or(`last_synced_at.is.null,last_synced_at.lt.${x}`);if(k)throw console.error("Error getting playlist count:",k),k;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 P=1e3,A=5,N=1e3,S=3e4;let _=N,m=0,g=null;for(;m<w;){if((b=u.current)!=null&&b.signal.aborted)throw new Error("Sync cancelled");console.log(`Fetching page of playlists${g?` after ID ${g}`:""}...`);let v=D.from("playlists").select("id, spotify_id, last_synced_at").or(`last_synced_at.is.null,last_synced_at.lt.${x}`).order("last_synced_at",{ascending:!0,nullsFirst:!0}).limit(P);g&&(v=v.gt("id",g));const{data:E,error:C}=await v;if(C)throw console.error("Error fetching playlists:",C),C;if(!E||E.length===0){console.log("No more playlists to process");break}console.log(`Processing page of ${E.length} playlists${g?` after ID ${g}`:""}`),g=E[E.length-1].id;for(let T=0;T<E.length;T+=A){if((j=u.current)!=null&&j.signal.aborted)throw new Error("Sync cancelled");const U=E.slice(T,Math.min(T+A,E.length)),z=Math.floor((m+T)/A)+1,ie=Math.ceil(w/A);console.log(`Processing batch ${z} of ${ie}`);try{const $=await Promise.allSettled(U.map(async q=>{var I,B,O,re,te,le;try{console.log(`Fetching details for playlist ${q.spotify_id}`);const ee=await Hs(q.spotify_id);if(!ee)throw console.error(`No data returned for playlist ${q.spotify_id}`),new Error("Playlist not found on Spotify");return console.log(`Successfully fetched details for playlist ${q.spotify_id}`),{id:q.id,name:ee.name,description:ee.description||"",image_url:((I=ee.images[0])==null?void 0:I.url)||"",followers:((B=ee.followers)==null?void 0:B.total)||0,track_count:((O=ee.tracks)==null?void 0:O.total)||0,curator_name:((re=ee.owner)==null?void 0:re.display_name)||null,curator_profile_url:((le=(te=ee.owner)==null?void 0:te.external_urls)==null?void 0:le.spotify)||null,curator_email:ee.curator_email||null,last_synced_at:new Date().toISOString(),updated_at:new Date().toISOString()}}catch(ee){throw console.error(`Failed to fetch playlist ${q.spotify_id}:`,ee),ee}}));_=N;let V=0,R=0;for(const q of $)if(q.status==="fulfilled"){const{error:I}=await D.from("playlists").update(q.value).eq("id",q.value.id);I?(console.error("Failed to update playlist:",I),R++):(console.log(`Successfully updated playlist ${q.value.id}`),V++)}else{console.error("Batch update failed:",q.reason);const I=q.reason instanceof Error?q.reason.message:"Unknown error";console.error("Detailed error:",{message:I,fullError:q.reason}),R++}c(q=>({current:m+T+U.length,updated:((q==null?void 0:q.updated)||0)+V,failed:((q==null?void 0:q.failed)||0)+R,total:w}))}catch($){if($ instanceof Error&&$.message.includes("rate limit")){console.log(`Rate limit hit. Waiting ${_/1e3} seconds before retrying...`),await new Promise(V=>setTimeout(V,_)),_=Math.min(_*2,S),T-=A;continue}throw $}await new Promise($=>setTimeout($,_))}m+=E.length}e(),n(!1)}catch(x){console.error("Sync failed:",x);const w=x instanceof Error?x.message:"Failed to sync playlists";console.error("Detailed error:",{error:x,message:w}),l(w)}finally{i(!1),u.current=null}},f=()=>{var b;a?(b=u.current)==null||b.abort():(n(!1),r==null||r())},p=()=>{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:p,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(ut,{className:"w-5 h-5"}),"Start Sync"]})]})}),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:f,className:"text-gray-400 hover:text-gray-500 transition-colors",children:t.jsx(ge,{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(Ye,{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(oe,{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(oe,{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(ut,{className:"w-5 h-5"}),"Start Sync"]})]})]})]})})]})}function uc(){const[r,e]=y.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(dc,{onComplete:()=>e({type:"success",message:"Successfully synced playlists with Spotify"})}),t.jsxs(rc,{defaultValue:"playlists",className:"space-y-6",children:[t.jsxs(En,{children:[t.jsx(Ps,{value:"playlists",children:"Playlists"}),t.jsx(Ps,{value:"genres",children:"Genres & Sub-genres"})]}),t.jsx(As,{value:"playlists",children:t.jsx(lc,{onSuccess:()=>e({type:"success",message:"Successfully imported playlists"})})}),t.jsx(As,{value:"genres",children:t.jsx(nc,{onSuccess:()=>e({type:"success",message:"Successfully imported genres and sub-genres"})})})]})]}),r&&t.jsx(De,{message:r.message,type:r.type,onClose:()=>e(null)})]})}function hc({isOpen:r,onClose:e,onConfirm:s,isCleaning:n,progress:a}){if(!r)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(ge,{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(ce,{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:s,className:"px-4 py-2 bg-blue-500 text-white rounded-lg hover:bg-blue-600",children:"Start Cleaning"})]})]})]})})}async function fc(){return{success:!0}}function mc(){const[r,e]=y.useState(""),[s,n]=y.useState(""),[a,i]=y.useState(""),[o,l]=y.useState(!1),[d,c]=y.useState(!1),[u,h]=y.useState(!1),[f,p]=y.useState(!1),[b,j]=y.useState(null),[x,w]=y.useState(null),k=async S=>{if(S.preventDefault(),s!==a){j({type:"error",message:"New passwords do not match"});return}l(!0);try{j({type:"success",message:"Password updated successfully"}),e(""),n(""),i("")}catch(_){console.error("Failed to update password:",_),j({type:"error",message:"Failed to update password"})}finally{l(!1)}},P=async()=>{c(!0);try{await fc(),j({type:"success",message:"Genres and sub-genres have been set up successfully"})}catch(S){console.error("Failed to setup genres:",S),j({type:"error",message:"Failed to setup genres and sub-genres"})}finally{c(!1)}},A=async()=>{p(!0)},N=async()=>{h(!0),p(!0);try{const{count:S,error:_}=await D.from("playlists").select("*",{count:"exact",head:!0});if(_)throw _;if(!S)throw new Error("No playlists found");w({total:S,processed:0,updated:0});let m=!0,g=0;const v=50;for(;m;){const{data:E,error:C}=await D.from("playlists").select("id, description").range(g,g+v-1);if(C)throw C;if(!E||E.length===0){m=!1;break}for(const T of E){const{description:U,extractedEmail:z}=Nn(T.description);if(U!==T.description||z){const{error:ie}=await D.from("playlists").update({description:U,curator_email:z,updated_at:new Date().toISOString()}).eq("id",T.id);if(ie){console.error(`Failed to update playlist ${T.id}:`,ie);continue}w($=>$?{...$,updated:$.updated+1}:null)}w(ie=>ie?{...ie,processed:ie.processed+1}:null)}g+=v}j({type:"success",message:`Processed ${x==null?void 0:x.processed} playlists, updated ${x==null?void 0:x.updated} descriptions`})}catch(S){console.error("Failed to clean descriptions:",S),j({type:"error",message:S instanceof Error?S.message:"Failed to clean descriptions"})}finally{h(!1),p(!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:P,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(ce,{className:"w-5 h-5 animate-spin"}):t.jsx(ut,{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:A,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(ce,{className:"w-5 h-5 animate-spin"}):t.jsx(Wo,{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:k,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:r,onChange:S=>e(S.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:s,onChange:S=>n(S.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:S=>i(S.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(ce,{className:"w-5 h-5 animate-spin"}):t.jsx(Jo,{className:"w-5 h-5"}),o?"Updating...":"Update Password"]})]})]})]}),t.jsx(hc,{isOpen:f,onClose:()=>p(!1),onConfirm:N,isCleaning:u,progress:x}),b&&t.jsx(De,{message:b.message,type:b.type,onClose:()=>j(null)})]})}function gc(){var p,b;const[r,e]=y.useState(""),[s,n]=y.useState(""),[a,i]=y.useState(""),[o,l]=y.useState(!1),d=He(),c=Qe(),{signIn:u}=Us(),h=((b=(p=c.state)==null?void 0:p.from)==null?void 0:b.pathname)||"/admin",f=async j=>{j.preventDefault(),i(""),l(!0);try{await u(r.trim(),s),d(h,{replace:!0})}catch(x){console.error("Login failed:",x),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(Go,{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:r,onChange:j=>e(j.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:s,onChange:j=>n(j.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(oe,{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(ce,{className:"w-5 h-5 animate-spin"}):"Sign in"})]})]})})}function pc(){return t.jsx(bn,{children:t.jsx("div",{className:"min-h-screen flex flex-col",children:t.jsxs(zn,{children:[t.jsx(ue,{path:"/",element:t.jsxs(t.Fragment,{children:[t.jsx(Ae,{}),t.jsx(nl,{}),t.jsx(Oe,{})]})}),t.jsx(ue,{path:"/playlists",element:t.jsxs(t.Fragment,{children:[t.jsx(Ae,{}),t.jsx(Ol,{}),t.jsx(Oe,{})]})}),t.jsx(ue,{path:"/submit",element:t.jsxs(t.Fragment,{children:[t.jsx(Ae,{}),t.jsx($l,{}),t.jsx(Oe,{})]})}),t.jsx(ue,{path:"/submit/genre",element:t.jsxs(t.Fragment,{children:[t.jsx(Ae,{}),t.jsx(Rl,{}),t.jsx(Oe,{})]})}),t.jsx(ue,{path:"/playlist/:slug/*",element:t.jsxs(t.Fragment,{children:[t.jsx(Ae,{}),t.jsx(Pl,{}),t.jsx(Oe,{})]})}),t.jsx(ue,{path:"/genres",element:t.jsxs(t.Fragment,{children:[t.jsx(Ae,{}),t.jsx(Ml,{}),t.jsx(Oe,{})]})}),t.jsx(ue,{path:"/genre/:genre",element:t.jsxs(t.Fragment,{children:[t.jsx(Ae,{}),t.jsx(Ll,{}),t.jsx(Oe,{})]})}),t.jsx(ue,{path:"/genre/:genre/:subGenre",element:t.jsxs(t.Fragment,{children:[t.jsx(Ae,{}),t.jsx(Ul,{}),t.jsx(Oe,{})]})}),t.jsx(ue,{path:"/about",element:t.jsxs(t.Fragment,{children:[t.jsx(Ae,{}),t.jsx(ql,{}),t.jsx(Oe,{})]})}),t.jsx(ue,{path:"/for-curators",element:t.jsxs(t.Fragment,{children:[t.jsx(Ae,{}),t.jsx(Gl,{}),t.jsx(Oe,{})]})}),t.jsx(ue,{path:"/admin/login",element:t.jsx(gc,{})}),t.jsxs(ue,{path:"/admin",element:t.jsx(zl,{}),children:[t.jsx(ue,{index:!0,element:t.jsx(Jl,{})}),t.jsx(ue,{path:"playlists",element:t.jsx(Yl,{})}),t.jsx(ue,{path:"submissions",element:t.jsx(Xl,{})}),t.jsx(ue,{path:"genres",element:t.jsx(sc,{})}),t.jsx(ue,{path:"import",element:t.jsx(uc,{})}),t.jsx(ue,{path:"settings",element:t.jsx(mc,{})})]}),t.jsx(ue,{path:"*",element:t.jsx(Pr,{to:"/",replace:!0})})]})})})}const xc={};Ar(document.getElementById("root")).render(t.jsx(y.StrictMode,{children:t.jsx(Fr,{context:xc,children:t.jsx(Hn,{children:t.jsx(To,{children:t.jsx(bn,{children:t.jsx(pc,{})})})})})}));export{ce as L,Gs as P,pt as S,De as T,Il as u}; //# sourceMappingURL=index-BaFeowp1.js.map