const __vite__mapDeps=(i,m=__vite__mapDeps,d=(m.f||(m.f=["assets/FeaturedPlaylists-DrQp35r3.js","assets/ui-vendor-DYHpVWUc.js","assets/react-vendor-Dv0pxvir.js","assets/FAQSection-DYdRED9D.js","assets/AdditionalInfoSection-DphltVm4.js"])))=>i.map(i=>d[i]);
var Fn=Object.defineProperty;var Un=(r,e,s)=>e in r?Fn(r,e,{enumerable:!0,configurable:!0,writable:!0,value:s}):r[e]=s;var Ne=(r,e,s)=>Un(r,typeof e!="symbol"?e+"":e,s);import{j as t,u as Mn,C as qn,a as Bn,b as sr,D as Gn,c as zn,S as Hn,v as Wn,s as Jn,K as Kn,P as Vn,L as $r,T as Ir,d as Rr,R as Yn}from"./ui-vendor-DYHpVWUc.js";import{a as Dr,g as Zt,r as y,R as ze,c as Zn,d as ve,L as X,u as et,e as We,f as Lr,h as Ms,N as Fr,O as Qn,i as Xn,j as ue,B as ea}from"./react-vendor-Dv0pxvir.js";(function(){const e=document.createElement("link").relList;if(e&&e.supports&&e.supports("modulepreload"))return;for(const a of document.querySelectorAll('link[rel="modulepreload"]'))n(a);new MutationObserver(a=>{for(const i of a)if(i.type==="childList")for(const o of i.addedNodes)o.tagName==="LINK"&&o.rel==="modulepreload"&&n(o)}).observe(document,{childList:!0,subtree:!0});function 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 Ur,rr=Dr;Ur=rr.createRoot,rr.hydrateRoot;var ta=typeof Element<"u",sa=typeof Map=="function",ra=typeof Set=="function",na=typeof ArrayBuffer=="function"&&!!ArrayBuffer.isView;function Bt(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(!Bt(r[n],e[n]))return!1;return!0}var i;if(sa&&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(!Bt(n.value[1],e.get(n.value[0])))return!1;return!0}if(ra&&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(na&&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(ta&&r instanceof Element)return!1;for(n=s;n--!==0;)if(!((a[n]==="_owner"||a[n]==="__v"||a[n]==="__o")&&r.$$typeof)&&!Bt(r[a[n]],e[a[n]]))return!1;return!0}return r!==r&&e!==e}var aa=function(e,s){try{return Bt(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 ia=Zt(aa);var oa=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}},la=oa;const nr=Zt(la);var ca=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 da=Zt(ca);var Mr=(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))(Mr||{}),cs={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"]}},ar=Object.values(Mr),qs={accesskey:"accessKey",charset:"charSet",class:"className",contenteditable:"contentEditable",contextmenu:"contextMenu","http-equiv":"httpEquiv",itemprop:"itemProp",tabindex:"tabIndex"},ua=Object.entries(qs).reduce((r,[e,s])=>(r[s]=e,r),{}),Ee="data-rh",dt={DEFAULT_TITLE:"defaultTitle",DEFER:"defer",ENCODE_SPECIAL_CHARACTERS:"encodeSpecialCharacters",ON_CHANGE_CLIENT_STATE:"onChangeClientState",TITLE_TEMPLATE:"titleTemplate",PRIORITIZE_SEO_TAGS:"prioritizeSeoTags"},ut=(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},ha=r=>{let e=ut(r,"title");const s=ut(r,dt.TITLE_TEMPLATE);if(Array.isArray(e)&&(e=e.join("")),s&&e)return s.replace(/%s/g,()=>e);const n=ut(r,dt.DEFAULT_TITLE);return e||n||void 0},fa=r=>ut(r,dt.ON_CHANGE_CLIENT_STATE)||(()=>{}),ds=(r,e)=>e.filter(s=>typeof s[r]<"u").map(s=>s[r]).reduce((s,n)=>({...s,...n}),{}),ma=(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},[]),ga=r=>console&&typeof console.warn=="function"&&console.warn(r),jt=(r,e,s)=>{const n={};return s.filter(a=>Array.isArray(a[r])?!0:(typeof a[r]<"u"&&ga(`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()},pa=(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},xa=r=>({baseTag:ma(["href"],r),bodyAttributes:ds("bodyAttributes",r),defer:ut(r,dt.DEFER),encode:ut(r,dt.ENCODE_SPECIAL_CHARACTERS),htmlAttributes:ds("htmlAttributes",r),linkTags:jt("link",["rel","href"],r),metaTags:jt("meta",["name","charset","http-equiv","property","itemprop"],r),noscriptTags:jt("noscript",["innerHTML"],r),onChangeClientState:fa(r),scriptTags:jt("script",["src","innerHTML"],r),styleTags:jt("style",["cssText"],r),title:ha(r),titleAttributes:ds("titleAttributes",r),prioritizeSeoTags:pa(r,dt.PRIORITIZE_SEO_TAGS)}),qr=r=>Array.isArray(r)?r.join(""):r,ya=(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},us=(r,e)=>Array.isArray(r)?r.reduce((s,n)=>(ya(n,e)?s.priority.push(n):s.default.push(n),s),{priority:[],default:[]}):{default:r,priority:[]},ir=(r,e)=>({...r,[e]:void 0}),ba=["noscript","script","style"],vs=(r,e=!0)=>e===!1?String(r):String(r).replace(/&/g,"&amp;").replace(/</g,"&lt;").replace(/>/g,"&gt;").replace(/"/g,"&quot;").replace(/'/g,"&#x27;"),Br=r=>Object.keys(r).reduce((e,s)=>{const n=typeof r[s]<"u"?`${s}="${r[s]}"`:`${s}`;return e?`${e} ${n}`:n},""),wa=(r,e,s,n)=>{const a=Br(s),i=qr(e);return a?`<${r} ${Ee}="true" ${a}>${vs(i,n)}</${r}>`:`<${r} ${Ee}="true">${vs(i,n)}</${r}>`},va=(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}="${vs(i[u],s)}"`;return c?`${c} ${h}`:h},""),l=i.innerHTML||i.cssText||"",d=ba.indexOf(r)===-1;return`${n}<${r} ${Ee}="true" ${o}${d?"/>":`>${l}</${r}>`}`},""),Gr=(r,e={})=>Object.keys(r).reduce((s,n)=>{const a=qs[n];return s[a||n]=r[n],s},e),ja=(r,e,s)=>{const n={key:e,[Ee]:!0},a=Gr(s,n);return[ze.createElement("title",a,e)]},Gt=(r,e)=>e.map((s,n)=>{const a={key:n,[Ee]:!0};return Object.keys(s).forEach(i=>{const l=qs[i]||i;if(l==="innerHTML"||l==="cssText"){const d=s.innerHTML||s.cssText;a.dangerouslySetInnerHTML={__html:d}}else a[l]=s[i]}),ze.createElement(r,a)}),je=(r,e,s=!0)=>{switch(r){case"title":return{toComponent:()=>ja(r,e.title,e.titleAttributes),toString:()=>wa(r,e.title,e.titleAttributes,s)};case"bodyAttributes":case"htmlAttributes":return{toComponent:()=>Gr(e),toString:()=>Br(e)};default:return{toComponent:()=>Gt(r,e),toString:()=>va(r,e,s)}}},_a=({metaTags:r,linkTags:e,scriptTags:s,encode:n})=>{const a=us(r,cs.meta),i=us(e,cs.link),o=us(s,cs.script);return{priorityMethods:{toComponent:()=>[...Gt("meta",a.priority),...Gt("link",i.priority),...Gt("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}},Na=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}=_a(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)}},js=Na,Rt=[],zr=!!(typeof window<"u"&&window.document&&window.document.createElement),_s=class{constructor(r,e){Ne(this,"instances",[]);Ne(this,"canUseDOM",zr);Ne(this,"context");Ne(this,"value",{setHelmet:r=>{this.context.helmet=r},helmetInstances:{get:()=>this.canUseDOM?Rt:this.instances,add:r=>{(this.canUseDOM?Rt:this.instances).push(r)},remove:r=>{const e=(this.canUseDOM?Rt:this.instances).indexOf(r);(this.canUseDOM?Rt:this.instances).splice(e,1)}}});this.context=r,this.canUseDOM=e||!1,e||(r.helmet=js({baseTag:[],bodyAttributes:{},htmlAttributes:{},linkTags:[],metaTags:[],noscriptTags:[],scriptTags:[],styleTags:[],title:"",titleAttributes:{}}))}},Sa={},Hr=ze.createContext(Sa),Xe,Wr=(Xe=class extends y.Component{constructor(s){super(s);Ne(this,"helmetData");this.helmetData=new _s(this.props.context||{},Xe.canUseDOM)}render(){return ze.createElement(Hr.Provider,{value:this.helmetData.value},this.props.children)}},Ne(Xe,"canUseDOM",zr),Xe),nt=(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}},Ns=(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(","))},ka=(r,e)=>{typeof r<"u"&&document.title!==r&&(document.title=qr(r)),Ns("title",e)},or=(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;Ns("body",n),Ns("html",a),ka(h,f);const p={baseTag:nt("base",s),linkTags:nt("link",i),metaTags:nt("meta",o),noscriptTags:nt("noscript",l),scriptTags:nt("script",c),styleTags:nt("style",u)},b={},_={};Object.keys(p).forEach(x=>{const{newTags:w,oldTags:E}=p[x];w.length&&(b[x]=w),E.length&&(_[x]=p[x].oldTags)}),e&&e(),d(r,b,_)},_t=null,Ea=r=>{_t&&cancelAnimationFrame(_t),r.defer?_t=requestAnimationFrame(()=>{or(r,()=>{_t=null})}):(or(r),_t=null)},Ca=Ea,lr=class extends y.Component{constructor(){super(...arguments);Ne(this,"rendered",!1)}shouldComponentUpdate(e){return!da(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=xa(e.get().map(i=>{const o={...i.props};return delete o.context,o}));Wr.canUseDOM?Ca(a):js&&(n=js(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}},ws,Ta=(ws=class extends y.Component{shouldComponentUpdate(r){return!ia(ir(this.props,"helmetData"),ir(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 nr(ar.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 ${ar.join(", ")} are allowed. Helmet does not support rendering <${r.type}> elements. Refer to our API for more information.`),nr(!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 ze.Children.forEach(r,n=>{if(!n||!n.props)return;const{children:a,...i}=n.props,o=Object.keys(i).reduce((d,c)=>(d[ua[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 _s)){const a=n;n=new _s(a.context,!0),delete s.helmetData}return n?ze.createElement(lr,{...s,context:n.value}):ze.createElement(Hr.Consumer,null,a=>ze.createElement(lr,{...s,context:a}))}},Ne(ws,"defaultProps",{defer:!0,encodeSpecialCharacters:!0,prioritizeSeoTags:!1}),ws);const Pa="modulepreload",Aa=function(r){return"/"+r},cr={},Ue=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=Aa(d),d in cr)return;cr[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":Pa,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)})},Oa=r=>{let e;return r?e=r:typeof fetch>"u"?e=(...s)=>Ue(async()=>{const{default:n}=await Promise.resolve().then(()=>xt);return{default:n}},void 0).then(({default:n})=>n(...s)):e=fetch,(...s)=>e(...s)};class Bs extends Error{constructor(e,s="FunctionsError",n){super(e),this.name=s,this.context=n}}class $a extends Bs{constructor(e){super("Failed to send a request to the Edge Function","FunctionsFetchError",e)}}class Ia extends Bs{constructor(e){super("Relay Error invoking the Edge Function","FunctionsRelayError",e)}}class Ra extends Bs{constructor(e){super("Edge Function returned a non-2xx status code","FunctionsHttpError",e)}}var Ss;(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"})(Ss||(Ss={}));var Da=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 La{constructor(e,{headers:s={},customFetch:n,region:a=Ss.Any}={}){this.url=e,this.headers=s,this.region=a,this.fetch=Oa(n)}setAuth(e){this.headers.Authorization=`Bearer ${e}`}invoke(e,s={}){var n;return Da(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 $a(b)}),h=u.headers.get("x-relay-error");if(h&&h==="true")throw new Ia(u);if(!u.ok)throw new Ra(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 we={},Gs={},Qt={},At={},Xt={},es={},Fa=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")},ft=Fa();const Ua=ft.fetch,Jr=ft.fetch.bind(ft),Kr=ft.Headers,Ma=ft.Request,qa=ft.Response,xt=Object.freeze(Object.defineProperty({__proto__:null,Headers:Kr,Request:Ma,Response:qa,default:Jr,fetch:Ua},Symbol.toStringTag,{value:"Module"})),Ba=Zn(xt);var ts={};Object.defineProperty(ts,"__esModule",{value:!0});let Ga=class extends Error{constructor(e){super(e.message),this.name="PostgrestError",this.details=e.details,this.hint=e.hint,this.code=e.code}};ts.default=Ga;var Vr=ve&&ve.__importDefault||function(r){return r&&r.__esModule?r:{default:r}};Object.defineProperty(es,"__esModule",{value:!0});const za=Vr(Ba),Ha=Vr(ts);let Wa=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=za.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 _=(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("/");_&&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 _=await i.text();try{c=JSON.parse(_),Array.isArray(c)&&i.status===404&&(u=[],c=null,f=200,p="OK")}catch{i.status===404&&_===""?(f=204,p="No Content"):c={message:_}}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 Ha.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)}returns(){return this}overrideTypes(){return this}};es.default=Wa;var Ja=ve&&ve.__importDefault||function(r){return r&&r.__esModule?r:{default:r}};Object.defineProperty(Xt,"__esModule",{value:!0});const Ka=Ja(es);let Va=class extends Ka.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}};Xt.default=Va;var Ya=ve&&ve.__importDefault||function(r){return r&&r.__esModule?r:{default:r}};Object.defineProperty(At,"__esModule",{value:!0});const Za=Ya(Xt);let Qa=class extends Za.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}};At.default=Qa;var Xa=ve&&ve.__importDefault||function(r){return r&&r.__esModule?r:{default:r}};Object.defineProperty(Qt,"__esModule",{value:!0});const Nt=Xa(At);let ei=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 Nt.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 Nt.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 Nt.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 Nt.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 Nt.default({method:s,url:this.url,headers:this.headers,schema:this.schema,fetch:this.fetch,allowEmpty:!1})}};Qt.default=ei;var ss={},rs={};Object.defineProperty(rs,"__esModule",{value:!0});rs.version=void 0;rs.version="0.0.0-automated";Object.defineProperty(ss,"__esModule",{value:!0});ss.DEFAULT_HEADERS=void 0;const ti=rs;ss.DEFAULT_HEADERS={"X-Client-Info":`postgrest-js/${ti.version}`};var Yr=ve&&ve.__importDefault||function(r){return r&&r.__esModule?r:{default:r}};Object.defineProperty(Gs,"__esModule",{value:!0});const si=Yr(Qt),ri=Yr(At),ni=ss;let ai=class Zr{constructor(e,{headers:s={},schema:n,fetch:a}={}){this.url=e,this.headers=Object.assign(Object.assign({},ni.DEFAULT_HEADERS),s),this.schemaName=n,this.fetch=a}from(e){const s=new URL(`${this.url}/${e}`);return new si.default(s,{headers:Object.assign({},this.headers),schema:this.schemaName,fetch:this.fetch})}schema(e){return new Zr(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 ri.default({method:o,url:l,headers:c,schema:this.schemaName,body:d,fetch:this.fetch,allowEmpty:!1})}};Gs.default=ai;var yt=ve&&ve.__importDefault||function(r){return r&&r.__esModule?r:{default:r}};Object.defineProperty(we,"__esModule",{value:!0});we.PostgrestError=we.PostgrestBuilder=we.PostgrestTransformBuilder=we.PostgrestFilterBuilder=we.PostgrestQueryBuilder=we.PostgrestClient=void 0;const Qr=yt(Gs);we.PostgrestClient=Qr.default;const Xr=yt(Qt);we.PostgrestQueryBuilder=Xr.default;const en=yt(At);we.PostgrestFilterBuilder=en.default;const tn=yt(Xt);we.PostgrestTransformBuilder=tn.default;const sn=yt(es);we.PostgrestBuilder=sn.default;const rn=yt(ts);we.PostgrestError=rn.default;var ii=we.default={PostgrestClient:Qr.default,PostgrestQueryBuilder:Xr.default,PostgrestFilterBuilder:en.default,PostgrestTransformBuilder:tn.default,PostgrestBuilder:sn.default,PostgrestError:rn.default};const{PostgrestClient:oi,PostgrestQueryBuilder:Hc,PostgrestFilterBuilder:Wc,PostgrestTransformBuilder:Jc,PostgrestBuilder:Kc,PostgrestError:Vc}=ii;let ks;typeof window>"u"?ks=require("ws"):ks=window.WebSocket;const li="2.11.10",ci={"X-Client-Info":`realtime-js/${li}`},di="1.0.0",nn=1e4,ui=1e3;var ht;(function(r){r[r.connecting=0]="connecting",r[r.open=1]="open",r[r.closing=2]="closing",r[r.closed=3]="closed"})(ht||(ht={}));var pe;(function(r){r.closed="closed",r.errored="errored",r.joined="joined",r.joining="joining",r.leaving="leaving"})(pe||(pe={}));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 Es;(function(r){r.websocket="websocket"})(Es||(Es={}));var Ze;(function(r){r.Connecting="connecting",r.Open="open",r.Closing="closing",r.Closed="closed"})(Ze||(Ze={}));class hi{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 an{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 dr=(r,e,s={})=>{var n;const a=(n=s.skipTypes)!==null&&n!==void 0?n:[];return Object.keys(e).reduce((i,o)=>(i[o]=fi(o,r,e,a),i),{})},fi=(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)?on(i,o):Cs(o)},on=(r,e)=>{if(r.charAt(0)==="_"){const s=r.slice(1,r.length);return xi(e,s)}switch(r){case Q.bool:return mi(e);case Q.float4:case Q.float8:case Q.int2:case Q.int4:case Q.int8:case Q.numeric:case Q.oid:return gi(e);case Q.json:case Q.jsonb:return pi(e);case Q.timestamp:return yi(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 Cs(e);default:return Cs(e)}},Cs=r=>r,mi=r=>{switch(r){case"t":return!0;case"f":return!1;default:return r}},gi=r=>{if(typeof r=="string"){const e=parseFloat(r);if(!Number.isNaN(e))return e}return r},pi=r=>{if(typeof r=="string")try{return JSON.parse(r)}catch(e){return console.log(`JSON parse error: ${e}`),r}return r},xi=(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=>on(e,l))}return r},yi=r=>typeof r=="string"?r.replace(" ","T"):r,ln=r=>{let e=r;return e=e.replace(/^ws/i,"http"),e=e.replace(/(\/socket\/websocket|\/socket|\/websocket)\/?$/i,""),e.replace(/\/+$/,"")};class hs{constructor(e,s,n={},a=nn){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 ur;(function(r){r.SYNC="sync",r.JOIN="join",r.LEAVE="leave"})(ur||(ur={}));class Et{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=Et.syncState(this.state,a,i,o),this.pendingDiffs.forEach(d=>{this.state=Et.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=Et.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),_=h.filter(x=>f.indexOf(x.presence_ref)<0);b.length>0&&(l[c]=b),_.length>0&&(d[c]=_)}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 hr;(function(r){r.ALL="*",r.INSERT="INSERT",r.UPDATE="UPDATE",r.DELETE="DELETE"})(hr||(hr={}));var fr;(function(r){r.BROADCAST="broadcast",r.PRESENCE="presence",r.POSTGRES_CHANGES="postgres_changes",r.SYSTEM="system"})(fr||(fr={}));var Fe;(function(r){r.SUBSCRIBED="SUBSCRIBED",r.TIMED_OUT="TIMED_OUT",r.CLOSED="CLOSED",r.CHANNEL_ERROR="CHANNEL_ERROR"})(Fe||(Fe={}));class zs{constructor(e,s={config:{}},n){this.topic=e,this.params=s,this.socket=n,this.bindings={},this.state=pe.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 hs(this,ke.join,this.params,this.timeout),this.rejoinTimer=new an(()=>this._rejoinUntilConnected(),this.socket.reconnectAfterMs),this.joinPush.receive("ok",()=>{this.state=pe.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=pe.closed,this.socket._remove(this)}),this._onError(a=>{this._isLeaving()||this._isClosed()||(this.socket.log("channel",`error ${this.topic}`,a),this.state=pe.errored,this.rejoinTimer.scheduleTimeout())}),this.joinPush.receive("timeout",()=>{this._isJoining()&&(this.socket.log("channel",`timeout ${this.topic}`,this.joinPush.timeout),this.state=pe.errored,this.rejoinTimer.scheduleTimeout())}),this._on(ke.reply,{},(a,i)=>{this._trigger(this._replyEventName(i),a)}),this.presence=new Et(this),this.broadcastEndpointURL=ln(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==null?void 0:e(Fe.CHANNEL_ERROR,u)),this._onClose(()=>e==null?void 0:e(Fe.CLOSED));const d={},c={broadcast:i,presence:o,postgres_changes:(a=(n=this.bindings.postgres_changes)===null||n===void 0?void 0:n.map(u=>u.filter))!==null&&a!==void 0?a:[],private:l};this.socket.accessTokenValue&&(d.access_token=this.socket.accessTokenValue),this.updateJoinPayload(Object.assign({config:c},d)),this.joinedOnce=!0,this._rejoin(s),this.joinPush.receive("ok",async({postgres_changes:u})=>{var h;if(this.socket.setAuth(),u===void 0){e==null||e(Fe.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 _=0;_<p;_++){const x=f[_],{filter:{event:w,schema:E,table:k,filter:A}}=x,N=u&&u[_];if(N&&N.event===w&&N.schema===E&&N.table===k&&N.filter===A)b.push(Object.assign(Object.assign({},x),{id:N.id}));else{this.unsubscribe(),this.state=pe.errored,e==null||e(Fe.CHANNEL_ERROR,new Error("mismatch between server and client bindings for postgres changes"));return}}this.bindings.postgres_changes=b,e&&e(Fe.SUBSCRIBED);return}}).receive("error",u=>{this.state=pe.errored,e==null||e(Fe.CHANNEL_ERROR,new Error(JSON.stringify(Object.values(u).join(", ")||"error")))}).receive("timeout",()=>{e==null||e(Fe.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,d={method:"POST",headers:{Authorization:this.socket.accessTokenValue?`Bearer ${this.socket.accessTokenValue}`:"",apikey:this.socket.apiKey?this.socket.apiKey:"","Content-Type":"application/json"},body:JSON.stringify({messages:[{topic:this.subTopic,event:i,payload:o,private:this.private}]})};try{const c=await this._fetchWithTimeout(this.broadcastEndpointURL,d,(n=s.timeout)!==null&&n!==void 0?n:this.timeout);return await((a=c.body)===null||a===void 0?void 0:a.cancel()),c.ok?"ok":"error"}catch(c){return c.name==="AbortError"?"timed out":"error"}}else return new Promise(i=>{var o,l,d;const c=this._push(e.type,e,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=pe.leaving;const s=()=>{this.socket.log("channel",`leave ${this.topic}`),this._trigger(ke.close,"leave",this._joinRef())};return this.joinPush.destroy(),new Promise(n=>{const a=new hs(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",{})})}teardown(){this.pushBuffer.forEach(e=>e.destroy()),this.rejoinTimer&&clearTimeout(this.rejoinTimer.timer),this.joinPush.destroy()}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 hs(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,_,x;return((b=p.filter)===null||b===void 0?void 0:b.event)==="*"||((x=(_=p.filter)===null||_===void 0?void 0:_.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,_,x,w,E,k;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&&((_=s.ids)===null||_===void 0?void 0:_.includes(A))&&(N==="*"||(N==null?void 0:N.toLocaleLowerCase())===((x=s.data)===null||x===void 0?void 0:x.type.toLocaleLowerCase()))}else{const A=(E=(w=p==null?void 0:p.filter)===null||w===void 0?void 0:w.event)===null||E===void 0?void 0:E.toLocaleLowerCase();return A==="*"||A===((k=s==null?void 0:s.event)===null||k===void 0?void 0:k.toLocaleLowerCase())}else return p.type.toLocaleLowerCase()===o}).map(p=>{if(typeof f=="object"&&"ids"in f){const b=f.data,{schema:_,table:x,commit_timestamp:w,type:E,errors:k}=b;f=Object.assign(Object.assign({},{schema:_,table:x,commit_timestamp:w,eventType:E,new:{},old:{},errors:k}),this._getPayloadRecords(b))}p.callback(f,n)})}_isClosed(){return this.state===pe.closed}_isJoined(){return this.state===pe.joined}_isJoining(){return this.state===pe.joining}_isLeaving(){return this.state===pe.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&&zs.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=pe.joining,this.joinPush.resend(e))}_getPayloadRecords(e){const s={new:{},old:{}};return(e.type==="INSERT"||e.type==="UPDATE")&&(s.new=dr(e.columns,e.record)),(e.type==="UPDATE"||e.type==="DELETE")&&(s.old=dr(e.columns,e.old_record)),s}}const mr=()=>{},bi=`
  addEventListener("message", (e) => {
    if (e.data.event === "start") {
      setInterval(() => postMessage({ event: "keepAlive" }), e.data.interval);
    }
  });`;class wi{constructor(e,s){var n;this.accessTokenValue=null,this.apiKey=null,this.channels=new Array,this.endPoint="",this.httpEndpoint="",this.headers=ci,this.params={},this.timeout=nn,this.heartbeatIntervalMs=25e3,this.heartbeatTimer=void 0,this.pendingHeartbeatRef=null,this.heartbeatCallback=mr,this.ref=0,this.logger=mr,this.conn=null,this.sendBuffer=[],this.serializer=new hi,this.stateChangeCallbacks={open:[],close:[],error:[],message:[]},this.accessToken=null,this._resolveFetch=i=>{let o;return i?o=i:typeof fetch>"u"?o=(...l)=>Ue(async()=>{const{default:d}=await Promise.resolve().then(()=>xt);return{default:d}},void 0).then(({default:d})=>d(...l)):o=fetch,(...l)=>o(...l)},this.endPoint=`${e}/${Es.websocket}`,this.httpEndpoint=ln(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.logLevel||s!=null&&s.log_level)&&(this.logLevel=s.logLevel||s.log_level,this.params=Object.assign(Object.assign({},this.params),{log_level:this.logLevel})),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.accessTokenValue=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 an(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}this.accessToken=(s==null?void 0:s.accessToken)||null}connect(){if(!this.conn){if(this.transport||(this.transport=ks),this.transport){typeof window<"u"&&this.transport===window.WebSocket?this.conn=new this.transport(this.endpointURL()):this.conn=new this.transport(this.endpointURL(),void 0,{headers:this.headers}),this.setupConnection();return}this.conn=new vi(this.endpointURL(),void 0,{close:()=>{this.conn=null}})}}endpointURL(){return this._appendParams(this.endPoint,Object.assign({},this.params,{vsn:di}))}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(),this.channels.forEach(n=>n.teardown()))}getChannels(){return this.channels}async removeChannel(e){const s=await e.unsubscribe();return this.channels=this.channels.filter(n=>n._joinRef!==e._joinRef),this.channels.length===0&&this.disconnect(),s}async removeAllChannels(){const e=await Promise.all(this.channels.map(s=>s.unsubscribe()));return this.channels=[],this.disconnect(),e}log(e,s,n){this.logger(e,s,n)}connectionState(){switch(this.conn&&this.conn.readyState){case ht.connecting:return Ze.Connecting;case ht.open:return Ze.Open;case ht.closing:return Ze.Closing;default:return Ze.Closed}}isConnected(){return this.connectionState()===Ze.Open}channel(e,s={config:{}}){const n=`realtime:${e}`,a=this.getChannels().find(i=>i.topic===n);if(a)return a;{const i=new zs(`realtime:${e}`,s,this);return this.channels.push(i),i}}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)}async setAuth(e=null){let s=e||this.accessToken&&await this.accessToken()||this.accessTokenValue;this.accessTokenValue!=s&&(this.accessTokenValue=s,this.channels.forEach(n=>{s&&n.updateJoinPayload({access_token:s,version:this.headers&&this.headers["X-Client-Info"]}),n.joinedOnce&&n._isJoined()&&n._push(ke.access_token,{access_token:s})}))}async sendHeartbeat(){var e;if(!this.isConnected()){this.heartbeatCallback("disconnected");return}if(this.pendingHeartbeatRef){this.pendingHeartbeatRef=null,this.log("transport","heartbeat timeout. Attempting to re-establish connection"),this.heartbeatCallback("timeout"),(e=this.conn)===null||e===void 0||e.close(ui,"hearbeat timeout");return}this.pendingHeartbeatRef=this._makeRef(),this.push({topic:"phoenix",event:"heartbeat",payload:{},ref:this.pendingHeartbeatRef}),this.heartbeatCallback("sent"),await this.setAuth()}onHeartbeat(e){this.heartbeatCallback=e}flushSendBuffer(){this.isConnected()&&this.sendBuffer.length>0&&(this.sendBuffer.forEach(e=>e()),this.sendBuffer=[])}_makeRef(){let e=this.ref+1;return e===this.ref?this.ref=0:this.ref=e,this.ref.toString()}_leaveOpenTopic(e){let 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.topic!==e.topic)}setupConnection(){this.conn&&(this.conn.binaryType="arraybuffer",this.conn.onopen=()=>this._onConnOpen(),this.conn.onerror=e=>this._onConnError(e),this.conn.onmessage=e=>this._onConnMessage(e),this.conn.onclose=e=>this._onConnClose(e))}_onConnMessage(e){this.decode(e.data,s=>{let{topic:n,event:a,payload:i,ref:o}=s;n==="phoenix"&&a==="phx_reply"&&this.heartbeatCallback(s.payload.status=="ok"?"ok":"error"),o&&o===this.pendingHeartbeatRef&&(this.pendingHeartbeatRef=null),this.log("receive",`${i.status||""} ${n} ${a} ${o&&"("+o+")"||""}`,i),Array.from(this.channels).filter(l=>l._isMember(n)).forEach(l=>l._trigger(a,i,o)),this.stateChangeCallbacks.message.forEach(l=>l(s))})}_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}`}_workerObjectUrl(e){let s;if(e)s=e;else{const n=new Blob([bi],{type:"application/javascript"});s=URL.createObjectURL(n)}return s}}class vi{constructor(e,s,n){this.binaryType="arraybuffer",this.onclose=()=>{},this.onerror=()=>{},this.onmessage=()=>{},this.onopen=()=>{},this.readyState=ht.connecting,this.send=()=>{},this.url=null,this.url=e,this.close=n.close}}class Hs 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 ji extends Hs{constructor(e,s){super(e),this.name="StorageApiError",this.status=s}toJSON(){return{name:this.name,message:this.message,status:this.status}}}class Ts extends Hs{constructor(e,s){super(e),this.name="StorageUnknownError",this.originalError=s}}var _i=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 cn=r=>{let e;return r?e=r:typeof fetch>"u"?e=(...s)=>Ue(async()=>{const{default:n}=await Promise.resolve().then(()=>xt);return{default:n}},void 0).then(({default:n})=>n(...s)):e=fetch,(...s)=>e(...s)},Ni=()=>_i(void 0,void 0,void 0,function*(){return typeof Response>"u"?(yield Ue(()=>Promise.resolve().then(()=>xt),void 0)).Response:Response}),Ps=r=>{if(Array.isArray(r))return r.map(s=>Ps(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]=Ps(n)}),e};var tt=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 fs=r=>r.msg||r.message||r.error_description||r.error||JSON.stringify(r),Si=(r,e,s)=>tt(void 0,void 0,void 0,function*(){const n=yield Ni();r instanceof n&&!(s!=null&&s.noResolveJson)?r.json().then(a=>{e(new ji(fs(a),r.status||500))}).catch(a=>{e(new Ts(fs(a),a))}):e(new Ts(fs(r),r))}),ki=(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 Ot(r,e,s,n,a,i){return tt(this,void 0,void 0,function*(){return new Promise((o,l)=>{r(s,ki(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=>Si(d,l,n))})})}function Wt(r,e,s,n){return tt(this,void 0,void 0,function*(){return Ot(r,"GET",e,s,n)})}function Be(r,e,s,n,a){return tt(this,void 0,void 0,function*(){return Ot(r,"POST",e,n,a,s)})}function Ei(r,e,s,n,a){return tt(this,void 0,void 0,function*(){return Ot(r,"PUT",e,n,a,s)})}function Ci(r,e,s,n){return tt(this,void 0,void 0,function*(){return Ot(r,"HEAD",e,Object.assign(Object.assign({},s),{noResolveJson:!0}),n)})}function dn(r,e,s,n,a){return tt(this,void 0,void 0,function*(){return Ot(r,"DELETE",e,n,a,s)})}var be=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 Ti={limit:100,offset:0,sortBy:{column:"name",order:"asc"}},gr={cacheControl:"3600",contentType:"text/plain;charset=UTF-8",upsert:!1};class Pi{constructor(e,s={},n,a){this.url=e,this.headers=s,this.bucketId=n,this.fetch=cn(a)}uploadOrUpdate(e,s,n,a){return be(this,void 0,void 0,function*(){try{let i;const o=Object.assign(Object.assign({},gr),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 be(this,void 0,void 0,function*(){return this.uploadOrUpdate("POST",e,s,n)})}uploadToSignedUrl(e,s,n,a){return be(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:gr.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 be(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 Be(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 Hs("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 be(this,void 0,void 0,function*(){return this.uploadOrUpdate("PUT",e,s,n)})}move(e,s,n){return be(this,void 0,void 0,function*(){try{return{data:yield Be(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 be(this,void 0,void 0,function*(){try{return{data:{path:(yield Be(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 be(this,void 0,void 0,function*(){try{let a=this._getFinalPath(e),i=yield Be(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 be(this,void 0,void 0,function*(){try{const a=yield Be(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 be(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 Wt(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 be(this,void 0,void 0,function*(){const s=this._getFinalPath(e);try{const n=yield Wt(this.fetch,`${this.url}/object/info/${s}`,{headers:this.headers});return{data:Ps(n),error:null}}catch(n){if(fe(n))return{data:null,error:n};throw n}})}exists(e){return be(this,void 0,void 0,function*(){const s=this._getFinalPath(e);try{return yield Ci(this.fetch,`${this.url}/object/${s}`,{headers:this.headers}),{data:!0,error:null}}catch(n){if(fe(n)&&n instanceof Ts){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 be(this,void 0,void 0,function*(){try{return{data:yield dn(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 be(this,void 0,void 0,function*(){try{const a=Object.assign(Object.assign(Object.assign({},Ti),s),{prefix:e||""});return{data:yield Be(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 Ai="2.7.1",Oi={"X-Client-Info":`storage-js/${Ai}`};var at=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 $i{constructor(e,s={},n){this.url=e,this.headers=Object.assign(Object.assign({},Oi),s),this.fetch=cn(n)}listBuckets(){return at(this,void 0,void 0,function*(){try{return{data:yield Wt(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 at(this,void 0,void 0,function*(){try{return{data:yield Wt(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 at(this,void 0,void 0,function*(){try{return{data:yield Be(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 at(this,void 0,void 0,function*(){try{return{data:yield Ei(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 at(this,void 0,void 0,function*(){try{return{data:yield Be(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 at(this,void 0,void 0,function*(){try{return{data:yield dn(this.fetch,`${this.url}/bucket/${e}`,{},{headers:this.headers}),error:null}}catch(s){if(fe(s))return{data:null,error:s};throw s}})}}class Ii extends $i{constructor(e,s={},n){super(e,s,n)}from(e){return new Pi(this.url,this.headers,e,this.fetch)}}const Ri="2.50.0";let kt="";typeof Deno<"u"?kt="deno":typeof document<"u"?kt="web":typeof navigator<"u"&&navigator.product==="ReactNative"?kt="react-native":kt="node";const Di={"X-Client-Info":`supabase-js-${kt}/${Ri}`},Li={headers:Di},Fi={schema:"public"},Ui={autoRefreshToken:!0,persistSession:!0,detectSessionInUrl:!0,flowType:"implicit"},Mi={};var qi=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 Bi=r=>{let e;return r?e=r:typeof fetch>"u"?e=Jr:e=fetch,(...s)=>e(...s)},Gi=()=>typeof Headers>"u"?Kr:Headers,zi=(r,e,s)=>{const n=Bi(s),a=Gi();return(i,o)=>qi(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 Hi=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 Wi(r){return r.endsWith("/")?r:r+"/"}function Ji(r,e){var s,n;const{db:a,auth:i,realtime:o,global:l}=r,{db:d,auth:c,realtime:u,global:h}=e,f={db:Object.assign(Object.assign({},d),a),auth:Object.assign(Object.assign({},c),i),realtime:Object.assign(Object.assign({},u),o),global:Object.assign(Object.assign(Object.assign({},h),l),{headers:Object.assign(Object.assign({},(s=h==null?void 0:h.headers)!==null&&s!==void 0?s:{}),(n=l==null?void 0:l.headers)!==null&&n!==void 0?n:{})}),accessToken:()=>Hi(this,void 0,void 0,function*(){return""})};return r.accessToken?f.accessToken=r.accessToken:delete f.accessToken,f}const un="2.70.0",ct=30*1e3,As=3,ms=As*ct,Ki="http://localhost:9999",Vi="supabase.auth.token",Yi={"X-Client-Info":`gotrue-js/${un}`},Os="X-Supabase-Api-Version",hn={"2024-01-01":{timestamp:Date.parse("2024-01-01T00:00:00.0Z"),name:"2024-01-01"}},Zi=/^([a-z0-9_-]{4})*($|[a-z0-9_-]{3}$|[a-z0-9_-]{2}$)$/i,Qi=6e5;class Ws extends Error{constructor(e,s,n){super(e),this.__isAuthError=!0,this.name="AuthError",this.status=s,this.code=n}}function U(r){return typeof r=="object"&&r!==null&&"__isAuthError"in r}class Xi extends Ws{constructor(e,s,n){super(e,s,n),this.name="AuthApiError",this.status=s,this.code=n}}function eo(r){return U(r)&&r.name==="AuthApiError"}class fn extends Ws{constructor(e,s){super(e),this.name="AuthUnknownError",this.originalError=s}}class Je extends Ws{constructor(e,s,n,a){super(e,n,a),this.name=s,this.status=n}}class qe extends Je{constructor(){super("Auth session missing!","AuthSessionMissingError",400,void 0)}}function to(r){return U(r)&&r.name==="AuthSessionMissingError"}class Dt extends Je{constructor(){super("Auth session or user missing","AuthInvalidTokenResponseError",500,void 0)}}class Lt extends Je{constructor(e){super(e,"AuthInvalidCredentialsError",400,void 0)}}class Ft extends Je{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}}}function so(r){return U(r)&&r.name==="AuthImplicitGrantRedirectError"}class pr extends Je{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 $s extends Je{constructor(e,s){super(e,"AuthRetryableFetchError",s,void 0)}}function gs(r){return U(r)&&r.name==="AuthRetryableFetchError"}class xr extends Je{constructor(e,s,n){super(e,"AuthWeakPasswordError",s,"weak_password"),this.reasons=n}}class Ct extends Je{constructor(e){super(e,"AuthInvalidJwtError",400,"invalid_jwt")}}const Jt="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_".split(""),yr=` 	
\r=`.split(""),ro=(()=>{const r=new Array(128);for(let e=0;e<r.length;e+=1)r[e]=-1;for(let e=0;e<yr.length;e+=1)r[yr[e].charCodeAt(0)]=-2;for(let e=0;e<Jt.length;e+=1)r[Jt[e].charCodeAt(0)]=e;return r})();function br(r,e,s){if(r!==null)for(e.queue=e.queue<<8|r,e.queuedBits+=8;e.queuedBits>=6;){const n=e.queue>>e.queuedBits-6&63;s(Jt[n]),e.queuedBits-=6}else if(e.queuedBits>0)for(e.queue=e.queue<<6-e.queuedBits,e.queuedBits=6;e.queuedBits>=6;){const n=e.queue>>e.queuedBits-6&63;s(Jt[n]),e.queuedBits-=6}}function mn(r,e,s){const n=ro[r];if(n>-1)for(e.queue=e.queue<<6|n,e.queuedBits+=6;e.queuedBits>=8;)s(e.queue>>e.queuedBits-8&255),e.queuedBits-=8;else{if(n===-2)return;throw new Error(`Invalid Base64-URL character "${String.fromCharCode(r)}"`)}}function wr(r){const e=[],s=o=>{e.push(String.fromCodePoint(o))},n={utf8seq:0,codepoint:0},a={queue:0,queuedBits:0},i=o=>{io(o,n,s)};for(let o=0;o<r.length;o+=1)mn(r.charCodeAt(o),a,i);return e.join("")}function no(r,e){if(r<=127){e(r);return}else if(r<=2047){e(192|r>>6),e(128|r&63);return}else if(r<=65535){e(224|r>>12),e(128|r>>6&63),e(128|r&63);return}else if(r<=1114111){e(240|r>>18),e(128|r>>12&63),e(128|r>>6&63),e(128|r&63);return}throw new Error(`Unrecognized Unicode codepoint: ${r.toString(16)}`)}function ao(r,e){for(let s=0;s<r.length;s+=1){let n=r.charCodeAt(s);if(n>55295&&n<=56319){const a=(n-55296)*1024&65535;n=(r.charCodeAt(s+1)-56320&65535|a)+65536,s+=1}no(n,e)}}function io(r,e,s){if(e.utf8seq===0){if(r<=127){s(r);return}for(let n=1;n<6;n+=1)if(!(r>>7-n&1)){e.utf8seq=n;break}if(e.utf8seq===2)e.codepoint=r&31;else if(e.utf8seq===3)e.codepoint=r&15;else if(e.utf8seq===4)e.codepoint=r&7;else throw new Error("Invalid UTF-8 sequence");e.utf8seq-=1}else if(e.utf8seq>0){if(r<=127)throw new Error("Invalid UTF-8 sequence");e.codepoint=e.codepoint<<6|r&63,e.utf8seq-=1,e.utf8seq===0&&s(e.codepoint)}}function oo(r){const e=[],s={queue:0,queuedBits:0},n=a=>{e.push(a)};for(let a=0;a<r.length;a+=1)mn(r.charCodeAt(a),s,n);return new Uint8Array(e)}function lo(r){const e=[];return ao(r,s=>e.push(s)),new Uint8Array(e)}function co(r){const e=[],s={queue:0,queuedBits:0},n=a=>{e.push(a)};return r.forEach(a=>br(a,s,n)),br(null,s,n),e.join("")}function uo(r){return Math.round(Date.now()/1e3)+r}function ho(){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 window<"u"&&typeof document<"u",Ve={tested:!1,writable:!1},Tt=()=>{if(!Se())return!1;try{if(typeof globalThis.localStorage!="object")return!1}catch{return!1}if(Ve.tested)return Ve.writable;const r=`lswt-${Math.random()}${Math.random()}`;try{globalThis.localStorage.setItem(r,r),globalThis.localStorage.removeItem(r),Ve.tested=!0,Ve.writable=!0}catch{Ve.tested=!0,Ve.writable=!1}return Ve.writable};function fo(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 gn=r=>{let e;return r?e=r:typeof fetch>"u"?e=(...s)=>Ue(async()=>{const{default:n}=await Promise.resolve().then(()=>xt);return{default:n}},void 0).then(({default:n})=>n(...s)):e=fetch,(...s)=>e(...s)},mo=r=>typeof r=="object"&&r!==null&&"status"in r&&"ok"in r&&"json"in r&&typeof r.json=="function",pn=async(r,e,s)=>{await r.setItem(e,JSON.stringify(s))},Ut=async(r,e)=>{const s=await r.getItem(e);if(!s)return null;try{return JSON.parse(s)}catch{return s}},Mt=async(r,e)=>{await r.removeItem(e)};class ns{constructor(){this.promise=new ns.promiseConstructor((e,s)=>{this.resolve=e,this.reject=s})}}ns.promiseConstructor=Promise;function ps(r){const e=r.split(".");if(e.length!==3)throw new Ct("Invalid JWT structure");for(let n=0;n<e.length;n++)if(!Zi.test(e[n]))throw new Ct("JWT not in base64url format");return{header:JSON.parse(wr(e[0])),payload:JSON.parse(wr(e[1])),signature:oo(e[2]),raw:{header:e[0],payload:e[1]}}}async function go(r){return await new Promise(e=>{setTimeout(()=>e(null),r)})}function po(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 xo(r){return("0"+r.toString(16)).substr(-2)}function yo(){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,xo).join("")}async function bo(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("")}async function wo(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 bo(r);return btoa(s).replace(/\+/g,"-").replace(/\//g,"_").replace(/=+$/,"")}async function it(r,e,s=!1){const n=yo();let a=n;s&&(a+="/PASSWORD_RECOVERY"),await pn(r,`${e}-code-verifier`,a);const i=await wo(n);return[i,n===i?"plain":"s256"]}const vo=/^2[0-9]{3}-(0[1-9]|1[0-2])-(0[1-9]|1[0-9]|2[0-9]|3[0-1])$/i;function jo(r){const e=r.headers.get(Os);if(!e||!e.match(vo))return null;try{return new Date(`${e}T00:00:00.0Z`)}catch{return null}}function _o(r){if(!r)throw new Error("Missing exp claim");const e=Math.floor(Date.now()/1e3);if(r<=e)throw new Error("JWT has expired")}function No(r){switch(r){case"RS256":return{name:"RSASSA-PKCS1-v1_5",hash:{name:"SHA-256"}};case"ES256":return{name:"ECDSA",namedCurve:"P-256",hash:{name:"SHA-256"}};default:throw new Error("Invalid alg claim")}}const So=/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/;function ot(r){if(!So.test(r))throw new Error("@supabase/auth-js: Expected parameter to be UUID but is not")}var ko=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 Ye=r=>r.msg||r.message||r.error_description||r.error||JSON.stringify(r),Eo=[502,503,504];async function vr(r){var e;if(!mo(r))throw new $s(Ye(r),0);if(Eo.includes(r.status))throw new $s(Ye(r),r.status);let s;try{s=await r.json()}catch(i){throw new fn(Ye(i),i)}let n;const a=jo(r);if(a&&a.getTime()>=hn["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 xr(Ye(s),r.status,((e=s.weak_password)===null||e===void 0?void 0:e.reasons)||[]);if(n==="session_not_found")throw new qe}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 xr(Ye(s),r.status,s.weak_password.reasons);throw new Xi(Ye(s),r.status||500,n)}const Co=(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 z(r,e,s,n){var a;const i=Object.assign({},n==null?void 0:n.headers);i[Os]||(i[Os]=hn["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 To(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 To(r,e,s,n,a,i){const o=Co(e,n,a,i);let l;try{l=await r(s,Object.assign({},o))}catch(d){throw console.error(d),new $s(Ye(d),0)}if(l.ok||await vr(l),n!=null&&n.noResolveJson)return l;try{return await l.json()}catch(d){await vr(d)}}function Le(r){var e;let s=null;$o(r)&&(s=Object.assign({},r),r.expires_at||(s.expires_at=uo(r.expires_in)));const n=(e=r.user)!==null&&e!==void 0?e:r;return{data:{session:s,user:n},error:null}}function jr(r){const e=Le(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 Po(r){return{data:r,error:null}}function Ao(r){const{action_link:e,email_otp:s,hashed_token:n,redirect_to:a,verification_type:i}=r,o=ko(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 Oo(r){return r}function $o(r){return r.access_token&&r.refresh_token&&r.expires_in}const xs=["global","local","others"];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};class Ro{constructor({url:e="",headers:s={},fetch:n}){this.url=e,this.headers=s,this.fetch=gn(n),this.mfa={listFactors:this._listFactors.bind(this),deleteFactor:this._deleteFactor.bind(this)}}async signOut(e,s=xs[0]){if(xs.indexOf(s)<0)throw new Error(`@supabase/auth-js: Parameter scope must be one of ${xs.join(", ")}`);try{return await z(this.fetch,"POST",`${this.url}/logout?scope=${s}`,{headers:this.headers,jwt:e,noResolveJson:!0}),{data:null,error:null}}catch(n){if(U(n))return{data:null,error:n};throw n}}async inviteUserByEmail(e,s={}){try{return await z(this.fetch,"POST",`${this.url}/invite`,{body:{email:e,data:s.data},headers:this.headers,redirectTo:s.redirectTo,xform:Ge})}catch(n){if(U(n))return{data:{user:null},error:n};throw n}}async generateLink(e){try{const{options:s}=e,n=Io(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 z(this.fetch,"POST",`${this.url}/admin/generate_link`,{body:a,headers:this.headers,xform:Ao,redirectTo:s==null?void 0:s.redirectTo})}catch(s){if(U(s))return{data:{properties:null,user:null},error:s};throw s}}async createUser(e){try{return await z(this.fetch,"POST",`${this.url}/admin/users`,{body:e,headers:this.headers,xform:Ge})}catch(s){if(U(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 z(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:Oo});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 _=parseInt(b.split(";")[0].split("=")[1].substring(0,1)),x=JSON.parse(b.split(";")[1].split("=")[1]);c[`${x}Page`]=_}),c.total=parseInt(f)),{data:Object.assign(Object.assign({},h),c),error:null}}catch(c){if(U(c))return{data:{users:[]},error:c};throw c}}async getUserById(e){ot(e);try{return await z(this.fetch,"GET",`${this.url}/admin/users/${e}`,{headers:this.headers,xform:Ge})}catch(s){if(U(s))return{data:{user:null},error:s};throw s}}async updateUserById(e,s){ot(e);try{return await z(this.fetch,"PUT",`${this.url}/admin/users/${e}`,{body:s,headers:this.headers,xform:Ge})}catch(n){if(U(n))return{data:{user:null},error:n};throw n}}async deleteUser(e,s=!1){ot(e);try{return await z(this.fetch,"DELETE",`${this.url}/admin/users/${e}`,{headers:this.headers,body:{should_soft_delete:s},xform:Ge})}catch(n){if(U(n))return{data:{user:null},error:n};throw n}}async _listFactors(e){ot(e.userId);try{const{data:s,error:n}=await z(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(U(s))return{data:null,error:s};throw s}}async _deleteFactor(e){ot(e.userId),ot(e.id);try{return{data:await z(this.fetch,"DELETE",`${this.url}/admin/users/${e.userId}/factors/${e.id}`,{headers:this.headers}),error:null}}catch(s){if(U(s))return{data:null,error:s};throw s}}}const Do={getItem:r=>Tt()?globalThis.localStorage.getItem(r):null,setItem:(r,e)=>{Tt()&&globalThis.localStorage.setItem(r,e)},removeItem:r=>{Tt()&&globalThis.localStorage.removeItem(r)}};function _r(r={}){return{getItem:e=>r[e]||null,setItem:(e,s)=>{r[e]=s},removeItem:e=>{delete r[e]}}}function Lo(){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 lt={debug:!!(globalThis&&Tt()&&globalThis.localStorage&&globalThis.localStorage.getItem("supabase.gotrue-js.locks.debug")==="true")};class xn extends Error{constructor(e){super(e),this.isAcquireTimeout=!0}}class Fo extends xn{}async function Uo(r,e,s){lt.debug&&console.log("@supabase/gotrue-js: navigatorLock: acquire lock",r,e);const n=new globalThis.AbortController;return e>0&&setTimeout(()=>{n.abort(),lt.debug&&console.log("@supabase/gotrue-js: navigatorLock acquire timed out",r)},e),await Promise.resolve().then(()=>globalThis.navigator.locks.request(r,e===0?{mode:"exclusive",ifAvailable:!0}:{mode:"exclusive",signal:n.signal},async a=>{if(a){lt.debug&&console.log("@supabase/gotrue-js: navigatorLock: acquired",r,a.name);try{return await s()}finally{lt.debug&&console.log("@supabase/gotrue-js: navigatorLock: released",r,a.name)}}else{if(e===0)throw lt.debug&&console.log("@supabase/gotrue-js: navigatorLock: not immediately available",r),new Fo(`Acquiring an exclusive Navigator LockManager lock "${r}" immediately failed`);if(lt.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()}}))}Lo();const Mo={url:Ki,storageKey:Vi,autoRefreshToken:!0,persistSession:!0,detectSessionInUrl:!0,headers:Yi,flowType:"implicit",debug:!1,hasCustomAuthorizationHeader:!1};async function Nr(r,e,s){return await s()}class Pt{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=Pt.nextInstanceID,Pt.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({},Mo),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 Ro({url:a.url,headers:a.headers,fetch:a.fetch}),this.url=a.url,this.headers=a.headers,this.fetch=gn(a.fetch),this.lock=a.lock||Nr,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=Uo:this.lock=Nr,this.jwks={keys:[]},this.jwks_cached_at=Number.MIN_SAFE_INTEGER,this.mfa={verify:this._verify.bind(this),enroll:this._enroll.bind(this),unenroll:this._unenroll.bind(this),challenge:this._challenge.bind(this),listFactors:this._listFactors.bind(this),challengeAndVerify:this._challengeAndVerify.bind(this),getAuthenticatorAssuranceLevel:this._getAuthenticatorAssuranceLevel.bind(this)},this.persistSession?a.storage?this.storage=a.storage:Tt()?this.storage=Do:(this.memoryStorage={},this.storage=_r(this.memoryStorage)):(this.memoryStorage={},this.storage=_r(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} (${un}) ${new Date().toISOString()}`,...e),this}async initialize(){return this.initializePromise?await this.initializePromise:(this.initializePromise=(async()=>await this._acquireLock(-1,async()=>await this._initialize()))(),await this.initializePromise)}async _initialize(){var e;try{const s=fo(window.location.href);let n="none";if(this._isImplicitGrantCallback(s)?n="implicit":await this._isPKCECallback(s)&&(n="pkce"),Se()&&this.detectSessionInUrl&&n!=="none"){const{data:a,error:i}=await this._getSessionFromURL(s,n);if(i){if(this._debug("#_initialize()","error detecting session from URL",i),so(i)){const d=(e=i.details)===null||e===void 0?void 0:e.code;if(d==="identity_already_exists"||d==="identity_not_found"||d==="single_identity_not_deletable")return{error:i}}return await this._removeSession(),{error:i}}const{session:o,redirectType:l}=a;return this._debug("#_initialize()","detected session in URL",o,"redirect type",l),await this._saveSession(o),setTimeout(async()=>{l==="recovery"?await this._notifyAllSubscribers("PASSWORD_RECOVERY",o):await this._notifyAllSubscribers("SIGNED_IN",o)},0),{error:null}}return await this._recoverAndRefresh(),{error:null}}catch(s){return U(s)?{error:s}:{error:new fn("Unexpected error during initialization",s)}}finally{await this._handleVisibilityChange(),this._debug("#_initialize()","end")}}async signInAnonymously(e){var s,n,a;try{const i=await z(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:Le}),{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(U(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 it(this.storage,this.storageKey)),i=await z(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:Le})}else if("phone"in e){const{phone:u,password:h,options:f}=e;i=await z(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:Le})}else throw new Lt("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(U(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 z(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:jr})}else if("phone"in e){const{phone:i,password:o,options:l}=e;s=await z(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:jr})}else throw new Lt("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 Dt}:(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(U(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 signInWithWeb3(e){const{chain:s}=e;if(s==="solana")return await this.signInWithSolana(e);throw new Error(`@supabase/auth-js: Unsupported chain "${s}"`)}async signInWithSolana(e){var s,n,a,i,o,l,d,c,u,h,f,p;let b,_;if("message"in e)b=e.message,_=e.signature;else{const{chain:x,wallet:w,statement:E,options:k}=e;let A;if(Se())if(typeof w=="object")A=w;else{const S=window;if("solana"in S&&typeof S.solana=="object"&&("signIn"in S.solana&&typeof S.solana.signIn=="function"||"signMessage"in S.solana&&typeof S.solana.signMessage=="function"))A=S.solana;else throw new Error("@supabase/auth-js: No compatible Solana wallet interface on the window object (window.solana) detected. Make sure the user already has a wallet installed and connected for this app. Prefer passing the wallet interface object directly to signInWithWeb3({ chain: 'solana', wallet: resolvedUserWallet }) instead.")}else{if(typeof w!="object"||!(k!=null&&k.url))throw new Error("@supabase/auth-js: Both wallet and url must be specified in non-browser environments.");A=w}const N=new URL((s=k==null?void 0:k.url)!==null&&s!==void 0?s:window.location.href);if("signIn"in A&&A.signIn){const S=await A.signIn(Object.assign(Object.assign(Object.assign({issuedAt:new Date().toISOString()},k==null?void 0:k.signInWithSolana),{version:"1",domain:N.host,uri:N.href}),E?{statement:E}:null));let j;if(Array.isArray(S)&&S[0]&&typeof S[0]=="object")j=S[0];else if(S&&typeof S=="object"&&"signedMessage"in S&&"signature"in S)j=S;else throw new Error("@supabase/auth-js: Wallet method signIn() returned unrecognized value");if("signedMessage"in j&&"signature"in j&&(typeof j.signedMessage=="string"||j.signedMessage instanceof Uint8Array)&&j.signature instanceof Uint8Array)b=typeof j.signedMessage=="string"?j.signedMessage:new TextDecoder().decode(j.signedMessage),_=j.signature;else throw new Error("@supabase/auth-js: Wallet method signIn() API returned object without signedMessage and signature fields")}else{if(!("signMessage"in A)||typeof A.signMessage!="function"||!("publicKey"in A)||typeof A!="object"||!A.publicKey||!("toBase58"in A.publicKey)||typeof A.publicKey.toBase58!="function")throw new Error("@supabase/auth-js: Wallet does not have a compatible signMessage() and publicKey.toBase58() API");b=[`${N.host} wants you to sign in with your Solana account:`,A.publicKey.toBase58(),...E?["",E,""]:[""],"Version: 1",`URI: ${N.href}`,`Issued At: ${(a=(n=k==null?void 0:k.signInWithSolana)===null||n===void 0?void 0:n.issuedAt)!==null&&a!==void 0?a:new Date().toISOString()}`,...!((i=k==null?void 0:k.signInWithSolana)===null||i===void 0)&&i.notBefore?[`Not Before: ${k.signInWithSolana.notBefore}`]:[],...!((o=k==null?void 0:k.signInWithSolana)===null||o===void 0)&&o.expirationTime?[`Expiration Time: ${k.signInWithSolana.expirationTime}`]:[],...!((l=k==null?void 0:k.signInWithSolana)===null||l===void 0)&&l.chainId?[`Chain ID: ${k.signInWithSolana.chainId}`]:[],...!((d=k==null?void 0:k.signInWithSolana)===null||d===void 0)&&d.nonce?[`Nonce: ${k.signInWithSolana.nonce}`]:[],...!((c=k==null?void 0:k.signInWithSolana)===null||c===void 0)&&c.requestId?[`Request ID: ${k.signInWithSolana.requestId}`]:[],...!((h=(u=k==null?void 0:k.signInWithSolana)===null||u===void 0?void 0:u.resources)===null||h===void 0)&&h.length?["Resources",...k.signInWithSolana.resources.map(j=>`- ${j}`)]:[]].join(`
`);const S=await A.signMessage(new TextEncoder().encode(b),"utf8");if(!S||!(S instanceof Uint8Array))throw new Error("@supabase/auth-js: Wallet signMessage() API returned an recognized value");_=S}}try{const{data:x,error:w}=await z(this.fetch,"POST",`${this.url}/token?grant_type=web3`,{headers:this.headers,body:Object.assign({chain:"solana",message:b,signature:co(_)},!((f=e.options)===null||f===void 0)&&f.captchaToken?{gotrue_meta_security:{captcha_token:(p=e.options)===null||p===void 0?void 0:p.captchaToken}}:null),xform:Le});if(w)throw w;return!x||!x.session||!x.user?{data:{user:null,session:null},error:new Dt}:(x.session&&(await this._saveSession(x.session),await this._notifyAllSubscribers("SIGNED_IN",x.session)),{data:Object.assign({},x),error:w})}catch(x){if(U(x))return{data:{user:null,session:null},error:x};throw x}}async _exchangeCodeForSession(e){const s=await Ut(this.storage,`${this.storageKey}-code-verifier`),[n,a]=(s??"").split("/");try{const{data:i,error:o}=await z(this.fetch,"POST",`${this.url}/token?grant_type=pkce`,{headers:this.headers,body:{auth_code:e,code_verifier:n},xform:Le});if(await Mt(this.storage,`${this.storageKey}-code-verifier`),o)throw o;return!i||!i.session||!i.user?{data:{user:null,session:null,redirectType:null},error:new Dt}:(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(U(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 z(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:Le}),{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 Dt}:(d.session&&(await this._saveSession(d.session),await this._notifyAllSubscribers("SIGNED_IN",d.session)),{data:d,error:c})}catch(s){if(U(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 it(this.storage,this.storageKey));const{error:h}=await z(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 z(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 Lt("You must provide either an email or phone number.")}catch(l){if(U(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 z(this.fetch,"POST",`${this.url}/verify`,{headers:this.headers,body:Object.assign(Object.assign({},e),{gotrue_meta_security:{captcha_token:i}}),redirectTo:a,xform:Le});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(U(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 it(this.storage,this.storageKey)),await z(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:Po})}catch(i){if(U(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 qe;const{error:a}=await z(this.fetch,"GET",`${this.url}/reauthenticate`,{headers:this.headers,jwt:s.access_token});return{data:{user:null,session:null},error:a}})}catch(e){if(U(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 z(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 z(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 Lt("You must provide either an email or phone number and a type")}catch(s){if(U(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 Ut(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*1e3-Date.now()<ms:!1;if(this._debug("#__loadSession()",`session has${n?"":" not"} expired`,"expires_at",e.expires_at),!n){if(this.storage.isServer){let o=this.suppressGetSessionWarning;e=new Proxy(e,{get:(d,c,u)=>(!o&&c==="user"&&(console.warn("Using the user object as returned from supabase.auth.getSession() or from some supabase.auth.onAuthStateChange() events could be insecure! This value comes directly from the storage medium (usually cookies on the server) and may not be authentic. Use supabase.auth.getUser() instead which authenticates the data by contacting the Supabase Auth server."),o=!0,this.suppressGetSessionWarning=!0),Reflect.get(d,c,u))})}return{data:{session:e},error:null}}const{session:a,error:i}=await this._callRefreshToken(e.refresh_token);return i?{data:{session:null},error:i}:{data:{session:a},error:null}}finally{this._debug("#__loadSession()","end")}}async getUser(e){return e?await this._getUser(e):(await this.initializePromise,await this._acquireLock(-1,async()=>await this._getUser()))}async _getUser(e){try{return e?await z(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 qe}:await z(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(U(s))return to(s)&&(await this._removeSession(),await Mt(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 qe;const o=a.session;let l=null,d=null;this.flowType==="pkce"&&e.email!=null&&([l,d]=await it(this.storage,this.storageKey));const{data:c,error:u}=await z(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(U(n))return{data:{user:null},error:n};throw n}}async setSession(e){return await this.initializePromise,await this._acquireLock(-1,async()=>await this._setSession(e))}async _setSession(e){try{if(!e.access_token||!e.refresh_token)throw new qe;const s=Date.now()/1e3;let n=s,a=!0,i=null;const{payload:o}=ps(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(U(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 qe;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(U(s))return{data:{user:null,session:null},error:s};throw s}}async _getSessionFromURL(e,s){try{if(!Se())throw new Ft("No browser detected.");if(e.error||e.error_description||e.error_code)throw new Ft(e.error_description||"Error in URL with unspecified error_description",{error:e.error||"unspecified_error",code:e.error_code||"unspecified_code"});switch(s){case"implicit":if(this.flowType==="pkce")throw new pr("Not a valid PKCE flow url.");break;case"pkce":if(this.flowType==="implicit")throw new Ft("Not a valid implicit grant flow url.");break;default:}if(s==="pkce"){if(this._debug("#_initialize()","begin","is PKCE flow",!0),!e.code)throw new pr("No code detected.");const{data:E,error:k}=await this._exchangeCodeForSession(e.code);if(k)throw k;const A=new URL(window.location.href);return A.searchParams.delete("code"),window.history.replaceState(window.history.state,"",A.toString()),{data:{session:E.session,redirectType:null},error:null}}const{provider_token:n,provider_refresh_token:a,access_token:i,refresh_token:o,expires_in:l,expires_at:d,token_type:c}=e;if(!i||!l||!o||!c)throw new Ft("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<=ct&&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:_,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:_.user};return window.location.hash="",this._debug("#_getSessionFromURL()","clearing window.location.hash"),{data:{session:w,redirectType:e.type},error:null}}catch(n){if(U(n))return{data:{session:null,redirectType:null},error:n};throw n}}_isImplicitGrantCallback(e){return!!(e.access_token||e.error_description)}async _isPKCECallback(e){const s=await Ut(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&&!(eo(l)&&(l.status===404||l.status===401||l.status===403)))return{error:l}}return e!=="others"&&(await this._removeSession(),await Mt(this.storage,`${this.storageKey}-code-verifier`)),{error:null}})}onAuthStateChange(e){const s=ho(),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 it(this.storage,this.storageKey,!0));try{return await z(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(U(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(U(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 z(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(U(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 z(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(U(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 po(async a=>(a>0&&await go(200*Math.pow(2,a-1)),this._debug(s,"refreshing attempt",a),await z(this.fetch,"POST",`${this.url}/token?grant_type=refresh_token`,{body:{refresh_token:e},headers:this.headers,xform:Le})),(a,i)=>{const o=200*Math.pow(2,a);return i&&gs(i)&&Date.now()+o-n<ct})}catch(n){if(this._debug(s,"error",n),U(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 Ut(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=((e=n.expires_at)!==null&&e!==void 0?e:1/0)*1e3-Date.now()<ms;if(this._debug(s,`session has${a?"":" not"} expired with margin of ${ms}s`),a){if(this.autoRefreshToken&&n.refresh_token){const{error:i}=await this._callRefreshToken(n.refresh_token);i&&(console.error(i),gs(i)||(this._debug(s,"refresh failed with a non-retryable error, removing the session",i),await this._removeSession()))}}else await this._notifyAllSubscribers("SIGNED_IN",n)}catch(n){this._debug(s,"error",n),console.error(n);return}finally{this._debug(s,"end")}}async _callRefreshToken(e){var s,n;if(!e)throw new qe;if(this.refreshingDeferred)return this.refreshingDeferred.promise;const a=`#_callRefreshToken(${e.substring(0,5)}...)`;this._debug(a,"begin");try{this.refreshingDeferred=new ns;const{data:i,error:o}=await this._refreshAccessToken(e);if(o)throw o;if(!i.session)throw new qe;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),U(i)){const o={session:null,error:i};return gs(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 pn(this.storage,this.storageKey,e)}async _removeSession(){this._debug("#_removeSession()"),await Mt(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(),ct);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)/ct);this._debug("#_autoRefreshTokenTick()",`access token expires in ${a} ticks, a tick lasts ${ct}ms, refresh threshold is ${As} ticks`),a<=As&&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 xn)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 it(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 z(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(U(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 z(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(U(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 z(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(U(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 z(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(U(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{payload:o}=ps(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}}))}async fetchJwk(e,s={keys:[]}){let n=s.keys.find(o=>o.kid===e);if(n||(n=this.jwks.keys.find(o=>o.kid===e),n&&this.jwks_cached_at+Qi>Date.now()))return n;const{data:a,error:i}=await z(this.fetch,"GET",`${this.url}/.well-known/jwks.json`,{headers:this.headers});if(i)throw i;if(!a.keys||a.keys.length===0)throw new Ct("JWKS is empty");if(this.jwks=a,this.jwks_cached_at=Date.now(),n=a.keys.find(o=>o.kid===e),!n)throw new Ct("No matching signing key found in JWKS");return n}async getClaims(e,s={keys:[]}){try{let n=e;if(!n){const{data:p,error:b}=await this.getSession();if(b||!p.session)return{data:null,error:b};n=p.session.access_token}const{header:a,payload:i,signature:o,raw:{header:l,payload:d}}=ps(n);if(_o(i.exp),!a.kid||a.alg==="HS256"||!("crypto"in globalThis&&"subtle"in globalThis.crypto)){const{error:p}=await this.getUser(n);if(p)throw p;return{data:{claims:i,header:a,signature:o},error:null}}const c=No(a.alg),u=await this.fetchJwk(a.kid,s),h=await crypto.subtle.importKey("jwk",u,c,!0,["verify"]);if(!await crypto.subtle.verify(c,h,o,lo(`${l}.${d}`)))throw new Ct("Invalid JWT signature");return{data:{claims:i,header:a,signature:o},error:null}}catch(n){if(U(n))return{data:null,error:n};throw n}}}Pt.nextInstanceID=0;const qo=Pt;class Bo extends qo{constructor(e){super(e)}}var Go=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 zo{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=Wi(e),d=new URL(l);this.realtimeUrl=new URL("realtime/v1",d),this.realtimeUrl.protocol=this.realtimeUrl.protocol.replace("http","ws"),this.authUrl=new URL("auth/v1",d),this.storageUrl=new URL("storage/v1",d),this.functionsUrl=new URL("functions/v1",d);const c=`sb-${d.hostname.split(".")[0]}-auth-token`,u={db:Fi,realtime:Mi,auth:Object.assign(Object.assign({},Ui),{storageKey:c}),global:Li},h=Ji(n??{},u);this.storageKey=(a=h.auth.storageKey)!==null&&a!==void 0?a:"",this.headers=(i=h.global.headers)!==null&&i!==void 0?i:{},h.accessToken?(this.accessToken=h.accessToken,this.auth=new Proxy({},{get:(f,p)=>{throw new Error(`@supabase/supabase-js: Supabase Client is configured with the accessToken option, accessing supabase.auth.${String(p)} is not possible`)}})):this.auth=this._initSupabaseAuthClient((o=h.auth)!==null&&o!==void 0?o:{},this.headers,h.global.fetch),this.fetch=zi(s,this._getAccessToken.bind(this),h.global.fetch),this.realtime=this._initRealtimeClient(Object.assign({headers:this.headers,accessToken:this._getAccessToken.bind(this)},h.realtime)),this.rest=new oi(new URL("rest/v1",d).href,{headers:this.headers,schema:h.db.schema,fetch:this.fetch}),h.accessToken||this._listenForAuthEvents()}get functions(){return new La(this.functionsUrl.href,{headers:this.headers,customFetch:this.fetch})}get storage(){return new Ii(this.storageUrl.href,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 Go(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){const h={Authorization:`Bearer ${this.supabaseKey}`,apikey:`${this.supabaseKey}`};return new Bo({url:this.authUrl.href,headers:Object.assign(Object.assign({},h),c),storageKey:i,autoRefreshToken:e,persistSession:s,detectSessionInUrl:n,storage:a,flowType:o,lock:l,debug:d,fetch:u,hasCustomAuthorizationHeader:"Authorization"in this.headers})}_initRealtimeClient(e){return new wi(this.realtimeUrl.href,Object.assign(Object.assign({},e),{params:Object.assign({apikey:this.supabaseKey},e==null?void 0:e.params)}))}_listenForAuthEvents(){return this.auth.onAuthStateChange((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.changedAccessToken=n:e==="SIGNED_OUT"&&(this.realtime.setAuth(),s=="STORAGE"&&this.auth.signOut(),this.changedAccessToken=void 0)}}const Ho=(r,e,s)=>new zo(r,e,s),Wo="https://ftwlzdhkzqfuosdorgjt.supabase.co",Jo="eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJpc3MiOiJzdXBhYmFzZSIsInJlZiI6ImZ0d2x6ZGhrenFmdW9zZG9yZ2p0Iiwicm9sZSI6ImFub24iLCJpYXQiOjE3MzE1Mjc0MzksImV4cCI6MjA0NzEwMzQzOX0.msaWtaLGNMDiyuxIOFDwULWee0nqcM7p_LAYWB14j1k",D=Ho(Wo,Jo,{auth:{persistSession:!0,autoRefreshToken:!0,detectSessionInUrl:!0}}),yn=y.createContext({user:null,isAdmin:!1,loading:!0,signIn:async()=>{},signOut:async()=>{}}),ys="ben@phippsmusic.com";function Ko({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===ys)),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===ys)):(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!==ys)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(yn.Provider,{value:{user:e,isAdmin:n,loading:i,signIn:l,signOut:d},children:r})}function Js(){return y.useContext(yn)}/**
 * @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 Vo={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 Yo=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,...Vo,width:a,height:a,stroke:n,strokeWidth:o?Number(i)*24/Number(a):i,className:["lucide",`lucide-${Yo(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 Zo=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 He=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 bn=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 Is=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 Qe=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 wn=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 Qo=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 Sr=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 Xo=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 el=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 tl=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 sl=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 rl=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 vn=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 nl=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 al=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 Rs=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 jn=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 il=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 ol=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 ll=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 _n=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 cl=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 Nn=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 xe=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 as=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 dl=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 Ks=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 mt=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 ul=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 is=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 Sn=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 hl=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 fl=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 kn=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 En=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 Vs=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 Kt=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 os=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 $t=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 kr=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 ml=L("Zap",[["polygon",{points:"13 2 3 14 12 14 11 22 21 10 12 10 13 2",key:"45s27k"}]]);class Cn 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(Zo,{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(mt,{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 gl(r){return r>=1e6?(r/1e6).toFixed(1)+"M":r>=1e3?(r/1e3).toFixed(1)+"K":r.toString()}function Er(){const r=new Date;return`${r.getFullYear()}-${r.getMonth()+1}-${r.getDate()}`}function qt(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 pl({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(jn,{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(xe,{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=et(),[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(as,{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(cl,{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(pl,{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(as,{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 Ke({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(Ta,{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 Vt="last_submission_data",xl=30*24*60*60*1e3;function Tn(r){try{const e={artistName:r.artistName,email:r.email,lastTrack:r.track,lastUpdated:Date.now()};localStorage.setItem(Vt,JSON.stringify(e))}catch(e){console.error("Failed to save submission data:",e)}}function gt(){try{const r=localStorage.getItem(Vt);if(!r)return null;const e=JSON.parse(r);return Date.now()-e.lastUpdated>xl?(localStorage.removeItem(Vt),null):{artistName:e.artistName,email:e.email,lastTrack:e.lastTrack}}catch(r){return console.error("Failed to retrieve submission data:",r),null}}function Pn(){try{localStorage.removeItem(Vt),localStorage.removeItem("trackSubmissions"),localStorage.removeItem("playlist_submissions"),localStorage.removeItem("spotify_token"),sessionStorage.clear()}catch(r){console.error("Failed to reset storage data:",r)}}const yl=y.lazy(()=>Ue(()=>import("./FeaturedPlaylists-DrQp35r3.js"),__vite__mapDeps([0,1,2])).then(r=>({default:r.FeaturedPlaylists}))),bl=y.lazy(()=>Ue(()=>Promise.resolve().then(()=>Wl),void 0).then(r=>({default:r.SubmissionModal}))),wl=()=>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."})]})]})]})})}),vl=()=>{var e,s;const r=gt();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:()=>{Pn(),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(yl,{})})})]})})},jl=()=>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 _l(){const[r,e]=y.useState(null);return t.jsxs(t.Fragment,{children:[t.jsx(Ke,{}),t.jsxs("main",{children:[t.jsx(wl,{}),t.jsxs("div",{className:"container mx-auto px-4 pb-12",children:[t.jsx(y.Suspense,{fallback:null,children:t.jsx(vl,{})}),t.jsx(jl,{}),t.jsxs(y.Suspense,{fallback:null,children:[t.jsx(Nl,{}),t.jsx(Sl,{})]})]}),r&&t.jsx(y.Suspense,{fallback:null,children:t.jsx(bl,{playlist:r,onClose:()=>e(null),onSubmit:()=>e(null)})})]})]})}const Nl=y.lazy(()=>Ue(()=>import("./FAQSection-DYdRED9D.js"),__vite__mapDeps([3,1,2]))),Sl=y.lazy(()=>Ue(()=>import("./AdditionalInfoSection-DphltVm4.js"),__vite__mapDeps([4,1,2])));function kl(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:_}=await D.from("playlist_details").select("*").eq("genre",p.genre).neq("id",p.id).order("followers",{ascending:!1}).limit(4);!_&&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 Ds="playlist_submissions";function El(r,e){try{const s=JSON.parse(localStorage.getItem(Ds)||"[]"),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(Ds,JSON.stringify(s))}catch(s){console.error("Failed to track submission:",s)}}function An(r,e){try{const n=JSON.parse(localStorage.getItem(Ds)||"[]").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 Ls="scrollPositions",Cl=5*60*1e3,Tl=10,Pl=100;function Cr(){try{return JSON.parse(sessionStorage.getItem(Ls)||"[]")}catch{return[]}}const On={savePosition(r,e){try{const s=Cr(),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(Ls,JSON.stringify(a))}}catch(s){console.error("Failed to save scroll position:",s)}},restorePosition(r,e){try{const s=Cr(),n=s.find(a=>a.pathname===r);if(n){const a=s.filter(l=>l!==n);sessionStorage.setItem(Ls,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>=Tl){window.scrollTo({top:d,behavior:"instant"});return}i++,setTimeout(o,Pl)};setTimeout(o,50)}}catch(s){console.error("Failed to restore scroll position:",s)}}};function Ys({playlist:r,onSubmit:e,isRelated:s,priority:n=!1,hideSubmit:a=!1}){const i=We(),o=et(),[l]=Lr(),[d,c]=y.useState(!1),u=gt(),h=(u==null?void 0:u.lastTrack)&&An(r.id,u.lastTrack.external_urls.spotify),f=p=>{p.preventDefault(),s||On.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(vn,{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(En,{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(xe,{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($t,{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(os,{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(wn,{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(Sn,{className:"w-3.5 h-3.5"}),"Submit"]})})]})}const Yt=10,bs=24*60*60*1e3;function zt(r){return $l(r,"track")||r}function Al(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=zt(r),i=s.filter(d=>n-d.timestamp<bs);i.length<s.length&&localStorage.setItem("trackSubmissions",JSON.stringify(i));const o=i.find(d=>zt(d.spotifyUrl)===a&&d.playlistId===e);if(o)return{allowed:!1,remainingSubmissions:0,timeUntilReset:Math.max(0,bs-(n-o.timestamp)),totalSubmissions:i.length,alreadySubmittedToPlaylist:!0};const l=i.filter(d=>zt(d.spotifyUrl)===a);if(l.length>=Yt){const d=l.reduce((u,h)=>h.timestamp<u.timestamp?h:u);return{allowed:!1,remainingSubmissions:0,timeUntilReset:Math.max(0,bs-(n-d.timestamp)),totalSubmissions:l.length,alreadySubmittedToPlaylist:!1}}return{allowed:!0,remainingSubmissions:Yt-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 Ol(r,e){if(!(!r||!e))try{const s=JSON.parse(localStorage.getItem("trackSubmissions")||"[]");s.push({timestamp:Date.now(),spotifyUrl:zt(r),playlistId:e}),localStorage.setItem("trackSubmissions",JSON.stringify(s))}catch(s){console.error("Failed to record submission:",s)}}function $l(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 Tr=/([a-zA-Z0-9._-]+@[a-zA-Z0-9._-]+\.[a-zA-Z0-9._-]+)/gi,Il=/(?:e-?mail|email)\s*:*\s*/gi,Rl=/(?:https?:\/\/)?(?:(?:www|bit|t|tinyurl)\.[a-z]{2,}|[a-z0-9-]+(?:\.[a-z]{2,})+)(?:\/[^\s]*)?/gi,Dl=/(?:https?:\/\/|;to\/|\.com\/|\.co\/|\.ly\/|\.be\/|href=")[^\s]*/gi,Ll=/<[^>]*>|<[^>]*$/g,Fl=/&([a-z0-9]+|#[0-9]{1,6}|#x[0-9a-fA-F]{1,6});/gi,Ul=/(?:@[\w-]+|#[\w-]+)/g;function Ml(r){const e=document.createElement("textarea");return r.replace(Fl,(s,n)=>(e.innerHTML=s,e.value||s))}function $n(r){let e=r,s=null;const n=r.match(Tr);return n&&(s=n[0].toLowerCase(),e=e.replace(Tr,"")),e=e.replace(Il,""),e=e.replace(Rl,"").replace(Dl,""),e=e.replace(Ll,""),e=e.replace(Ul,""),e=Ml(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 ql="5285db074532404885ad78daec8e7640",Bl="4a1752bc53e241bca760677d06c5a9b2",Pr=15e3;let Ar=0;function Gl(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 pt(r,e){if(!r)return null;try{const s=Gl(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 Zs(){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(`${ql}:${Bl}`)}`},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 Qs(r){const s=Date.now()-Ar;return s<Pr&&await new Promise(n=>setTimeout(n,Pr-s)),Ar=Date.now(),r()}async function Xs(r){try{return await Qs(async()=>{const e=await Zs(),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}=$n(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 zl(r){if(!r.trim())return[];try{return await Qs(async()=>{var a;const e=await Zs(),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 Or(r){if(!r)return null;try{return await Qs(async()=>{const e=await Zs(),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 Hl(r,e){const[s,n]=y.useState(r);return y.useEffect(()=>{const a=setTimeout(()=>{n(r)},e);return()=>{clearTimeout(a)}},[r,e]),s}function In({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=Hl(a,300),_=y.useRef(null);y.useEffect(()=>{const N=S=>{_.current&&!_.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 zl(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=pt(e,"track");if(S){c(!0),p(null);try{const j=await Or(S);j?r(j):p("Track not found")}catch(j){console.error("Failed to fetch initial track:",j),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=pt(N,"track");if(S){c(!0);try{const j=await Or(S);j?x(j):p("Invalid Spotify URL or track not found")}catch(j){console.error("Failed to fetch track:",j),p("Failed to load track. Please try again.")}finally{c(!1)}}},E=N=>{N.preventDefault(),N.stopPropagation(),n(),i(""),p(null),h(!1),setTimeout(()=>{var j;const S=(j=_.current)==null?void 0:j.querySelector("input");S&&S.focus()},0)},k=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:E,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:_,className:"relative",children:[t.jsxs("div",{className:"relative",children:[t.jsx(is,{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:k,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:j=>{j.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(j=>j.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 Ht={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 bt({playlist:r,onClose:e,onSubmit:s}){const[n,a]=y.useState(()=>{var E;const w=gt();return{spotifyUrl:((E=w==null?void 0:w.lastTrack)==null?void 0:E.external_urls.spotify)||"",artistName:(w==null?void 0:w.artistName)||"",email:(w==null?void 0:w.email)||"",message:""}}),[i,o]=y.useState(()=>{const w=gt();return(w==null?void 0:w.lastTrack)||null}),[l,d]=y.useState({}),[c,u]=y.useState({allowed:!0,remainingSubmissions:Yt,timeUntilReset:null,totalSubmissions:0,alreadySubmittedToPlaylist:!1}),[h,f]=y.useState("");y.useEffect(()=>{const w=k=>{const A=document.querySelector(".modal-content");A&&!A.contains(k.target)&&e()},E=k=>{k.key==="Escape"&&e()};return document.addEventListener("mousedown",w),document.addEventListener("keydown",E),()=>{document.removeEventListener("mousedown",w),document.removeEventListener("keydown",E)}},[e]),y.useEffect(()=>{if(n.spotifyUrl){const w=Al(n.spotifyUrl,r.id);u(w)}},[n.spotifyUrl,r.id]),y.useEffect(()=>{let w;const E=()=>{if(c.timeUntilReset){const k=Math.floor(c.timeUntilReset/36e5),A=Math.floor(c.timeUntilReset%(1e3*60*60)/(1e3*60)),N=Math.floor(c.timeUntilReset%(1e3*60)/1e3);f(`${k}h ${A}m ${N}s`)}};return c.timeUntilReset&&(E(),w=setInterval(()=>{const k=c.timeUntilReset-1e3;k<=0?(clearInterval(w),u(A=>({...A,timeUntilReset:null,allowed:!0}))):(u(A=>({...A,timeUntilReset:k})),E())},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 E=pt(n.spotifyUrl,"track");if(!E||!i)throw new Error("Invalid track selection");await Ht.submit({playlistId:r.id,trackId:E,trackName:i.name,trackUrl:n.spotifyUrl,artistName:n.artistName,email:n.email,message:n.message}),Tn({artistName:n.artistName,email:n.email,track:i}),Ol(n.spotifyUrl,r.id),El(r.id,n.spotifyUrl),s(n)}catch(E){console.error("Failed to submit track:",E),d(k=>({...k,submit:"Failed to submit track. Please try again."}))}},_=w=>{o(w),a(E=>{var k;return{...E,spotifyUrl:w.external_urls.spotify,artistName:((k=w.artists[0])==null?void 0:k.name)||E.artistName}}),d(E=>({...E,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,"/",Yt," 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(Rs,{className:"w-4 h-4"}),"Search and Select Your Track"]}),t.jsx(In,{onTrackSelect:_,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(os,{className:"w-4 h-4"}),"Artist Name"]}),t.jsx("input",{type:"text",placeholder:"Your artist name",value:n.artistName,onChange:w=>a(E=>({...E,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(_n,{className:"w-4 h-4"}),"Email"]}),t.jsx("input",{type:"email",placeholder:"your@email.com",value:n.email,onChange:w=>a(E=>({...E,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(Nn,{className:"w-4 h-4"}),"Message (Optional)"]}),t.jsx("textarea",{placeholder:"Tell the curator about your track...",value:n.message,onChange:w=>a(E=>({...E,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(xe,{className:"w-4 h-4"}),"Submit Track"]})]})]})]})})}const Wl=Object.freeze(Object.defineProperty({__proto__:null,SubmissionModal:bt},Symbol.toStringTag,{value:"Module"}));function Jl({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:Is,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 Re(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 Dr.createPortal(t.jsx(Jl,{...r}),e)}function Kl({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 Vl(){var N;const{slug:r}=Ms(),e=We(),s=et(),[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}=kl(r||""),[b,_]=y.useState(!1);y.useEffect(()=>{_(!1)},[r]),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:j}=await D.from("playlist_details").select("*",{count:"exact",head:!0}).eq("genre",c.genre);d(j||0)}}c&&S()},[c]);const x=gt(),w=c&&(x==null?void 0:x.lastTrack)&&An(c.id,x.lastTrack.external_urls.spotify),E=()=>{var j;const S=(j=s.state)==null?void 0:j.from;e(S==="genre"?-1:"/")},k=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(j){console.error("Failed to submit track:",j),o({type:"error",message:"Failed to submit track. Please try again."})}};if(u)return t.jsx("div",{className:"container mx-auto px-4 py-8",children:t.jsxs("div",{className:"animate-pulse",children:[t.jsx("div",{className:"h-8 w-48 bg-gray-200 rounded mb-6"}),t.jsx("div",{className:"bg-white shadow-lg",children:t.jsxs("div",{className:"grid md:grid-cols-2",children:[t.jsx("div",{className:"aspect-square bg-gray-200"}),t.jsxs("div",{className:"p-6",children:[t.jsx("div",{className:"h-8 w-3/4 bg-gray-200 rounded mb-4"}),t.jsx("div",{className:"h-4 w-1/2 bg-gray-200 rounded mb-4"}),t.jsx("div",{className:"h-20 bg-gray-200 rounded mb-4"})]})]})})]})});if(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:E,className:"text-green-600 hover:text-green-700 flex items-center gap-2 mx-auto",children:[t.jsx(He,{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:E,className:"text-green-600 hover:text-green-700 flex items-center gap-2 mx-auto",children:[t.jsx(He,{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(Ke,{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(Kl,{playlist:c,baseUrl:window.location.origin}),t.jsxs("main",{className:"container mx-auto px-4 py-8",children:[t.jsxs("button",{onClick:E,className:"inline-flex items-center gap-2 text-green-600 hover:text-green-700 mb-6",children:[t.jsx(He,{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(vn,{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:()=>_(!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(os,{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(xe,{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($t,{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(wn,{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(Sn,{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(Ys,{playlist:S,onSubmit:()=>a(!0),isRelated:!0,hideSubmit:!0},S.id))})]}),n&&c&&t.jsx(bt,{playlist:c,onClose:()=>a(!1),onSubmit:k}),i&&t.jsx(Re,{message:i.message,type:i.type,onClose:()=>o(null)})]})]})}function Yl({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(is,{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(xe,{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 St="playlist_state";function It(r){const[e,s]=y.useState(()=>{try{const _=sessionStorage.getItem(St);if(_){const x=JSON.parse(_);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 _=sessionStorage.getItem(St);if(_){const x=JSON.parse(_);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(St);if(x){const w=JSON.parse(x);return JSON.stringify(w.filters)!==JSON.stringify(r)}return!0})()&&(s([]),u(1),d(!0),sessionStorage.removeItem(St))},[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 _={playlists:e,currentPage:c,filters:r||{}};sessionStorage.setItem(St,JSON.stringify(_))}},[e,c,r]),y.useEffect(()=>{async function _(){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 j=D.from("playlist_details").select("*",{count:"exact"}).eq("featured",!1).order("created_at",{ascending:!1});if(r!=null&&r.search){const v=`%${r.search}%`;j=j.or(`name.ilike.${v},description.ilike.${v}`)}const{data:m,count:g}=await j.range(S,S+p-1);if(c===1){const v=[...N||[],...m||[]];s(v)}else s(v=>{const C=new Set(v.map(P=>P.id)),T=(m||[]).filter(P=>!C.has(P.id));return[...v,...T]});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 j=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}%`;j=j.or(`name.ilike.${v},description.ilike.${v}`)}const{data:m,count:g}=await j.range(S,S+p-1);if(c===1){const v=[...N||[],...m||[]];s(v)}else s(v=>{const C=new Set(v.map(P=>P.id)),T=(m||[]).filter(P=>!C.has(P.id));return[...v,...T]});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:E,error:k,count:A}=await x;if(k)throw k;f(A||0),s(N=>{const S=E||[];if(c===1)return S;const j=new Set(N.map(g=>g.id)),m=S.filter(g=>!j.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)}}_()},[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(_=>_+1)},currentPage:c,totalCount:h,itemsPerPage:p}}function Zl(){var S,j;const r=et(),[e,s]=Lr(),[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}=It({...n,genre:n.genre||void 0,subGenre:n.subGenre||void 0}),[p,b]=y.useState(null),[_,x]=y.useState(null),w=gt(),[E,k]=y.useState(!0);y.useEffect(()=>{var m;if(!o&&i.length>0&&E){const g=(m=r.state)==null?void 0:m.filters;g!=null&&g.fromSubmission?window.scrollTo(0,0):On.restorePosition(r.pathname,s),k(!1)}},[o,i.length,r.pathname,r.state,s,E]),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(Ke,{}),t.jsxs("main",{children:[t.jsxs("div",{className:"container mx-auto px-4 pb-12",children:[t.jsx(Yl,{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:(j=w.lastTrack.artists[0])==null?void 0:j.name})]})]}),t.jsx("button",{onClick:()=>{Pn(),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(Ys,{playlist:m,onSubmit:v=>b(i.find(C=>C.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(bt,{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.`})}}),_&&t.jsx(Re,{message:_.message,type:_.type,onClose:()=>x(null)})]})]})}function Ql(){const r=We(),[e,s]=y.useState(null);y.useEffect(()=>{typeof window<"u"&&window.prerenderReady!==void 0&&(window.prerenderReady=!0)},[]);const n=a=>{var i;Tn({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(He,{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(In,{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(bn,{className:"w-5 h-5"})]})]})]})}function Xl(){const r=We(),{genres:e}=Ie(),[s,n]=y.useState(""),[a,i]=y.useState(""),o=e.find(u=>u.id===s),l=(o==null?void 0:o.subGenres)||[],d=u=>{i(u)},c=u=>{if(!s||!o)return;const h=a?l.find(f=>f.id===a):null;window.scrollTo(0,0),r("/playlists",{state:{filters:{genre:o.name,subGenre:(h==null?void 0:h.name)||"",fromSubmission:!0}},replace:!0})};return t.jsx("div",{className:"container mx-auto px-4 py-8 max-w-4xl",children:t.jsxs("div",{className:"space-y-8",children:[t.jsxs("div",{className:"text-center",children:[t.jsx("h1",{className:"text-3xl font-bold mb-2",children:"Select Your Genre"}),t.jsx("p",{className:"text-gray-600",children:"Choose the main category that best fits your track"})]}),t.jsxs("div",{children:[t.jsx("h2",{className:"text-lg font-medium mb-3",children:"Main Genre"}),t.jsx("div",{className:"grid grid-cols-2 sm:grid-cols-3 md:grid-cols-4 gap-3",children:e.map(u=>t.jsxs("button",{onClick:()=>{n(u.id),i("")},className:`p-4 text-center border-2 rounded-lg transition-colors ${s===u.id?"border-green-500 bg-green-50":"border-gray-200 hover:border-green-500 hover:bg-green-50"}`,children:[t.jsx(xe,{className:"w-6 h-6 mx-auto mb-2 text-gray-600"}),t.jsx("span",{className:"font-medium",children:u.name})]},u.id))})]}),s&&l.length>0&&t.jsxs("div",{children:[t.jsx("h2",{className:"text-lg font-medium mb-3",children:"Sub-genre (Optional)"}),t.jsx("div",{className:"grid grid-cols-2 sm:grid-cols-3 md:grid-cols-4 gap-3",children:l.map(u=>t.jsx("button",{onClick:()=>d(u.id),className:`p-3 text-center border-2 rounded-lg transition-colors ${a===u.id?"border-green-500 bg-green-50":"border-gray-200 hover:border-green-500 hover:bg-green-50"}`,children:t.jsx("span",{className:"font-medium",children:u.name})},u.id))})]}),t.jsxs("div",{className:"flex justify-between items-center",children:[t.jsxs("button",{onClick:()=>r("/submit"),className:"flex items-center gap-2 text-gray-600 hover:text-gray-800 transition-colors",children:[t.jsx(He,{className:"w-5 h-5"}),"Back to Track Selection"]}),t.jsxs("button",{onClick:()=>c(),disabled:!s,className:`flex items-center gap-2 px-6 py-3 rounded-lg font-medium transition-colors ${s?"bg-green-500 text-white hover:bg-green-600":"bg-gray-200 text-gray-500 cursor-not-allowed"}`,children:["Continue to Playlists",t.jsx(bn,{className:"w-5 h-5"})]})]})]})})}function ec(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=Er(),N=[...h].sort((S,j)=>{const m=qt(`${A}-${S.id}`),g=qt(`${A}-${j.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:_}=await p;if(_)throw _;const w=[...h||[],...b||[]].filter((A,N,S)=>N===S.findIndex(j=>j.id===A.id)),E=Er(),k=w.sort((A,N)=>{const S=qt(`${E}-${A.id}`),j=qt(`${E}-${N.id}`);return S-j});a(k.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 Rn({genre:r,subGenre:e,totalCount:s,onViewAll:n}){const{playlists:a,loading:i}=ec(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(Ys,{playlist:b,onSubmit:_=>l(a.find(x=>x.id===_)||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(bt,{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(Re,{message:d.message,type:d.type,onClose:()=>c(null)})]})}const tc="https://ftwlzdhkzqfuosdorgjt.supabase.co/storage/v1/object/public/playlistpartner%20public/playlistpartner%20og%20image.png";function sc(){const{genre:r}=Ms(),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=We(),{totalCount:f}=It({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`,_=`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(E){console.error("Failed to submit track:",E),u({type:"error",message:"Failed to submit track. Please try again."})}};return t.jsxs(t.Fragment,{children:[t.jsx(Ke,{title:b,description:_,image:tc,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(He,{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(xe,{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(Rn,{genre:a.name,totalCount:f,onViewAll:p}),l&&i&&t.jsx(bt,{playlist:i,onClose:()=>{d(!1),o(null)},onSubmit:x}),c&&t.jsx(Re,{message:c.message,type:c.type,onClose:()=>u(null)})]})]})}const rc="https://ftwlzdhkzqfuosdorgjt.supabase.co/storage/v1/object/public/playlistpartner%20public/playlistpartner%20og%20image.png";function nc(){const{genre:r,subGenre:e}=Ms(),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=We(),{totalCount:_}=It({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`,E=`Submit your ${l.name} tracks to ${_} Spotify playlists for free. Connect with independent curators and grow your audience — no signup needed.`,k=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(Ke,{title:w,description:E,image:rc,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(He,{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(xe,{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:[_," Playlists"]})})]})]})}),t.jsx(Rn,{genre:o.name,subGenre:l.name,totalCount:_,onViewAll:x}),u&&d&&t.jsx(bt,{playlist:d,onClose:()=>{h(!1),c(null)},onSubmit:k}),f&&t.jsx(Re,{message:f.message,type:f.type,onClose:()=>p(null)})]})]})}function ac(){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(Ke,{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(He,{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(xe,{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 ic(){const{totalCount:r}=It({});return t.jsxs(t.Fragment,{children:[t.jsx(Ke,{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(as,{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(sl,{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(ml,{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($t,{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 oc(){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=pt(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(Ke,{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(as,{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(Xo,{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($t,{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(Qe,{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(Qe,{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(Qe,{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(Qe,{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(Qe,{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 lc({children:r}){const{user:e,isAdmin:s,loading:n}=Js(),a=et();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(Fr,{to:"/admin/login",state:{from:a},replace:!0}):t.jsx(t.Fragment,{children:r})}function cc(){const r=et(),e=We(),{signOut:s}=Js(),n=[{path:"/admin",icon:al,label:"Dashboard"},{path:"/admin/playlists",icon:xe,label:"Playlists"},{path:"/admin/submissions",icon:nl,label:"Submissions"},{path:"/admin/genres",icon:il,label:"Genres"},{path:"/admin/import",icon:Kt,label:"Import"},{path:"/admin/settings",icon:hl,label:"Settings"}],a=async()=>{try{await s(),e("/admin/login")}catch(i){console.error("Failed to log out:",i)}};return t.jsx(lc,{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(ll,{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(Qn,{})})})]})})})}function dc({stats:r}){const e=[{label:"Total Playlists",value:(r==null?void 0:r.totalPlaylists.toLocaleString())||"0",icon:xe}];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 uc(){const{totalCount:r}=It({}),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(dc,{stats:e})]})}function hc({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=pt(x,"playlist");if(!w)throw new Error("Invalid Spotify playlist URL");const E=await Xs(w);if(!E)throw new Error("Playlist not found on Spotify");o(k=>{var A,N,S,j,m;return{...k,name:E.name,description:E.description||k.description,imageUrl:((A=E.images[0])==null?void 0:A.url)||k.imageUrl,followers:((N=E.followers)==null?void 0:N.total)||0,curatorName:((S=E.owner)==null?void 0:S.display_name)||k.curatorName,curatorProfileUrl:((m=(j=E.owner)==null?void 0:j.external_urls)==null?void 0:m.spotify)||k.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)}}},_=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=pt(i.spotifyUrl,"playlist");if(!w)throw new Error("Invalid Spotify playlist URL");const E={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(E)}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:_,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(Rs,{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(xe,{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($t,{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(E=>({...E,subGenres:[...E.subGenres,x.id]})):o(E=>({...E,subGenres:E.subGenres.filter(k=>k!==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(os,{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(Rs,{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 fc({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 _=10;for(let x=0;x<p.length;x+=_){if((f=c.current)!=null&&f.signal.aborted)throw new Error("Sync cancelled");const w=p.slice(x,Math.min(x+_,p.length)),E=await Promise.allSettled(w.map(async N=>{var S,j,m,g,v,C;try{const T=await Xs(N.spotify_id);if(!T)throw new Error("Playlist not found on Spotify");return{id:N.id,name:T.name,description:T.description||"",image_url:((S=T.images[0])==null?void 0:S.url)||"",followers:((j=T.followers)==null?void 0:j.total)||0,track_count:((m=T.tracks)==null?void 0:m.total)||0,curator_name:((g=T.owner)==null?void 0:g.display_name)||null,curator_profile_url:((C=(v=T.owner)==null?void 0:v.external_urls)==null?void 0:C.spotify)||null,updated_at:new Date().toISOString()}}catch(T){throw console.error(`Failed to fetch playlist ${N.spotify_id}:`,T),T}}));let k=0,A=0;for(const N of E)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++):k++}else A++;d(N=>N?{...N,current:Math.min(x+_,p.length),updated:N.updated+k,failed:N.failed+A}:null),x+_<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(Qe,{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(mt,{className:"w-5 h-5"}),"Start Sync"]})]})]})]})}):null}function mc(){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:_,error:x}=await D.from("sub_genres").select("*");if(x)throw x;const w=p.map(E=>({...E,sub_genres:E.sub_genre_ids?E.sub_genre_ids.map(k=>{var A;return(A=_.find(N=>N.id===k))==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||[]),_={...f,sub_genres:(b==null?void 0:b.map(x=>x.name))||[]};return e(x=>[_,...x]),_}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 _=[];if(f.sub_genre_ids){const{data:w}=await D.from("sub_genres").select("*").in("id",f.sub_genre_ids);_=(w==null?void 0:w.map(E=>E.name))||[]}const x={...p,sub_genres:_};return e(w=>w.map(E=>E.id===h?x:E)),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(_=>_.id===h?{..._,featured:f}:_))}catch(p){throw console.error("Failed to update featured status:",p),p}}}}function gc(){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:_,deletePlaylist:x,toggleFeatured:w}=mc(),E=()=>{n(!1),l({type:"success",message:"Playlists synced successfully"}),p()},k=async j=>{try{a?(await _(a.id,j),l({type:"success",message:"Playlist updated successfully"})):(await b(j),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(j,m)=>{if(window.confirm(`Are you sure you want to delete "${m}"?`))try{await x(j),l({type:"success",message:`${m} has been deleted`}),p()}catch{l({type:"error",message:"Failed to delete playlist"})}},N=async(j,m)=>{try{await w(j,!m),l({type:"success",message:`Playlist ${m?"removed from":"added to"} featured list`})}catch{l({type:"error",message:"Failed to update featured status"})}},S=u.filter(j=>!(d.search&&!j.name.toLowerCase().includes(d.search.toLowerCase())||d.genre&&j.genre_id!==d.genre||d.status==="claimed"&&!j.claimed||d.status==="unclaimed"&&j.claimed));return f?t.jsx("div",{className:"p-8 text-center",children:t.jsxs("div",{className:"flex items-center justify-center gap-2 text-red-600",children:[t.jsx(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(mt,{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(Ks,{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(is,{className:"absolute left-3 top-1/2 transform -translate-y-1/2 text-gray-400 w-5 h-5"}),t.jsx("input",{type:"text",placeholder:"Search playlists...",value:d.search,onChange:j=>c({...d,search:j.target.value}),className:"w-full pl-10 pr-4 py-2 border border-gray-300 rounded-lg"})]}),t.jsxs("select",{value:d.genre,onChange:j=>c({...d,genre:j.target.value}),className:"border border-gray-300 rounded-lg px-4 py-2",children:[t.jsx("option",{value:"",children:"All Genres"}),Array.from(new Set(u.map(j=>j.genre_id))).map(j=>{var g;const m=(g=u.find(v=>v.genre_id===j))==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:j=>c({...d,status:j.target.value}),className:"border border-gray-300 rounded-lg px-4 py-2",children:[t.jsx("option",{value:"",children:"Claimed / Unclaimed"}),t.jsx("option",{value:"claimed",children:"Claimed"}),t.jsx("option",{value:"unclaimed",children:"Unclaimed"})]}),t.jsxs("select",{value:d.sortBy,onChange:j=>{c({...d,sortBy:j.target.value}),p({...d,sortBy:j.target.value})},className:"border border-gray-300 rounded-lg px-4 py-2",children:[t.jsx("option",{value:"created_at_desc",children:"Latest First"}),t.jsx("option",{value:"featured_desc",children:"Featured First"}),t.jsx("option",{value:"followers_desc",children:"Most Followers"}),t.jsx("option",{value:"followers_asc",children:"Least Followers"})]})]})}),t.jsx("div",{className:"bg-white rounded-lg shadow-sm overflow-hidden",children:t.jsxs("table",{className:"w-full",children:[t.jsx("thead",{children:t.jsxs("tr",{className:"bg-gray-50",children:[t.jsx("th",{className:"px-6 py-3 text-left text-sm font-medium text-gray-500",children:"Name"}),t.jsx("th",{className:"px-6 py-3 text-left text-sm font-medium text-gray-500",children:"Genre"}),t.jsx("th",{className:"px-6 py-3 text-left text-sm font-medium text-gray-500",children:"Sub-genres"}),t.jsx("th",{className:"px-6 py-3 text-left text-sm font-medium text-gray-500",children:"Curator"}),t.jsx("th",{className:"px-6 py-3 text-left text-sm font-medium text-gray-500",children:"Followers"}),t.jsx("th",{className:"px-6 py-3 text-left text-sm font-medium text-gray-500",children:"Claimed"}),t.jsx("th",{className:"px-6 py-3 text-left text-sm font-medium text-gray-500",children:"Actions"})]})}),t.jsx("tbody",{className:"divide-y divide-gray-200",children:h?t.jsx("tr",{children:t.jsx("td",{colSpan:7,className:"px-6 py-8 text-center",children:t.jsx(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(j=>{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:j.image_url,alt:j.name,className:"w-10 h-10 rounded-sm object-cover mr-3"}),t.jsx("span",{className:"font-medium",children:j.name})]})}),t.jsx("td",{className:"px-6 py-4",children:(m=j.genres)==null?void 0:m.name}),t.jsx("td",{className:"px-6 py-4",children:(g=j.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:j.curator_name||"Unclaimed"}),t.jsx("td",{className:"px-6 py-4",children:gl(j.followers)}),t.jsx("td",{className:"px-6 py-4",children:t.jsx("span",{className:`inline-flex items-center px-2.5 py-0.5 rounded-full text-xs font-medium ${j.claimed?"bg-green-100 text-green-800":"bg-yellow-100 text-yellow-800"}`,children:j.claimed?"Claimed":"Unclaimed"})}),t.jsx("td",{className:"px-6 py-4",children:t.jsxs("div",{className:"flex items-center gap-2",children:[t.jsx("button",{onClick:()=>N(j.id,j.featured),className:"p-1 hover:bg-gray-100 rounded",title:j.featured?"Remove from featured":"Add to featured",children:t.jsx(En,{className:`w-4 h-4 ${j.featured?"text-yellow-400 fill-yellow-400":"text-gray-400"}`})}),t.jsx("button",{onClick:()=>i(j),className:"p-1 hover:bg-gray-100 rounded",children:t.jsx(kn,{className:"w-4 h-4 text-gray-500"})}),t.jsx("button",{onClick:()=>A(j.id,j.name),className:"p-1 hover:bg-gray-100 rounded",children:t.jsx(Vs,{className:"w-4 h-4 text-red-500"})})]})})]},j.id)})})]})}),(r||a)&&t.jsx(hc,{playlist:a,onClose:()=>{e(!1),i(null)},onSuccess:k}),s&&t.jsx(fc,{isOpen:s,onClose:()=>n(!1),onComplete:E}),o&&t.jsx(Re,{message:o.message,type:o.type,onClose:()=>l(null)})]})}function pc(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 Ht.getForPlaylist(r):await Ht.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 Ht.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 xc({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(xe,{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(el,{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(_n,{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(jn,{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(Sr,{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(Sr,{className:"w-4 h-4 text-gray-400"}),t.jsxs("span",{children:["Reviewed: ",new Date(r.reviewed_at).toLocaleString()]})]})]})]})]})]})})}function yc(){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}=pc(),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(is,{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(Is,{className:"w-3 h-3"}),f.status==="rejected"&&t.jsx(kr,{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(Is,{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(rl,{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(kr,{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(Nn,{className:"w-5 h-5"})})]})})]},f.id)})})]})}),s&&t.jsx(xc,{submission:s,onClose:()=>n(null)}),r&&t.jsx(Re,{message:r.message,type:r.type,onClose:()=>e(null)})]})}function bc({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),[_,x]=y.useState(null),{createGenre:w,updateGenre:E}=Ie(),k=(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((T,P)=>P!==g).map(T=>$e(T.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(T=>$e(T.name))).size!==l.length)throw new Error("Duplicate sub-genres are not allowed");const v={name:n.trim(),description:i.trim(),subGenres:l.map(T=>({name:T.name.trim(),description:T.description.trim()}))};let C;r?C=await E(r.id,v):C=await w(v),s(C)}catch(g){console.error("Failed to save genre:",g),x(g instanceof Error?g.message:"Failed to save genre")}finally{b(!1)}},N=()=>{try{k(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};k(v,m);const C=[...l];C[m]=v,d(C),f(null),x(null)}catch(v){x(v instanceof Error?v.message:"Invalid sub-genre")}},j=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(Ks,{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(dl,{className:"w-4 h-4 text-gray-600"})}),t.jsx("button",{type:"button",onClick:()=>j(g),className:"p-1 hover:bg-red-100 rounded transition-colors",title:"Remove sub-genre",children:t.jsx(Vs,{className:"w-4 h-4 text-red-500"})})]})]}),t.jsx("p",{className:"text-sm text-gray-600",children:m.description})]})},g))})]}),_&&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:_})]}),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 wc({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}=Mn({id:r}),f={transform:qn.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(tl,{className:"w-5 h-5"})}),t.jsx("div",{className:"p-2 bg-green-50 rounded-lg",children:t.jsx(xe,{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(kn,{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(Vs,{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(Qo,{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 vc(){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=Bn(sr(Vn),sr(Kn,{coordinateGetter:Jn})),f=async b=>{const{active:_,over:x}=b;if(x&&_.id!==x.id){const w=r.findIndex(k=>k.id===_.id),E=r.findIndex(k=>k.id===x.id);try{await a(w,E),u({type:"success",message:"Genre order updated successfully"})}catch{u({type:"error",message:"Failed to update genre order"})}}},p=async(b,_)=>{if(window.confirm(`Are you sure you want to delete "${_}" and all its sub-genres?`))try{await n(b),u({type:"success",message:`${_} 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(Ks,{className:"w-5 h-5"}),"Add Genre"]})]}),t.jsxs("div",{className:"space-y-4",children:[t.jsx(Gn,{sensors:h,collisionDetection:zn,onDragEnd:f,children:t.jsx(Hn,{items:r.map(b=>b.id),strategy:Wn,children:r.map(b=>t.jsx(wc,{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(xe,{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(bc,{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(Re,{message:c.message,type:c.type,onClose:()=>u(null)})]})}const jc=Yn,Dn=y.forwardRef(({className:r,...e},s)=>t.jsx($r,{ref:s,className:"inline-flex h-10 items-center justify-center rounded-lg bg-gray-100 p-1 text-gray-500 mb-4",...e}));Dn.displayName=$r.displayName;const Fs=y.forwardRef(({className:r,...e},s)=>t.jsx(Ir,{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}));Fs.displayName=Ir.displayName;const Us=y.forwardRef(({className:r,...e},s)=>t.jsx(Rr,{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}));Us.displayName=Rr.displayName;function _c({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 _=(await i.text()).split(`
`),x=_[0].split(",").map(P=>P.trim()),E=["Name","Slug","Description"].filter(P=>!x.includes(P));if(E.length>0)throw new Error(`Missing required columns in genres file: ${E.join(", ")}`);const k=[];for(let P=1;P<_.length;P++){if(!_[P].trim())continue;const M=_[P].split(",").map(H=>H.trim());k.push({Name:M[x.indexOf("Name")],Slug:M[x.indexOf("Slug")],Description:M[x.indexOf("Description")]})}u({stage:"Processing genres",current:1,total:2});const N=(await l.text()).split(`
`),S=N[0].split(",").map(P=>P.trim()),m=["Name","Slug","Description"].filter(P=>!S.includes(P));if(m.length>0)throw new Error(`Missing required columns in sub-genres file: ${m.join(", ")}`);const g=[];for(let P=1;P<N.length;P++){if(!N[P].trim())continue;const M=N[P].split(",").map(H=>H.trim());g.push({Name:M[S.indexOf("Name")],Slug:M[S.indexOf("Slug")],Description:M[S.indexOf("Description")]})}u({stage:"Importing data",current:0,total:k.length+g.length});for(const P of k){const{error:M}=await D.from("genres").insert({name:P.Name,slug:P.Slug||$e(P.Name),description:P.Description});if(M&&M.code!=="23505")throw M;u(H=>H?{...H,current:H.current+1}:null)}const{data:v,error:C}=await D.from("genres").select("id, name, slug");if(C)throw C;const T=new Map(v.map(P=>[P.name.toLowerCase(),P.id]));for(const P of g){const M=v.find(H=>P.Slug.includes(H.slug)||P.Name.toLowerCase().includes(H.name.toLowerCase()));if(M){const{error:H}=await D.from("sub_genres").insert({name:P.Name,slug:P.Slug||$e(P.Name),description:P.Description,genre_id:M.id});if(H&&H.code!=="23505")throw H}u(H=>H?{...H,current:H.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 _=b.dataTransfer.files[0];_&&f(_)},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(Kt,{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 _=(x=b.target.files)==null?void 0:x[0];_&&f(_)},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 _=b.dataTransfer.files[0];_&&p(_)},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(Kt,{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 _=(x=b.target.files)==null?void 0:x[0];_&&p(_)},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 Nc={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:_}=await D.from("playlists").select("id").eq("spotify_id",h.URL.split("/").pop()).single();if(_){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 Ln={exports:{}};/* @license
Papa Parse
v5.5.3
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 _(v),(this._handle.streamer=this)._config=v}).call(this,m),this.parseChunk=function(g,v){var C=parseInt(this._config.skipFirstNLines)||0;if(this.isFirstChunk&&0<C){let P=this._config.newline;P||(T=this._config.quoteChar||'"',P=this._handle.guessLineEndings(g,T)),g=[...g.split(P).slice(C)].join(P)}this.isFirstChunk&&j(this._config.beforeFirstChunk)&&(T=this._config.beforeFirstChunk(g))!==void 0&&(g=T),this.isFirstChunk=!1,this._halted=!1;var C=this._partialLine+g,T=(this._partialLine="",this._handle.parse(C,this._baseIndex,!this._finished));if(!this._handle.paused()&&!this._handle.aborted()){if(g=T.meta.cursor,C=(this._finished||(this._partialLine=C.substring(g-this._baseIndex),this._baseIndex=g),T&&T.data&&(this._rowCount+=T.data.length),this._finished||this._config.preview&&this._rowCount>=this._config.preview),o)n.postMessage({results:T,workerId:c.WORKER_ID,finished:C});else if(j(this._config.chunk)&&!v){if(this._config.chunk(T,this._handle),this._handle.paused()||this._handle.aborted())return void(this._halted=!0);this._completeResults=T=void 0}return this._config.step||this._config.chunk||(this._completeResults.data=this._completeResults.data.concat(T.data),this._completeResults.errors=this._completeResults.errors.concat(T.errors),this._completeResults.meta=T.meta),this._completed||!C||!j(this._config.complete)||T&&T.meta.aborted||(this._config.complete(this._completeResults,this._input),this._completed=!0),C||T&&T.meta.paused||this._nextChunk(),T}this._halted=!0},this._sendError=function(g){j(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,C=this._config.downloadRequestHeaders;for(v in C)g.setRequestHeader(v,C[v])}var T;this._config.chunkSize&&(T=this._start+this._config.chunkSize-1,g.setRequestHeader("Range","bytes="+this._start+"-"+T));try{g.send(this._config.downloadRequestBody)}catch(P){this._chunkError(P.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,C=typeof FileReader<"u";this.stream=function(T){this._input=T,v=T.slice||T.webkitSlice||T.mozSlice,C?((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 T=this._input,P=(this._config.chunkSize&&(P=Math.min(this._start+this._config.chunkSize,this._input.size),T=v.call(T,this._start,P)),g.readAsText(T,this._config.encoding));C||this._chunkLoaded({target:{result:P}})},this._chunkLoaded=function(T){this._start+=this._config.chunkSize,this._finished=!this._config.chunkSize||this._start>=this._input.size,this.parseChunk(T.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,C;if(!this._finished)return v=this._config.chunkSize,g=v?(C=g.substring(0,v),g.substring(v)):(C=g,""),this._finished=!g,this.parseChunk(C)}}function b(m){u.call(this,m=m||{});var g=[],v=!0,C=!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(T){this._input=T,this._input.on("data",this._streamData),this._input.on("end",this._streamEnd),this._input.on("error",this._streamError)},this._checkIsFinished=function(){C&&g.length===1&&(this._finished=!0)},this._nextChunk=function(){this._checkIsFinished(),g.length?this.parseChunk(g.shift()):v=!0},this._streamData=S(function(T){try{g.push(typeof T=="string"?T:T.toString(this._config.encoding)),v&&(v=!1,this._checkIsFinished(),this.parseChunk(g.shift()))}catch(P){this._streamError(P)}},this),this._streamError=S(function(T){this._streamCleanUp(),this._sendError(T)},this),this._streamEnd=S(function(){this._streamCleanUp(),C=!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 _(m){var g,v,C,T,P=Math.pow(2,53),M=-P,H=/^\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,I=0,B=!1,R=!1,G=[],O={data:[],errors:[],meta:{}};function re(W){return m.skipEmptyLines==="greedy"?W.join("").trim()==="":W.length===1&&W[0].length===0}function te(){if(O&&C&&(ee("Delimiter","UndetectableDelimiter","Unable to auto-detect delimiting character; defaulted to '"+c.DefaultDelimiter+"'"),C=!1),m.skipEmptyLines&&(O.data=O.data.filter(function(F){return!re(F)})),le()){let F=function(ae,de){j(m.transformHeader)&&(ae=m.transformHeader(ae,de)),G.push(ae)};if(O)if(Array.isArray(O.data[0])){for(var W=0;le()&&W<O.data.length;W++)O.data[W].forEach(F);O.data.splice(0,1)}else O.data.forEach(F)}function K(F,ae){for(var de=m.header?{}:[],Y=0;Y<F.length;Y++){var Z=Y,J=F[Y],J=((_e,q)=>(se=>(m.dynamicTypingFunction&&m.dynamicTyping[se]===void 0&&(m.dynamicTyping[se]=m.dynamicTypingFunction(se)),(m.dynamicTyping[se]||m.dynamicTyping)===!0))(_e)?q==="true"||q==="TRUE"||q!=="false"&&q!=="FALSE"&&((se=>{if(H.test(se)&&(se=parseFloat(se),M<se&&se<P))return 1})(q)?parseFloat(q):ie.test(q)?new Date(q):q===""?null:q):q)(Z=m.header?Y>=G.length?"__parsed_extra":G[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>G.length?ee("FieldMismatch","TooManyFields","Too many fields: expected "+G.length+" fields but parsed "+Y,I+ae):Y<G.length&&ee("FieldMismatch","TooFewFields","Too few fields: expected "+G.length+" fields but parsed "+Y,I+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(K),ne=O.data.length):O.data=K(O.data,0),m.header&&O.meta&&(O.meta.fields=G),I+=ne)}function le(){return m.header&&G.length===0}function ee(W,K,ne,F){W={type:W,code:K,message:ne},F!==void 0&&(W.row=F),O.errors.push(W)}j(m.step)&&(T=m.step,m.step=function(W){O=W,le()?te():(te(),O.data.length!==0&&(V+=W.data.length,m.preview&&V>m.preview?v.abort():(O.data=O.data[0],T(O,$))))}),this.parse=function(W,K,ne){var F=m.quoteChar||'"',F=(m.newline||(m.newline=this.guessLineEndings(W,F)),C=!1,m.delimiter?j(m.delimiter)&&(m.delimiter=m.delimiter(W),O.meta.delimiter=m.delimiter):((F=((ae,de,Y,Z,J)=>{var _e,q,se,Me;J=J||[",","	","|",";",c.RECORD_SEP,c.UNIT_SEP];for(var st=0;st<J.length;st++){for(var Ce,wt=J[st],me=0,Te=0,he=0,ye=(se=void 0,new w({comments:Z,delimiter:wt,newline:de,preview:10}).parse(ae)),De=0;De<ye.data.length;De++)Y&&re(ye.data[De])?he++:(Ce=ye.data[De].length,Te+=Ce,se===void 0?se=Ce:0<Ce&&(me+=Math.abs(Ce-se),se=Ce));0<ye.data.length&&(Te/=ye.data.length-he),(q===void 0||me<=q)&&(Me===void 0||Me<Te)&&1.99<Te&&(q=me,_e=wt,Me=Te)}return{successful:!!(m.delimiter=_e),bestDelimiter:_e}})(W,m.newline,m.skipEmptyLines,m.comments,m.delimitersToGuess)).successful?m.delimiter=F.bestDelimiter:(C=!0,m.delimiter=c.DefaultDelimiter),O.meta.delimiter=m.delimiter),N(m));return m.preview&&m.header&&F.preview++,g=W,v=new w(F),O=v.parse(g,K,ne),te(),B?{meta:{paused:!0}}:O||{meta:{paused:!1}}},this.paused=function(){return B},this.pause=function(){B=!0,v.abort(),g=j(m.chunk)?"":g.substring(v.getCharIndex())},this.resume=function(){$.streamer._halted?(B=!1,$.streamer.parseChunk(g,!0)):setTimeout($.resume,3)},this.aborted=function(){return R},this.abort=function(){R=!0,v.abort(),O.meta.aborted=!0,j(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,C=m.comments,T=m.step,P=m.preview,M=m.fastMode,H=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=","),C===g)throw new Error("Comment character same as delimiter");C===!0?C="#":(typeof C!="string"||-1<c.BAD_DELIMITERS.indexOf(C))&&(C=!1),v!==`
`&&v!=="\r"&&v!==`\r
`&&(v=`
`);var I=0,B=!1;this.parse=function(R,G,O){if(typeof R!="string")throw new Error("Input must be a string");var re=R.length,te=g.length,le=v.length,ee=C.length,W=j(T),K=[],ne=[],F=[],ae=I=0;if(!R)return me();if(M||M!==!1&&R.indexOf($)===-1){for(var de=R.split(v),Y=0;Y<de.length;Y++){if(F=de[Y],I+=F.length,Y!==de.length-1)I+=v.length;else if(O)return me();if(!C||F.substring(0,ee)!==C){if(W){if(K=[],Me(F.split(g)),Te(),B)return me()}else Me(F.split(g));if(P&&P<=Y)return K=K.slice(0,P),me(!0)}}return me()}for(var Z=R.indexOf(g,I),J=R.indexOf(v,I),_e=new RegExp(x(V)+x($),"g"),q=R.indexOf($,I);;)if(R[I]===$)for(q=I,I++;;){if((q=R.indexOf($,q+1))===-1)return O||ne.push({type:"Quotes",code:"MissingQuotes",message:"Quoted field unterminated",row:K.length,index:I}),Ce();if(q===re-1)return Ce(R.substring(I,q).replace(_e,$));if($===V&&R[q+1]===V)q++;else if($===V||q===0||R[q-1]!==V){Z!==-1&&Z<q+1&&(Z=R.indexOf(g,q+1));var se=st((J=J!==-1&&J<q+1?R.indexOf(v,q+1):J)===-1?Z:Math.min(Z,J));if(R.substr(q+1+se,te)===g){F.push(R.substring(I,q).replace(_e,$)),R[I=q+1+se+te]!==$&&(q=R.indexOf($,I)),Z=R.indexOf(g,I),J=R.indexOf(v,I);break}if(se=st(J),R.substring(q+1+se,q+1+se+le)===v){if(F.push(R.substring(I,q).replace(_e,$)),wt(q+1+se+le),Z=R.indexOf(g,I),q=R.indexOf($,I),W&&(Te(),B))return me();if(P&&K.length>=P)return me(!0);break}ne.push({type:"Quotes",code:"InvalidQuotes",message:"Trailing quote on quoted field is malformed",row:K.length,index:I}),q++}}else if(C&&F.length===0&&R.substring(I,I+ee)===C){if(J===-1)return me();I=J+le,J=R.indexOf(v,I),Z=R.indexOf(g,I)}else if(Z!==-1&&(Z<J||J===-1))F.push(R.substring(I,Z)),I=Z+te,Z=R.indexOf(g,I);else{if(J===-1)break;if(F.push(R.substring(I,J)),wt(J+le),W&&(Te(),B))return me();if(P&&K.length>=P)return me(!0)}return Ce();function Me(he){K.push(he),ae=I}function st(he){var ye=0;return ye=he!==-1&&(he=R.substring(q+1,he))&&he.trim()===""?he.length:ye}function Ce(he){return O||(he===void 0&&(he=R.substring(I)),F.push(he),I=re,Me(F),W&&Te()),me()}function wt(he){I=he,Me(F),F=[],J=R.indexOf(v,I)}function me(he){if(m.header&&!G&&K.length&&!ie){var ye=K[0],De=Object.create(null),ls=new Set(ye);let er=!1;for(let rt=0;rt<ye.length;rt++){let Pe=ye[rt];if(De[Pe=j(m.transformHeader)?m.transformHeader(Pe,rt):Pe]){let vt,tr=De[Pe];for(;vt=Pe+"_"+tr,tr++,ls.has(vt););ls.add(vt),ye[rt]=vt,De[Pe]++,er=!0,(H=H===null?{}:H)[vt]=Pe}else De[Pe]=1,ye[rt]=Pe;ls.add(Pe)}er&&console.warn("Duplicate headers found and renamed."),ie=!0}return{data:K,errors:ne,meta:{delimiter:g,linebreak:v,aborted:B,truncated:!!he,cursor:ae+(G||0),renamedHeaders:H}}}function Te(){T(me()),K=[],ne=[]}},this.abort=function(){B=!0},this.getCharIndex=function(){return I}}function E(m){var g=m.data,v=l[g.workerId],C=!1;if(g.error)v.userError(g.error,g.file);else if(g.results&&g.results.data){var T={abort:function(){C=!0,k(g.workerId,{data:[],errors:[],meta:{aborted:!0}})},pause:A,resume:A};if(j(v.userStep)){for(var P=0;P<g.results.data.length&&(v.userStep({data:g.results.data[P],errors:g.results.errors,meta:g.results.meta},T),!C);P++);delete g.results}else j(v.userChunk)&&(v.userChunk(g.results,T,g.file),delete g.results)}g.finished&&!C&&k(g.workerId,g.results)}function k(m,g){var v=l[m];j(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 j(m){return typeof m=="function"}return c.parse=function(m,g){var v=(g=g||{}).dynamicTyping||!1;if(j(v)&&(g.dynamicTypingFunction=v,v={}),g.dynamicTyping=v,g.transform=!!j(g.transform)&&g.transform,!g.worker||!c.WORKERS_SUPPORTED)return v=null,c.NODE_STREAM_INPUT,typeof m=="string"?(m=(C=>C.charCodeAt(0)!==65279?C:C.slice(1))(m),v=new(g.download?h:p)(g)):m.readable===!0&&j(m.read)&&j(m.on)?v=new b(g):(n.File&&m instanceof File||m instanceof Object)&&(v=new f(g)),v.stream(m);(v=(()=>{var C;return!!c.WORKERS_SUPPORTED&&(C=(()=>{var T=n.URL||n.webkitURL||null,P=s.toString();return c.BLOB_URL||(c.BLOB_URL=T.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; ","(",P,")();"],{type:"text/javascript"})))})(),(C=new n.Worker(C)).onmessage=E,C.id=d++,l[C.id]=C)})()).userStep=g.step,v.userChunk=g.chunk,v.userComplete=g.complete,v.userError=g.error,g.step=j(g.step),g.chunk=j(g.chunk),g.complete=j(g.complete),g.error=j(g.error),delete g.worker,v.postMessage({input:m,config:g,workerId:v.id})},c.unparse=function(m,g){var v=!1,C=!0,T=",",P=`\r
`,M='"',H=M+M,ie=!1,$=null,V=!1,I=((()=>{if(typeof g=="object"){if(typeof g.delimiter!="string"||c.BAD_DELIMITERS.filter(function(G){return g.delimiter.indexOf(G)!==-1}).length||(T=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"&&(P=g.newline),typeof g.quoteChar=="string"&&(M=g.quoteChar),typeof g.header=="boolean"&&(C=g.header),Array.isArray(g.columns)){if(g.columns.length===0)throw new Error("Option columns is empty");$=g.columns}g.escapeChar!==void 0&&(H=g.escapeChar+M),g.escapeFormulae instanceof RegExp?V=g.escapeFormulae:typeof g.escapeFormulae=="boolean"&&g.escapeFormulae&&(V=/^[=+\-@\t\r].*$/)}})(),new RegExp(x(M),"g"));if(typeof m=="string"&&(m=JSON.parse(m)),Array.isArray(m)){if(!m.length||Array.isArray(m[0]))return B(null,m,ie);if(typeof m[0]=="object")return B($||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])),B(m.fields||[],m.data||[],ie);throw new Error("Unable to serialize unrecognized input");function B(G,O,re){var te="",le=(typeof G=="string"&&(G=JSON.parse(G)),typeof O=="string"&&(O=JSON.parse(O)),Array.isArray(G)&&0<G.length),ee=!Array.isArray(O[0]);if(le&&C){for(var W=0;W<G.length;W++)0<W&&(te+=T),te+=R(G[W],W);0<O.length&&(te+=P)}for(var K=0;K<O.length;K++){var ne=(le?G:O[K]).length,F=!1,ae=le?Object.keys(O[K]).length===0:O[K].length===0;if(re&&!le&&(F=re==="greedy"?O[K].join("").trim()==="":O[K].length===1&&O[K][0].length===0),re==="greedy"&&le){for(var de=[],Y=0;Y<ne;Y++){var Z=ee?G[Y]:Y;de.push(O[K][Z])}F=de.join("").trim()===""}if(!F){for(var J=0;J<ne;J++){0<J&&!ae&&(te+=T);var _e=le&&ee?G[J]:J;te+=R(O[K][_e],J)}K<O.length-1&&(!re||0<ne&&!ae)&&(te+=P)}}return te}function R(G,O){var re,te;return G==null?"":G.constructor===Date?JSON.stringify(G).slice(1,25):(te=!1,V&&typeof G=="string"&&V.test(G)&&(G="'"+G,te=!0),re=G.toString().replace(I,H),(te=te||v===!0||typeof v=="function"&&v(G,O)||Array.isArray(v)&&v[O]||((le,ee)=>{for(var W=0;W<ee.length;W++)if(-1<le.indexOf(ee[W]))return!0;return!1})(re,c.BAD_DELIMITERS)||-1<re.indexOf(T)||re.charAt(0)===" "||re.charAt(re.length-1)===" ")?M+re+M: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=_,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(P){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 M=0;M<this.files.length;M++)v.push({file:this.files[M],inputElem:this,instanceConfig:a.extend({},g)})}),C(),this;function C(){if(v.length===0)j(m.complete)&&m.complete();else{var P,M,H,ie,$=v[0];if(j(m.before)){var V=m.before($.file,$.inputElem);if(typeof V=="object"){if(V.action==="abort")return P="AbortError",M=$.file,H=$.inputElem,ie=V.reason,void(j(m.error)&&m.error({name:P},M,H,ie));if(V.action==="skip")return void T();typeof V.config=="object"&&($.instanceConfig=a.extend($.instanceConfig,V.config))}else if(V==="skip")return void T()}var I=$.instanceConfig.complete;$.instanceConfig.complete=function(B){j(I)&&I(B,$.file,$.inputElem),T()},c.parse($.file,$.instanceConfig)}}function T(){v.splice(0,1),C()}}),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})})(Ln);var Sc=Ln.exports;const kc=Zt(Sc),Ec=({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),_=async()=>{try{s(!0),a(null),b(null);const N=await Nc.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(j=>({row:j.row,error:j.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 j=>{var C;const m=(C=j.target)==null?void 0:C.result,{data:g,errors:v}=kc.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)},[]),E=y.useCallback(N=>{N.preventDefault(),N.stopPropagation(),f(!1)},[]),k=y.useCallback(N=>{N.preventDefault(),N.stopPropagation(),f(!1);const S=N.dataTransfer.files[0];S&&x(S)},[]),A=N=>{var j;const S=(j=N.target.files)==null?void 0:j[0];S&&x(S),N.target.value=""};return t.jsxs("div",{className:"space-y-4",children:[t.jsx("div",{onDragOver:w,onDragLeave:E,onDrop:k,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(Kt,{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:_,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 Tc({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,_;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:E}=await D.from("playlists").select("*",{count:"exact",head:!0}).or(`last_synced_at.is.null,last_synced_at.lt.${x}`);if(E)throw console.error("Error getting playlist count:",E),E;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 k=1e3,A=5,N=1e3,S=3e4;let j=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(k);g&&(v=v.gt("id",g));const{data:C,error:T}=await v;if(T)throw console.error("Error fetching playlists:",T),T;if(!C||C.length===0){console.log("No more playlists to process");break}console.log(`Processing page of ${C.length} playlists${g?` after ID ${g}`:""}`),g=C[C.length-1].id;for(let P=0;P<C.length;P+=A){if((_=u.current)!=null&&_.signal.aborted)throw new Error("Sync cancelled");const M=C.slice(P,Math.min(P+A,C.length)),H=Math.floor((m+P)/A)+1,ie=Math.ceil(w/A);console.log(`Processing batch ${H} of ${ie}`);try{const $=await Promise.allSettled(M.map(async B=>{var R,G,O,re,te,le;try{console.log(`Fetching details for playlist ${B.spotify_id}`);const ee=await Xs(B.spotify_id);if(!ee)throw console.error(`No data returned for playlist ${B.spotify_id}`),new Error("Playlist not found on Spotify");return console.log(`Successfully fetched details for playlist ${B.spotify_id}`),{id:B.id,name:ee.name,description:ee.description||"",image_url:((R=ee.images[0])==null?void 0:R.url)||"",followers:((G=ee.followers)==null?void 0:G.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 ${B.spotify_id}:`,ee),ee}}));j=N;let V=0,I=0;for(const B of $)if(B.status==="fulfilled"){const{error:R}=await D.from("playlists").update(B.value).eq("id",B.value.id);R?(console.error("Failed to update playlist:",R),I++):(console.log(`Successfully updated playlist ${B.value.id}`),V++)}else{console.error("Batch update failed:",B.reason);const R=B.reason instanceof Error?B.reason.message:"Unknown error";console.error("Detailed error:",{message:R,fullError:B.reason}),I++}c(B=>({current:m+P+M.length,updated:((B==null?void 0:B.updated)||0)+V,failed:((B==null?void 0:B.failed)||0)+I,total:w}))}catch($){if($ instanceof Error&&$.message.includes("rate limit")){console.log(`Rate limit hit. Waiting ${j/1e3} seconds before retrying...`),await new Promise(V=>setTimeout(V,j)),j=Math.min(j*2,S),P-=A;continue}throw $}await new Promise($=>setTimeout($,j))}m+=C.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(mt,{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(Qe,{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(mt,{className:"w-5 h-5"}),"Start Sync"]})]})]})]})})]})}function Pc(){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(Tc,{onComplete:()=>e({type:"success",message:"Successfully synced playlists with Spotify"})}),t.jsxs(jc,{defaultValue:"playlists",className:"space-y-6",children:[t.jsxs(Dn,{children:[t.jsx(Fs,{value:"playlists",children:"Playlists"}),t.jsx(Fs,{value:"genres",children:"Genres & Sub-genres"})]}),t.jsx(Us,{value:"playlists",children:t.jsx(Ec,{onSuccess:()=>e({type:"success",message:"Successfully imported playlists"})})}),t.jsx(Us,{value:"genres",children:t.jsx(_c,{onSuccess:()=>e({type:"success",message:"Successfully imported genres and sub-genres"})})})]})]}),r&&t.jsx(Re,{message:r.message,type:r.type,onClose:()=>e(null)})]})}function Ac({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 Oc(){return{success:!0}}function $c(){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,_]=y.useState(null),[x,w]=y.useState(null),E=async S=>{if(S.preventDefault(),s!==a){_({type:"error",message:"New passwords do not match"});return}l(!0);try{_({type:"success",message:"Password updated successfully"}),e(""),n(""),i("")}catch(j){console.error("Failed to update password:",j),_({type:"error",message:"Failed to update password"})}finally{l(!1)}},k=async()=>{c(!0);try{await Oc(),_({type:"success",message:"Genres and sub-genres have been set up successfully"})}catch(S){console.error("Failed to setup genres:",S),_({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:j}=await D.from("playlists").select("*",{count:"exact",head:!0});if(j)throw j;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:C,error:T}=await D.from("playlists").select("id, description").range(g,g+v-1);if(T)throw T;if(!C||C.length===0){m=!1;break}for(const P of C){const{description:M,extractedEmail:H}=$n(P.description);if(M!==P.description||H){const{error:ie}=await D.from("playlists").update({description:M,curator_email:H,updated_at:new Date().toISOString()}).eq("id",P.id);if(ie){console.error(`Failed to update playlist ${P.id}:`,ie);continue}w($=>$?{...$,updated:$.updated+1}:null)}w(ie=>ie?{...ie,processed:ie.processed+1}:null)}g+=v}_({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),_({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:k,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(mt,{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(fl,{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:E,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(ul,{className:"w-5 h-5"}),o?"Updating...":"Update Password"]})]})]})]}),t.jsx(Ac,{isOpen:f,onClose:()=>p(!1),onConfirm:N,isCleaning:u,progress:x}),b&&t.jsx(Re,{message:b.message,type:b.type,onClose:()=>_(null)})]})}function Ic(){var p,b;const[r,e]=y.useState(""),[s,n]=y.useState(""),[a,i]=y.useState(""),[o,l]=y.useState(!1),d=We(),c=et(),{signIn:u}=Js(),h=((b=(p=c.state)==null?void 0:p.from)==null?void 0:b.pathname)||"/admin",f=async _=>{_.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(ol,{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:_=>e(_.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:_=>n(_.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 Rc(){return t.jsx(Cn,{children:t.jsx("div",{className:"min-h-screen flex flex-col",children:t.jsxs(Xn,{children:[t.jsx(ue,{path:"/",element:t.jsxs(t.Fragment,{children:[t.jsx(Ae,{}),t.jsx(_l,{}),t.jsx(Oe,{})]})}),t.jsx(ue,{path:"/playlists",element:t.jsxs(t.Fragment,{children:[t.jsx(Ae,{}),t.jsx(Zl,{}),t.jsx(Oe,{})]})}),t.jsx(ue,{path:"/submit",element:t.jsxs(t.Fragment,{children:[t.jsx(Ae,{}),t.jsx(Ql,{}),t.jsx(Oe,{})]})}),t.jsx(ue,{path:"/submit/genre",element:t.jsxs(t.Fragment,{children:[t.jsx(Ae,{}),t.jsx(Xl,{}),t.jsx(Oe,{})]})}),t.jsx(ue,{path:"/playlist/:slug/*",element:t.jsxs(t.Fragment,{children:[t.jsx(Ae,{}),t.jsx(Vl,{}),t.jsx(Oe,{})]})}),t.jsx(ue,{path:"/genres",element:t.jsxs(t.Fragment,{children:[t.jsx(Ae,{}),t.jsx(ac,{}),t.jsx(Oe,{})]})}),t.jsx(ue,{path:"/genre/:genre",element:t.jsxs(t.Fragment,{children:[t.jsx(Ae,{}),t.jsx(sc,{}),t.jsx(Oe,{})]})}),t.jsx(ue,{path:"/genre/:genre/:subGenre",element:t.jsxs(t.Fragment,{children:[t.jsx(Ae,{}),t.jsx(nc,{}),t.jsx(Oe,{})]})}),t.jsx(ue,{path:"/about",element:t.jsxs(t.Fragment,{children:[t.jsx(Ae,{}),t.jsx(ic,{}),t.jsx(Oe,{})]})}),t.jsx(ue,{path:"/for-curators",element:t.jsxs(t.Fragment,{children:[t.jsx(Ae,{}),t.jsx(oc,{}),t.jsx(Oe,{})]})}),t.jsx(ue,{path:"/admin/login",element:t.jsx(Ic,{})}),t.jsxs(ue,{path:"/admin",element:t.jsx(cc,{}),children:[t.jsx(ue,{index:!0,element:t.jsx(uc,{})}),t.jsx(ue,{path:"playlists",element:t.jsx(gc,{})}),t.jsx(ue,{path:"submissions",element:t.jsx(yc,{})}),t.jsx(ue,{path:"genres",element:t.jsx(vc,{})}),t.jsx(ue,{path:"import",element:t.jsx(Pc,{})}),t.jsx(ue,{path:"settings",element:t.jsx($c,{})})]}),t.jsx(ue,{path:"*",element:t.jsx(Fr,{to:"/",replace:!0})})]})})})}const Dc={};Ur(document.getElementById("root")).render(t.jsx(y.StrictMode,{children:t.jsx(Wr,{context:Dc,children:t.jsx(ea,{children:t.jsx(Ko,{children:t.jsx(Cn,{children:t.jsx(Rc,{})})})})})}));export{ce as L,Ys as P,bt as S,Re as T,ec as u};
//# sourceMappingURL=index-beUvGvb6.js.map