const __vite__mapDeps=(i,m=__vite__mapDeps,d=(m.f||(m.f=["assets/FeaturedPlaylists-BAdlXALt.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 Xn=Object.defineProperty;var ea=(s,e,r)=>e in s?Xn(s,e,{enumerable:!0,configurable:!0,writable:!0,value:r}):s[e]=r;var Ae=(s,e,r)=>ea(s,typeof e!="symbol"?e+"":e,r);import{j as t,u as ta,C as sa,a as ra,b as pr,D as na,c as aa,S as ia,v as oa,s as la,K as ca,P as da,L as Vr,T as Jr,d as Yr,R as ua}from"./ui-vendor-DYHpVWUc.js";import{a as Qr,g as is,r as b,R as Ze,c as ha,d as Ee,L as J,u as it,e as Xe,f as Zr,h as Bt,N as Xr,O as fa,i as ma,j as he,B as ga}from"./react-vendor-Dv0pxvir.js";(function(){const e=document.createElement("link").relList;if(e&&e.supports&&e.supports("modulepreload"))return;for(const a of document.querySelectorAll('link[rel="modulepreload"]'))n(a);new MutationObserver(a=>{for(const i of a)if(i.type==="childList")for(const o of i.addedNodes)o.tagName==="LINK"&&o.rel==="modulepreload"&&n(o)}).observe(document,{childList:!0,subtree:!0});function r(a){const i={};return a.integrity&&(i.integrity=a.integrity),a.referrerPolicy&&(i.referrerPolicy=a.referrerPolicy),a.crossOrigin==="use-credentials"?i.credentials="include":a.crossOrigin==="anonymous"?i.credentials="omit":i.credentials="same-origin",i}function n(a){if(a.ep)return;a.ep=!0;const i=r(a);fetch(a.href,i)}})();var en,xr=Qr;en=xr.createRoot,xr.hydrateRoot;var pa=typeof Element<"u",xa=typeof Map=="function",ya=typeof Set=="function",ba=typeof ArrayBuffer=="function"&&!!ArrayBuffer.isView;function Qt(s,e){if(s===e)return!0;if(s&&e&&typeof s=="object"&&typeof e=="object"){if(s.constructor!==e.constructor)return!1;var r,n,a;if(Array.isArray(s)){if(r=s.length,r!=e.length)return!1;for(n=r;n--!==0;)if(!Qt(s[n],e[n]))return!1;return!0}var i;if(xa&&s instanceof Map&&e instanceof Map){if(s.size!==e.size)return!1;for(i=s.entries();!(n=i.next()).done;)if(!e.has(n.value[0]))return!1;for(i=s.entries();!(n=i.next()).done;)if(!Qt(n.value[1],e.get(n.value[0])))return!1;return!0}if(ya&&s instanceof Set&&e instanceof Set){if(s.size!==e.size)return!1;for(i=s.entries();!(n=i.next()).done;)if(!e.has(n.value[0]))return!1;return!0}if(ba&&ArrayBuffer.isView(s)&&ArrayBuffer.isView(e)){if(r=s.length,r!=e.length)return!1;for(n=r;n--!==0;)if(s[n]!==e[n])return!1;return!0}if(s.constructor===RegExp)return s.source===e.source&&s.flags===e.flags;if(s.valueOf!==Object.prototype.valueOf&&typeof s.valueOf=="function"&&typeof e.valueOf=="function")return s.valueOf()===e.valueOf();if(s.toString!==Object.prototype.toString&&typeof s.toString=="function"&&typeof e.toString=="function")return s.toString()===e.toString();if(a=Object.keys(s),r=a.length,r!==Object.keys(e).length)return!1;for(n=r;n--!==0;)if(!Object.prototype.hasOwnProperty.call(e,a[n]))return!1;if(pa&&s instanceof Element)return!1;for(n=r;n--!==0;)if(!((a[n]==="_owner"||a[n]==="__v"||a[n]==="__o")&&s.$$typeof)&&!Qt(s[a[n]],e[a[n]]))return!1;return!0}return s!==s&&e!==e}var wa=function(e,r){try{return Qt(e,r)}catch(n){if((n.message||"").match(/stack|recursion/i))return console.warn("react-fast-compare cannot handle circular refs"),!1;throw n}};const va=is(wa);var ja=function(s,e,r,n,a,i,o,l){if(!s){var d;if(e===void 0)d=new Error("Minified exception occurred; use the non-minified dev environment for the full error message and additional helpful warnings.");else{var c=[r,n,a,i,o,l],u=0;d=new Error(e.replace(/%s/g,function(){return c[u++]})),d.name="Invariant Violation"}throw d.framesToPop=1,d}},_a=ja;const yr=is(_a);var Na=function(e,r,n,a){var i=n?n.call(a,e,r):void 0;if(i!==void 0)return!!i;if(e===r)return!0;if(typeof e!="object"||!e||typeof r!="object"||!r)return!1;var o=Object.keys(e),l=Object.keys(r);if(o.length!==l.length)return!1;for(var d=Object.prototype.hasOwnProperty.bind(r),c=0;c<o.length;c++){var u=o[c];if(!d(u))return!1;var h=e[u],f=r[u];if(i=n?n.call(a,h,f,u):void 0,i===!1||i===void 0&&h!==f)return!1}return!0};const Sa=is(Na);var tn=(s=>(s.BASE="base",s.BODY="body",s.HEAD="head",s.HTML="html",s.LINK="link",s.META="meta",s.NOSCRIPT="noscript",s.SCRIPT="script",s.STYLE="style",s.TITLE="title",s.FRAGMENT="Symbol(react.fragment)",s))(tn||{}),bs={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"]}},br=Object.values(tn),Zs={accesskey:"accessKey",charset:"charSet",class:"className",contenteditable:"contentEditable",contextmenu:"contextMenu","http-equiv":"httpEquiv",itemprop:"itemProp",tabindex:"tabIndex"},ka=Object.entries(Zs).reduce((s,[e,r])=>(s[r]=e,s),{}),Ie="data-rh",xt={DEFAULT_TITLE:"defaultTitle",DEFER:"defer",ENCODE_SPECIAL_CHARACTERS:"encodeSpecialCharacters",ON_CHANGE_CLIENT_STATE:"onChangeClientState",TITLE_TEMPLATE:"titleTemplate",PRIORITIZE_SEO_TAGS:"prioritizeSeoTags"},yt=(s,e)=>{for(let r=s.length-1;r>=0;r-=1){const n=s[r];if(Object.prototype.hasOwnProperty.call(n,e))return n[e]}return null},Ea=s=>{let e=yt(s,"title");const r=yt(s,xt.TITLE_TEMPLATE);if(Array.isArray(e)&&(e=e.join("")),r&&e)return r.replace(/%s/g,()=>e);const n=yt(s,xt.DEFAULT_TITLE);return e||n||void 0},Ca=s=>yt(s,xt.ON_CHANGE_CLIENT_STATE)||(()=>{}),ws=(s,e)=>e.filter(r=>typeof r[s]<"u").map(r=>r[s]).reduce((r,n)=>({...r,...n}),{}),Ta=(s,e)=>e.filter(r=>typeof r.base<"u").map(r=>r.base).reverse().reduce((r,n)=>{if(!r.length){const a=Object.keys(n);for(let i=0;i<a.length;i+=1){const l=a[i].toLowerCase();if(s.indexOf(l)!==-1&&n[l])return r.concat(n)}}return r},[]),Pa=s=>console&&typeof console.warn=="function"&&console.warn(s),Tt=(s,e,r)=>{const n={};return r.filter(a=>Array.isArray(a[s])?!0:(typeof a[s]<"u"&&Pa(`Helmet: ${s} should be of type "Array". Instead found type "${typeof a[s]}"`),!1)).map(a=>a[s]).reverse().reduce((a,i)=>{const o={};i.filter(d=>{let c;const u=Object.keys(d);for(let f=0;f<u.length;f+=1){const p=u[f],v=p.toLowerCase();e.indexOf(v)!==-1&&!(c==="rel"&&d[c].toLowerCase()==="canonical")&&!(v==="rel"&&d[v].toLowerCase()==="stylesheet")&&(c=v),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()},Aa=(s,e)=>{if(Array.isArray(s)&&s.length){for(let r=0;r<s.length;r+=1)if(s[r][e])return!0}return!1},Oa=s=>({baseTag:Ta(["href"],s),bodyAttributes:ws("bodyAttributes",s),defer:yt(s,xt.DEFER),encode:yt(s,xt.ENCODE_SPECIAL_CHARACTERS),htmlAttributes:ws("htmlAttributes",s),linkTags:Tt("link",["rel","href"],s),metaTags:Tt("meta",["name","charset","http-equiv","property","itemprop"],s),noscriptTags:Tt("noscript",["innerHTML"],s),onChangeClientState:Ca(s),scriptTags:Tt("script",["src","innerHTML"],s),styleTags:Tt("style",["cssText"],s),title:Ea(s),titleAttributes:ws("titleAttributes",s),prioritizeSeoTags:Aa(s,xt.PRIORITIZE_SEO_TAGS)}),sn=s=>Array.isArray(s)?s.join(""):s,La=(s,e)=>{const r=Object.keys(s);for(let n=0;n<r.length;n+=1)if(e[r[n]]&&e[r[n]].includes(s[r[n]]))return!0;return!1},vs=(s,e)=>Array.isArray(s)?s.reduce((r,n)=>(La(n,e)?r.priority.push(n):r.default.push(n),r),{priority:[],default:[]}):{default:s,priority:[]},wr=(s,e)=>({...s,[e]:void 0}),Ia=["noscript","script","style"],Os=(s,e=!0)=>e===!1?String(s):String(s).replace(/&/g,"&").replace(/</g,"<").replace(/>/g,">").replace(/"/g,""").replace(/'/g,"'"),rn=s=>Object.keys(s).reduce((e,r)=>{const n=typeof s[r]<"u"?`${r}="${s[r]}"`:`${r}`;return e?`${e} ${n}`:n},""),Ra=(s,e,r,n)=>{const a=rn(r),i=sn(e);return a?`<${s} ${Ie}="true" ${a}>${Os(i,n)}</${s}>`:`<${s} ${Ie}="true">${Os(i,n)}</${s}>`},Da=(s,e,r=!0)=>e.reduce((n,a)=>{const i=a,o=Object.keys(i).filter(c=>!(c==="innerHTML"||c==="cssText")).reduce((c,u)=>{const h=typeof i[u]>"u"?u:`${u}="${Os(i[u],r)}"`;return c?`${c} ${h}`:h},""),l=i.innerHTML||i.cssText||"",d=Ia.indexOf(s)===-1;return`${n}<${s} ${Ie}="true" ${o}${d?"/>":`>${l}</${s}>`}`},""),nn=(s,e={})=>Object.keys(s).reduce((r,n)=>{const a=Zs[n];return r[a||n]=s[n],r},e),$a=(s,e,r)=>{const n={key:e,[Ie]:!0},a=nn(r,n);return[Ze.createElement("title",a,e)]},Zt=(s,e)=>e.map((r,n)=>{const a={key:n,[Ie]:!0};return Object.keys(r).forEach(i=>{const l=Zs[i]||i;if(l==="innerHTML"||l==="cssText"){const d=r.innerHTML||r.cssText;a.dangerouslySetInnerHTML={__html:d}}else a[l]=r[i]}),Ze.createElement(s,a)}),Te=(s,e,r=!0)=>{switch(s){case"title":return{toComponent:()=>$a(s,e.title,e.titleAttributes),toString:()=>Ra(s,e.title,e.titleAttributes,r)};case"bodyAttributes":case"htmlAttributes":return{toComponent:()=>nn(e),toString:()=>rn(e)};default:return{toComponent:()=>Zt(s,e),toString:()=>Da(s,e,r)}}},Ua=({metaTags:s,linkTags:e,scriptTags:r,encode:n})=>{const a=vs(s,bs.meta),i=vs(e,bs.link),o=vs(r,bs.script);return{priorityMethods:{toComponent:()=>[...Zt("meta",a.priority),...Zt("link",i.priority),...Zt("script",o.priority)],toString:()=>`${Te("meta",a.priority,n)} ${Te("link",i.priority,n)} ${Te("script",o.priority,n)}`},metaTags:a.default,linkTags:i.default,scriptTags:o.default}},Ba=s=>{const{baseTag:e,bodyAttributes:r,encode:n=!0,htmlAttributes:a,noscriptTags:i,styleTags:o,title:l="",titleAttributes:d,prioritizeSeoTags:c}=s;let{linkTags:u,metaTags:h,scriptTags:f}=s,p={toComponent:()=>{},toString:()=>""};return c&&({priorityMethods:p,linkTags:u,metaTags:h,scriptTags:f}=Ua(s)),{priority:p,base:Te("base",e,n),bodyAttributes:Te("bodyAttributes",r,n),htmlAttributes:Te("htmlAttributes",a,n),link:Te("link",u,n),meta:Te("meta",h,n),noscript:Te("noscript",i,n),script:Te("script",f,n),style:Te("style",o,n),title:Te("title",{title:l,titleAttributes:d},n)}},Ls=Ba,Ht=[],an=!!(typeof window<"u"&&window.document&&window.document.createElement),Is=class{constructor(s,e){Ae(this,"instances",[]);Ae(this,"canUseDOM",an);Ae(this,"context");Ae(this,"value",{setHelmet:s=>{this.context.helmet=s},helmetInstances:{get:()=>this.canUseDOM?Ht:this.instances,add:s=>{(this.canUseDOM?Ht:this.instances).push(s)},remove:s=>{const e=(this.canUseDOM?Ht:this.instances).indexOf(s);(this.canUseDOM?Ht:this.instances).splice(e,1)}}});this.context=s,this.canUseDOM=e||!1,e||(s.helmet=Ls({baseTag:[],bodyAttributes:{},htmlAttributes:{},linkTags:[],metaTags:[],noscriptTags:[],scriptTags:[],styleTags:[],title:"",titleAttributes:{}}))}},Ma={},on=Ze.createContext(Ma),at,ln=(at=class extends b.Component{constructor(r){super(r);Ae(this,"helmetData");this.helmetData=new Is(this.props.context||{},at.canUseDOM)}render(){return Ze.createElement(on.Provider,{value:this.helmetData.value},this.props.children)}},Ae(at,"canUseDOM",an),at),ct=(s,e)=>{const r=document.head||document.querySelector("head"),n=r.querySelectorAll(`${s}[${Ie}]`),a=[].slice.call(n),i=[];let o;return e&&e.length&&e.forEach(l=>{const d=document.createElement(s);for(const c in l)if(Object.prototype.hasOwnProperty.call(l,c))if(c==="innerHTML")d.innerHTML=l.innerHTML;else if(c==="cssText")d.styleSheet?d.styleSheet.cssText=l.cssText:d.appendChild(document.createTextNode(l.cssText));else{const u=c,h=typeof l[u]>"u"?"":l[u];d.setAttribute(c,h)}d.setAttribute(Ie,"true"),a.some((c,u)=>(o=u,d.isEqualNode(c)))?a.splice(o,1):i.push(d)}),a.forEach(l=>{var d;return(d=l.parentNode)==null?void 0:d.removeChild(l)}),i.forEach(l=>r.appendChild(l)),{oldTags:a,newTags:i}},Rs=(s,e)=>{const r=document.getElementsByTagName(s)[0];if(!r)return;const n=r.getAttribute(Ie),a=n?n.split(","):[],i=[...a],o=Object.keys(e);for(const l of o){const d=e[l]||"";r.getAttribute(l)!==d&&r.setAttribute(l,d),a.indexOf(l)===-1&&a.push(l);const c=i.indexOf(l);c!==-1&&i.splice(c,1)}for(let l=i.length-1;l>=0;l-=1)r.removeAttribute(i[l]);a.length===i.length?r.removeAttribute(Ie):r.getAttribute(Ie)!==o.join(",")&&r.setAttribute(Ie,o.join(","))},Fa=(s,e)=>{typeof s<"u"&&document.title!==s&&(document.title=sn(s)),Rs("title",e)},vr=(s,e)=>{const{baseTag:r,bodyAttributes:n,htmlAttributes:a,linkTags:i,metaTags:o,noscriptTags:l,onChangeClientState:d,scriptTags:c,styleTags:u,title:h,titleAttributes:f}=s;Rs("body",n),Rs("html",a),Fa(h,f);const p={baseTag:ct("base",r),linkTags:ct("link",i),metaTags:ct("meta",o),noscriptTags:ct("noscript",l),scriptTags:ct("script",c),styleTags:ct("style",u)},v={},w={};Object.keys(p).forEach(x=>{const{newTags:y,oldTags:P}=p[x];y.length&&(v[x]=y),P.length&&(w[x]=p[x].oldTags)}),e&&e(),d(s,v,w)},Pt=null,qa=s=>{Pt&&cancelAnimationFrame(Pt),s.defer?Pt=requestAnimationFrame(()=>{vr(s,()=>{Pt=null})}):(vr(s),Pt=null)},Ga=qa,jr=class extends b.Component{constructor(){super(...arguments);Ae(this,"rendered",!1)}shouldComponentUpdate(e){return!Sa(e,this.props)}componentDidUpdate(){this.emitChange()}componentWillUnmount(){const{helmetInstances:e}=this.props.context;e.remove(this),this.emitChange()}emitChange(){const{helmetInstances:e,setHelmet:r}=this.props.context;let n=null;const a=Oa(e.get().map(i=>{const o={...i.props};return delete o.context,o}));ln.canUseDOM?Ga(a):Ls&&(n=Ls(a)),r(n)}init(){if(this.rendered)return;this.rendered=!0;const{helmetInstances:e}=this.props.context;e.add(this),this.emitChange()}render(){return this.init(),null}},As,Ka=(As=class extends b.Component{shouldComponentUpdate(s){return!va(wr(this.props,"helmetData"),wr(s,"helmetData"))}mapNestedChildrenToProps(s,e){if(!e)return null;switch(s.type){case"script":case"noscript":return{innerHTML:e};case"style":return{cssText:e};default:throw new Error(`<${s.type} /> elements are self-closing and can not contain children. Refer to our API for more information.`)}}flattenArrayTypeChildren(s,e,r,n){return{...e,[s.type]:[...e[s.type]||[],{...r,...this.mapNestedChildrenToProps(s,n)}]}}mapObjectTypeChildren(s,e,r,n){switch(s.type){case"title":return{...e,[s.type]:n,titleAttributes:{...r}};case"body":return{...e,bodyAttributes:{...r}};case"html":return{...e,htmlAttributes:{...r}};default:return{...e,[s.type]:{...r}}}}mapArrayTypeChildrenToProps(s,e){let r={...e};return Object.keys(s).forEach(n=>{r={...r,[n]:s[n]}}),r}warnOnInvalidChildren(s,e){return yr(br.some(r=>s.type===r),typeof s.type=="function"?"You may be attempting to nest <Helmet> components within each other, which is not allowed. Refer to our API for more information.":`Only elements types ${br.join(", ")} are allowed. Helmet does not support rendering <${s.type}> elements. Refer to our API for more information.`),yr(!e||typeof e=="string"||Array.isArray(e)&&!e.some(r=>typeof r!="string"),`Helmet expects a string as a child of <${s.type}>. Did you forget to wrap your children in braces? ( <${s.type}>{\`\`}</${s.type}> ) Refer to our API for more information.`),!0}mapChildrenToProps(s,e){let r={};return Ze.Children.forEach(s,n=>{if(!n||!n.props)return;const{children:a,...i}=n.props,o=Object.keys(i).reduce((d,c)=>(d[ka[c]||c]=i[c],d),{});let{type:l}=n;switch(typeof l=="symbol"?l=l.toString():this.warnOnInvalidChildren(n,a),l){case"Symbol(react.fragment)":e=this.mapChildrenToProps(a,e);break;case"link":case"meta":case"noscript":case"script":case"style":r=this.flattenArrayTypeChildren(n,r,o,a);break;default:e=this.mapObjectTypeChildren(n,e,o,a);break}}),this.mapArrayTypeChildrenToProps(r,e)}render(){const{children:s,...e}=this.props;let r={...e},{helmetData:n}=e;if(s&&(r=this.mapChildrenToProps(s,r)),n&&!(n instanceof Is)){const a=n;n=new Is(a.context,!0),delete r.helmetData}return n?Ze.createElement(jr,{...r,context:n.value}):Ze.createElement(on.Consumer,null,a=>Ze.createElement(jr,{...r,context:a}))}},Ae(As,"defaultProps",{defer:!0,encodeSpecialCharacters:!0,prioritizeSeoTags:!1}),As);const Ha="modulepreload",za=function(s){return"/"+s},_r={},Ve=function(e,r,n){let a=Promise.resolve();if(r&&r.length>0){document.getElementsByTagName("link");const o=document.querySelector("meta[property=csp-nonce]"),l=(o==null?void 0:o.nonce)||(o==null?void 0:o.getAttribute("nonce"));a=Promise.allSettled(r.map(d=>{if(d=za(d),d in _r)return;_r[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":Ha,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)})},Wa=s=>{let e;return s?e=s:typeof fetch>"u"?e=(...r)=>Ve(async()=>{const{default:n}=await Promise.resolve().then(()=>Nt);return{default:n}},void 0).then(({default:n})=>n(...r)):e=fetch,(...r)=>e(...r)};class Xs extends Error{constructor(e,r="FunctionsError",n){super(e),this.name=r,this.context=n}}class Va extends Xs{constructor(e){super("Failed to send a request to the Edge Function","FunctionsFetchError",e)}}class Ja extends Xs{constructor(e){super("Relay Error invoking the Edge Function","FunctionsRelayError",e)}}class Ya extends Xs{constructor(e){super("Edge Function returned a non-2xx status code","FunctionsHttpError",e)}}var Ds;(function(s){s.Any="any",s.ApNortheast1="ap-northeast-1",s.ApNortheast2="ap-northeast-2",s.ApSouth1="ap-south-1",s.ApSoutheast1="ap-southeast-1",s.ApSoutheast2="ap-southeast-2",s.CaCentral1="ca-central-1",s.EuCentral1="eu-central-1",s.EuWest1="eu-west-1",s.EuWest2="eu-west-2",s.EuWest3="eu-west-3",s.SaEast1="sa-east-1",s.UsEast1="us-east-1",s.UsWest1="us-west-1",s.UsWest2="us-west-2"})(Ds||(Ds={}));var Qa=function(s,e,r,n){function a(i){return i instanceof r?i:new r(function(o){o(i)})}return new(r||(r=Promise))(function(i,o){function l(u){try{c(n.next(u))}catch(h){o(h)}}function d(u){try{c(n.throw(u))}catch(h){o(h)}}function c(u){u.done?i(u.value):a(u.value).then(l,d)}c((n=n.apply(s,e||[])).next())})};class Za{constructor(e,{headers:r={},customFetch:n,region:a=Ds.Any}={}){this.url=e,this.headers=r,this.region=a,this.fetch=Wa(n)}setAuth(e){this.headers.Authorization=`Bearer ${e}`}invoke(e,r={}){var n;return Qa(this,void 0,void 0,function*(){try{const{headers:a,method:i,body:o}=r;let l={},{region:d}=r;d||(d=this.region),d&&d!=="any"&&(l["x-region"]=d);let c;o&&(a&&!Object.prototype.hasOwnProperty.call(a,"Content-Type")||!a)&&(typeof Blob<"u"&&o instanceof Blob||o instanceof ArrayBuffer?(l["Content-Type"]="application/octet-stream",c=o):typeof o=="string"?(l["Content-Type"]="text/plain",c=o):typeof FormData<"u"&&o instanceof FormData?c=o:(l["Content-Type"]="application/json",c=JSON.stringify(o)));const u=yield this.fetch(`${this.url}/${e}`,{method:i||"POST",headers:Object.assign(Object.assign(Object.assign({},l),this.headers),a),body:c}).catch(v=>{throw new Va(v)}),h=u.headers.get("x-relay-error");if(h&&h==="true")throw new Ja(u);if(!u.ok)throw new Ya(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 Ne={},er={},os={},Mt={},ls={},cs={},Xa=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")},wt=Xa();const ei=wt.fetch,cn=wt.fetch.bind(wt),dn=wt.Headers,ti=wt.Request,si=wt.Response,Nt=Object.freeze(Object.defineProperty({__proto__:null,Headers:dn,Request:ti,Response:si,default:cn,fetch:ei},Symbol.toStringTag,{value:"Module"})),ri=ha(Nt);var ds={};Object.defineProperty(ds,"__esModule",{value:!0});let ni=class extends Error{constructor(e){super(e.message),this.name="PostgrestError",this.details=e.details,this.hint=e.hint,this.code=e.code}};ds.default=ni;var un=Ee&&Ee.__importDefault||function(s){return s&&s.__esModule?s:{default:s}};Object.defineProperty(cs,"__esModule",{value:!0});const ai=un(ri),ii=un(ds);let oi=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=ai.default:this.fetch=fetch}throwOnError(){return this.shouldThrowOnError=!0,this}setHeader(e,r){return this.headers=Object.assign({},this.headers),this.headers[e]=r,this}then(e,r){this.schema===void 0||(["GET","HEAD"].includes(this.method)?this.headers["Accept-Profile"]=this.schema:this.headers["Content-Profile"]=this.schema),this.method!=="GET"&&this.method!=="HEAD"&&(this.headers["Content-Type"]="application/json");const n=this.fetch;let a=n(this.url.toString(),{method:this.method,headers:this.headers,body:JSON.stringify(this.body),signal:this.signal}).then(async i=>{var o,l,d;let c=null,u=null,h=null,f=i.status,p=i.statusText;if(i.ok){if(this.method!=="HEAD"){const y=await i.text();y===""||(this.headers.Accept==="text/csv"||this.headers.Accept&&this.headers.Accept.includes("application/vnd.pgrst.plan+text")?u=y:u=JSON.parse(y))}const w=(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("/");w&&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 w=await i.text();try{c=JSON.parse(w),Array.isArray(c)&&i.status===404&&(u=[],c=null,f=200,p="OK")}catch{i.status===404&&w===""?(f=204,p="No Content"):c={message:w}}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 ii.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,r)}returns(){return this}overrideTypes(){return this}};cs.default=oi;var li=Ee&&Ee.__importDefault||function(s){return s&&s.__esModule?s:{default:s}};Object.defineProperty(ls,"__esModule",{value:!0});const ci=li(cs);let di=class extends ci.default{select(e){let r=!1;const n=(e??"*").split("").map(a=>/\s/.test(a)&&!r?"":(a==='"'&&(r=!r),a)).join("");return this.url.searchParams.set("select",n),this.headers.Prefer&&(this.headers.Prefer+=","),this.headers.Prefer+="return=representation",this}order(e,{ascending:r=!0,nullsFirst:n,foreignTable:a,referencedTable:i=a}={}){const o=i?`${i}.order`:"order",l=this.url.searchParams.get(o);return this.url.searchParams.set(o,`${l?`${l},`:""}${e}.${r?"asc":"desc"}${n===void 0?"":n?".nullsfirst":".nullslast"}`),this}limit(e,{foreignTable:r,referencedTable:n=r}={}){const a=typeof n>"u"?"limit":`${n}.limit`;return this.url.searchParams.set(a,`${e}`),this}range(e,r,{foreignTable:n,referencedTable:a=n}={}){const i=typeof a>"u"?"offset":`${a}.offset`,o=typeof a>"u"?"limit":`${a}.limit`;return this.url.searchParams.set(i,`${e}`),this.url.searchParams.set(o,`${r-e+1}`),this}abortSignal(e){return this.signal=e,this}single(){return this.headers.Accept="application/vnd.pgrst.object+json",this}maybeSingle(){return this.method==="GET"?this.headers.Accept="application/json":this.headers.Accept="application/vnd.pgrst.object+json",this.isMaybeSingle=!0,this}csv(){return this.headers.Accept="text/csv",this}geojson(){return this.headers.Accept="application/geo+json",this}explain({analyze:e=!1,verbose:r=!1,settings:n=!1,buffers:a=!1,wal:i=!1,format:o="text"}={}){var l;const d=[e?"analyze":null,r?"verbose":null,n?"settings":null,a?"buffers":null,i?"wal":null].filter(Boolean).join("|"),c=(l=this.headers.Accept)!==null&&l!==void 0?l:"application/json";return this.headers.Accept=`application/vnd.pgrst.plan+${o}; for="${c}"; options=${d};`,o==="json"?this:this}rollback(){var e;return((e=this.headers.Prefer)!==null&&e!==void 0?e:"").trim().length>0?this.headers.Prefer+=",tx=rollback":this.headers.Prefer="tx=rollback",this}returns(){return this}};ls.default=di;var ui=Ee&&Ee.__importDefault||function(s){return s&&s.__esModule?s:{default:s}};Object.defineProperty(Mt,"__esModule",{value:!0});const hi=ui(ls);let fi=class extends hi.default{eq(e,r){return this.url.searchParams.append(e,`eq.${r}`),this}neq(e,r){return this.url.searchParams.append(e,`neq.${r}`),this}gt(e,r){return this.url.searchParams.append(e,`gt.${r}`),this}gte(e,r){return this.url.searchParams.append(e,`gte.${r}`),this}lt(e,r){return this.url.searchParams.append(e,`lt.${r}`),this}lte(e,r){return this.url.searchParams.append(e,`lte.${r}`),this}like(e,r){return this.url.searchParams.append(e,`like.${r}`),this}likeAllOf(e,r){return this.url.searchParams.append(e,`like(all).{${r.join(",")}}`),this}likeAnyOf(e,r){return this.url.searchParams.append(e,`like(any).{${r.join(",")}}`),this}ilike(e,r){return this.url.searchParams.append(e,`ilike.${r}`),this}ilikeAllOf(e,r){return this.url.searchParams.append(e,`ilike(all).{${r.join(",")}}`),this}ilikeAnyOf(e,r){return this.url.searchParams.append(e,`ilike(any).{${r.join(",")}}`),this}is(e,r){return this.url.searchParams.append(e,`is.${r}`),this}in(e,r){const n=Array.from(new Set(r)).map(a=>typeof a=="string"&&new RegExp("[,()]").test(a)?`"${a}"`:`${a}`).join(",");return this.url.searchParams.append(e,`in.(${n})`),this}contains(e,r){return typeof r=="string"?this.url.searchParams.append(e,`cs.${r}`):Array.isArray(r)?this.url.searchParams.append(e,`cs.{${r.join(",")}}`):this.url.searchParams.append(e,`cs.${JSON.stringify(r)}`),this}containedBy(e,r){return typeof r=="string"?this.url.searchParams.append(e,`cd.${r}`):Array.isArray(r)?this.url.searchParams.append(e,`cd.{${r.join(",")}}`):this.url.searchParams.append(e,`cd.${JSON.stringify(r)}`),this}rangeGt(e,r){return this.url.searchParams.append(e,`sr.${r}`),this}rangeGte(e,r){return this.url.searchParams.append(e,`nxl.${r}`),this}rangeLt(e,r){return this.url.searchParams.append(e,`sl.${r}`),this}rangeLte(e,r){return this.url.searchParams.append(e,`nxr.${r}`),this}rangeAdjacent(e,r){return this.url.searchParams.append(e,`adj.${r}`),this}overlaps(e,r){return typeof r=="string"?this.url.searchParams.append(e,`ov.${r}`):this.url.searchParams.append(e,`ov.{${r.join(",")}}`),this}textSearch(e,r,{config:n,type:a}={}){let i="";a==="plain"?i="pl":a==="phrase"?i="ph":a==="websearch"&&(i="w");const o=n===void 0?"":`(${n})`;return this.url.searchParams.append(e,`${i}fts${o}.${r}`),this}match(e){return Object.entries(e).forEach(([r,n])=>{this.url.searchParams.append(r,`eq.${n}`)}),this}not(e,r,n){return this.url.searchParams.append(e,`not.${r}.${n}`),this}or(e,{foreignTable:r,referencedTable:n=r}={}){const a=n?`${n}.or`:"or";return this.url.searchParams.append(a,`(${e})`),this}filter(e,r,n){return this.url.searchParams.append(e,`${r}.${n}`),this}};Mt.default=fi;var mi=Ee&&Ee.__importDefault||function(s){return s&&s.__esModule?s:{default:s}};Object.defineProperty(os,"__esModule",{value:!0});const At=mi(Mt);let gi=class{constructor(e,{headers:r={},schema:n,fetch:a}){this.url=e,this.headers=r,this.schema=n,this.fetch=a}select(e,{head:r=!1,count:n}={}){const a=r?"HEAD":"GET";let i=!1;const o=(e??"*").split("").map(l=>/\s/.test(l)&&!i?"":(l==='"'&&(i=!i),l)).join("");return this.url.searchParams.set("select",o),n&&(this.headers.Prefer=`count=${n}`),new At.default({method:a,url:this.url,headers:this.headers,schema:this.schema,fetch:this.fetch,allowEmpty:!1})}insert(e,{count:r,defaultToNull:n=!0}={}){const a="POST",i=[];if(this.headers.Prefer&&i.push(this.headers.Prefer),r&&i.push(`count=${r}`),n||i.push("missing=default"),this.headers.Prefer=i.join(","),Array.isArray(e)){const o=e.reduce((l,d)=>l.concat(Object.keys(d)),[]);if(o.length>0){const l=[...new Set(o)].map(d=>`"${d}"`);this.url.searchParams.set("columns",l.join(","))}}return new At.default({method:a,url:this.url,headers:this.headers,schema:this.schema,body:e,fetch:this.fetch,allowEmpty:!1})}upsert(e,{onConflict:r,ignoreDuplicates:n=!1,count:a,defaultToNull:i=!0}={}){const o="POST",l=[`resolution=${n?"ignore":"merge"}-duplicates`];if(r!==void 0&&this.url.searchParams.set("on_conflict",r),this.headers.Prefer&&l.push(this.headers.Prefer),a&&l.push(`count=${a}`),i||l.push("missing=default"),this.headers.Prefer=l.join(","),Array.isArray(e)){const d=e.reduce((c,u)=>c.concat(Object.keys(u)),[]);if(d.length>0){const c=[...new Set(d)].map(u=>`"${u}"`);this.url.searchParams.set("columns",c.join(","))}}return new At.default({method:o,url:this.url,headers:this.headers,schema:this.schema,body:e,fetch:this.fetch,allowEmpty:!1})}update(e,{count:r}={}){const n="PATCH",a=[];return this.headers.Prefer&&a.push(this.headers.Prefer),r&&a.push(`count=${r}`),this.headers.Prefer=a.join(","),new At.default({method:n,url:this.url,headers:this.headers,schema:this.schema,body:e,fetch:this.fetch,allowEmpty:!1})}delete({count:e}={}){const r="DELETE",n=[];return e&&n.push(`count=${e}`),this.headers.Prefer&&n.unshift(this.headers.Prefer),this.headers.Prefer=n.join(","),new At.default({method:r,url:this.url,headers:this.headers,schema:this.schema,fetch:this.fetch,allowEmpty:!1})}};os.default=gi;var us={},hs={};Object.defineProperty(hs,"__esModule",{value:!0});hs.version=void 0;hs.version="0.0.0-automated";Object.defineProperty(us,"__esModule",{value:!0});us.DEFAULT_HEADERS=void 0;const pi=hs;us.DEFAULT_HEADERS={"X-Client-Info":`postgrest-js/${pi.version}`};var hn=Ee&&Ee.__importDefault||function(s){return s&&s.__esModule?s:{default:s}};Object.defineProperty(er,"__esModule",{value:!0});const xi=hn(os),yi=hn(Mt),bi=us;let wi=class fn{constructor(e,{headers:r={},schema:n,fetch:a}={}){this.url=e,this.headers=Object.assign(Object.assign({},bi.DEFAULT_HEADERS),r),this.schemaName=n,this.fetch=a}from(e){const r=new URL(`${this.url}/${e}`);return new xi.default(r,{headers:Object.assign({},this.headers),schema:this.schemaName,fetch:this.fetch})}schema(e){return new fn(this.url,{headers:this.headers,schema:e,fetch:this.fetch})}rpc(e,r={},{head:n=!1,get:a=!1,count:i}={}){let o;const l=new URL(`${this.url}/rpc/${e}`);let d;n||a?(o=n?"HEAD":"GET",Object.entries(r).filter(([u,h])=>h!==void 0).map(([u,h])=>[u,Array.isArray(h)?`{${h.join(",")}}`:`${h}`]).forEach(([u,h])=>{l.searchParams.append(u,h)})):(o="POST",d=r);const c=Object.assign({},this.headers);return i&&(c.Prefer=`count=${i}`),new yi.default({method:o,url:l,headers:c,schema:this.schemaName,body:d,fetch:this.fetch,allowEmpty:!1})}};er.default=wi;var St=Ee&&Ee.__importDefault||function(s){return s&&s.__esModule?s:{default:s}};Object.defineProperty(Ne,"__esModule",{value:!0});Ne.PostgrestError=Ne.PostgrestBuilder=Ne.PostgrestTransformBuilder=Ne.PostgrestFilterBuilder=Ne.PostgrestQueryBuilder=Ne.PostgrestClient=void 0;const mn=St(er);Ne.PostgrestClient=mn.default;const gn=St(os);Ne.PostgrestQueryBuilder=gn.default;const pn=St(Mt);Ne.PostgrestFilterBuilder=pn.default;const xn=St(ls);Ne.PostgrestTransformBuilder=xn.default;const yn=St(cs);Ne.PostgrestBuilder=yn.default;const bn=St(ds);Ne.PostgrestError=bn.default;var vi=Ne.default={PostgrestClient:mn.default,PostgrestQueryBuilder:gn.default,PostgrestFilterBuilder:pn.default,PostgrestTransformBuilder:xn.default,PostgrestBuilder:yn.default,PostgrestError:bn.default};const{PostgrestClient:ji,PostgrestQueryBuilder:jd,PostgrestFilterBuilder:_d,PostgrestTransformBuilder:Nd,PostgrestBuilder:Sd,PostgrestError:kd}=vi;let $s;typeof window>"u"?$s=require("ws"):$s=window.WebSocket;const _i="2.11.10",Ni={"X-Client-Info":`realtime-js/${_i}`},Si="1.0.0",wn=1e4,ki=1e3;var bt;(function(s){s[s.connecting=0]="connecting",s[s.open=1]="open",s[s.closing=2]="closing",s[s.closed=3]="closed"})(bt||(bt={}));var we;(function(s){s.closed="closed",s.errored="errored",s.joined="joined",s.joining="joining",s.leaving="leaving"})(we||(we={}));var Le;(function(s){s.close="phx_close",s.error="phx_error",s.join="phx_join",s.reply="phx_reply",s.leave="phx_leave",s.access_token="access_token"})(Le||(Le={}));var Us;(function(s){s.websocket="websocket"})(Us||(Us={}));var rt;(function(s){s.Connecting="connecting",s.Open="open",s.Closing="closing",s.Closed="closed"})(rt||(rt={}));class Ei{constructor(){this.HEADER_LENGTH=1}decode(e,r){return e.constructor===ArrayBuffer?r(this._binaryDecode(e)):r(typeof e=="string"?JSON.parse(e):{})}_binaryDecode(e){const r=new DataView(e),n=new TextDecoder;return this._decodeBroadcast(e,r,n)}_decodeBroadcast(e,r,n){const a=r.getUint8(1),i=r.getUint8(2);let o=this.HEADER_LENGTH+2;const l=n.decode(e.slice(o,o+a));o=o+a;const d=n.decode(e.slice(o,o+i));o=o+i;const c=JSON.parse(n.decode(e.slice(o,e.byteLength)));return{ref:null,topic:l,event:d,payload:c}}}class vn{constructor(e,r){this.callback=e,this.timerCalc=r,this.timer=void 0,this.tries=0,this.callback=e,this.timerCalc=r}reset(){this.tries=0,clearTimeout(this.timer)}scheduleTimeout(){clearTimeout(this.timer),this.timer=setTimeout(()=>{this.tries=this.tries+1,this.callback()},this.timerCalc(this.tries+1))}}var oe;(function(s){s.abstime="abstime",s.bool="bool",s.date="date",s.daterange="daterange",s.float4="float4",s.float8="float8",s.int2="int2",s.int4="int4",s.int4range="int4range",s.int8="int8",s.int8range="int8range",s.json="json",s.jsonb="jsonb",s.money="money",s.numeric="numeric",s.oid="oid",s.reltime="reltime",s.text="text",s.time="time",s.timestamp="timestamp",s.timestamptz="timestamptz",s.timetz="timetz",s.tsrange="tsrange",s.tstzrange="tstzrange"})(oe||(oe={}));const Nr=(s,e,r={})=>{var n;const a=(n=r.skipTypes)!==null&&n!==void 0?n:[];return Object.keys(e).reduce((i,o)=>(i[o]=Ci(o,s,e,a),i),{})},Ci=(s,e,r,n)=>{const a=e.find(l=>l.name===s),i=a==null?void 0:a.type,o=r[s];return i&&!n.includes(i)?jn(i,o):Bs(o)},jn=(s,e)=>{if(s.charAt(0)==="_"){const r=s.slice(1,s.length);return Oi(e,r)}switch(s){case oe.bool:return Ti(e);case oe.float4:case oe.float8:case oe.int2:case oe.int4:case oe.int8:case oe.numeric:case oe.oid:return Pi(e);case oe.json:case oe.jsonb:return Ai(e);case oe.timestamp:return Li(e);case oe.abstime:case oe.date:case oe.daterange:case oe.int4range:case oe.int8range:case oe.money:case oe.reltime:case oe.text:case oe.time:case oe.timestamptz:case oe.timetz:case oe.tsrange:case oe.tstzrange:return Bs(e);default:return Bs(e)}},Bs=s=>s,Ti=s=>{switch(s){case"t":return!0;case"f":return!1;default:return s}},Pi=s=>{if(typeof s=="string"){const e=parseFloat(s);if(!Number.isNaN(e))return e}return s},Ai=s=>{if(typeof s=="string")try{return JSON.parse(s)}catch(e){return console.log(`JSON parse error: ${e}`),s}return s},Oi=(s,e)=>{if(typeof s!="string")return s;const r=s.length-1,n=s[r];if(s[0]==="{"&&n==="}"){let i;const o=s.slice(1,r);try{i=JSON.parse("["+o+"]")}catch{i=o?o.split(","):[]}return i.map(l=>jn(e,l))}return s},Li=s=>typeof s=="string"?s.replace(" ","T"):s,_n=s=>{let e=s;return e=e.replace(/^ws/i,"http"),e=e.replace(/(\/socket\/websocket|\/socket|\/websocket)\/?$/i,""),e.replace(/\/+$/,"")};class js{constructor(e,r,n={},a=wn){this.channel=e,this.event=r,this.payload=n,this.timeout=a,this.sent=!1,this.timeoutTimer=void 0,this.ref="",this.receivedResp=null,this.recHooks=[],this.refEvent=null}resend(e){this.timeout=e,this._cancelRefEvent(),this.ref="",this.refEvent=null,this.receivedResp=null,this.sent=!1,this.send()}send(){this._hasReceived("timeout")||(this.startTimeout(),this.sent=!0,this.channel.socket.push({topic:this.channel.topic,event:this.event,payload:this.payload,ref:this.ref,join_ref:this.channel._joinRef()}))}updatePayload(e){this.payload=Object.assign(Object.assign({},this.payload),e)}receive(e,r){var n;return this._hasReceived(e)&&r((n=this.receivedResp)===null||n===void 0?void 0:n.response),this.recHooks.push({status:e,callback:r}),this}startTimeout(){if(this.timeoutTimer)return;this.ref=this.channel.socket._makeRef(),this.refEvent=this.channel._replyEventName(this.ref);const e=r=>{this._cancelRefEvent(),this._cancelTimeout(),this.receivedResp=r,this._matchReceive(r)};this.channel._on(this.refEvent,{},e),this.timeoutTimer=setTimeout(()=>{this.trigger("timeout",{})},this.timeout)}trigger(e,r){this.refEvent&&this.channel._trigger(this.refEvent,{status:e,response:r})}destroy(){this._cancelRefEvent(),this._cancelTimeout()}_cancelRefEvent(){this.refEvent&&this.channel._off(this.refEvent,{})}_cancelTimeout(){clearTimeout(this.timeoutTimer),this.timeoutTimer=void 0}_matchReceive({status:e,response:r}){this.recHooks.filter(n=>n.status===e).forEach(n=>n.callback(r))}_hasReceived(e){return this.receivedResp&&this.receivedResp.status===e}}var Sr;(function(s){s.SYNC="sync",s.JOIN="join",s.LEAVE="leave"})(Sr||(Sr={}));class It{constructor(e,r){this.channel=e,this.state={},this.pendingDiffs=[],this.joinRef=null,this.caller={onJoin:()=>{},onLeave:()=>{},onSync:()=>{}};const n=(r==null?void 0:r.events)||{state:"presence_state",diff:"presence_diff"};this.channel._on(n.state,{},a=>{const{onJoin:i,onLeave:o,onSync:l}=this.caller;this.joinRef=this.channel._joinRef(),this.state=It.syncState(this.state,a,i,o),this.pendingDiffs.forEach(d=>{this.state=It.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=It.syncDiff(this.state,a,i,o),l())}),this.onJoin((a,i,o)=>{this.channel._trigger("presence",{event:"join",key:a,currentPresences:i,newPresences:o})}),this.onLeave((a,i,o)=>{this.channel._trigger("presence",{event:"leave",key:a,currentPresences:i,leftPresences:o})}),this.onSync(()=>{this.channel._trigger("presence",{event:"sync"})})}static syncState(e,r,n,a){const i=this.cloneDeep(e),o=this.transformState(r),l={},d={};return this.map(i,(c,u)=>{o[c]||(d[c]=u)}),this.map(o,(c,u)=>{const h=i[c];if(h){const f=u.map(x=>x.presence_ref),p=h.map(x=>x.presence_ref),v=u.filter(x=>p.indexOf(x.presence_ref)<0),w=h.filter(x=>f.indexOf(x.presence_ref)<0);v.length>0&&(l[c]=v),w.length>0&&(d[c]=w)}else l[c]=u}),this.syncDiff(i,{joins:l,leaves:d},n,a)}static syncDiff(e,r,n,a){const{joins:i,leaves:o}={joins:this.transformState(r.joins),leaves:this.transformState(r.leaves)};return n||(n=()=>{}),a||(a=()=>{}),this.map(i,(l,d)=>{var c;const u=(c=e[l])!==null&&c!==void 0?c:[];if(e[l]=this.cloneDeep(d),u.length>0){const h=e[l].map(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,r){return Object.getOwnPropertyNames(e).map(n=>r(n,e[n]))}static transformState(e){return e=this.cloneDeep(e),Object.getOwnPropertyNames(e).reduce((r,n)=>{const a=e[n];return"metas"in a?r[n]=a.metas.map(i=>(i.presence_ref=i.phx_ref,delete i.phx_ref,delete i.phx_ref_prev,i)):r[n]=a,r},{})}static cloneDeep(e){return JSON.parse(JSON.stringify(e))}onJoin(e){this.caller.onJoin=e}onLeave(e){this.caller.onLeave=e}onSync(e){this.caller.onSync=e}inPendingSyncState(){return!this.joinRef||this.joinRef!==this.channel._joinRef()}}var kr;(function(s){s.ALL="*",s.INSERT="INSERT",s.UPDATE="UPDATE",s.DELETE="DELETE"})(kr||(kr={}));var Er;(function(s){s.BROADCAST="broadcast",s.PRESENCE="presence",s.POSTGRES_CHANGES="postgres_changes",s.SYSTEM="system"})(Er||(Er={}));var ze;(function(s){s.SUBSCRIBED="SUBSCRIBED",s.TIMED_OUT="TIMED_OUT",s.CLOSED="CLOSED",s.CHANNEL_ERROR="CHANNEL_ERROR"})(ze||(ze={}));class tr{constructor(e,r={config:{}},n){this.topic=e,this.params=r,this.socket=n,this.bindings={},this.state=we.closed,this.joinedOnce=!1,this.pushBuffer=[],this.subTopic=e.replace(/^realtime:/i,""),this.params.config=Object.assign({broadcast:{ack:!1,self:!1},presence:{key:""},private:!1},r.config),this.timeout=this.socket.timeout,this.joinPush=new js(this,Le.join,this.params,this.timeout),this.rejoinTimer=new vn(()=>this._rejoinUntilConnected(),this.socket.reconnectAfterMs),this.joinPush.receive("ok",()=>{this.state=we.joined,this.rejoinTimer.reset(),this.pushBuffer.forEach(a=>a.send()),this.pushBuffer=[]}),this._onClose(()=>{this.rejoinTimer.reset(),this.socket.log("channel",`close ${this.topic} ${this._joinRef()}`),this.state=we.closed,this.socket._remove(this)}),this._onError(a=>{this._isLeaving()||this._isClosed()||(this.socket.log("channel",`error ${this.topic}`,a),this.state=we.errored,this.rejoinTimer.scheduleTimeout())}),this.joinPush.receive("timeout",()=>{this._isJoining()&&(this.socket.log("channel",`timeout ${this.topic}`,this.joinPush.timeout),this.state=we.errored,this.rejoinTimer.scheduleTimeout())}),this._on(Le.reply,{},(a,i)=>{this._trigger(this._replyEventName(i),a)}),this.presence=new It(this),this.broadcastEndpointURL=_n(this.socket.endPoint)+"/api/broadcast",this.private=this.params.config.private||!1}subscribe(e,r=this.timeout){var n,a;if(this.socket.isConnected()||this.socket.connect(),this.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(ze.CHANNEL_ERROR,u)),this._onClose(()=>e==null?void 0:e(ze.CLOSED));const d={},c={broadcast:i,presence:o,postgres_changes:(a=(n=this.bindings.postgres_changes)===null||n===void 0?void 0:n.map(u=>u.filter))!==null&&a!==void 0?a:[],private:l};this.socket.accessTokenValue&&(d.access_token=this.socket.accessTokenValue),this.updateJoinPayload(Object.assign({config:c},d)),this.joinedOnce=!0,this._rejoin(r),this.joinPush.receive("ok",async({postgres_changes:u})=>{var h;if(this.socket.setAuth(),u===void 0){e==null||e(ze.SUBSCRIBED);return}else{const f=this.bindings.postgres_changes,p=(h=f==null?void 0:f.length)!==null&&h!==void 0?h:0,v=[];for(let w=0;w<p;w++){const x=f[w],{filter:{event:y,schema:P,table:_,filter:A}}=x,S=u&&u[w];if(S&&S.event===y&&S.schema===P&&S.table===_&&S.filter===A)v.push(Object.assign(Object.assign({},x),{id:S.id}));else{this.unsubscribe(),this.state=we.errored,e==null||e(ze.CHANNEL_ERROR,new Error("mismatch between server and client bindings for postgres changes"));return}}this.bindings.postgres_changes=v,e&&e(ze.SUBSCRIBED);return}}).receive("error",u=>{this.state=we.errored,e==null||e(ze.CHANNEL_ERROR,new Error(JSON.stringify(Object.values(u).join(", ")||"error")))}).receive("timeout",()=>{e==null||e(ze.TIMED_OUT)})}return this}presenceState(){return this.presence.state}async track(e,r={}){return await this.send({type:"presence",event:"track",payload:e},r.timeout||this.timeout)}async untrack(e={}){return await this.send({type:"presence",event:"untrack"},e)}on(e,r,n){return this._on(e,r,n)}async send(e,r={}){var n,a;if(!this._canPush()&&e.type==="broadcast"){const{event:i,payload:o}=e,d={method:"POST",headers:{Authorization:this.socket.accessTokenValue?`Bearer ${this.socket.accessTokenValue}`:"",apikey:this.socket.apiKey?this.socket.apiKey:"","Content-Type":"application/json"},body:JSON.stringify({messages:[{topic:this.subTopic,event:i,payload:o,private:this.private}]})};try{const c=await this._fetchWithTimeout(this.broadcastEndpointURL,d,(n=r.timeout)!==null&&n!==void 0?n:this.timeout);return await((a=c.body)===null||a===void 0?void 0:a.cancel()),c.ok?"ok":"error"}catch(c){return c.name==="AbortError"?"timed out":"error"}}else return new Promise(i=>{var o,l,d;const c=this._push(e.type,e,r.timeout||this.timeout);e.type==="broadcast"&&!(!((d=(l=(o=this.params)===null||o===void 0?void 0:o.config)===null||l===void 0?void 0:l.broadcast)===null||d===void 0)&&d.ack)&&i("ok"),c.receive("ok",()=>i("ok")),c.receive("error",()=>i("error")),c.receive("timeout",()=>i("timed out"))})}updateJoinPayload(e){this.joinPush.updatePayload(e)}unsubscribe(e=this.timeout){this.state=we.leaving;const r=()=>{this.socket.log("channel",`leave ${this.topic}`),this._trigger(Le.close,"leave",this._joinRef())};return this.joinPush.destroy(),new Promise(n=>{const a=new js(this,Le.leave,{},e);a.receive("ok",()=>{r(),n("ok")}).receive("timeout",()=>{r(),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,r,n){const a=new AbortController,i=setTimeout(()=>a.abort(),n),o=await this.socket.fetch(e,Object.assign(Object.assign({},r),{signal:a.signal}));return clearTimeout(i),o}_push(e,r,n=this.timeout){if(!this.joinedOnce)throw`tried to push '${e}' to '${this.topic}' before joining. Use channel.subscribe() before pushing events`;let a=new js(this,e,r,n);return this._canPush()?a.send():(a.startTimeout(),this.pushBuffer.push(a)),a}_onMessage(e,r,n){return r}_isMember(e){return this.topic===e}_joinRef(){return this.joinPush.ref}_trigger(e,r,n){var a,i;const o=e.toLocaleLowerCase(),{close:l,error:d,leave:c,join:u}=Le;if(n&&[l,d,c,u].indexOf(o)>=0&&n!==this._joinRef())return;let f=this._onMessage(o,r,n);if(r&&!f)throw"channel onMessage callbacks must return the payload, modified or unmodified";["insert","update","delete"].includes(o)?(a=this.bindings.postgres_changes)===null||a===void 0||a.filter(p=>{var v,w,x;return((v=p.filter)===null||v===void 0?void 0:v.event)==="*"||((x=(w=p.filter)===null||w===void 0?void 0:w.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 v,w,x,y,P,_;if(["broadcast","presence","postgres_changes"].includes(o))if("id"in p){const A=p.id,S=(v=p.filter)===null||v===void 0?void 0:v.event;return A&&((w=r.ids)===null||w===void 0?void 0:w.includes(A))&&(S==="*"||(S==null?void 0:S.toLocaleLowerCase())===((x=r.data)===null||x===void 0?void 0:x.type.toLocaleLowerCase()))}else{const A=(P=(y=p==null?void 0:p.filter)===null||y===void 0?void 0:y.event)===null||P===void 0?void 0:P.toLocaleLowerCase();return A==="*"||A===((_=r==null?void 0:r.event)===null||_===void 0?void 0:_.toLocaleLowerCase())}else return p.type.toLocaleLowerCase()===o}).map(p=>{if(typeof f=="object"&&"ids"in f){const v=f.data,{schema:w,table:x,commit_timestamp:y,type:P,errors:_}=v;f=Object.assign(Object.assign({},{schema:w,table:x,commit_timestamp:y,eventType:P,new:{},old:{},errors:_}),this._getPayloadRecords(v))}p.callback(f,n)})}_isClosed(){return this.state===we.closed}_isJoined(){return this.state===we.joined}_isJoining(){return this.state===we.joining}_isLeaving(){return this.state===we.leaving}_replyEventName(e){return`chan_reply_${e}`}_on(e,r,n){const a=e.toLocaleLowerCase(),i={type:a,filter:r,callback:n};return this.bindings[a]?this.bindings[a].push(i):this.bindings[a]=[i],this}_off(e,r){const n=e.toLocaleLowerCase();return this.bindings[n]=this.bindings[n].filter(a=>{var i;return!(((i=a.type)===null||i===void 0?void 0:i.toLocaleLowerCase())===n&&tr.isEqual(a.filter,r))}),this}static isEqual(e,r){if(Object.keys(e).length!==Object.keys(r).length)return!1;for(const n in e)if(e[n]!==r[n])return!1;return!0}_rejoinUntilConnected(){this.rejoinTimer.scheduleTimeout(),this.socket.isConnected()&&this._rejoin()}_onClose(e){this._on(Le.close,{},e)}_onError(e){this._on(Le.error,{},r=>e(r))}_canPush(){return this.socket.isConnected()&&this._isJoined()}_rejoin(e=this.timeout){this._isLeaving()||(this.socket._leaveOpenTopic(this.topic),this.state=we.joining,this.joinPush.resend(e))}_getPayloadRecords(e){const r={new:{},old:{}};return(e.type==="INSERT"||e.type==="UPDATE")&&(r.new=Nr(e.columns,e.record)),(e.type==="UPDATE"||e.type==="DELETE")&&(r.old=Nr(e.columns,e.old_record)),r}}const Cr=()=>{},Ii=` addEventListener("message", (e) => { if (e.data.event === "start") { setInterval(() => postMessage({ event: "keepAlive" }), e.data.interval); } });`;class Ri{constructor(e,r){var n;this.accessTokenValue=null,this.apiKey=null,this.channels=new Array,this.endPoint="",this.httpEndpoint="",this.headers=Ni,this.params={},this.timeout=wn,this.heartbeatIntervalMs=25e3,this.heartbeatTimer=void 0,this.pendingHeartbeatRef=null,this.heartbeatCallback=Cr,this.ref=0,this.logger=Cr,this.conn=null,this.sendBuffer=[],this.serializer=new Ei,this.stateChangeCallbacks={open:[],close:[],error:[],message:[]},this.accessToken=null,this._resolveFetch=i=>{let o;return i?o=i:typeof fetch>"u"?o=(...l)=>Ve(async()=>{const{default:d}=await Promise.resolve().then(()=>Nt);return{default:d}},void 0).then(({default:d})=>d(...l)):o=fetch,(...l)=>o(...l)},this.endPoint=`${e}/${Us.websocket}`,this.httpEndpoint=_n(e),r!=null&&r.transport?this.transport=r.transport:this.transport=null,r!=null&&r.params&&(this.params=r.params),r!=null&&r.headers&&(this.headers=Object.assign(Object.assign({},this.headers),r.headers)),r!=null&&r.timeout&&(this.timeout=r.timeout),r!=null&&r.logger&&(this.logger=r.logger),(r!=null&&r.logLevel||r!=null&&r.log_level)&&(this.logLevel=r.logLevel||r.log_level,this.params=Object.assign(Object.assign({},this.params),{log_level:this.logLevel})),r!=null&&r.heartbeatIntervalMs&&(this.heartbeatIntervalMs=r.heartbeatIntervalMs);const a=(n=r==null?void 0:r.params)===null||n===void 0?void 0:n.apikey;if(a&&(this.accessTokenValue=a,this.apiKey=a),this.reconnectAfterMs=r!=null&&r.reconnectAfterMs?r.reconnectAfterMs:i=>[1e3,2e3,5e3,1e4][i-1]||1e4,this.encode=r!=null&&r.encode?r.encode:(i,o)=>o(JSON.stringify(i)),this.decode=r!=null&&r.decode?r.decode:this.serializer.decode.bind(this.serializer),this.reconnectTimer=new vn(async()=>{this.disconnect(),this.connect()},this.reconnectAfterMs),this.fetch=this._resolveFetch(r==null?void 0:r.fetch),r!=null&&r.worker){if(typeof window<"u"&&!window.Worker)throw new Error("Web Worker is not supported");this.worker=(r==null?void 0:r.worker)||!1,this.workerUrl=r==null?void 0:r.workerUrl}this.accessToken=(r==null?void 0:r.accessToken)||null}connect(){if(!this.conn){if(this.transport||(this.transport=$s),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 Di(this.endpointURL(),void 0,{close:()=>{this.conn=null}})}}endpointURL(){return this._appendParams(this.endPoint,Object.assign({},this.params,{vsn:Si}))}disconnect(e,r){this.conn&&(this.conn.onclose=function(){},e?this.conn.close(e,r??""):this.conn.close(),this.conn=null,this.heartbeatTimer&&clearInterval(this.heartbeatTimer),this.reconnectTimer.reset(),this.channels.forEach(n=>n.teardown()))}getChannels(){return this.channels}async removeChannel(e){const r=await e.unsubscribe();return this.channels=this.channels.filter(n=>n._joinRef!==e._joinRef),this.channels.length===0&&this.disconnect(),r}async removeAllChannels(){const e=await Promise.all(this.channels.map(r=>r.unsubscribe()));return this.channels=[],this.disconnect(),e}log(e,r,n){this.logger(e,r,n)}connectionState(){switch(this.conn&&this.conn.readyState){case bt.connecting:return rt.Connecting;case bt.open:return rt.Open;case bt.closing:return rt.Closing;default:return rt.Closed}}isConnected(){return this.connectionState()===rt.Open}channel(e,r={config:{}}){const n=`realtime:${e}`,a=this.getChannels().find(i=>i.topic===n);if(a)return a;{const i=new tr(`realtime:${e}`,r,this);return this.channels.push(i),i}}push(e){const{topic:r,event:n,payload:a,ref:i}=e,o=()=>{this.encode(e,l=>{var d;(d=this.conn)===null||d===void 0||d.send(l)})};this.log("push",`${r} ${n} (${i})`,a),this.isConnected()?o():this.sendBuffer.push(o)}async setAuth(e=null){let r=e||this.accessToken&&await this.accessToken()||this.accessTokenValue;this.accessTokenValue!=r&&(this.accessTokenValue=r,this.channels.forEach(n=>{r&&n.updateJoinPayload({access_token:r,version:this.headers&&this.headers["X-Client-Info"]}),n.joinedOnce&&n._isJoined()&&n._push(Le.access_token,{access_token:r})}))}async sendHeartbeat(){var e;if(!this.isConnected()){this.heartbeatCallback("disconnected");return}if(this.pendingHeartbeatRef){this.pendingHeartbeatRef=null,this.log("transport","heartbeat timeout. Attempting to re-establish connection"),this.heartbeatCallback("timeout"),(e=this.conn)===null||e===void 0||e.close(ki,"hearbeat timeout");return}this.pendingHeartbeatRef=this._makeRef(),this.push({topic:"phoenix",event:"heartbeat",payload:{},ref:this.pendingHeartbeatRef}),this.heartbeatCallback("sent"),await this.setAuth()}onHeartbeat(e){this.heartbeatCallback=e}flushSendBuffer(){this.isConnected()&&this.sendBuffer.length>0&&(this.sendBuffer.forEach(e=>e()),this.sendBuffer=[])}_makeRef(){let e=this.ref+1;return e===this.ref?this.ref=0:this.ref=e,this.ref.toString()}_leaveOpenTopic(e){let r=this.channels.find(n=>n.topic===e&&(n._isJoined()||n._isJoining()));r&&(this.log("transport",`leaving duplicate topic "${e}"`),r.unsubscribe())}_remove(e){this.channels=this.channels.filter(r=>r.topic!==e.topic)}setupConnection(){this.conn&&(this.conn.binaryType="arraybuffer",this.conn.onopen=()=>this._onConnOpen(),this.conn.onerror=e=>this._onConnError(e),this.conn.onmessage=e=>this._onConnMessage(e),this.conn.onclose=e=>this._onConnClose(e))}_onConnMessage(e){this.decode(e.data,r=>{let{topic:n,event:a,payload:i,ref:o}=r;n==="phoenix"&&a==="phx_reply"&&this.heartbeatCallback(r.payload.status=="ok"?"ok":"error"),o&&o===this.pendingHeartbeatRef&&(this.pendingHeartbeatRef=null),this.log("receive",`${i.status||""} ${n} ${a} ${o&&"("+o+")"||""}`,i),Array.from(this.channels).filter(l=>l._isMember(n)).forEach(l=>l._trigger(a,i,o)),this.stateChangeCallbacks.message.forEach(l=>l(r))})}_onConnOpen(){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=r=>{this.log("worker","worker error",r.message),this.workerRef.terminate()},this.workerRef.onmessage=r=>{r.data.event==="keepAlive"&&this.sendHeartbeat()},this.workerRef.postMessage({event:"start",interval:this.heartbeatIntervalMs})}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(r=>r(e))}_onConnError(e){this.log("transport",e.message),this._triggerChanError(),this.stateChangeCallbacks.error.forEach(r=>r(e))}_triggerChanError(){this.channels.forEach(e=>e._trigger(Le.error))}_appendParams(e,r){if(Object.keys(r).length===0)return e;const n=e.match(/\?/)?"&":"?",a=new URLSearchParams(r);return`${e}${n}${a}`}_workerObjectUrl(e){let r;if(e)r=e;else{const n=new Blob([Ii],{type:"application/javascript"});r=URL.createObjectURL(n)}return r}}class Di{constructor(e,r,n){this.binaryType="arraybuffer",this.onclose=()=>{},this.onerror=()=>{},this.onmessage=()=>{},this.onopen=()=>{},this.readyState=bt.connecting,this.send=()=>{},this.url=null,this.url=e,this.close=n.close}}class sr extends Error{constructor(e){super(e),this.__isStorageError=!0,this.name="StorageError"}}function pe(s){return typeof s=="object"&&s!==null&&"__isStorageError"in s}class $i extends sr{constructor(e,r){super(e),this.name="StorageApiError",this.status=r}toJSON(){return{name:this.name,message:this.message,status:this.status}}}class Ms extends sr{constructor(e,r){super(e),this.name="StorageUnknownError",this.originalError=r}}var Ui=function(s,e,r,n){function a(i){return i instanceof r?i:new r(function(o){o(i)})}return new(r||(r=Promise))(function(i,o){function l(u){try{c(n.next(u))}catch(h){o(h)}}function d(u){try{c(n.throw(u))}catch(h){o(h)}}function c(u){u.done?i(u.value):a(u.value).then(l,d)}c((n=n.apply(s,e||[])).next())})};const Nn=s=>{let e;return s?e=s:typeof fetch>"u"?e=(...r)=>Ve(async()=>{const{default:n}=await Promise.resolve().then(()=>Nt);return{default:n}},void 0).then(({default:n})=>n(...r)):e=fetch,(...r)=>e(...r)},Bi=()=>Ui(void 0,void 0,void 0,function*(){return typeof Response>"u"?(yield Ve(()=>Promise.resolve().then(()=>Nt),void 0)).Response:Response}),Fs=s=>{if(Array.isArray(s))return s.map(r=>Fs(r));if(typeof s=="function"||s!==Object(s))return s;const e={};return Object.entries(s).forEach(([r,n])=>{const a=r.replace(/([-_][a-z])/gi,i=>i.toUpperCase().replace(/[-_]/g,""));e[a]=Fs(n)}),e};var ot=function(s,e,r,n){function a(i){return i instanceof r?i:new r(function(o){o(i)})}return new(r||(r=Promise))(function(i,o){function l(u){try{c(n.next(u))}catch(h){o(h)}}function d(u){try{c(n.throw(u))}catch(h){o(h)}}function c(u){u.done?i(u.value):a(u.value).then(l,d)}c((n=n.apply(s,e||[])).next())})};const _s=s=>s.msg||s.message||s.error_description||s.error||JSON.stringify(s),Mi=(s,e,r)=>ot(void 0,void 0,void 0,function*(){const n=yield Bi();s instanceof n&&!(r!=null&&r.noResolveJson)?s.json().then(a=>{e(new $i(_s(a),s.status||500))}).catch(a=>{e(new Ms(_s(a),a))}):e(new Ms(_s(s),s))}),Fi=(s,e,r,n)=>{const a={method:s,headers:(e==null?void 0:e.headers)||{}};return s==="GET"?a:(a.headers=Object.assign({"Content-Type":"application/json"},e==null?void 0:e.headers),n&&(a.body=JSON.stringify(n)),Object.assign(Object.assign({},a),r))};function Ft(s,e,r,n,a,i){return ot(this,void 0,void 0,function*(){return new Promise((o,l)=>{s(r,Fi(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=>Mi(d,l,n))})})}function ts(s,e,r,n){return ot(this,void 0,void 0,function*(){return Ft(s,"GET",e,r,n)})}function Ye(s,e,r,n,a){return ot(this,void 0,void 0,function*(){return Ft(s,"POST",e,n,a,r)})}function qi(s,e,r,n,a){return ot(this,void 0,void 0,function*(){return Ft(s,"PUT",e,n,a,r)})}function Gi(s,e,r,n){return ot(this,void 0,void 0,function*(){return Ft(s,"HEAD",e,Object.assign(Object.assign({},r),{noResolveJson:!0}),n)})}function Sn(s,e,r,n,a){return ot(this,void 0,void 0,function*(){return Ft(s,"DELETE",e,n,a,r)})}var _e=function(s,e,r,n){function a(i){return i instanceof r?i:new r(function(o){o(i)})}return new(r||(r=Promise))(function(i,o){function l(u){try{c(n.next(u))}catch(h){o(h)}}function d(u){try{c(n.throw(u))}catch(h){o(h)}}function c(u){u.done?i(u.value):a(u.value).then(l,d)}c((n=n.apply(s,e||[])).next())})};const Ki={limit:100,offset:0,sortBy:{column:"name",order:"asc"}},Tr={cacheControl:"3600",contentType:"text/plain;charset=UTF-8",upsert:!1};class Hi{constructor(e,r={},n,a){this.url=e,this.headers=r,this.bucketId=n,this.fetch=Nn(a)}uploadOrUpdate(e,r,n,a){return _e(this,void 0,void 0,function*(){try{let i;const o=Object.assign(Object.assign({},Tr),a);let l=Object.assign(Object.assign({},this.headers),e==="POST"&&{"x-upsert":String(o.upsert)});const d=o.metadata;typeof Blob<"u"&&n instanceof Blob?(i=new FormData,i.append("cacheControl",o.cacheControl),d&&i.append("metadata",this.encodeMetadata(d)),i.append("",n)):typeof FormData<"u"&&n instanceof FormData?(i=n,i.append("cacheControl",o.cacheControl),d&&i.append("metadata",this.encodeMetadata(d))):(i=n,l["cache-control"]=`max-age=${o.cacheControl}`,l["content-type"]=o.contentType,d&&(l["x-metadata"]=this.toBase64(this.encodeMetadata(d)))),a!=null&&a.headers&&(l=Object.assign(Object.assign({},l),a.headers));const c=this._removeEmptyFolders(r),u=this._getFinalPath(c),h=yield this.fetch(`${this.url}/object/${u}`,Object.assign({method:e,body:i,headers:l},o!=null&&o.duplex?{duplex:o.duplex}:{})),f=yield h.json();return h.ok?{data:{path:c,id:f.Id,fullPath:f.Key},error:null}:{data:null,error:f}}catch(i){if(pe(i))return{data:null,error:i};throw i}})}upload(e,r,n){return _e(this,void 0,void 0,function*(){return this.uploadOrUpdate("POST",e,r,n)})}uploadToSignedUrl(e,r,n,a){return _e(this,void 0,void 0,function*(){const i=this._removeEmptyFolders(e),o=this._getFinalPath(i),l=new URL(this.url+`/object/upload/sign/${o}`);l.searchParams.set("token",r);try{let d;const c=Object.assign({upsert:Tr.upsert},a),u=Object.assign(Object.assign({},this.headers),{"x-upsert":String(c.upsert)});typeof Blob<"u"&&n instanceof Blob?(d=new FormData,d.append("cacheControl",c.cacheControl),d.append("",n)):typeof FormData<"u"&&n instanceof FormData?(d=n,d.append("cacheControl",c.cacheControl)):(d=n,u["cache-control"]=`max-age=${c.cacheControl}`,u["content-type"]=c.contentType);const h=yield this.fetch(l.toString(),{method:"PUT",body:d,headers:u}),f=yield h.json();return h.ok?{data:{path:i,fullPath:f.Key},error:null}:{data:null,error:f}}catch(d){if(pe(d))return{data:null,error:d};throw d}})}createSignedUploadUrl(e,r){return _e(this,void 0,void 0,function*(){try{let n=this._getFinalPath(e);const a=Object.assign({},this.headers);r!=null&&r.upsert&&(a["x-upsert"]="true");const i=yield Ye(this.fetch,`${this.url}/object/upload/sign/${n}`,{},{headers:a}),o=new URL(this.url+i.url),l=o.searchParams.get("token");if(!l)throw new sr("No token returned by API");return{data:{signedUrl:o.toString(),path:e,token:l},error:null}}catch(n){if(pe(n))return{data:null,error:n};throw n}})}update(e,r,n){return _e(this,void 0,void 0,function*(){return this.uploadOrUpdate("PUT",e,r,n)})}move(e,r,n){return _e(this,void 0,void 0,function*(){try{return{data:yield Ye(this.fetch,`${this.url}/object/move`,{bucketId:this.bucketId,sourceKey:e,destinationKey:r,destinationBucket:n==null?void 0:n.destinationBucket},{headers:this.headers}),error:null}}catch(a){if(pe(a))return{data:null,error:a};throw a}})}copy(e,r,n){return _e(this,void 0,void 0,function*(){try{return{data:{path:(yield Ye(this.fetch,`${this.url}/object/copy`,{bucketId:this.bucketId,sourceKey:e,destinationKey:r,destinationBucket:n==null?void 0:n.destinationBucket},{headers:this.headers})).Key},error:null}}catch(a){if(pe(a))return{data:null,error:a};throw a}})}createSignedUrl(e,r,n){return _e(this,void 0,void 0,function*(){try{let a=this._getFinalPath(e),i=yield Ye(this.fetch,`${this.url}/object/sign/${a}`,Object.assign({expiresIn:r},n!=null&&n.transform?{transform:n.transform}:{}),{headers:this.headers});const o=n!=null&&n.download?`&download=${n.download===!0?"":n.download}`:"";return i={signedUrl:encodeURI(`${this.url}${i.signedURL}${o}`)},{data:i,error:null}}catch(a){if(pe(a))return{data:null,error:a};throw a}})}createSignedUrls(e,r,n){return _e(this,void 0,void 0,function*(){try{const a=yield Ye(this.fetch,`${this.url}/object/sign/${this.bucketId}`,{expiresIn:r,paths:e},{headers:this.headers}),i=n!=null&&n.download?`&download=${n.download===!0?"":n.download}`:"";return{data:a.map(o=>Object.assign(Object.assign({},o),{signedUrl:o.signedURL?encodeURI(`${this.url}${o.signedURL}${i}`):null})),error:null}}catch(a){if(pe(a))return{data:null,error:a};throw a}})}download(e,r){return _e(this,void 0,void 0,function*(){const a=typeof(r==null?void 0:r.transform)<"u"?"render/image/authenticated":"object",i=this.transformOptsToQueryString((r==null?void 0:r.transform)||{}),o=i?`?${i}`:"";try{const l=this._getFinalPath(e);return{data:yield(yield ts(this.fetch,`${this.url}/${a}/${l}${o}`,{headers:this.headers,noResolveJson:!0})).blob(),error:null}}catch(l){if(pe(l))return{data:null,error:l};throw l}})}info(e){return _e(this,void 0,void 0,function*(){const r=this._getFinalPath(e);try{const n=yield ts(this.fetch,`${this.url}/object/info/${r}`,{headers:this.headers});return{data:Fs(n),error:null}}catch(n){if(pe(n))return{data:null,error:n};throw n}})}exists(e){return _e(this,void 0,void 0,function*(){const r=this._getFinalPath(e);try{return yield Gi(this.fetch,`${this.url}/object/${r}`,{headers:this.headers}),{data:!0,error:null}}catch(n){if(pe(n)&&n instanceof Ms){const a=n.originalError;if([400,404].includes(a==null?void 0:a.status))return{data:!1,error:n}}throw n}})}getPublicUrl(e,r){const n=this._getFinalPath(e),a=[],i=r!=null&&r.download?`download=${r.download===!0?"":r.download}`:"";i!==""&&a.push(i);const l=typeof(r==null?void 0:r.transform)<"u"?"render/image":"object",d=this.transformOptsToQueryString((r==null?void 0:r.transform)||{});d!==""&&a.push(d);let c=a.join("&");return c!==""&&(c=`?${c}`),{data:{publicUrl:encodeURI(`${this.url}/${l}/public/${n}${c}`)}}}remove(e){return _e(this,void 0,void 0,function*(){try{return{data:yield Sn(this.fetch,`${this.url}/object/${this.bucketId}`,{prefixes:e},{headers:this.headers}),error:null}}catch(r){if(pe(r))return{data:null,error:r};throw r}})}list(e,r,n){return _e(this,void 0,void 0,function*(){try{const a=Object.assign(Object.assign(Object.assign({},Ki),r),{prefix:e||""});return{data:yield Ye(this.fetch,`${this.url}/object/list/${this.bucketId}`,a,{headers:this.headers},n),error:null}}catch(a){if(pe(a))return{data:null,error:a};throw a}})}encodeMetadata(e){return JSON.stringify(e)}toBase64(e){return typeof Buffer<"u"?Buffer.from(e).toString("base64"):btoa(e)}_getFinalPath(e){return`${this.bucketId}/${e}`}_removeEmptyFolders(e){return e.replace(/^\/|\/$/g,"").replace(/\/+/g,"/")}transformOptsToQueryString(e){const r=[];return e.width&&r.push(`width=${e.width}`),e.height&&r.push(`height=${e.height}`),e.resize&&r.push(`resize=${e.resize}`),e.format&&r.push(`format=${e.format}`),e.quality&&r.push(`quality=${e.quality}`),r.join("&")}}const zi="2.7.1",Wi={"X-Client-Info":`storage-js/${zi}`};var dt=function(s,e,r,n){function a(i){return i instanceof r?i:new r(function(o){o(i)})}return new(r||(r=Promise))(function(i,o){function l(u){try{c(n.next(u))}catch(h){o(h)}}function d(u){try{c(n.throw(u))}catch(h){o(h)}}function c(u){u.done?i(u.value):a(u.value).then(l,d)}c((n=n.apply(s,e||[])).next())})};class Vi{constructor(e,r={},n){this.url=e,this.headers=Object.assign(Object.assign({},Wi),r),this.fetch=Nn(n)}listBuckets(){return dt(this,void 0,void 0,function*(){try{return{data:yield ts(this.fetch,`${this.url}/bucket`,{headers:this.headers}),error:null}}catch(e){if(pe(e))return{data:null,error:e};throw e}})}getBucket(e){return dt(this,void 0,void 0,function*(){try{return{data:yield ts(this.fetch,`${this.url}/bucket/${e}`,{headers:this.headers}),error:null}}catch(r){if(pe(r))return{data:null,error:r};throw r}})}createBucket(e,r={public:!1}){return dt(this,void 0,void 0,function*(){try{return{data:yield Ye(this.fetch,`${this.url}/bucket`,{id:e,name:e,public:r.public,file_size_limit:r.fileSizeLimit,allowed_mime_types:r.allowedMimeTypes},{headers:this.headers}),error:null}}catch(n){if(pe(n))return{data:null,error:n};throw n}})}updateBucket(e,r){return dt(this,void 0,void 0,function*(){try{return{data:yield qi(this.fetch,`${this.url}/bucket/${e}`,{id:e,name:e,public:r.public,file_size_limit:r.fileSizeLimit,allowed_mime_types:r.allowedMimeTypes},{headers:this.headers}),error:null}}catch(n){if(pe(n))return{data:null,error:n};throw n}})}emptyBucket(e){return dt(this,void 0,void 0,function*(){try{return{data:yield Ye(this.fetch,`${this.url}/bucket/${e}/empty`,{},{headers:this.headers}),error:null}}catch(r){if(pe(r))return{data:null,error:r};throw r}})}deleteBucket(e){return dt(this,void 0,void 0,function*(){try{return{data:yield Sn(this.fetch,`${this.url}/bucket/${e}`,{},{headers:this.headers}),error:null}}catch(r){if(pe(r))return{data:null,error:r};throw r}})}}class Ji extends Vi{constructor(e,r={},n){super(e,r,n)}from(e){return new Hi(this.url,this.headers,e,this.fetch)}}const Yi="2.50.0";let Lt="";typeof Deno<"u"?Lt="deno":typeof document<"u"?Lt="web":typeof navigator<"u"&&navigator.product==="ReactNative"?Lt="react-native":Lt="node";const Qi={"X-Client-Info":`supabase-js-${Lt}/${Yi}`},Zi={headers:Qi},Xi={schema:"public"},eo={autoRefreshToken:!0,persistSession:!0,detectSessionInUrl:!0,flowType:"implicit"},to={};var so=function(s,e,r,n){function a(i){return i instanceof r?i:new r(function(o){o(i)})}return new(r||(r=Promise))(function(i,o){function l(u){try{c(n.next(u))}catch(h){o(h)}}function d(u){try{c(n.throw(u))}catch(h){o(h)}}function c(u){u.done?i(u.value):a(u.value).then(l,d)}c((n=n.apply(s,e||[])).next())})};const ro=s=>{let e;return s?e=s:typeof fetch>"u"?e=cn:e=fetch,(...r)=>e(...r)},no=()=>typeof Headers>"u"?dn:Headers,ao=(s,e,r)=>{const n=ro(r),a=no();return(i,o)=>so(void 0,void 0,void 0,function*(){var l;const d=(l=yield e())!==null&&l!==void 0?l:s;let c=new a(o==null?void 0:o.headers);return c.has("apikey")||c.set("apikey",s),c.has("Authorization")||c.set("Authorization",`Bearer ${d}`),n(i,Object.assign(Object.assign({},o),{headers:c}))})};var io=function(s,e,r,n){function a(i){return i instanceof r?i:new r(function(o){o(i)})}return new(r||(r=Promise))(function(i,o){function l(u){try{c(n.next(u))}catch(h){o(h)}}function d(u){try{c(n.throw(u))}catch(h){o(h)}}function c(u){u.done?i(u.value):a(u.value).then(l,d)}c((n=n.apply(s,e||[])).next())})};function oo(s){return s.endsWith("/")?s:s+"/"}function lo(s,e){var r,n;const{db:a,auth:i,realtime:o,global:l}=s,{db:d,auth:c,realtime:u,global:h}=e,f={db:Object.assign(Object.assign({},d),a),auth:Object.assign(Object.assign({},c),i),realtime:Object.assign(Object.assign({},u),o),global:Object.assign(Object.assign(Object.assign({},h),l),{headers:Object.assign(Object.assign({},(r=h==null?void 0:h.headers)!==null&&r!==void 0?r:{}),(n=l==null?void 0:l.headers)!==null&&n!==void 0?n:{})}),accessToken:()=>io(this,void 0,void 0,function*(){return""})};return s.accessToken?f.accessToken=s.accessToken:delete f.accessToken,f}const kn="2.70.0",gt=30*1e3,qs=3,Ns=qs*gt,co="http://localhost:9999",uo="supabase.auth.token",ho={"X-Client-Info":`gotrue-js/${kn}`},Gs="X-Supabase-Api-Version",En={"2024-01-01":{timestamp:Date.parse("2024-01-01T00:00:00.0Z"),name:"2024-01-01"}},fo=/^([a-z0-9_-]{4})*($|[a-z0-9_-]{3}$|[a-z0-9_-]{2}$)$/i,mo=6e5;class rr extends Error{constructor(e,r,n){super(e),this.__isAuthError=!0,this.name="AuthError",this.status=r,this.code=n}}function Y(s){return typeof s=="object"&&s!==null&&"__isAuthError"in s}class go extends rr{constructor(e,r,n){super(e,r,n),this.name="AuthApiError",this.status=r,this.code=n}}function po(s){return Y(s)&&s.name==="AuthApiError"}class Cn extends rr{constructor(e,r){super(e),this.name="AuthUnknownError",this.originalError=r}}class et extends rr{constructor(e,r,n,a){super(e,n,a),this.name=r,this.status=n}}class Je extends et{constructor(){super("Auth session missing!","AuthSessionMissingError",400,void 0)}}function xo(s){return Y(s)&&s.name==="AuthSessionMissingError"}class zt extends et{constructor(){super("Auth session or user missing","AuthInvalidTokenResponseError",500,void 0)}}class Wt extends et{constructor(e){super(e,"AuthInvalidCredentialsError",400,void 0)}}class Vt extends et{constructor(e,r=null){super(e,"AuthImplicitGrantRedirectError",500,void 0),this.details=null,this.details=r}toJSON(){return{name:this.name,message:this.message,status:this.status,details:this.details}}}function yo(s){return Y(s)&&s.name==="AuthImplicitGrantRedirectError"}class Pr extends et{constructor(e,r=null){super(e,"AuthPKCEGrantCodeExchangeError",500,void 0),this.details=null,this.details=r}toJSON(){return{name:this.name,message:this.message,status:this.status,details:this.details}}}class Ks extends et{constructor(e,r){super(e,"AuthRetryableFetchError",r,void 0)}}function Ss(s){return Y(s)&&s.name==="AuthRetryableFetchError"}class Ar extends et{constructor(e,r,n){super(e,"AuthWeakPasswordError",r,"weak_password"),this.reasons=n}}class Rt extends et{constructor(e){super(e,"AuthInvalidJwtError",400,"invalid_jwt")}}const ss="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_".split(""),Or=` \r=`.split(""),bo=(()=>{const s=new Array(128);for(let e=0;e<s.length;e+=1)s[e]=-1;for(let e=0;e<Or.length;e+=1)s[Or[e].charCodeAt(0)]=-2;for(let e=0;e<ss.length;e+=1)s[ss[e].charCodeAt(0)]=e;return s})();function Lr(s,e,r){if(s!==null)for(e.queue=e.queue<<8|s,e.queuedBits+=8;e.queuedBits>=6;){const n=e.queue>>e.queuedBits-6&63;r(ss[n]),e.queuedBits-=6}else if(e.queuedBits>0)for(e.queue=e.queue<<6-e.queuedBits,e.queuedBits=6;e.queuedBits>=6;){const n=e.queue>>e.queuedBits-6&63;r(ss[n]),e.queuedBits-=6}}function Tn(s,e,r){const n=bo[s];if(n>-1)for(e.queue=e.queue<<6|n,e.queuedBits+=6;e.queuedBits>=8;)r(e.queue>>e.queuedBits-8&255),e.queuedBits-=8;else{if(n===-2)return;throw new Error(`Invalid Base64-URL character "${String.fromCharCode(s)}"`)}}function Ir(s){const e=[],r=o=>{e.push(String.fromCodePoint(o))},n={utf8seq:0,codepoint:0},a={queue:0,queuedBits:0},i=o=>{jo(o,n,r)};for(let o=0;o<s.length;o+=1)Tn(s.charCodeAt(o),a,i);return e.join("")}function wo(s,e){if(s<=127){e(s);return}else if(s<=2047){e(192|s>>6),e(128|s&63);return}else if(s<=65535){e(224|s>>12),e(128|s>>6&63),e(128|s&63);return}else if(s<=1114111){e(240|s>>18),e(128|s>>12&63),e(128|s>>6&63),e(128|s&63);return}throw new Error(`Unrecognized Unicode codepoint: ${s.toString(16)}`)}function vo(s,e){for(let r=0;r<s.length;r+=1){let n=s.charCodeAt(r);if(n>55295&&n<=56319){const a=(n-55296)*1024&65535;n=(s.charCodeAt(r+1)-56320&65535|a)+65536,r+=1}wo(n,e)}}function jo(s,e,r){if(e.utf8seq===0){if(s<=127){r(s);return}for(let n=1;n<6;n+=1)if(!(s>>7-n&1)){e.utf8seq=n;break}if(e.utf8seq===2)e.codepoint=s&31;else if(e.utf8seq===3)e.codepoint=s&15;else if(e.utf8seq===4)e.codepoint=s&7;else throw new Error("Invalid UTF-8 sequence");e.utf8seq-=1}else if(e.utf8seq>0){if(s<=127)throw new Error("Invalid UTF-8 sequence");e.codepoint=e.codepoint<<6|s&63,e.utf8seq-=1,e.utf8seq===0&&r(e.codepoint)}}function _o(s){const e=[],r={queue:0,queuedBits:0},n=a=>{e.push(a)};for(let a=0;a<s.length;a+=1)Tn(s.charCodeAt(a),r,n);return new Uint8Array(e)}function No(s){const e=[];return vo(s,r=>e.push(r)),new Uint8Array(e)}function So(s){const e=[],r={queue:0,queuedBits:0},n=a=>{e.push(a)};return s.forEach(a=>Lr(a,r,n)),Lr(null,r,n),e.join("")}function ko(s){return Math.round(Date.now()/1e3)+s}function Eo(){return"xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx".replace(/[xy]/g,function(s){const e=Math.random()*16|0;return(s=="x"?e:e&3|8).toString(16)})}const Oe=()=>typeof window<"u"&&typeof document<"u",tt={tested:!1,writable:!1},Dt=()=>{if(!Oe())return!1;try{if(typeof globalThis.localStorage!="object")return!1}catch{return!1}if(tt.tested)return tt.writable;const s=`lswt-${Math.random()}${Math.random()}`;try{globalThis.localStorage.setItem(s,s),globalThis.localStorage.removeItem(s),tt.tested=!0,tt.writable=!0}catch{tt.tested=!0,tt.writable=!1}return tt.writable};function Co(s){const e={},r=new URL(s);if(r.hash&&r.hash[0]==="#")try{new URLSearchParams(r.hash.substring(1)).forEach((a,i)=>{e[i]=a})}catch{}return r.searchParams.forEach((n,a)=>{e[a]=n}),e}const Pn=s=>{let e;return s?e=s:typeof fetch>"u"?e=(...r)=>Ve(async()=>{const{default:n}=await Promise.resolve().then(()=>Nt);return{default:n}},void 0).then(({default:n})=>n(...r)):e=fetch,(...r)=>e(...r)},To=s=>typeof s=="object"&&s!==null&&"status"in s&&"ok"in s&&"json"in s&&typeof s.json=="function",An=async(s,e,r)=>{await s.setItem(e,JSON.stringify(r))},Jt=async(s,e)=>{const r=await s.getItem(e);if(!r)return null;try{return JSON.parse(r)}catch{return r}},Yt=async(s,e)=>{await s.removeItem(e)};class fs{constructor(){this.promise=new fs.promiseConstructor((e,r)=>{this.resolve=e,this.reject=r})}}fs.promiseConstructor=Promise;function ks(s){const e=s.split(".");if(e.length!==3)throw new Rt("Invalid JWT structure");for(let n=0;n<e.length;n++)if(!fo.test(e[n]))throw new Rt("JWT not in base64url format");return{header:JSON.parse(Ir(e[0])),payload:JSON.parse(Ir(e[1])),signature:_o(e[2]),raw:{header:e[0],payload:e[1]}}}async function Po(s){return await new Promise(e=>{setTimeout(()=>e(null),s)})}function Ao(s,e){return new Promise((n,a)=>{(async()=>{for(let i=0;i<1/0;i++)try{const o=await s(i);if(!e(i,null,o)){n(o);return}}catch(o){if(!e(i,o)){a(o);return}}})()})}function Oo(s){return("0"+s.toString(16)).substr(-2)}function Lo(){const e=new Uint32Array(56);if(typeof crypto>"u"){const r="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-._~",n=r.length;let a="";for(let i=0;i<56;i++)a+=r.charAt(Math.floor(Math.random()*n));return a}return crypto.getRandomValues(e),Array.from(e,Oo).join("")}async function Io(s){const r=new TextEncoder().encode(s),n=await crypto.subtle.digest("SHA-256",r),a=new Uint8Array(n);return Array.from(a).map(i=>String.fromCharCode(i)).join("")}async function Ro(s){if(!(typeof crypto<"u"&&typeof crypto.subtle<"u"&&typeof TextEncoder<"u"))return console.warn("WebCrypto API is not supported. Code challenge method will default to use plain instead of sha256."),s;const r=await Io(s);return btoa(r).replace(/\+/g,"-").replace(/\//g,"_").replace(/=+$/,"")}async function ut(s,e,r=!1){const n=Lo();let a=n;r&&(a+="/PASSWORD_RECOVERY"),await An(s,`${e}-code-verifier`,a);const i=await Ro(n);return[i,n===i?"plain":"s256"]}const Do=/^2[0-9]{3}-(0[1-9]|1[0-2])-(0[1-9]|1[0-9]|2[0-9]|3[0-1])$/i;function $o(s){const e=s.headers.get(Gs);if(!e||!e.match(Do))return null;try{return new Date(`${e}T00:00:00.0Z`)}catch{return null}}function Uo(s){if(!s)throw new Error("Missing exp claim");const e=Math.floor(Date.now()/1e3);if(s<=e)throw new Error("JWT has expired")}function Bo(s){switch(s){case"RS256":return{name:"RSASSA-PKCS1-v1_5",hash:{name:"SHA-256"}};case"ES256":return{name:"ECDSA",namedCurve:"P-256",hash:{name:"SHA-256"}};default:throw new Error("Invalid alg claim")}}const Mo=/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/;function ht(s){if(!Mo.test(s))throw new Error("@supabase/auth-js: Expected parameter to be UUID but is not")}var Fo=function(s,e){var r={};for(var n in s)Object.prototype.hasOwnProperty.call(s,n)&&e.indexOf(n)<0&&(r[n]=s[n]);if(s!=null&&typeof Object.getOwnPropertySymbols=="function")for(var a=0,n=Object.getOwnPropertySymbols(s);a<n.length;a++)e.indexOf(n[a])<0&&Object.prototype.propertyIsEnumerable.call(s,n[a])&&(r[n[a]]=s[n[a]]);return r};const st=s=>s.msg||s.message||s.error_description||s.error||JSON.stringify(s),qo=[502,503,504];async function Rr(s){var e;if(!To(s))throw new Ks(st(s),0);if(qo.includes(s.status))throw new Ks(st(s),s.status);let r;try{r=await s.json()}catch(i){throw new Cn(st(i),i)}let n;const a=$o(s);if(a&&a.getTime()>=En["2024-01-01"].timestamp&&typeof r=="object"&&r&&typeof r.code=="string"?n=r.code:typeof r=="object"&&r&&typeof r.error_code=="string"&&(n=r.error_code),n){if(n==="weak_password")throw new Ar(st(r),s.status,((e=r.weak_password)===null||e===void 0?void 0:e.reasons)||[]);if(n==="session_not_found")throw new Je}else if(typeof r=="object"&&r&&typeof r.weak_password=="object"&&r.weak_password&&Array.isArray(r.weak_password.reasons)&&r.weak_password.reasons.length&&r.weak_password.reasons.reduce((i,o)=>i&&typeof o=="string",!0))throw new Ar(st(r),s.status,r.weak_password.reasons);throw new go(st(r),s.status||500,n)}const Go=(s,e,r,n)=>{const a={method:s,headers:(e==null?void 0:e.headers)||{}};return s==="GET"?a:(a.headers=Object.assign({"Content-Type":"application/json;charset=UTF-8"},e==null?void 0:e.headers),a.body=JSON.stringify(n),Object.assign(Object.assign({},a),r))};async function te(s,e,r,n){var a;const i=Object.assign({},n==null?void 0:n.headers);i[Gs]||(i[Gs]=En["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 Ko(s,e,r+l,{headers:i,noResolveJson:n==null?void 0:n.noResolveJson},{},n==null?void 0:n.body);return n!=null&&n.xform?n==null?void 0:n.xform(d):{data:Object.assign({},d),error:null}}async function Ko(s,e,r,n,a,i){const o=Go(e,n,a,i);let l;try{l=await s(r,Object.assign({},o))}catch(d){throw console.error(d),new Ks(st(d),0)}if(l.ok||await Rr(l),n!=null&&n.noResolveJson)return l;try{return await l.json()}catch(d){await Rr(d)}}function He(s){var e;let r=null;Vo(s)&&(r=Object.assign({},s),s.expires_at||(r.expires_at=ko(s.expires_in)));const n=(e=s.user)!==null&&e!==void 0?e:s;return{data:{session:r,user:n},error:null}}function Dr(s){const e=He(s);return!e.error&&s.weak_password&&typeof s.weak_password=="object"&&Array.isArray(s.weak_password.reasons)&&s.weak_password.reasons.length&&s.weak_password.message&&typeof s.weak_password.message=="string"&&s.weak_password.reasons.reduce((r,n)=>r&&typeof n=="string",!0)&&(e.data.weak_password=s.weak_password),e}function Qe(s){var e;return{data:{user:(e=s.user)!==null&&e!==void 0?e:s},error:null}}function Ho(s){return{data:s,error:null}}function zo(s){const{action_link:e,email_otp:r,hashed_token:n,redirect_to:a,verification_type:i}=s,o=Fo(s,["action_link","email_otp","hashed_token","redirect_to","verification_type"]),l={action_link:e,email_otp:r,hashed_token:n,redirect_to:a,verification_type:i},d=Object.assign({},o);return{data:{properties:l,user:d},error:null}}function Wo(s){return s}function Vo(s){return s.access_token&&s.refresh_token&&s.expires_in}const Es=["global","local","others"];var Jo=function(s,e){var r={};for(var n in s)Object.prototype.hasOwnProperty.call(s,n)&&e.indexOf(n)<0&&(r[n]=s[n]);if(s!=null&&typeof Object.getOwnPropertySymbols=="function")for(var a=0,n=Object.getOwnPropertySymbols(s);a<n.length;a++)e.indexOf(n[a])<0&&Object.prototype.propertyIsEnumerable.call(s,n[a])&&(r[n[a]]=s[n[a]]);return r};class Yo{constructor({url:e="",headers:r={},fetch:n}){this.url=e,this.headers=r,this.fetch=Pn(n),this.mfa={listFactors:this._listFactors.bind(this),deleteFactor:this._deleteFactor.bind(this)}}async signOut(e,r=Es[0]){if(Es.indexOf(r)<0)throw new Error(`@supabase/auth-js: Parameter scope must be one of ${Es.join(", ")}`);try{return await te(this.fetch,"POST",`${this.url}/logout?scope=${r}`,{headers:this.headers,jwt:e,noResolveJson:!0}),{data:null,error:null}}catch(n){if(Y(n))return{data:null,error:n};throw n}}async inviteUserByEmail(e,r={}){try{return await te(this.fetch,"POST",`${this.url}/invite`,{body:{email:e,data:r.data},headers:this.headers,redirectTo:r.redirectTo,xform:Qe})}catch(n){if(Y(n))return{data:{user:null},error:n};throw n}}async generateLink(e){try{const{options:r}=e,n=Jo(e,["options"]),a=Object.assign(Object.assign({},n),r);return"newEmail"in n&&(a.new_email=n==null?void 0:n.newEmail,delete a.newEmail),await te(this.fetch,"POST",`${this.url}/admin/generate_link`,{body:a,headers:this.headers,xform:zo,redirectTo:r==null?void 0:r.redirectTo})}catch(r){if(Y(r))return{data:{properties:null,user:null},error:r};throw r}}async createUser(e){try{return await te(this.fetch,"POST",`${this.url}/admin/users`,{body:e,headers:this.headers,xform:Qe})}catch(r){if(Y(r))return{data:{user:null},error:r};throw r}}async listUsers(e){var r,n,a,i,o,l,d;try{const c={nextPage:null,lastPage:0,total:0},u=await te(this.fetch,"GET",`${this.url}/admin/users`,{headers:this.headers,noResolveJson:!0,query:{page:(n=(r=e==null?void 0:e.page)===null||r===void 0?void 0:r.toString())!==null&&n!==void 0?n:"",per_page:(i=(a=e==null?void 0:e.perPage)===null||a===void 0?void 0:a.toString())!==null&&i!==void 0?i:""},xform:Wo});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(v=>{const w=parseInt(v.split(";")[0].split("=")[1].substring(0,1)),x=JSON.parse(v.split(";")[1].split("=")[1]);c[`${x}Page`]=w}),c.total=parseInt(f)),{data:Object.assign(Object.assign({},h),c),error:null}}catch(c){if(Y(c))return{data:{users:[]},error:c};throw c}}async getUserById(e){ht(e);try{return await te(this.fetch,"GET",`${this.url}/admin/users/${e}`,{headers:this.headers,xform:Qe})}catch(r){if(Y(r))return{data:{user:null},error:r};throw r}}async updateUserById(e,r){ht(e);try{return await te(this.fetch,"PUT",`${this.url}/admin/users/${e}`,{body:r,headers:this.headers,xform:Qe})}catch(n){if(Y(n))return{data:{user:null},error:n};throw n}}async deleteUser(e,r=!1){ht(e);try{return await te(this.fetch,"DELETE",`${this.url}/admin/users/${e}`,{headers:this.headers,body:{should_soft_delete:r},xform:Qe})}catch(n){if(Y(n))return{data:{user:null},error:n};throw n}}async _listFactors(e){ht(e.userId);try{const{data:r,error:n}=await te(this.fetch,"GET",`${this.url}/admin/users/${e.userId}/factors`,{headers:this.headers,xform:a=>({data:{factors:a},error:null})});return{data:r,error:n}}catch(r){if(Y(r))return{data:null,error:r};throw r}}async _deleteFactor(e){ht(e.userId),ht(e.id);try{return{data:await te(this.fetch,"DELETE",`${this.url}/admin/users/${e.userId}/factors/${e.id}`,{headers:this.headers}),error:null}}catch(r){if(Y(r))return{data:null,error:r};throw r}}}const Qo={getItem:s=>Dt()?globalThis.localStorage.getItem(s):null,setItem:(s,e)=>{Dt()&&globalThis.localStorage.setItem(s,e)},removeItem:s=>{Dt()&&globalThis.localStorage.removeItem(s)}};function $r(s={}){return{getItem:e=>s[e]||null,setItem:(e,r)=>{s[e]=r},removeItem:e=>{delete s[e]}}}function Zo(){if(typeof globalThis!="object")try{Object.defineProperty(Object.prototype,"__magic__",{get:function(){return this},configurable:!0}),__magic__.globalThis=__magic__,delete Object.prototype.__magic__}catch{typeof self<"u"&&(self.globalThis=self)}}const ft={debug:!!(globalThis&&Dt()&&globalThis.localStorage&&globalThis.localStorage.getItem("supabase.gotrue-js.locks.debug")==="true")};class On extends Error{constructor(e){super(e),this.isAcquireTimeout=!0}}class Xo extends On{}async function el(s,e,r){ft.debug&&console.log("@supabase/gotrue-js: navigatorLock: acquire lock",s,e);const n=new globalThis.AbortController;return e>0&&setTimeout(()=>{n.abort(),ft.debug&&console.log("@supabase/gotrue-js: navigatorLock acquire timed out",s)},e),await Promise.resolve().then(()=>globalThis.navigator.locks.request(s,e===0?{mode:"exclusive",ifAvailable:!0}:{mode:"exclusive",signal:n.signal},async a=>{if(a){ft.debug&&console.log("@supabase/gotrue-js: navigatorLock: acquired",s,a.name);try{return await r()}finally{ft.debug&&console.log("@supabase/gotrue-js: navigatorLock: released",s,a.name)}}else{if(e===0)throw ft.debug&&console.log("@supabase/gotrue-js: navigatorLock: not immediately available",s),new Xo(`Acquiring an exclusive Navigator LockManager lock "${s}" immediately failed`);if(ft.debug)try{const i=await globalThis.navigator.locks.query();console.log("@supabase/gotrue-js: Navigator LockManager state",JSON.stringify(i,null," "))}catch(i){console.warn("@supabase/gotrue-js: Error when querying Navigator LockManager state",i)}return console.warn("@supabase/gotrue-js: Navigator LockManager returned a null lock when using #request without ifAvailable set to true, it appears this browser is not following the LockManager spec https://developer.mozilla.org/en-US/docs/Web/API/LockManager/request"),await r()}}))}Zo();const tl={url:co,storageKey:uo,autoRefreshToken:!0,persistSession:!0,detectSessionInUrl:!0,headers:ho,flowType:"implicit",debug:!1,hasCustomAuthorizationHeader:!1};async function Ur(s,e,r){return await r()}class $t{constructor(e){var r,n;this.memoryStorage=null,this.stateChangeEmitters=new Map,this.autoRefreshTicker=null,this.visibilityChangedCallback=null,this.refreshingDeferred=null,this.initializePromise=null,this.detectSessionInUrl=!0,this.hasCustomAuthorizationHeader=!1,this.suppressGetSessionWarning=!1,this.lockAcquired=!1,this.pendingInLock=[],this.broadcastChannel=null,this.logger=console.log,this.instanceID=$t.nextInstanceID,$t.nextInstanceID+=1,this.instanceID>0&&Oe()&&console.warn("Multiple GoTrueClient instances detected in the same browser context. It is not an error, but this should be avoided as it may produce undefined behavior when used concurrently under the same storage key.");const a=Object.assign(Object.assign({},tl),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 Yo({url:a.url,headers:a.headers,fetch:a.fetch}),this.url=a.url,this.headers=a.headers,this.fetch=Pn(a.fetch),this.lock=a.lock||Ur,this.detectSessionInUrl=a.detectSessionInUrl,this.flowType=a.flowType,this.hasCustomAuthorizationHeader=a.hasCustomAuthorizationHeader,a.lock?this.lock=a.lock:Oe()&&(!((r=globalThis==null?void 0:globalThis.navigator)===null||r===void 0)&&r.locks)?this.lock=el:this.lock=Ur,this.jwks={keys:[]},this.jwks_cached_at=Number.MIN_SAFE_INTEGER,this.mfa={verify:this._verify.bind(this),enroll:this._enroll.bind(this),unenroll:this._unenroll.bind(this),challenge:this._challenge.bind(this),listFactors:this._listFactors.bind(this),challengeAndVerify:this._challengeAndVerify.bind(this),getAuthenticatorAssuranceLevel:this._getAuthenticatorAssuranceLevel.bind(this)},this.persistSession?a.storage?this.storage=a.storage:Dt()?this.storage=Qo:(this.memoryStorage={},this.storage=$r(this.memoryStorage)):(this.memoryStorage={},this.storage=$r(this.memoryStorage)),Oe()&&globalThis.BroadcastChannel&&this.persistSession&&this.storageKey){try{this.broadcastChannel=new globalThis.BroadcastChannel(this.storageKey)}catch(i){console.error("Failed to create a new BroadcastChannel, multi-tab state changes will not be available",i)}(n=this.broadcastChannel)===null||n===void 0||n.addEventListener("message",async i=>{this._debug("received broadcast notification from other tab or client",i),await this._notifyAllSubscribers(i.data.event,i.data.session,!1)})}this.initialize()}_debug(...e){return this.logDebugMessages&&this.logger(`GoTrueClient@${this.instanceID} (${kn}) ${new Date().toISOString()}`,...e),this}async initialize(){return this.initializePromise?await this.initializePromise:(this.initializePromise=(async()=>await this._acquireLock(-1,async()=>await this._initialize()))(),await this.initializePromise)}async _initialize(){var e;try{const r=Co(window.location.href);let n="none";if(this._isImplicitGrantCallback(r)?n="implicit":await this._isPKCECallback(r)&&(n="pkce"),Oe()&&this.detectSessionInUrl&&n!=="none"){const{data:a,error:i}=await this._getSessionFromURL(r,n);if(i){if(this._debug("#_initialize()","error detecting session from URL",i),yo(i)){const d=(e=i.details)===null||e===void 0?void 0:e.code;if(d==="identity_already_exists"||d==="identity_not_found"||d==="single_identity_not_deletable")return{error:i}}return await this._removeSession(),{error:i}}const{session:o,redirectType:l}=a;return this._debug("#_initialize()","detected session in URL",o,"redirect type",l),await this._saveSession(o),setTimeout(async()=>{l==="recovery"?await this._notifyAllSubscribers("PASSWORD_RECOVERY",o):await this._notifyAllSubscribers("SIGNED_IN",o)},0),{error:null}}return await this._recoverAndRefresh(),{error:null}}catch(r){return Y(r)?{error:r}:{error:new Cn("Unexpected error during initialization",r)}}finally{await this._handleVisibilityChange(),this._debug("#_initialize()","end")}}async signInAnonymously(e){var r,n,a;try{const i=await te(this.fetch,"POST",`${this.url}/signup`,{headers:this.headers,body:{data:(n=(r=e==null?void 0:e.options)===null||r===void 0?void 0:r.data)!==null&&n!==void 0?n:{},gotrue_meta_security:{captcha_token:(a=e==null?void 0:e.options)===null||a===void 0?void 0:a.captchaToken}},xform:He}),{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(Y(i))return{data:{user:null,session:null},error:i};throw i}}async signUp(e){var r,n,a;try{let i;if("email"in e){const{email:u,password:h,options:f}=e;let p=null,v=null;this.flowType==="pkce"&&([p,v]=await ut(this.storage,this.storageKey)),i=await te(this.fetch,"POST",`${this.url}/signup`,{headers:this.headers,redirectTo:f==null?void 0:f.emailRedirectTo,body:{email:u,password:h,data:(r=f==null?void 0:f.data)!==null&&r!==void 0?r:{},gotrue_meta_security:{captcha_token:f==null?void 0:f.captchaToken},code_challenge:p,code_challenge_method:v},xform:He})}else if("phone"in e){const{phone:u,password:h,options:f}=e;i=await te(this.fetch,"POST",`${this.url}/signup`,{headers:this.headers,body:{phone:u,password:h,data:(n=f==null?void 0:f.data)!==null&&n!==void 0?n:{},channel:(a=f==null?void 0:f.channel)!==null&&a!==void 0?a:"sms",gotrue_meta_security:{captcha_token:f==null?void 0:f.captchaToken}},xform:He})}else throw new Wt("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(Y(i))return{data:{user:null,session:null},error:i};throw i}}async signInWithPassword(e){try{let r;if("email"in e){const{email:i,password:o,options:l}=e;r=await te(this.fetch,"POST",`${this.url}/token?grant_type=password`,{headers:this.headers,body:{email:i,password:o,gotrue_meta_security:{captcha_token:l==null?void 0:l.captchaToken}},xform:Dr})}else if("phone"in e){const{phone:i,password:o,options:l}=e;r=await te(this.fetch,"POST",`${this.url}/token?grant_type=password`,{headers:this.headers,body:{phone:i,password:o,gotrue_meta_security:{captcha_token:l==null?void 0:l.captchaToken}},xform:Dr})}else throw new Wt("You must provide either an email or phone number and a password");const{data:n,error:a}=r;return a?{data:{user:null,session:null},error:a}:!n||!n.session||!n.user?{data:{user:null,session:null},error:new zt}:(n.session&&(await this._saveSession(n.session),await this._notifyAllSubscribers("SIGNED_IN",n.session)),{data:Object.assign({user:n.user,session:n.session},n.weak_password?{weakPassword:n.weak_password}:null),error:a})}catch(r){if(Y(r))return{data:{user:null,session:null},error:r};throw r}}async signInWithOAuth(e){var r,n,a,i;return await this._handleProviderSignIn(e.provider,{redirectTo:(r=e.options)===null||r===void 0?void 0:r.redirectTo,scopes:(n=e.options)===null||n===void 0?void 0:n.scopes,queryParams:(a=e.options)===null||a===void 0?void 0:a.queryParams,skipBrowserRedirect:(i=e.options)===null||i===void 0?void 0:i.skipBrowserRedirect})}async exchangeCodeForSession(e){return await this.initializePromise,this._acquireLock(-1,async()=>this._exchangeCodeForSession(e))}async signInWithWeb3(e){const{chain:r}=e;if(r==="solana")return await this.signInWithSolana(e);throw new Error(`@supabase/auth-js: Unsupported chain "${r}"`)}async signInWithSolana(e){var r,n,a,i,o,l,d,c,u,h,f,p;let v,w;if("message"in e)v=e.message,w=e.signature;else{const{chain:x,wallet:y,statement:P,options:_}=e;let A;if(Oe())if(typeof y=="object")A=y;else{const N=window;if("solana"in N&&typeof N.solana=="object"&&("signIn"in N.solana&&typeof N.solana.signIn=="function"||"signMessage"in N.solana&&typeof N.solana.signMessage=="function"))A=N.solana;else throw new Error("@supabase/auth-js: No compatible Solana wallet interface on the window object (window.solana) detected. Make sure the user already has a wallet installed and connected for this app. Prefer passing the wallet interface object directly to signInWithWeb3({ chain: 'solana', wallet: resolvedUserWallet }) instead.")}else{if(typeof y!="object"||!(_!=null&&_.url))throw new Error("@supabase/auth-js: Both wallet and url must be specified in non-browser environments.");A=y}const S=new URL((r=_==null?void 0:_.url)!==null&&r!==void 0?r:window.location.href);if("signIn"in A&&A.signIn){const N=await A.signIn(Object.assign(Object.assign(Object.assign({issuedAt:new Date().toISOString()},_==null?void 0:_.signInWithSolana),{version:"1",domain:S.host,uri:S.href}),P?{statement:P}:null));let j;if(Array.isArray(N)&&N[0]&&typeof N[0]=="object")j=N[0];else if(N&&typeof N=="object"&&"signedMessage"in N&&"signature"in N)j=N;else throw new Error("@supabase/auth-js: Wallet method signIn() returned unrecognized value");if("signedMessage"in j&&"signature"in j&&(typeof j.signedMessage=="string"||j.signedMessage instanceof Uint8Array)&&j.signature instanceof Uint8Array)v=typeof j.signedMessage=="string"?j.signedMessage:new TextDecoder().decode(j.signedMessage),w=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");v=[`${S.host} wants you to sign in with your Solana account:`,A.publicKey.toBase58(),...P?["",P,""]:[""],"Version: 1",`URI: ${S.href}`,`Issued At: ${(a=(n=_==null?void 0:_.signInWithSolana)===null||n===void 0?void 0:n.issuedAt)!==null&&a!==void 0?a:new Date().toISOString()}`,...!((i=_==null?void 0:_.signInWithSolana)===null||i===void 0)&&i.notBefore?[`Not Before: ${_.signInWithSolana.notBefore}`]:[],...!((o=_==null?void 0:_.signInWithSolana)===null||o===void 0)&&o.expirationTime?[`Expiration Time: ${_.signInWithSolana.expirationTime}`]:[],...!((l=_==null?void 0:_.signInWithSolana)===null||l===void 0)&&l.chainId?[`Chain ID: ${_.signInWithSolana.chainId}`]:[],...!((d=_==null?void 0:_.signInWithSolana)===null||d===void 0)&&d.nonce?[`Nonce: ${_.signInWithSolana.nonce}`]:[],...!((c=_==null?void 0:_.signInWithSolana)===null||c===void 0)&&c.requestId?[`Request ID: ${_.signInWithSolana.requestId}`]:[],...!((h=(u=_==null?void 0:_.signInWithSolana)===null||u===void 0?void 0:u.resources)===null||h===void 0)&&h.length?["Resources",..._.signInWithSolana.resources.map(j=>`- ${j}`)]:[]].join(` `);const N=await A.signMessage(new TextEncoder().encode(v),"utf8");if(!N||!(N instanceof Uint8Array))throw new Error("@supabase/auth-js: Wallet signMessage() API returned an recognized value");w=N}}try{const{data:x,error:y}=await te(this.fetch,"POST",`${this.url}/token?grant_type=web3`,{headers:this.headers,body:Object.assign({chain:"solana",message:v,signature:So(w)},!((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:He});if(y)throw y;return!x||!x.session||!x.user?{data:{user:null,session:null},error:new zt}:(x.session&&(await this._saveSession(x.session),await this._notifyAllSubscribers("SIGNED_IN",x.session)),{data:Object.assign({},x),error:y})}catch(x){if(Y(x))return{data:{user:null,session:null},error:x};throw x}}async _exchangeCodeForSession(e){const r=await Jt(this.storage,`${this.storageKey}-code-verifier`),[n,a]=(r??"").split("/");try{const{data:i,error:o}=await te(this.fetch,"POST",`${this.url}/token?grant_type=pkce`,{headers:this.headers,body:{auth_code:e,code_verifier:n},xform:He});if(await Yt(this.storage,`${this.storageKey}-code-verifier`),o)throw o;return!i||!i.session||!i.user?{data:{user:null,session:null,redirectType:null},error:new zt}:(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(Y(i))return{data:{user:null,session:null,redirectType:null},error:i};throw i}}async signInWithIdToken(e){try{const{options:r,provider:n,token:a,access_token:i,nonce:o}=e,l=await te(this.fetch,"POST",`${this.url}/token?grant_type=id_token`,{headers:this.headers,body:{provider:n,id_token:a,access_token:i,nonce:o,gotrue_meta_security:{captcha_token:r==null?void 0:r.captchaToken}},xform:He}),{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 zt}:(d.session&&(await this._saveSession(d.session),await this._notifyAllSubscribers("SIGNED_IN",d.session)),{data:d,error:c})}catch(r){if(Y(r))return{data:{user:null,session:null},error:r};throw r}}async signInWithOtp(e){var r,n,a,i,o;try{if("email"in e){const{email:l,options:d}=e;let c=null,u=null;this.flowType==="pkce"&&([c,u]=await ut(this.storage,this.storageKey));const{error:h}=await te(this.fetch,"POST",`${this.url}/otp`,{headers:this.headers,body:{email:l,data:(r=d==null?void 0:d.data)!==null&&r!==void 0?r:{},create_user:(n=d==null?void 0:d.shouldCreateUser)!==null&&n!==void 0?n:!0,gotrue_meta_security:{captcha_token:d==null?void 0:d.captchaToken},code_challenge:c,code_challenge_method:u},redirectTo:d==null?void 0:d.emailRedirectTo});return{data:{user:null,session:null},error:h}}if("phone"in e){const{phone:l,options:d}=e,{data:c,error:u}=await te(this.fetch,"POST",`${this.url}/otp`,{headers:this.headers,body:{phone:l,data:(a=d==null?void 0:d.data)!==null&&a!==void 0?a:{},create_user:(i=d==null?void 0:d.shouldCreateUser)!==null&&i!==void 0?i:!0,gotrue_meta_security:{captcha_token:d==null?void 0:d.captchaToken},channel:(o=d==null?void 0:d.channel)!==null&&o!==void 0?o:"sms"}});return{data:{user:null,session:null,messageId:c==null?void 0:c.message_id},error:u}}throw new Wt("You must provide either an email or phone number.")}catch(l){if(Y(l))return{data:{user:null,session:null},error:l};throw l}}async verifyOtp(e){var r,n;try{let a,i;"options"in e&&(a=(r=e.options)===null||r===void 0?void 0:r.redirectTo,i=(n=e.options)===null||n===void 0?void 0:n.captchaToken);const{data:o,error:l}=await te(this.fetch,"POST",`${this.url}/verify`,{headers:this.headers,body:Object.assign(Object.assign({},e),{gotrue_meta_security:{captcha_token:i}}),redirectTo:a,xform:He});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(Y(a))return{data:{user:null,session:null},error:a};throw a}}async signInWithSSO(e){var r,n,a;try{let i=null,o=null;return this.flowType==="pkce"&&([i,o]=await ut(this.storage,this.storageKey)),await te(this.fetch,"POST",`${this.url}/sso`,{body:Object.assign(Object.assign(Object.assign(Object.assign(Object.assign({},"providerId"in e?{provider_id:e.providerId}:null),"domain"in e?{domain:e.domain}:null),{redirect_to:(n=(r=e.options)===null||r===void 0?void 0:r.redirectTo)!==null&&n!==void 0?n:void 0}),!((a=e==null?void 0:e.options)===null||a===void 0)&&a.captchaToken?{gotrue_meta_security:{captcha_token:e.options.captchaToken}}:null),{skip_http_redirect:!0,code_challenge:i,code_challenge_method:o}),headers:this.headers,xform:Ho})}catch(i){if(Y(i))return{data:null,error:i};throw i}}async reauthenticate(){return await this.initializePromise,await this._acquireLock(-1,async()=>await this._reauthenticate())}async _reauthenticate(){try{return await this._useSession(async e=>{const{data:{session:r},error:n}=e;if(n)throw n;if(!r)throw new Je;const{error:a}=await te(this.fetch,"GET",`${this.url}/reauthenticate`,{headers:this.headers,jwt:r.access_token});return{data:{user:null,session:null},error:a}})}catch(e){if(Y(e))return{data:{user:null,session:null},error:e};throw e}}async resend(e){try{const r=`${this.url}/resend`;if("email"in e){const{email:n,type:a,options:i}=e,{error:o}=await te(this.fetch,"POST",r,{headers:this.headers,body:{email:n,type:a,gotrue_meta_security:{captcha_token:i==null?void 0:i.captchaToken}},redirectTo:i==null?void 0:i.emailRedirectTo});return{data:{user:null,session:null},error:o}}else if("phone"in e){const{phone:n,type:a,options:i}=e,{data:o,error:l}=await te(this.fetch,"POST",r,{headers:this.headers,body:{phone:n,type:a,gotrue_meta_security:{captcha_token:i==null?void 0:i.captchaToken}}});return{data:{user:null,session:null,messageId:o==null?void 0:o.message_id},error:l}}throw new Wt("You must provide either an email or phone number and a type")}catch(r){if(Y(r))return{data:{user:null,session:null},error:r};throw r}}async getSession(){return await this.initializePromise,await this._acquireLock(-1,async()=>this._useSession(async r=>r))}async _acquireLock(e,r){this._debug("#_acquireLock","begin",e);try{if(this.lockAcquired){const n=this.pendingInLock.length?this.pendingInLock[this.pendingInLock.length-1]:Promise.resolve(),a=(async()=>(await n,await r()))();return this.pendingInLock.push((async()=>{try{await a}catch{}})()),a}return await this.lock(`lock:${this.storageKey}`,e,async()=>{this._debug("#_acquireLock","lock acquired for storage key",this.storageKey);try{this.lockAcquired=!0;const n=r();for(this.pendingInLock.push((async()=>{try{await n}catch{}})()),await n;this.pendingInLock.length;){const a=[...this.pendingInLock];await Promise.all(a),this.pendingInLock.splice(0,a.length)}return await n}finally{this._debug("#_acquireLock","lock released for storage key",this.storageKey),this.lockAcquired=!1}})}finally{this._debug("#_acquireLock","end")}}async _useSession(e){this._debug("#_useSession","begin");try{const r=await this.__loadSession();return await e(r)}finally{this._debug("#_useSession","end")}}async __loadSession(){this._debug("#__loadSession()","begin"),this.lockAcquired||this._debug("#__loadSession()","used outside of an acquired lock!",new Error().stack);try{let e=null;const r=await Jt(this.storage,this.storageKey);if(this._debug("#getSession()","session from storage",r),r!==null&&(this._isValidSession(r)?e=r:(this._debug("#getSession()","session from storage is not valid"),await this._removeSession())),!e)return{data:{session:null},error:null};const n=e.expires_at?e.expires_at*1e3-Date.now()<Ns:!1;if(this._debug("#__loadSession()",`session has${n?"":" not"} expired`,"expires_at",e.expires_at),!n){if(this.storage.isServer){let o=this.suppressGetSessionWarning;e=new Proxy(e,{get:(d,c,u)=>(!o&&c==="user"&&(console.warn("Using the user object as returned from supabase.auth.getSession() or from some supabase.auth.onAuthStateChange() events could be insecure! This value comes directly from the storage medium (usually cookies on the server) and may not be authentic. Use supabase.auth.getUser() instead which authenticates the data by contacting the Supabase Auth server."),o=!0,this.suppressGetSessionWarning=!0),Reflect.get(d,c,u))})}return{data:{session:e},error:null}}const{session:a,error:i}=await this._callRefreshToken(e.refresh_token);return i?{data:{session:null},error:i}:{data:{session:a},error:null}}finally{this._debug("#__loadSession()","end")}}async getUser(e){return e?await this._getUser(e):(await this.initializePromise,await this._acquireLock(-1,async()=>await this._getUser()))}async _getUser(e){try{return e?await te(this.fetch,"GET",`${this.url}/user`,{headers:this.headers,jwt:e,xform:Qe}):await this._useSession(async r=>{var n,a,i;const{data:o,error:l}=r;if(l)throw l;return!(!((n=o.session)===null||n===void 0)&&n.access_token)&&!this.hasCustomAuthorizationHeader?{data:{user:null},error:new Je}:await te(this.fetch,"GET",`${this.url}/user`,{headers:this.headers,jwt:(i=(a=o.session)===null||a===void 0?void 0:a.access_token)!==null&&i!==void 0?i:void 0,xform:Qe})})}catch(r){if(Y(r))return xo(r)&&(await this._removeSession(),await Yt(this.storage,`${this.storageKey}-code-verifier`)),{data:{user:null},error:r};throw r}}async updateUser(e,r={}){return await this.initializePromise,await this._acquireLock(-1,async()=>await this._updateUser(e,r))}async _updateUser(e,r={}){try{return await this._useSession(async n=>{const{data:a,error:i}=n;if(i)throw i;if(!a.session)throw new Je;const o=a.session;let l=null,d=null;this.flowType==="pkce"&&e.email!=null&&([l,d]=await ut(this.storage,this.storageKey));const{data:c,error:u}=await te(this.fetch,"PUT",`${this.url}/user`,{headers:this.headers,redirectTo:r==null?void 0:r.emailRedirectTo,body:Object.assign(Object.assign({},e),{code_challenge:l,code_challenge_method:d}),jwt:o.access_token,xform:Qe});if(u)throw u;return o.user=c.user,await this._saveSession(o),await this._notifyAllSubscribers("USER_UPDATED",o),{data:{user:o.user},error:null}})}catch(n){if(Y(n))return{data:{user:null},error:n};throw n}}async setSession(e){return await this.initializePromise,await this._acquireLock(-1,async()=>await this._setSession(e))}async _setSession(e){try{if(!e.access_token||!e.refresh_token)throw new Je;const r=Date.now()/1e3;let n=r,a=!0,i=null;const{payload:o}=ks(e.access_token);if(o.exp&&(n=o.exp,a=n<=r),a){const{session:l,error:d}=await this._callRefreshToken(e.refresh_token);if(d)return{data:{user:null,session:null},error:d};if(!l)return{data:{user:null,session:null},error:null};i=l}else{const{data:l,error:d}=await this._getUser(e.access_token);if(d)throw d;i={access_token:e.access_token,refresh_token:e.refresh_token,user:l.user,token_type:"bearer",expires_in:n-r,expires_at:n},await this._saveSession(i),await this._notifyAllSubscribers("SIGNED_IN",i)}return{data:{user:i.user,session:i},error:null}}catch(r){if(Y(r))return{data:{session:null,user:null},error:r};throw r}}async refreshSession(e){return await this.initializePromise,await this._acquireLock(-1,async()=>await this._refreshSession(e))}async _refreshSession(e){try{return await this._useSession(async r=>{var n;if(!e){const{data:o,error:l}=r;if(l)throw l;e=(n=o.session)!==null&&n!==void 0?n:void 0}if(!(e!=null&&e.refresh_token))throw new Je;const{session:a,error:i}=await this._callRefreshToken(e.refresh_token);return i?{data:{user:null,session:null},error:i}:a?{data:{user:a.user,session:a},error:null}:{data:{user:null,session:null},error:null}})}catch(r){if(Y(r))return{data:{user:null,session:null},error:r};throw r}}async _getSessionFromURL(e,r){try{if(!Oe())throw new Vt("No browser detected.");if(e.error||e.error_description||e.error_code)throw new Vt(e.error_description||"Error in URL with unspecified error_description",{error:e.error||"unspecified_error",code:e.error_code||"unspecified_code"});switch(r){case"implicit":if(this.flowType==="pkce")throw new Pr("Not a valid PKCE flow url.");break;case"pkce":if(this.flowType==="implicit")throw new Vt("Not a valid implicit grant flow url.");break;default:}if(r==="pkce"){if(this._debug("#_initialize()","begin","is PKCE flow",!0),!e.code)throw new Pr("No code detected.");const{data:P,error:_}=await this._exchangeCodeForSession(e.code);if(_)throw _;const A=new URL(window.location.href);return A.searchParams.delete("code"),window.history.replaceState(window.history.state,"",A.toString()),{data:{session:P.session,redirectType:null},error:null}}const{provider_token:n,provider_refresh_token:a,access_token:i,refresh_token:o,expires_in:l,expires_at:d,token_type:c}=e;if(!i||!l||!o||!c)throw new Vt("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<=gt&&console.warn(`@supabase/gotrue-js: Session as retrieved from URL expires in ${p}s, should have been closer to ${h}s`);const v=f-h;u-v>=120?console.warn("@supabase/gotrue-js: Session as retrieved from URL was issued over 120s ago, URL could be stale",v,f,u):u-v<0&&console.warn("@supabase/gotrue-js: Session as retrieved from URL was issued in the future? Check the device clock for skew",v,f,u);const{data:w,error:x}=await this._getUser(i);if(x)throw x;const y={provider_token:n,provider_refresh_token:a,access_token:i,expires_in:h,expires_at:f,refresh_token:o,token_type:c,user:w.user};return window.location.hash="",this._debug("#_getSessionFromURL()","clearing window.location.hash"),{data:{session:y,redirectType:e.type},error:null}}catch(n){if(Y(n))return{data:{session:null,redirectType:null},error:n};throw n}}_isImplicitGrantCallback(e){return!!(e.access_token||e.error_description)}async _isPKCECallback(e){const r=await Jt(this.storage,`${this.storageKey}-code-verifier`);return!!(e.code&&r)}async signOut(e={scope:"global"}){return await this.initializePromise,await this._acquireLock(-1,async()=>await this._signOut(e))}async _signOut({scope:e}={scope:"global"}){return await this._useSession(async r=>{var n;const{data:a,error:i}=r;if(i)return{error:i};const o=(n=a.session)===null||n===void 0?void 0:n.access_token;if(o){const{error:l}=await this.admin.signOut(o,e);if(l&&!(po(l)&&(l.status===404||l.status===401||l.status===403)))return{error:l}}return e!=="others"&&(await this._removeSession(),await Yt(this.storage,`${this.storageKey}-code-verifier`)),{error:null}})}onAuthStateChange(e){const r=Eo(),n={id:r,callback:e,unsubscribe:()=>{this._debug("#unsubscribe()","state change callback with id removed",r),this.stateChangeEmitters.delete(r)}};return this._debug("#onAuthStateChange()","registered callback with id",r),this.stateChangeEmitters.set(r,n),(async()=>(await this.initializePromise,await this._acquireLock(-1,async()=>{this._emitInitialSession(r)})))(),{data:{subscription:n}}}async _emitInitialSession(e){return await this._useSession(async r=>{var n,a;try{const{data:{session:i},error:o}=r;if(o)throw o;await((n=this.stateChangeEmitters.get(e))===null||n===void 0?void 0:n.callback("INITIAL_SESSION",i)),this._debug("INITIAL_SESSION","callback id",e,"session",i)}catch(i){await((a=this.stateChangeEmitters.get(e))===null||a===void 0?void 0:a.callback("INITIAL_SESSION",null)),this._debug("INITIAL_SESSION","callback id",e,"error",i),console.error(i)}})}async resetPasswordForEmail(e,r={}){let n=null,a=null;this.flowType==="pkce"&&([n,a]=await ut(this.storage,this.storageKey,!0));try{return await te(this.fetch,"POST",`${this.url}/recover`,{body:{email:e,code_challenge:n,code_challenge_method:a,gotrue_meta_security:{captcha_token:r.captchaToken}},headers:this.headers,redirectTo:r.redirectTo})}catch(i){if(Y(i))return{data:null,error:i};throw i}}async getUserIdentities(){var e;try{const{data:r,error:n}=await this.getUser();if(n)throw n;return{data:{identities:(e=r.user.identities)!==null&&e!==void 0?e:[]},error:null}}catch(r){if(Y(r))return{data:null,error:r};throw r}}async linkIdentity(e){var r;try{const{data:n,error:a}=await this._useSession(async i=>{var o,l,d,c,u;const{data:h,error:f}=i;if(f)throw f;const 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 te(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 Oe()&&!(!((r=e.options)===null||r===void 0)&&r.skipBrowserRedirect)&&window.location.assign(n==null?void 0:n.url),{data:{provider:e.provider,url:n==null?void 0:n.url},error:null}}catch(n){if(Y(n))return{data:{provider:e.provider,url:null},error:n};throw n}}async unlinkIdentity(e){try{return await this._useSession(async r=>{var n,a;const{data:i,error:o}=r;if(o)throw o;return await te(this.fetch,"DELETE",`${this.url}/user/identities/${e.identity_id}`,{headers:this.headers,jwt:(a=(n=i.session)===null||n===void 0?void 0:n.access_token)!==null&&a!==void 0?a:void 0})})}catch(r){if(Y(r))return{data:null,error:r};throw r}}async _refreshAccessToken(e){const r=`#_refreshAccessToken(${e.substring(0,5)}...)`;this._debug(r,"begin");try{const n=Date.now();return await Ao(async a=>(a>0&&await Po(200*Math.pow(2,a-1)),this._debug(r,"refreshing attempt",a),await te(this.fetch,"POST",`${this.url}/token?grant_type=refresh_token`,{body:{refresh_token:e},headers:this.headers,xform:He})),(a,i)=>{const o=200*Math.pow(2,a);return i&&Ss(i)&&Date.now()+o-n<gt})}catch(n){if(this._debug(r,"error",n),Y(n))return{data:{session:null,user:null},error:n};throw n}finally{this._debug(r,"end")}}_isValidSession(e){return typeof e=="object"&&e!==null&&"access_token"in e&&"refresh_token"in e&&"expires_at"in e}async _handleProviderSignIn(e,r){const n=await this._getUrlForProvider(`${this.url}/authorize`,e,{redirectTo:r.redirectTo,scopes:r.scopes,queryParams:r.queryParams});return this._debug("#_handleProviderSignIn()","provider",e,"options",r,"url",n),Oe()&&!r.skipBrowserRedirect&&window.location.assign(n),{data:{provider:e,url:n},error:null}}async _recoverAndRefresh(){var e;const r="#_recoverAndRefresh()";this._debug(r,"begin");try{const n=await Jt(this.storage,this.storageKey);if(this._debug(r,"session from storage",n),!this._isValidSession(n)){this._debug(r,"session is not valid"),n!==null&&await this._removeSession();return}const a=((e=n.expires_at)!==null&&e!==void 0?e:1/0)*1e3-Date.now()<Ns;if(this._debug(r,`session has${a?"":" not"} expired with margin of ${Ns}s`),a){if(this.autoRefreshToken&&n.refresh_token){const{error:i}=await this._callRefreshToken(n.refresh_token);i&&(console.error(i),Ss(i)||(this._debug(r,"refresh failed with a non-retryable error, removing the session",i),await this._removeSession()))}}else await this._notifyAllSubscribers("SIGNED_IN",n)}catch(n){this._debug(r,"error",n),console.error(n);return}finally{this._debug(r,"end")}}async _callRefreshToken(e){var r,n;if(!e)throw new Je;if(this.refreshingDeferred)return this.refreshingDeferred.promise;const a=`#_callRefreshToken(${e.substring(0,5)}...)`;this._debug(a,"begin");try{this.refreshingDeferred=new fs;const{data:i,error:o}=await this._refreshAccessToken(e);if(o)throw o;if(!i.session)throw new Je;await this._saveSession(i.session),await this._notifyAllSubscribers("TOKEN_REFRESHED",i.session);const l={session:i.session,error:null};return this.refreshingDeferred.resolve(l),l}catch(i){if(this._debug(a,"error",i),Y(i)){const o={session:null,error:i};return Ss(i)||await this._removeSession(),(r=this.refreshingDeferred)===null||r===void 0||r.resolve(o),o}throw(n=this.refreshingDeferred)===null||n===void 0||n.reject(i),i}finally{this.refreshingDeferred=null,this._debug(a,"end")}}async _notifyAllSubscribers(e,r,n=!0){const a=`#_notifyAllSubscribers(${e})`;this._debug(a,"begin",r,`broadcast = ${n}`);try{this.broadcastChannel&&n&&this.broadcastChannel.postMessage({event:e,session:r});const i=[],o=Array.from(this.stateChangeEmitters.values()).map(async l=>{try{await l.callback(e,r)}catch(d){i.push(d)}});if(await Promise.all(o),i.length>0){for(let l=0;l<i.length;l+=1)console.error(i[l]);throw i[0]}}finally{this._debug(a,"end")}}async _saveSession(e){this._debug("#_saveSession()",e),this.suppressGetSessionWarning=!0,await An(this.storage,this.storageKey,e)}async _removeSession(){this._debug("#_removeSession()"),await Yt(this.storage,this.storageKey),await this._notifyAllSubscribers("SIGNED_OUT",null)}_removeVisibilityChangedCallback(){this._debug("#_removeVisibilityChangedCallback()");const e=this.visibilityChangedCallback;this.visibilityChangedCallback=null;try{e&&Oe()&&(window!=null&&window.removeEventListener)&&window.removeEventListener("visibilitychange",e)}catch(r){console.error("removing visibilitychange callback failed",r)}}async _startAutoRefresh(){await this._stopAutoRefresh(),this._debug("#_startAutoRefresh()");const e=setInterval(()=>this._autoRefreshTokenTick(),gt);this.autoRefreshTicker=e,e&&typeof e=="object"&&typeof e.unref=="function"?e.unref():typeof Deno<"u"&&typeof Deno.unrefTimer=="function"&&Deno.unrefTimer(e),setTimeout(async()=>{await this.initializePromise,await this._autoRefreshTokenTick()},0)}async _stopAutoRefresh(){this._debug("#_stopAutoRefresh()");const e=this.autoRefreshTicker;this.autoRefreshTicker=null,e&&clearInterval(e)}async startAutoRefresh(){this._removeVisibilityChangedCallback(),await this._startAutoRefresh()}async stopAutoRefresh(){this._removeVisibilityChangedCallback(),await this._stopAutoRefresh()}async _autoRefreshTokenTick(){this._debug("#_autoRefreshTokenTick()","begin");try{await this._acquireLock(0,async()=>{try{const e=Date.now();try{return await this._useSession(async r=>{const{data:{session:n}}=r;if(!n||!n.refresh_token||!n.expires_at){this._debug("#_autoRefreshTokenTick()","no session");return}const a=Math.floor((n.expires_at*1e3-e)/gt);this._debug("#_autoRefreshTokenTick()",`access token expires in ${a} ticks, a tick lasts ${gt}ms, refresh threshold is ${qs} ticks`),a<=qs&&await this._callRefreshToken(n.refresh_token)})}catch(r){console.error("Auto refresh tick failed with error. This is likely a transient error.",r)}}finally{this._debug("#_autoRefreshTokenTick()","end")}})}catch(e){if(e.isAcquireTimeout||e instanceof On)this._debug("auto refresh token tick lock not available");else throw e}}async _handleVisibilityChange(){if(this._debug("#_handleVisibilityChange()"),!Oe()||!(window!=null&&window.addEventListener))return this.autoRefreshToken&&this.startAutoRefresh(),!1;try{this.visibilityChangedCallback=async()=>await this._onVisibilityChanged(!1),window==null||window.addEventListener("visibilitychange",this.visibilityChangedCallback),await this._onVisibilityChanged(!0)}catch(e){console.error("_handleVisibilityChange",e)}}async _onVisibilityChanged(e){const r=`#_onVisibilityChanged(${e})`;this._debug(r,"visibilityState",document.visibilityState),document.visibilityState==="visible"?(this.autoRefreshToken&&this._startAutoRefresh(),e||(await this.initializePromise,await this._acquireLock(-1,async()=>{if(document.visibilityState!=="visible"){this._debug(r,"acquired the lock to recover the session, but the browser visibilityState is no longer visible, aborting");return}await this._recoverAndRefresh()}))):document.visibilityState==="hidden"&&this.autoRefreshToken&&this._stopAutoRefresh()}async _getUrlForProvider(e,r,n){const a=[`provider=${encodeURIComponent(r)}`];if(n!=null&&n.redirectTo&&a.push(`redirect_to=${encodeURIComponent(n.redirectTo)}`),n!=null&&n.scopes&&a.push(`scopes=${encodeURIComponent(n.scopes)}`),this.flowType==="pkce"){const[i,o]=await ut(this.storage,this.storageKey),l=new URLSearchParams({code_challenge:`${encodeURIComponent(i)}`,code_challenge_method:`${encodeURIComponent(o)}`});a.push(l.toString())}if(n!=null&&n.queryParams){const i=new URLSearchParams(n.queryParams);a.push(i.toString())}return n!=null&&n.skipBrowserRedirect&&a.push(`skip_http_redirect=${n.skipBrowserRedirect}`),`${e}?${a.join("&")}`}async _unenroll(e){try{return await this._useSession(async r=>{var n;const{data:a,error:i}=r;return i?{data:null,error:i}:await te(this.fetch,"DELETE",`${this.url}/factors/${e.factorId}`,{headers:this.headers,jwt:(n=a==null?void 0:a.session)===null||n===void 0?void 0:n.access_token})})}catch(r){if(Y(r))return{data:null,error:r};throw r}}async _enroll(e){try{return await this._useSession(async r=>{var n,a;const{data:i,error:o}=r;if(o)return{data:null,error:o};const l=Object.assign({friendly_name:e.friendlyName,factor_type:e.factorType},e.factorType==="phone"?{phone:e.phone}:{issuer:e.issuer}),{data:d,error:c}=await te(this.fetch,"POST",`${this.url}/factors`,{body:l,headers:this.headers,jwt:(n=i==null?void 0:i.session)===null||n===void 0?void 0:n.access_token});return c?{data:null,error:c}:(e.factorType==="totp"&&(!((a=d==null?void 0:d.totp)===null||a===void 0)&&a.qr_code)&&(d.totp.qr_code=`data:image/svg+xml;utf-8,${d.totp.qr_code}`),{data:d,error:null})})}catch(r){if(Y(r))return{data:null,error:r};throw r}}async _verify(e){return this._acquireLock(-1,async()=>{try{return await this._useSession(async r=>{var n;const{data:a,error:i}=r;if(i)return{data:null,error:i};const{data:o,error:l}=await te(this.fetch,"POST",`${this.url}/factors/${e.factorId}/verify`,{body:{code:e.code,challenge_id:e.challengeId},headers:this.headers,jwt:(n=a==null?void 0:a.session)===null||n===void 0?void 0:n.access_token});return l?{data:null,error:l}:(await this._saveSession(Object.assign({expires_at:Math.round(Date.now()/1e3)+o.expires_in},o)),await this._notifyAllSubscribers("MFA_CHALLENGE_VERIFIED",o),{data:o,error:l})})}catch(r){if(Y(r))return{data:null,error:r};throw r}})}async _challenge(e){return this._acquireLock(-1,async()=>{try{return await this._useSession(async r=>{var n;const{data:a,error:i}=r;return i?{data:null,error:i}:await te(this.fetch,"POST",`${this.url}/factors/${e.factorId}/challenge`,{body:{channel:e.channel},headers:this.headers,jwt:(n=a==null?void 0:a.session)===null||n===void 0?void 0:n.access_token})})}catch(r){if(Y(r))return{data:null,error:r};throw r}})}async _challengeAndVerify(e){const{data:r,error:n}=await this._challenge({factorId:e.factorId});return n?{data:null,error:n}:await this._verify({factorId:e.factorId,challengeId:r.id,code:e.code})}async _listFactors(){const{data:{user:e},error:r}=await this.getUser();if(r)return{data:null,error:r};const n=(e==null?void 0:e.factors)||[],a=n.filter(o=>o.factor_type==="totp"&&o.status==="verified"),i=n.filter(o=>o.factor_type==="phone"&&o.status==="verified");return{data:{all:n,totp:a,phone:i},error:null}}async _getAuthenticatorAssuranceLevel(){return this._acquireLock(-1,async()=>await this._useSession(async e=>{var r,n;const{data:{session:a},error:i}=e;if(i)return{data:null,error:i};if(!a)return{data:{currentLevel:null,nextLevel:null,currentAuthenticationMethods:[]},error:null};const{payload:o}=ks(a.access_token);let l=null;o.aal&&(l=o.aal);let d=l;((n=(r=a.user.factors)===null||r===void 0?void 0:r.filter(h=>h.status==="verified"))!==null&&n!==void 0?n:[]).length>0&&(d="aal2");const u=o.amr||[];return{data:{currentLevel:l,nextLevel:d,currentAuthenticationMethods:u},error:null}}))}async fetchJwk(e,r={keys:[]}){let n=r.keys.find(o=>o.kid===e);if(n||(n=this.jwks.keys.find(o=>o.kid===e),n&&this.jwks_cached_at+mo>Date.now()))return n;const{data:a,error:i}=await te(this.fetch,"GET",`${this.url}/.well-known/jwks.json`,{headers:this.headers});if(i)throw i;if(!a.keys||a.keys.length===0)throw new Rt("JWKS is empty");if(this.jwks=a,this.jwks_cached_at=Date.now(),n=a.keys.find(o=>o.kid===e),!n)throw new Rt("No matching signing key found in JWKS");return n}async getClaims(e,r={keys:[]}){try{let n=e;if(!n){const{data:p,error:v}=await this.getSession();if(v||!p.session)return{data:null,error:v};n=p.session.access_token}const{header:a,payload:i,signature:o,raw:{header:l,payload:d}}=ks(n);if(Uo(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=Bo(a.alg),u=await this.fetchJwk(a.kid,r),h=await crypto.subtle.importKey("jwk",u,c,!0,["verify"]);if(!await crypto.subtle.verify(c,h,o,No(`${l}.${d}`)))throw new Rt("Invalid JWT signature");return{data:{claims:i,header:a,signature:o},error:null}}catch(n){if(Y(n))return{data:null,error:n};throw n}}}$t.nextInstanceID=0;const sl=$t;class rl extends sl{constructor(e){super(e)}}var nl=function(s,e,r,n){function a(i){return i instanceof r?i:new r(function(o){o(i)})}return new(r||(r=Promise))(function(i,o){function l(u){try{c(n.next(u))}catch(h){o(h)}}function d(u){try{c(n.throw(u))}catch(h){o(h)}}function c(u){u.done?i(u.value):a(u.value).then(l,d)}c((n=n.apply(s,e||[])).next())})};class al{constructor(e,r,n){var a,i,o;if(this.supabaseUrl=e,this.supabaseKey=r,!e)throw new Error("supabaseUrl is required.");if(!r)throw new Error("supabaseKey is required.");const l=oo(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:Xi,realtime:to,auth:Object.assign(Object.assign({},eo),{storageKey:c}),global:Zi},h=lo(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=ao(r,this._getAccessToken.bind(this),h.global.fetch),this.realtime=this._initRealtimeClient(Object.assign({headers:this.headers,accessToken:this._getAccessToken.bind(this)},h.realtime)),this.rest=new ji(new URL("rest/v1",d).href,{headers:this.headers,schema:h.db.schema,fetch:this.fetch}),h.accessToken||this._listenForAuthEvents()}get functions(){return new Za(this.functionsUrl.href,{headers:this.headers,customFetch:this.fetch})}get storage(){return new Ji(this.storageUrl.href,this.headers,this.fetch)}from(e){return this.rest.from(e)}schema(e){return this.rest.schema(e)}rpc(e,r={},n={}){return this.rest.rpc(e,r,n)}channel(e,r={config:{}}){return this.realtime.channel(e,r)}getChannels(){return this.realtime.getChannels()}removeChannel(e){return this.realtime.removeChannel(e)}removeAllChannels(){return this.realtime.removeAllChannels()}_getAccessToken(){var e,r;return nl(this,void 0,void 0,function*(){if(this.accessToken)return yield this.accessToken();const{data:n}=yield this.auth.getSession();return(r=(e=n.session)===null||e===void 0?void 0:e.access_token)!==null&&r!==void 0?r:null})}_initSupabaseAuthClient({autoRefreshToken:e,persistSession:r,detectSessionInUrl:n,storage:a,storageKey:i,flowType:o,lock:l,debug:d},c,u){const h={Authorization:`Bearer ${this.supabaseKey}`,apikey:`${this.supabaseKey}`};return new rl({url:this.authUrl.href,headers:Object.assign(Object.assign({},h),c),storageKey:i,autoRefreshToken:e,persistSession:r,detectSessionInUrl:n,storage:a,flowType:o,lock:l,debug:d,fetch:u,hasCustomAuthorizationHeader:"Authorization"in this.headers})}_initRealtimeClient(e){return new Ri(this.realtimeUrl.href,Object.assign(Object.assign({},e),{params:Object.assign({apikey:this.supabaseKey},e==null?void 0:e.params)}))}_listenForAuthEvents(){return this.auth.onAuthStateChange((r,n)=>{this._handleTokenChanged(r,"CLIENT",n==null?void 0:n.access_token)})}_handleTokenChanged(e,r,n){(e==="TOKEN_REFRESHED"||e==="SIGNED_IN")&&this.changedAccessToken!==n?this.changedAccessToken=n:e==="SIGNED_OUT"&&(this.realtime.setAuth(),r=="STORAGE"&&this.auth.signOut(),this.changedAccessToken=void 0)}}const il=(s,e,r)=>new al(s,e,r),ol="https://ftwlzdhkzqfuosdorgjt.supabase.co",ll="eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJpc3MiOiJzdXBhYmFzZSIsInJlZiI6ImZ0d2x6ZGhrenFmdW9zZG9yZ2p0Iiwicm9sZSI6ImFub24iLCJpYXQiOjE3MzE1Mjc0MzksImV4cCI6MjA0NzEwMzQzOX0.msaWtaLGNMDiyuxIOFDwULWee0nqcM7p_LAYWB14j1k",W=il(ol,ll,{auth:{persistSession:!0,autoRefreshToken:!0,detectSessionInUrl:!0}}),Ln=b.createContext({user:null,isAdmin:!1,loading:!0,signIn:async()=>{},signOut:async()=>{}}),Cs="ben@phippsmusic.com";function cl({children:s}){const[e,r]=b.useState(null),[n,a]=b.useState(!1),[i,o]=b.useState(!0);b.useEffect(()=>{W.auth.getSession().then(({data:{session:u}})=>{u!=null&&u.user&&(r({id:u.user.id,email:u.user.email||""}),a(u.user.email===Cs)),o(!1)});const{data:{subscription:c}}=W.auth.onAuthStateChange((u,h)=>{h!=null&&h.user?(r({id:h.user.id,email:h.user.email||""}),a(h.user.email===Cs)):(r(null),a(!1)),o(!1)});return()=>{c.unsubscribe()}},[]);const l=async(c,u)=>{o(!0);try{const{data:h,error:f}=await W.auth.signInWithPassword({email:c,password:u});if(f)throw f;if(h.user.email!==Cs)throw await W.auth.signOut(),new Error("Unauthorized access");r({id:h.user.id,email:h.user.email}),a(!0)}catch(h){throw console.error("Sign in failed:",h),h}finally{o(!1)}},d=async()=>{try{await W.auth.signOut(),r(null),a(!1)}catch(c){throw console.error("Sign out failed:",c),c}};return t.jsx(Ln.Provider,{value:{user:e,isAdmin:n,loading:i,signIn:l,signOut:d},children:s})}function nr(){return b.useContext(Ln)}/** * @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 dl={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 ul=s=>s.replace(/([a-z0-9])([A-Z])/g,"$1-$2").toLowerCase().trim(),z=(s,e)=>{const r=b.forwardRef(({color:n="currentColor",size:a=24,strokeWidth:i=2,absoluteStrokeWidth:o,className:l="",children:d,...c},u)=>b.createElement("svg",{ref:u,...dl,width:a,height:a,stroke:n,strokeWidth:o?Number(i)*24/Number(a):i,className:["lucide",`lucide-${ul(s)}`,l].join(" "),...c},[...e.map(([h,f])=>b.createElement(h,f)),...Array.isArray(d)?d:[d]]));return r.displayName=`${s}`,r};/** * @license lucide-react v0.344.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const fe=z("AlertCircle",[["circle",{cx:"12",cy:"12",r:"10",key:"1mglay"}],["line",{x1:"12",x2:"12",y1:"8",y2:"12",key:"1pkeuh"}],["line",{x1:"12",x2:"12.01",y1:"16",y2:"16",key:"4dfq90"}]]);/** * @license lucide-react v0.344.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const hl=z("AlertTriangle",[["path",{d:"m21.73 18-8-14a2 2 0 0 0-3.48 0l-8 14A2 2 0 0 0 4 21h16a2 2 0 0 0 1.73-3Z",key:"c3ski4"}],["path",{d:"M12 9v4",key:"juzpu7"}],["path",{d:"M12 17h.01",key:"p32p05"}]]);/** * @license lucide-react v0.344.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const We=z("ArrowLeft",[["path",{d:"m12 19-7-7 7-7",key:"1l729n"}],["path",{d:"M19 12H5",key:"x3x0zl"}]]);/** * @license lucide-react v0.344.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const Ut=z("ArrowRight",[["path",{d:"M5 12h14",key:"1ays0h"}],["path",{d:"m12 5 7 7-7 7",key:"xquz4c"}]]);/** * @license lucide-react v0.344.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const ms=z("Calendar",[["path",{d:"M8 2v4",key:"1cmpym"}],["path",{d:"M16 2v4",key:"4m81vk"}],["rect",{width:"18",height:"18",x:"3",y:"4",rx:"2",key:"1hopcy"}],["path",{d:"M3 10h18",key:"8toen8"}]]);/** * @license lucide-react v0.344.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const Hs=z("CheckCircle2",[["circle",{cx:"12",cy:"12",r:"10",key:"1mglay"}],["path",{d:"m9 12 2 2 4-4",key:"dzmm74"}]]);/** * @license lucide-react v0.344.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const nt=z("CheckCircle",[["path",{d:"M22 11.08V12a10 10 0 1 1-5.93-9.14",key:"g774vq"}],["path",{d:"m9 11 3 3L22 4",key:"1pflzl"}]]);/** * @license lucide-react v0.344.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const In=z("Check",[["path",{d:"M20 6 9 17l-5-5",key:"1gmf2c"}]]);/** * @license lucide-react v0.344.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const fl=z("ChevronRight",[["path",{d:"m9 18 6-6-6-6",key:"mthhwq"}]]);/** * @license lucide-react v0.344.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const Br=z("Clock",[["circle",{cx:"12",cy:"12",r:"10",key:"1mglay"}],["polyline",{points:"12 6 12 12 16 14",key:"68esgv"}]]);/** * @license lucide-react v0.344.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const ml=z("Disc",[["circle",{cx:"12",cy:"12",r:"10",key:"1mglay"}],["circle",{cx:"12",cy:"12",r:"2",key:"1c9p78"}]]);/** * @license lucide-react v0.344.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const gl=z("ExternalLink",[["path",{d:"M15 3h6v6",key:"1q9fwt"}],["path",{d:"M10 14 21 3",key:"gplh6r"}],["path",{d:"M18 13v6a2 2 0 0 1-2 2H5a2 2 0 0 1-2-2V8a2 2 0 0 1 2-2h6",key:"a6xqqp"}]]);/** * @license lucide-react v0.344.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const pl=z("GripVertical",[["circle",{cx:"9",cy:"12",r:"1",key:"1vctgf"}],["circle",{cx:"9",cy:"5",r:"1",key:"hp0tcf"}],["circle",{cx:"9",cy:"19",r:"1",key:"fkjjf6"}],["circle",{cx:"15",cy:"12",r:"1",key:"1tmaij"}],["circle",{cx:"15",cy:"5",r:"1",key:"19l28e"}],["circle",{cx:"15",cy:"19",r:"1",key:"f4zoj3"}]]);/** * @license lucide-react v0.344.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const xl=z("Heart",[["path",{d:"M19 14c1.49-1.46 3-3.21 3-5.5A5.5 5.5 0 0 0 16.5 3c-1.76 0-3 .5-4.5 2-1.5-1.5-2.74-2-4.5-2A5.5 5.5 0 0 0 2 8.5c0 2.3 1.5 4.05 3 5.5l7 7Z",key:"c3ymky"}]]);/** * @license lucide-react v0.344.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const yl=z("History",[["path",{d:"M3 12a9 9 0 1 0 9-9 9.75 9.75 0 0 0-6.74 2.74L3 8",key:"1357e3"}],["path",{d:"M3 3v5h5",key:"1xhq8a"}],["path",{d:"M12 7v5l4 2",key:"1fdv2h"}]]);/** * @license lucide-react v0.344.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const Rn=z("Image",[["rect",{width:"18",height:"18",x:"3",y:"3",rx:"2",ry:"2",key:"1m3agn"}],["circle",{cx:"9",cy:"9",r:"2",key:"af1f0g"}],["path",{d:"m21 15-3.086-3.086a2 2 0 0 0-2.828 0L6 21",key:"1xmnt7"}]]);/** * @license lucide-react v0.344.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const bl=z("Inbox",[["polyline",{points:"22 12 16 12 14 15 10 15 8 12 2 12",key:"o97t9d"}],["path",{d:"M5.45 5.11 2 12v6a2 2 0 0 0 2 2h16a2 2 0 0 0 2-2v-6l-3.45-6.89A2 2 0 0 0 16.76 4H7.24a2 2 0 0 0-1.79 1.11z",key:"oot6mr"}]]);/** * @license lucide-react v0.344.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const wl=z("LayoutDashboard",[["rect",{width:"7",height:"9",x:"3",y:"3",rx:"1",key:"10lvy0"}],["rect",{width:"7",height:"5",x:"14",y:"3",rx:"1",key:"16une8"}],["rect",{width:"7",height:"9",x:"14",y:"12",rx:"1",key:"1hutg5"}],["rect",{width:"7",height:"5",x:"3",y:"16",rx:"1",key:"ldoo1y"}]]);/** * @license lucide-react v0.344.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const zs=z("Link",[["path",{d:"M10 13a5 5 0 0 0 7.54.54l3-3a5 5 0 0 0-7.07-7.07l-1.72 1.71",key:"1cjeqo"}],["path",{d:"M14 11a5 5 0 0 0-7.54-.54l-3 3a5 5 0 0 0 7.07 7.07l1.71-1.71",key:"19qd67"}]]);/** * @license lucide-react v0.344.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const Dn=z("ListMusic",[["path",{d:"M21 15V6",key:"h1cx4g"}],["path",{d:"M18.5 18a2.5 2.5 0 1 0 0-5 2.5 2.5 0 0 0 0 5Z",key:"8saifv"}],["path",{d:"M12 12H3",key:"18klou"}],["path",{d:"M16 6H3",key:"1wxfjs"}],["path",{d:"M12 18H3",key:"11ftsu"}]]);/** * @license lucide-react v0.344.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const vl=z("List",[["line",{x1:"8",x2:"21",y1:"6",y2:"6",key:"7ey8pc"}],["line",{x1:"8",x2:"21",y1:"12",y2:"12",key:"rjfblc"}],["line",{x1:"8",x2:"21",y1:"18",y2:"18",key:"c3b1m8"}],["line",{x1:"3",x2:"3.01",y1:"6",y2:"6",key:"1g7gq3"}],["line",{x1:"3",x2:"3.01",y1:"12",y2:"12",key:"1pjlvk"}],["line",{x1:"3",x2:"3.01",y1:"18",y2:"18",key:"28t2mc"}]]);/** * @license lucide-react v0.344.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const me=z("Loader2",[["path",{d:"M21 12a9 9 0 1 1-6.219-8.56",key:"13zald"}]]);/** * @license lucide-react v0.344.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const jl=z("Lock",[["rect",{width:"18",height:"11",x:"3",y:"11",rx:"2",ry:"2",key:"1w4ew1"}],["path",{d:"M7 11V7a5 5 0 0 1 10 0v4",key:"fwvmzm"}]]);/** * @license lucide-react v0.344.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const _l=z("LogOut",[["path",{d:"M9 21H5a2 2 0 0 1-2-2V5a2 2 0 0 1 2-2h4",key:"1uf3rs"}],["polyline",{points:"16 17 21 12 16 7",key:"1gabdz"}],["line",{x1:"21",x2:"9",y1:"12",y2:"12",key:"1uyos4"}]]);/** * @license lucide-react v0.344.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const $n=z("Mail",[["rect",{width:"20",height:"16",x:"2",y:"4",rx:"2",key:"18n3k1"}],["path",{d:"m22 7-8.97 5.7a1.94 1.94 0 0 1-2.06 0L2 7",key:"1ocrg3"}]]);/** * @license lucide-react v0.344.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const Nl=z("Menu",[["line",{x1:"4",x2:"20",y1:"12",y2:"12",key:"1e0a9i"}],["line",{x1:"4",x2:"20",y1:"6",y2:"6",key:"1owob3"}],["line",{x1:"4",x2:"20",y1:"18",y2:"18",key:"yk5zj1"}]]);/** * @license lucide-react v0.344.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const Un=z("MessageSquare",[["path",{d:"M21 15a2 2 0 0 1-2 2H7l-4 4V5a2 2 0 0 1 2-2h14a2 2 0 0 1 2 2z",key:"1lielz"}]]);/** * @license lucide-react v0.344.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const ve=z("Music2",[["circle",{cx:"8",cy:"18",r:"4",key:"1fc0mg"}],["path",{d:"M12 18V2l7 4",key:"g04rme"}]]);/** * @license lucide-react v0.344.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const gs=z("Music4",[["path",{d:"M9 18V5l12-2v13",key:"1jmyc2"}],["path",{d:"m9 9 12-2",key:"1e64n2"}],["circle",{cx:"6",cy:"18",r:"3",key:"fqmcym"}],["circle",{cx:"18",cy:"16",r:"3",key:"1hluhg"}]]);/** * @license lucide-react v0.344.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const Sl=z("Newspaper",[["path",{d:"M4 22h16a2 2 0 0 0 2-2V4a2 2 0 0 0-2-2H8a2 2 0 0 0-2 2v16a2 2 0 0 1-2 2Zm0 0a2 2 0 0 1-2-2v-9c0-1.1.9-2 2-2h2",key:"7pis2x"}],["path",{d:"M18 14h-8",key:"sponae"}],["path",{d:"M15 18h-5",key:"95g1m2"}],["path",{d:"M10 6h8v4h-8V6Z",key:"smlsk5"}]]);/** * @license lucide-react v0.344.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const kl=z("Pen",[["path",{d:"M17 3a2.85 2.83 0 1 1 4 4L7.5 20.5 2 22l1.5-5.5Z",key:"5qss01"}]]);/** * @license lucide-react v0.344.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const ar=z("Plus",[["path",{d:"M5 12h14",key:"1ays0h"}],["path",{d:"M12 5v14",key:"s699le"}]]);/** * @license lucide-react v0.344.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const vt=z("RefreshCw",[["path",{d:"M3 12a9 9 0 0 1 9-9 9.75 9.75 0 0 1 6.74 2.74L21 8",key:"v9h5vc"}],["path",{d:"M21 3v5h-5",key:"1q7to0"}],["path",{d:"M21 12a9 9 0 0 1-9 9 9.75 9.75 0 0 1-6.74-2.74L3 16",key:"3uifl3"}],["path",{d:"M8 16H3v5",key:"1cv678"}]]);/** * @license lucide-react v0.344.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const El=z("Save",[["path",{d:"M19 21H5a2 2 0 0 1-2-2V5a2 2 0 0 1 2-2h11l5 5v11a2 2 0 0 1-2 2z",key:"1owoqh"}],["polyline",{points:"17 21 17 13 7 13 7 21",key:"1md35c"}],["polyline",{points:"7 3 7 8 15 8",key:"8nz8an"}]]);/** * @license lucide-react v0.344.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const ps=z("Search",[["circle",{cx:"11",cy:"11",r:"8",key:"4ej97u"}],["path",{d:"m21 21-4.3-4.3",key:"1qie3q"}]]);/** * @license lucide-react v0.344.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const Bn=z("Send",[["path",{d:"m22 2-7 20-4-9-9-4Z",key:"1q3vgg"}],["path",{d:"M22 2 11 13",key:"nzbqef"}]]);/** * @license lucide-react v0.344.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const Cl=z("Settings",[["path",{d:"M12.22 2h-.44a2 2 0 0 0-2 2v.18a2 2 0 0 1-1 1.73l-.43.25a2 2 0 0 1-2 0l-.15-.08a2 2 0 0 0-2.73.73l-.22.38a2 2 0 0 0 .73 2.73l.15.1a2 2 0 0 1 1 1.72v.51a2 2 0 0 1-1 1.74l-.15.09a2 2 0 0 0-.73 2.73l.22.38a2 2 0 0 0 2.73.73l.15-.08a2 2 0 0 1 2 0l.43.25a2 2 0 0 1 1 1.73V20a2 2 0 0 0 2 2h.44a2 2 0 0 0 2-2v-.18a2 2 0 0 1 1-1.73l.43-.25a2 2 0 0 1 2 0l.15.08a2 2 0 0 0 2.73-.73l.22-.39a2 2 0 0 0-.73-2.73l-.15-.08a2 2 0 0 1-1-1.74v-.5a2 2 0 0 1 1-1.74l.15-.09a2 2 0 0 0 .73-2.73l-.22-.38a2 2 0 0 0-2.73-.73l-.15.08a2 2 0 0 1-2 0l-.43-.25a2 2 0 0 1-1-1.73V4a2 2 0 0 0-2-2z",key:"1qme2f"}],["circle",{cx:"12",cy:"12",r:"3",key:"1v7zrd"}]]);/** * @license lucide-react v0.344.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const Tl=z("Sparkles",[["path",{d:"m12 3-1.912 5.813a2 2 0 0 1-1.275 1.275L3 12l5.813 1.912a2 2 0 0 1 1.275 1.275L12 21l1.912-5.813a2 2 0 0 1 1.275-1.275L21 12l-5.813-1.912a2 2 0 0 1-1.275-1.275L12 3Z",key:"17u4zn"}],["path",{d:"M5 3v4",key:"bklmnn"}],["path",{d:"M19 17v4",key:"iiml17"}],["path",{d:"M3 5h4",key:"nem4j1"}],["path",{d:"M17 19h4",key:"lbex7p"}]]);/** * @license lucide-react v0.344.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const Mn=z("SquarePen",[["path",{d:"M12 3H5a2 2 0 0 0-2 2v14a2 2 0 0 0 2 2h14a2 2 0 0 0 2-2v-7",key:"1m0v6g"}],["path",{d:"M18.375 2.625a2.121 2.121 0 1 1 3 3L12 15l-4 1 1-4Z",key:"1lpok0"}]]);/** * @license lucide-react v0.344.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const Fn=z("Star",[["polygon",{points:"12 2 15.09 8.26 22 9.27 17 14.14 18.18 21.02 12 17.77 5.82 21.02 7 14.14 2 9.27 8.91 8.26 12 2",key:"8f66p6"}]]);/** * @license lucide-react v0.344.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const Ws=z("Tag",[["path",{d:"M12.586 2.586A2 2 0 0 0 11.172 2H4a2 2 0 0 0-2 2v7.172a2 2 0 0 0 .586 1.414l8.704 8.704a2.426 2.426 0 0 0 3.42 0l6.58-6.58a2.426 2.426 0 0 0 0-3.42z",key:"vktsd0"}],["circle",{cx:"7.5",cy:"7.5",r:".5",fill:"currentColor",key:"kqv944"}]]);/** * @license lucide-react v0.344.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const ir=z("Trash2",[["path",{d:"M3 6h18",key:"d0wm0j"}],["path",{d:"M19 6v14c0 1-1 2-2 2H7c-1 0-2-1-2-2V6",key:"4alrt4"}],["path",{d:"M8 6V4c0-1 1-2 2-2h4c1 0 2 1 2 2v2",key:"v07s0e"}],["line",{x1:"10",x2:"10",y1:"11",y2:"17",key:"1uufr5"}],["line",{x1:"14",x2:"14",y1:"11",y2:"17",key:"xtxkd"}]]);/** * @license lucide-react v0.344.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const rs=z("Upload",[["path",{d:"M21 15v4a2 2 0 0 1-2 2H5a2 2 0 0 1-2-2v-4",key:"ih7n3h"}],["polyline",{points:"17 8 12 3 7 8",key:"t8dd8p"}],["line",{x1:"12",x2:"12",y1:"3",y2:"15",key:"widbto"}]]);/** * @license lucide-react v0.344.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const qt=z("User",[["path",{d:"M19 21v-2a4 4 0 0 0-4-4H9a4 4 0 0 0-4 4v2",key:"975kel"}],["circle",{cx:"12",cy:"7",r:"4",key:"17ys0d"}]]);/** * @license lucide-react v0.344.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const Gt=z("Users",[["path",{d:"M16 21v-2a4 4 0 0 0-4-4H6a4 4 0 0 0-4 4v2",key:"1yyitq"}],["circle",{cx:"9",cy:"7",r:"4",key:"nufk8"}],["path",{d:"M22 21v-2a4 4 0 0 0-3-3.87",key:"kshegd"}],["path",{d:"M16 3.13a4 4 0 0 1 0 7.75",key:"1da9ce"}]]);/** * @license lucide-react v0.344.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const Mr=z("XCircle",[["circle",{cx:"12",cy:"12",r:"10",key:"1mglay"}],["path",{d:"m15 9-6 6",key:"1uzhvr"}],["path",{d:"m9 9 6 6",key:"z0biqf"}]]);/** * @license lucide-react v0.344.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const be=z("X",[["path",{d:"M18 6 6 18",key:"1bl5f8"}],["path",{d:"m6 6 12 12",key:"d8bk6v"}]]);/** * @license lucide-react v0.344.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const Pl=z("Zap",[["polygon",{points:"13 2 3 14 12 14 11 22 21 10 12 10 13 2",key:"45s27k"}]]);class qn extends b.Component{constructor(){super(...arguments);Ae(this,"state",{hasError:!1,error:null});Ae(this,"handleRetry",()=>{window.location.reload()})}static getDerivedStateFromError(r){return{hasError:!0,error:r}}componentDidCatch(r,n){console.error("Uncaught error:",r,n)}render(){var r,n;if(this.state.hasError){const i=((r=this.state.error)==null?void 0:r.message.includes("Supabase"))?"Unable to connect to the database. Please check your connection and try again.":"Something went wrong. Please try refreshing the page.";return t.jsx("div",{className:"min-h-screen flex items-center justify-center bg-gray-50 p-4",children:t.jsxs("div",{className:"bg-white p-6 rounded-lg shadow-lg max-w-md w-full",children:[t.jsxs("div",{className:"flex items-center gap-3 text-red-600 mb-4",children:[t.jsx(hl,{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(vt,{className:"w-4 h-4"}),"Retry"]})]})})}return this.props.children}}function Fe(){const[s,e]=b.useState([]),[r,n]=b.useState(!0),[a,i]=b.useState(null);return b.useEffect(()=>{async function o(){try{n(!0),i(null);const{data:l,error:d}=await W.from("genres").select("*").order("display_order");if(d)throw d;const{data:c,error:u}=await W.from("sub_genres").select("*").order("name");if(u)throw u;const h=l.map(f=>({...f,subGenres:c.filter(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:s,loading:r,error:a}}function Me(s){return s?s.toLowerCase().includes("r&b")?"rnb-soul":s.toString().toLowerCase().trim().replace(/[^\w\s-]/g,"").replace(/\s+/g,"-").replace(/-+/g,"-").replace(/^-+|-+$/g,""):""}function Al(s){return s>=1e6?(s/1e6).toFixed(1)+"M":s>=1e3?(s/1e3).toFixed(1)+"K":s.toString()}function Fr(){const s=new Date;return`${s.getFullYear()}-${s.getMonth()+1}-${s.getDate()}`}function mt(s){let e=0;for(let r=0;r<s.length;r++){const n=s.charCodeAt(r);e=(e<<5)-e+n,e=e&e}return e}function Ol({onClose:s}){const{genres:e,loading:r}=Fe();if(r)return t.jsx("div",{className:"p-6",children:t.jsx("div",{className:"grid grid-cols-3 gap-4",children:[...Array(6)].map((a,i)=>t.jsx("div",{className:"h-12 bg-gray-100 rounded-lg animate-pulse"},`skeleton-${i}`))})});const n=e.reduce((a,i,o)=>{const l=Math.floor(o/Math.ceil(e.length/3));return a[l]||(a[l]=[]),a[l].push(i),a},[]);return t.jsxs("div",{className:"p-6",children:[t.jsxs(J,{to:"/genres",onClick:s,className:"flex items-center gap-2 p-3 mb-4 text-gray-600 hover:text-green-600 hover:bg-gray-50 rounded-lg transition-colors",children:[t.jsx(Dn,{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(J,{to:`/genre/${Me(o.name)}`,onClick:s,className:"flex items-center gap-2 p-3 rounded-lg hover:bg-gray-50 text-gray-900 group",children:[t.jsx("div",{className:"p-1.5 bg-gray-50 rounded group-hover:bg-green-50 transition-colors",children:t.jsx(ve,{className:"w-4 h-4 text-gray-500 group-hover:text-green-600"})}),t.jsx("span",{className:"font-medium",children:o.name})]},o.id))},i))})]})}function Se(){const s=it(),[e,r]=b.useState(!1),[n,a]=b.useState(!1),i=b.useRef();b.useRef(null);const o=s.pathname.startsWith("/submit"),l=()=>{i.current&&clearTimeout(i.current),r(!0)},d=()=>{i.current=setTimeout(()=>{r(!1)},300)};return b.useEffect(()=>{a(!1)},[s.pathname]),b.useEffect(()=>()=>{i.current&&clearTimeout(i.current)},[]),t.jsx("header",{className:"bg-gradient-to-r from-green-500 to-green-600 text-white relative z-50",children:t.jsxs("div",{className:"container mx-auto px-4",children:[t.jsxs("div",{className:"flex justify-between items-center h-16",children:[t.jsxs(J,{to:"/",className:"flex items-center gap-3 hover:opacity-90 transition-opacity",children:[t.jsx(gs,{className:"w-8 h-8"}),t.jsx("h1",{className:"text-2xl font-bold whitespace-nowrap",children:"Playlist Partner"})]}),!o&&t.jsx(J,{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(be,{className:"w-6 h-6"}):t.jsx(Nl,{className:"w-6 h-6"})}),t.jsxs("div",{className:"hidden md:flex items-center gap-8",children:[t.jsx(J,{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(J,{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(Ol,{onClose:()=>r(!1)})]})]}),t.jsx(J,{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(J,{to:"/about",className:"flex items-center gap-2 text-white hover:text-white/90 transition-colors py-2 px-3 -ml-3",children:"About"}),t.jsx(J,{to:"/blog",className:"flex items-center gap-2 text-white hover:text-white/90 transition-colors py-2 px-3 -ml-3",children:"Blog"}),!o&&t.jsx(J,{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(J,{to:"/playlists",className:"block px-4 py-2 hover:bg-white/10 rounded-lg",onClick:()=>a(!1),children:"Browse Playlists"}),t.jsx(J,{to:"/genres",className:"block px-4 py-2 hover:bg-white/10 rounded-lg",onClick:()=>a(!1),children:"Browse Genres"}),t.jsx(J,{to:"/for-curators",className:"block px-4 py-2 hover:bg-white/10 rounded-lg",onClick:()=>a(!1),children:"For Curators"}),t.jsx(J,{to:"/about",className:"block px-4 py-2 hover:bg-white/10 rounded-lg",onClick:()=>a(!1),children:"About"}),t.jsx(J,{to:"/blog",className:"block px-4 py-2 hover:bg-white/10 rounded-lg",onClick:()=>a(!1),children:"Blog"})]})})]})})}function ke(){const{genres:s}=Fe();return t.jsx("footer",{className:"bg-gray-900 text-gray-300 mt-auto",children:t.jsxs("div",{className:"container mx-auto px-4 py-12",children:[t.jsxs("div",{className:"mb-12",children:[t.jsxs("div",{className:"flex items-center gap-3 mb-4",children:[t.jsx(gs,{className:"w-8 h-8"}),t.jsx("h2",{className:"text-2xl font-bold",children:"Playlist Partner"})]}),t.jsx("p",{className:"text-gray-400 max-w-2xl",children:"Artists have made over 100,000+ successful submissions through Playlist Partner. No barriers, no fees—just music finding its rightful audience. Your next fan is waiting."})]}),t.jsxs("div",{className:"border-t border-gray-800 pt-8",children:[t.jsx("h3",{className:"text-lg font-semibold mb-6",children:"Browse Genres"}),t.jsx("div",{className:"grid grid-cols-2 sm:grid-cols-3 md:grid-cols-4 lg:grid-cols-6 gap-x-4 gap-y-3",children:s.map(e=>t.jsx(J,{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 Re({title:s,description:e,image:r="https://ftwlzdhkzqfuosdorgjt.supabase.co/storage/v1/object/public/playlistpartner%20public/playlistpartner%20og%20image.png",url:n,type:a="website",noIndex:i=!1,playlist:o}){var f;const l=o?`Submit Music to ${o.name} - Free Spotify Playlist Submission`:s||"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(Ka,{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:r,"data-react-helmet":"true"}),t.jsx("meta",{property:"og:image:width",content:"1200"}),t.jsx("meta",{property:"og:image:height",content:"630"}),t.jsx("meta",{name:"twitter:card",content:"summary_large_image"}),t.jsx("meta",{name:"twitter:title",content:l,"data-react-helmet":"true"}),t.jsx("meta",{name:"twitter:description",content:c,"data-react-helmet":"true"}),t.jsx("meta",{name:"twitter:image",content:r,"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 ns="last_submission_data",Ll=30*24*60*60*1e3;function Gn(s){try{const e={artistName:s.artistName,email:s.email,lastTrack:s.track,lastUpdated:Date.now()};localStorage.setItem(ns,JSON.stringify(e))}catch(e){console.error("Failed to save submission data:",e)}}function jt(){try{const s=localStorage.getItem(ns);if(!s)return null;const e=JSON.parse(s);return Date.now()-e.lastUpdated>Ll?(localStorage.removeItem(ns),null):{artistName:e.artistName,email:e.email,lastTrack:e.lastTrack}}catch(s){return console.error("Failed to retrieve submission data:",s),null}}function Kn(){try{localStorage.removeItem(ns),localStorage.removeItem("trackSubmissions"),localStorage.removeItem("playlist_submissions"),localStorage.removeItem("spotify_token"),sessionStorage.clear()}catch(s){console.error("Failed to reset storage data:",s)}}const Il="b3nqx2d7xn8z",xs="Gd8Ew0Lh23gU7yKZuGaXkMfTUv-wZN0cXjJ1sd4A1cI",Rl=`https://cdn.contentful.com/spaces/${Il}`;async function or(s){const e=await fetch(`${Rl}${s}`,{headers:{Authorization:`Bearer ${xs}`}});if(!e.ok)throw new Error(`Contentful API error: ${e.status} ${e.statusText}`);return e}function lr(s){const{items:e,includes:r}=s;if(!r||!r.Asset)return e;const n=new Map;return r.Asset.forEach(a=>{n.set(a.sys.id,a)}),e.map(a=>{var o,l;const i={...a};if((l=(o=a.fields.featuredImage)==null?void 0:o.sys)!=null&&l.id){const d=n.get(a.fields.featuredImage.sys.id);d&&(i.fields.featuredImage=d)}return i})}async function Dl(s=10,e=0){try{const n=await(await or(`/entries?access_token=${xs}&content_type=post&limit=${s}&skip=${e}&order=-fields.publishDate&include=1`)).json();return{items:lr(n),total:n.total}}catch(r){throw console.error("Error fetching blog posts:",r),r}}async function $l(s){try{const r=await(await or(`/entries?access_token=${xs}&content_type=post&fields.slug=${s}&limit=1&include=1`)).json();return r.items.length===0?null:lr(r)[0]}catch(e){throw console.error("Error fetching blog post:",e),e}}async function cr(s,e=10,r=0){try{const a=await(await or(`/entries?access_token=${xs}&content_type=post&fields.category=${s}&limit=${e}&skip=${r}&order=-fields.publishDate&include=1`)).json();return{items:lr(a),total:a.total}}catch(n){throw console.error("Error fetching blog posts by category:",n),n}}function Ul(){const[s,e]=b.useState([]),[r,n]=b.useState(!0);b.useEffect(()=>{a()},[]);async function a(){try{const l=await cr("News",3,0);e(l.items)}catch(l){console.error("Error loading news:",l)}finally{n(!1)}}function i(l){return new Date(l).toLocaleDateString("en-US",{month:"short",day:"numeric"})}function o(l){return l.startsWith("//")?`https:${l}`:l}return r?t.jsx("div",{className:"my-16",children:t.jsxs("div",{className:"max-w-[1400px] mx-auto",children:[t.jsx("h2",{className:"text-2xl font-semibold text-gray-900 mb-8",children:"Latest News from Playlist Partner"}),t.jsx("div",{className:"grid md:grid-cols-3 gap-6",children:[1,2,3].map(l=>t.jsxs("div",{className:"bg-gray-100 rounded-lg p-6 animate-pulse",children:[t.jsx("div",{className:"h-6 bg-gray-200 rounded mb-3"}),t.jsx("div",{className:"h-4 bg-gray-200 rounded mb-2"}),t.jsx("div",{className:"h-4 bg-gray-200 rounded w-2/3"})]},l))})]})}):s.length===0?null:t.jsx("div",{className:"my-16",children:t.jsxs("div",{className:"max-w-[1400px] mx-auto",children:[t.jsx("h2",{className:"text-2xl font-semibold text-gray-900 mb-8",children:"Latest News from Playlist Partner"}),t.jsxs("div",{className:"grid md:grid-cols-3 gap-6",children:[s.slice(0,2).map(l=>{var d,c,u;return t.jsxs(J,{to:`/blog/news/${l.fields.slug}`,className:"group bg-white border border-gray-200 rounded-lg overflow-hidden hover:border-green-500 hover:shadow-md transition-all",children:[((u=(c=(d=l.fields.featuredImage)==null?void 0:d.fields)==null?void 0:c.file)==null?void 0:u.url)&&t.jsx("div",{className:"aspect-[3/2] overflow-hidden",children:t.jsx("img",{src:o(l.fields.featuredImage.fields.file.url),alt:l.fields.featuredImage.fields.title||l.fields.title,className:"w-full h-full object-cover group-hover:scale-105 transition-transform duration-300"})}),t.jsxs("div",{className:"p-6",children:[t.jsx("h3",{className:"text-lg font-semibold text-gray-900 group-hover:text-green-600 transition-colors line-clamp-2 mb-3",children:l.fields.title}),l.fields.excerpt&&t.jsx("p",{className:"text-gray-600 text-sm mb-4 line-clamp-2",children:l.fields.excerpt}),t.jsxs("div",{className:"flex items-center justify-between",children:[t.jsxs("div",{className:"flex items-center gap-1 text-xs text-gray-500",children:[t.jsx(ms,{className:"w-3 h-3"}),t.jsx("span",{children:i(l.fields.publishDate||l.sys.createdAt)})]}),t.jsxs("span",{className:"text-green-600 text-sm flex items-center gap-1 group-hover:gap-2 transition-all",children:["Read",t.jsx(Ut,{className:"w-4 h-4"})]})]})]})]},l.sys.id)}),t.jsx(J,{to:"/blog/news",className:"group bg-gradient-to-br from-green-50 to-green-100 border border-green-200 rounded-lg overflow-hidden hover:border-green-500 hover:shadow-md transition-all flex flex-col",children:t.jsxs("div",{className:"flex-1 flex flex-col justify-center items-center text-center p-6",children:[t.jsx("div",{className:"mb-4",children:t.jsx("div",{className:"w-16 h-16 bg-green-600 rounded-full flex items-center justify-center group-hover:scale-110 transition-transform",children:t.jsx(Ut,{className:"w-8 h-8 text-white"})})}),t.jsx("h3",{className:"text-lg font-semibold text-gray-900 mb-2",children:"See All News"}),t.jsx("p",{className:"text-gray-600 text-sm",children:"Stay updated with all our latest announcements and features"})]})})]})]})})}const Bl=b.lazy(()=>Ve(()=>import("./FeaturedPlaylists-BAdlXALt.js"),__vite__mapDeps([0,1,2])).then(s=>({default:s.FeaturedPlaylists}))),Ml=b.lazy(()=>Ve(()=>Promise.resolve().then(()=>fc),void 0).then(s=>({default:s.SubmissionModal}))),Fl=()=>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."})]})]})]})})}),ql=()=>{var e,r;const s=jt();return t.jsx("div",{className:"my-8 pt-8 border-t border-gray-200",children:t.jsxs("div",{className:"max-w-[1400px] mx-auto",children:[t.jsxs("h2",{className:"text-2xl font-semibold text-gray-900 mb-6",children:["Today's Featured Playlists - ",new Date().toLocaleDateString("en-US",{weekday:"long",month:"long",day:"numeric"})]}),(s==null?void 0:s.lastTrack)&&t.jsxs("div",{className:"mb-6 flex items-center justify-between bg-white p-4 shadow-sm rounded-lg",children:[t.jsxs("div",{className:"flex items-center gap-4",children:[t.jsx("img",{src:(e=s.lastTrack.album.images[2])==null?void 0:e.url,alt:s.lastTrack.name,className:"w-12 h-12 object-cover rounded-md",loading:"lazy"}),t.jsxs("div",{children:[t.jsx("p",{className:"font-medium",children:s.lastTrack.name}),t.jsx("p",{className:"text-sm text-gray-600",children:(r=s.lastTrack.artists[0])==null?void 0:r.name})]})]}),t.jsx("button",{onClick:()=>{Kn(),window.location.reload()},className:"p-2 hover:bg-gray-100 rounded-full transition-colors",title:"Clear selected track",children:t.jsx(be,{className:"w-5 h-5 text-gray-500"})})]}),t.jsx("div",{className:"border-l-4 border-green-500 pl-6",children:t.jsx(b.Suspense,{fallback:t.jsx("div",{className:"h-32 flex items-center justify-center",children:t.jsx(me,{className:"w-8 h-8 animate-spin"})}),children:t.jsx(Bl,{})})})]})})},Gl=()=>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(J,{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 Kl(){const[s,e]=b.useState(null);return t.jsxs(t.Fragment,{children:[t.jsx(Re,{}),t.jsxs("main",{children:[t.jsx(Fl,{}),t.jsxs("div",{className:"container mx-auto px-4 pb-12",children:[t.jsx(b.Suspense,{fallback:null,children:t.jsx(ql,{})}),t.jsx(Gl,{}),t.jsx(Ul,{}),t.jsxs(b.Suspense,{fallback:null,children:[t.jsx(Hl,{}),t.jsx(zl,{})]})]}),s&&t.jsx(b.Suspense,{fallback:null,children:t.jsx(Ml,{playlist:s,onClose:()=>e(null),onSubmit:()=>e(null)})})]})]})}const Hl=b.lazy(()=>Ve(()=>import("./FAQSection-DYdRED9D.js"),__vite__mapDeps([3,1,2]))),zl=b.lazy(()=>Ve(()=>import("./AdditionalInfoSection-DphltVm4.js"),__vite__mapDeps([4,1,2])));function Wl(s){const[e,r]=b.useState(null),[n,a]=b.useState(!0),[i,o]=b.useState(null),[l,d]=b.useState([]);return b.useEffect(()=>{let c=!0;async function u(){if(!s){o(new Error("Invalid playlist URL")),a(!1);return}try{a(!0),o(null);const{data:h,error:f}=await W.from("playlist_details").select("*").eq("slug",s).limit(1);if(f)throw f;if(!h||h.length===0)throw new Error("Playlist not found");const p=h[0];if(c){r(p);const{data:v,error:w}=await W.from("playlist_details").select("*").eq("genre",p.genre).neq("id",p.id).order("followers",{ascending:!1}).limit(4);!w&&v&&d(v)}}catch(h){console.error("Failed to fetch playlist:",h),c&&(o(h instanceof Error?h:new Error("Failed to fetch playlist")),r(null),d([]))}finally{c&&a(!1)}}return u(),()=>{c=!1}},[s]),{playlist:e,loading:n,error:i,relatedPlaylists:l,isNotFound:(i==null?void 0:i.message)==="Playlist not found"}}const Vs="playlist_submissions";function Vl(s,e){try{const r=JSON.parse(localStorage.getItem(Vs)||"[]"),n=r.find(a=>a.playlistId===s);n?n.tracks.some(a=>a.spotifyUrl===e)||n.tracks.push({spotifyUrl:e,timestamp:Date.now()}):r.push({playlistId:s,tracks:[{spotifyUrl:e,timestamp:Date.now()}]}),localStorage.setItem(Vs,JSON.stringify(r))}catch(r){console.error("Failed to track submission:",r)}}function Hn(s,e){try{const n=JSON.parse(localStorage.getItem(Vs)||"[]").find(a=>a.playlistId===s);return!!(n!=null&&n.tracks.some(a=>a.spotifyUrl===e))}catch(r){return console.error("Failed to check submission status:",r),!1}}const Js="scrollPositions",Jl=5*60*1e3,Yl=10,Ql=100;function qr(){try{return JSON.parse(sessionStorage.getItem(Js)||"[]")}catch{return[]}}const zn={savePosition(s,e){try{const r=qr(),n=window.scrollY;if(n>0){r.push({pathname:s,position:n,timestamp:Date.now(),searchParams:e==null?void 0:e.toString()});const a=r.filter(i=>Date.now()-i.timestamp<Jl);sessionStorage.setItem(Js,JSON.stringify(a))}}catch(r){console.error("Failed to save scroll position:",r)}},restorePosition(s,e){try{const r=qr(),n=r.find(a=>a.pathname===s);if(n){const a=r.filter(l=>l!==n);sessionStorage.setItem(Js,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>=Yl){window.scrollTo({top:d,behavior:"instant"});return}i++,setTimeout(o,Ql)};setTimeout(o,50)}}catch(r){console.error("Failed to restore scroll position:",r)}}};function dr({playlist:s,onSubmit:e,isRelated:r,priority:n=!1,hideSubmit:a=!1}){const i=Xe(),o=it(),[l]=Zr(),[d,c]=b.useState(!1),u=jt(),h=(u==null?void 0:u.lastTrack)&&Hn(s.id,u.lastTrack.external_urls.spotify),f=p=>{p.preventDefault(),r||zn.savePosition(o.pathname,l);const v=o.pathname.startsWith("/genre/");window.scrollTo({top:0,behavior:"instant"}),i(`/playlist/${s.slug}`,{state:{from:v?"genre":"home"}})};return t.jsxs("div",{className:"bg-white shadow-sm hover:shadow-md transition-shadow h-full flex flex-col",children:[t.jsxs("div",{className:"flex-1",children:[t.jsxs("a",{href:`/playlist/${s.slug}`,onClick:f,className:"cursor-pointer no-js-fallback",children:[t.jsxs("div",{className:"relative pb-[100%] bg-gray-100",children:[d||!s.image_url?t.jsx("div",{className:"absolute inset-0 flex items-center justify-center bg-gradient-to-br from-gray-100 to-gray-200",children:t.jsxs("div",{className:"text-center",children:[t.jsx(Rn,{className:"w-12 h-12 text-gray-400 mx-auto mb-2"}),t.jsx("div",{className:"text-sm text-gray-500 font-medium px-4 truncate max-w-[200px]",children:s.name})]})}):t.jsx("img",{src:s.image_url,alt:s.name,className:"absolute inset-0 w-full h-full object-cover sm:rounded-[2px] lg:rounded-[4px]",loading:n?"eager":"lazy",onError:()=>c(!0)}),s.featured&&t.jsxs("div",{className:"absolute top-2 right-2 bg-yellow-400 text-yellow-900 px-2 py-1 rounded-full text-xs font-medium flex items-center gap-1",children:[t.jsx(Fn,{className:"w-3 h-3"}),"Featured"]})]}),t.jsx("h3",{className:"text-base font-bold text-gray-900 mb-1 line-clamp-1 hover:text-green-600 transition-colors p-4 pb-0",children:s.name})]}),t.jsxs("div",{className:"p-4 pt-2",children:[t.jsx("p",{className:"text-sm text-gray-600 mb-2 line-clamp-2 flex-1",children:s.description}),t.jsxs("div",{className:"space-y-2",children:[t.jsxs("div",{className:"flex items-center gap-4 text-sm",children:[t.jsxs(J,{to:`/genre/${s.genre_slug}`,onClick:p=>p.stopPropagation(),className:"flex items-center text-gray-700 hover:text-green-600 transition-colors",children:[t.jsx(ve,{className:"w-4 h-4 mr-1 flex-shrink-0"}),t.jsx("span",{className:"truncate",children:s.genre})]}),t.jsxs("div",{className:"flex items-center text-gray-700",children:[t.jsx(Gt,{className:"w-4 h-4 mr-1 flex-shrink-0"}),t.jsx("span",{children:s.followers.toLocaleString()})]})]}),s.curator_name&&t.jsxs("div",{className:"flex items-center gap-2 text-sm text-gray-600",children:[t.jsx(qt,{className:"w-4 h-4 flex-shrink-0"}),s.curator_profile_url?t.jsx("a",{href:s.curator_profile_url,target:"_blank",rel:"noopener noreferrer",onClick:p=>p.stopPropagation(),className:"truncate hover:text-green-600 transition-colors",children:s.curator_name}):t.jsx("span",{className:"truncate",children:s.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(In,{className:"w-3.5 h-3.5"}),"Submitted"]}):t.jsxs("button",{onClick:p=>{p.stopPropagation(),e(s.id)},className:"flex items-center gap-1.5 bg-green-500 text-white px-3 py-1.5 rounded-full text-sm hover:bg-green-600 transition-colors",children:[t.jsx(Bn,{className:"w-3.5 h-3.5"}),"Submit"]})})]})}const as=10,Ts=24*60*60*1e3;function Xt(s){return ec(s,"track")||s}function Zl(s,e){try{if(!s||!e)return{allowed:!1,remainingSubmissions:0,timeUntilReset:null,totalSubmissions:0,alreadySubmittedToPlaylist:!1};const r=JSON.parse(localStorage.getItem("trackSubmissions")||"[]"),n=Date.now(),a=Xt(s),i=r.filter(d=>n-d.timestamp<Ts);i.length<r.length&&localStorage.setItem("trackSubmissions",JSON.stringify(i));const o=i.find(d=>Xt(d.spotifyUrl)===a&&d.playlistId===e);if(o)return{allowed:!1,remainingSubmissions:0,timeUntilReset:Math.max(0,Ts-(n-o.timestamp)),totalSubmissions:i.length,alreadySubmittedToPlaylist:!0};const l=i.filter(d=>Xt(d.spotifyUrl)===a);if(l.length>=as){const d=l.reduce((u,h)=>h.timestamp<u.timestamp?h:u);return{allowed:!1,remainingSubmissions:0,timeUntilReset:Math.max(0,Ts-(n-d.timestamp)),totalSubmissions:l.length,alreadySubmittedToPlaylist:!1}}return{allowed:!0,remainingSubmissions:as-l.length,timeUntilReset:null,totalSubmissions:l.length,alreadySubmittedToPlaylist:!1}}catch(r){return console.error("Rate limit check failed:",r),{allowed:!1,remainingSubmissions:0,timeUntilReset:null,totalSubmissions:0,alreadySubmittedToPlaylist:!1}}}function Xl(s,e){if(!(!s||!e))try{const r=JSON.parse(localStorage.getItem("trackSubmissions")||"[]");r.push({timestamp:Date.now(),spotifyUrl:Xt(s),playlistId:e}),localStorage.setItem("trackSubmissions",JSON.stringify(r))}catch(r){console.error("Failed to record submission:",r)}}function ec(s,e){if(!s)return null;try{const r=[new RegExp(`${e}/([a-zA-Z0-9]+)`),new RegExp(`${e}:([a-zA-Z0-9]+)`)];for(const n of r){const a=s.match(n);if(a&&a[1])return a[1]}return null}catch(r){return console.error("Failed to extract ID:",r),null}}const Gr=/([a-zA-Z0-9._-]+@[a-zA-Z0-9._-]+\.[a-zA-Z0-9._-]+)/gi,tc=/(?:e-?mail|email)\s*:*\s*/gi,sc=/(?:https?:\/\/)?(?:(?:www|bit|t|tinyurl)\.[a-z]{2,}|[a-z0-9-]+(?:\.[a-z]{2,})+)(?:\/[^\s]*)?/gi,rc=/(?:https?:\/\/|;to\/|\.com\/|\.co\/|\.ly\/|\.be\/|href=")[^\s]*/gi,nc=/<[^>]*>|<[^>]*$/g,ac=/&([a-z0-9]+|#[0-9]{1,6}|#x[0-9a-fA-F]{1,6});/gi,ic=/(?:@[\w-]+|#[\w-]+)/g;function oc(s){const e=document.createElement("textarea");return s.replace(ac,(r,n)=>(e.innerHTML=r,e.value||r))}function Wn(s){let e=s,r=null;const n=s.match(Gr);return n&&(r=n[0].toLowerCase(),e=e.replace(Gr,"")),e=e.replace(tc,""),e=e.replace(sc,"").replace(rc,""),e=e.replace(nc,""),e=e.replace(ic,""),e=oc(e),e=e.replace(/(?:submit|send|dm|message|follow|contact)(?:\s+(?:your?|us|me|tracks?|music|demos?|here))?\s*(?:@|at|to|via|through)\s*[^\n.]*/gi,"").replace(/;[^\s;]{2,}/g,"").replace(/([!?,.]){2,}/g,"$1").replace(/\s+/g," ").replace(/\n\s*\n/g,` `).trim(),{description:e,extractedEmail:r}}const lc="5285db074532404885ad78daec8e7640",cc="4a1752bc53e241bca760677d06c5a9b2",Kr=15e3;let Hr=0;function dc(s){try{if(s.startsWith("spotify:")){const r=s.split(":");return`https://open.spotify.com/${r[1]}/${r[2]}`}return`https://open.spotify.com${new URL(s).pathname}`}catch{return s}}function _t(s,e){if(!s)return null;try{const r=dc(s),n=[new RegExp(`${e}/([a-zA-Z0-9]+)`),new RegExp(`${e}:([a-zA-Z0-9]+)`)];for(const a of n){const i=r.match(a);if(i&&i[1])return i[1]}return null}catch(r){return console.error("Failed to extract ID:",r),null}}async function ur(){try{const s=localStorage.getItem("spotify_token");if(s){const a=JSON.parse(s);if(a.expires_at>Date.now())return a.access_token}const e=await fetch("https://accounts.spotify.com/api/token",{method:"POST",headers:{"Content-Type":"application/x-www-form-urlencoded",Authorization:`Basic ${btoa(`${lc}:${cc}`)}`},body:"grant_type=client_credentials"});if(!e.ok)throw new Error(`Failed to get access token: ${e.status} ${e.statusText}`);const r=await e.json(),n={access_token:r.access_token,expires_at:Date.now()+r.expires_in*1e3};return localStorage.setItem("spotify_token",JSON.stringify(n)),n.access_token}catch(s){throw console.error("Failed to get Spotify access token:",s),new Error("Failed to authenticate with Spotify")}}async function hr(s){const r=Date.now()-Hr;return r<Kr&&await new Promise(n=>setTimeout(n,Kr-r)),Hr=Date.now(),s()}async function fr(s){try{return await hr(async()=>{const e=await ur(),r=await fetch(`https://api.spotify.com/v1/playlists/${s}?fields=id,name,description,images,followers,owner(id,display_name,external_urls),tracks(total)`,{headers:{Authorization:`Bearer ${e}`}});if(!r.ok){if(r.status===404)return null;throw r.status===429?new Error("Rate limit exceeded. Please try again later."):new Error(`Failed to fetch playlist: ${r.status} ${r.statusText}`)}const n=await r.json(),{description:a,extractedEmail:i}=Wn(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 uc(s){if(!s.trim())return[];try{return await hr(async()=>{var a;const e=await ur(),r=await fetch(`https://api.spotify.com/v1/search?q=${encodeURIComponent(s)}&type=track&limit=5`,{headers:{Authorization:`Bearer ${e}`}});if(!r.ok)throw r.status===429?new Error("Rate limit exceeded. Please try again later."):new Error(`Search failed: ${r.status} ${r.statusText}`);const n=await r.json();if(!((a=n.tracks)!=null&&a.items))throw new Error("Invalid response format from Spotify API");return n.tracks.items})}catch(e){throw console.error("Failed to search tracks:",e),e instanceof Error?e:new Error("Failed to search tracks")}}async function zr(s){if(!s)return null;try{return await hr(async()=>{const e=await ur(),r=await fetch(`https://api.spotify.com/v1/tracks/${encodeURIComponent(s)}`,{headers:{Authorization:`Bearer ${e}`}});if(!r.ok){if(r.status===404)return null;throw r.status===429?new Error("Rate limit exceeded. Please try again later."):new Error(`Failed to fetch track: ${r.status} ${r.statusText}`)}const n=await r.json();if(!n.id||!n.name||!n.artists||!n.album)throw new Error("Invalid track data received from Spotify API");return n})}catch(e){throw console.error("Failed to fetch track:",e),e instanceof Error?e:new Error("Failed to fetch track data")}}function hc(s,e){const[r,n]=b.useState(s);return b.useEffect(()=>{const a=setTimeout(()=>{n(s)},e);return()=>{clearTimeout(a)}},[s,e]),r}function Vn({onTrackSelect:s,initialUrl:e,selectedTrack:r,onClearTrack:n}){var A;const[a,i]=b.useState(""),[o,l]=b.useState([]),[d,c]=b.useState(!1),[u,h]=b.useState(!1),[f,p]=b.useState(null),v=hc(a,300),w=b.useRef(null);b.useEffect(()=>{const S=N=>{w.current&&!w.current.contains(N.target)&&h(!1)};return document.addEventListener("mousedown",S),()=>document.removeEventListener("mousedown",S)},[]),b.useEffect(()=>{async function S(){if(!v.trim()){l([]);return}c(!0),p(null);try{const N=await uc(v);N.length===0&&p("No tracks found"),l(N),h(!0)}catch(N){console.error("Failed to fetch tracks:",N),p("Failed to search tracks. Please try again.")}finally{c(!1)}}S()},[v]),b.useEffect(()=>{async function S(){if(e){const N=_t(e,"track");if(N){c(!0),p(null);try{const j=await zr(N);j?s(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)}}}}S()},[e,s]);const x=async S=>{s(S),h(!1),i(""),p(null)},y=async S=>{i(S),p(null);const N=_t(S,"track");if(N){c(!0);try{const j=await zr(N);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)}}},P=S=>{S.preventDefault(),S.stopPropagation(),n(),i(""),p(null),h(!1),setTimeout(()=>{var j;const N=(j=w.current)==null?void 0:j.querySelector("input");N&&N.focus()},0)},_=S=>{S.key==="Enter"&&(S.preventDefault(),S.stopPropagation())};return r?t.jsxs("div",{className:"mt-3 p-3 bg-gray-50 rounded-lg flex items-center gap-4 group relative",children:[t.jsx("img",{src:(A=r.album.images[r.album.images.length-1])==null?void 0:A.url,alt:r.album.name,className:"w-16 h-16 object-cover rounded-md"}),t.jsxs("div",{className:"flex-1",children:[t.jsx("h3",{className:"font-medium text-gray-900",children:r.name}),t.jsx("p",{className:"text-sm text-gray-600",children:r.artists.map(S=>S.name).join(", ")}),t.jsx("p",{className:"text-xs text-gray-500",children:r.album.name})]}),t.jsx("button",{onClick:P,className:"absolute top-2 right-2 p-1 rounded-full bg-gray-200 hover:bg-gray-300 transition-colors","aria-label":"Clear selection",children:t.jsx(be,{className:"w-4 h-4 text-gray-600"})})]}):t.jsxs("div",{ref:w,className:"relative",children:[t.jsxs("div",{className:"relative",children:[t.jsx(ps,{className:"absolute left-3 top-1/2 transform -translate-y-1/2 text-gray-400 w-5 h-5"}),t.jsx("input",{type:"text",placeholder:"Search for your track or paste Spotify URL...",value:a,onChange:S=>y(S.target.value),onFocus:()=>h(!0),onKeyDown:_,className:"w-full pl-10 pr-4 py-2 border border-gray-300 rounded-lg focus:ring-2 focus:ring-green-500 focus:border-transparent"}),d&&t.jsx(me,{className:"absolute right-3 top-1/2 transform -translate-y-1/2 text-gray-400 w-5 h-5 animate-spin"})]}),f&&t.jsxs("div",{className:"mt-2 text-sm text-red-600 flex items-center gap-1",children:[t.jsx(fe,{className:"w-4 h-4"}),f]}),u&&(o.length>0||d)&&t.jsxs("div",{className:"absolute z-50 w-full mt-1 bg-white rounded-lg shadow-lg border border-gray-200 max-h-80 overflow-y-auto",children:[o.map(S=>{var N;return t.jsxs("button",{onClick:j=>{j.preventDefault(),x(S)},className:"w-full p-3 hover:bg-gray-50 flex items-center gap-3 border-b border-gray-100 last:border-0",children:[t.jsx("img",{src:(N=S.album.images[S.album.images.length-1])==null?void 0:N.url,alt:S.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:S.name}),t.jsx("p",{className:"text-sm text-gray-500 line-clamp-1",children:S.artists.map(j=>j.name).join(", ")})]})]},S.id)}),d&&t.jsxs("div",{className:"p-4 text-center text-gray-500",children:[t.jsx(me,{className:"w-6 h-6 animate-spin mx-auto"}),t.jsx("p",{className:"mt-2",children:"Searching tracks..."})]})]})]})}const es={async submit(s){const{data:e,error:r}=await W.from("submissions").insert({playlist_id:s.playlistId,track_id:s.trackId,track_name:s.trackName,track_url:s.trackUrl,artist_name:s.artistName,email:s.email,message:s.message,status:"pending",created_at:new Date().toISOString(),updated_at:new Date().toISOString()}).select(` *, playlist:playlists ( name ) `).single();if(r)throw console.error("Failed to create submission:",r),r;return e},async getAll(){const{data:s,error:e}=await W.from("submission_details").select("*").order("created_at",{ascending:!1});if(e)throw console.error("Failed to fetch submissions:",e),e;return s.map(r=>({...r,playlist:{name:r.playlist_name}}))},async getHistory(s){const{data:e,error:r}=await W.from("submission_details").select("*").eq("email",s).order("created_at",{ascending:!1});if(r)throw console.error("Failed to fetch submission history:",r),r;return e.map(n=>({...n,playlist:{name:n.playlist_name}}))},async getForPlaylist(s){const{data:e,error:r}=await W.from("submission_details").select("*").eq("playlist_id",s).order("created_at",{ascending:!1});if(r)throw console.error("Failed to fetch playlist submissions:",r),r;return e.map(n=>({...n,playlist:{name:n.playlist_name}}))},async updateStatus(s,e){const{data:r,error:n}=await W.from("submissions").update({status:e,reviewed_at:e==="pending"?null:new Date().toISOString(),updated_at:new Date().toISOString()}).eq("id",s).select(` *, playlist:playlists ( name ) `).single();if(n)throw console.error("Failed to update submission status:",n),n;return r}};function kt({playlist:s,onClose:e,onSubmit:r}){const[n,a]=b.useState(()=>{var P;const y=jt();return{spotifyUrl:((P=y==null?void 0:y.lastTrack)==null?void 0:P.external_urls.spotify)||"",artistName:(y==null?void 0:y.artistName)||"",email:(y==null?void 0:y.email)||"",message:""}}),[i,o]=b.useState(()=>{const y=jt();return(y==null?void 0:y.lastTrack)||null}),[l,d]=b.useState({}),[c,u]=b.useState({allowed:!0,remainingSubmissions:as,timeUntilReset:null,totalSubmissions:0,alreadySubmittedToPlaylist:!1}),[h,f]=b.useState("");b.useEffect(()=>{const y=_=>{const A=document.querySelector(".modal-content");A&&!A.contains(_.target)&&e()},P=_=>{_.key==="Escape"&&e()};return document.addEventListener("mousedown",y),document.addEventListener("keydown",P),()=>{document.removeEventListener("mousedown",y),document.removeEventListener("keydown",P)}},[e]),b.useEffect(()=>{if(n.spotifyUrl){const y=Zl(n.spotifyUrl,s.id);u(y)}},[n.spotifyUrl,s.id]),b.useEffect(()=>{let y;const P=()=>{if(c.timeUntilReset){const _=Math.floor(c.timeUntilReset/36e5),A=Math.floor(c.timeUntilReset%(1e3*60*60)/(1e3*60)),S=Math.floor(c.timeUntilReset%(1e3*60)/1e3);f(`${_}h ${A}m ${S}s`)}};return c.timeUntilReset&&(P(),y=setInterval(()=>{const _=c.timeUntilReset-1e3;_<=0?(clearInterval(y),u(A=>({...A,timeUntilReset:null,allowed:!0}))):(u(A=>({...A,timeUntilReset:_})),P())},1e3)),()=>{y&&clearInterval(y)}},[c.timeUntilReset]);const p=()=>{const y={};return i||(y.spotifyUrl="Please select a track"),n.artistName.trim()||(y.artistName="Artist name is required"),/^[^\s@]+@[^\s@]+\.[^\s@]+$/.test(n.email)||(y.email="Please enter a valid email address"),d(y),Object.keys(y).length===0},v=async y=>{if(y.preventDefault(),!(!c.allowed||c.alreadySubmittedToPlaylist)&&p())try{const P=_t(n.spotifyUrl,"track");if(!P||!i)throw new Error("Invalid track selection");await es.submit({playlistId:s.id,trackId:P,trackName:i.name,trackUrl:n.spotifyUrl,artistName:n.artistName,email:n.email,message:n.message}),Gn({artistName:n.artistName,email:n.email,track:i}),Xl(n.spotifyUrl,s.id),Vl(s.id,n.spotifyUrl),r(n)}catch(P){console.error("Failed to submit track:",P),d(_=>({..._,submit:"Failed to submit track. Please try again."}))}},w=y=>{o(y),a(P=>{var _;return{...P,spotifyUrl:y.external_urls.spotify,artistName:((_=y.artists[0])==null?void 0:_.name)||P.artistName}}),d(P=>({...P,spotifyUrl:void 0}))},x=()=>{o(null),a(y=>({...y,spotifyUrl:"",artistName:y.artistName})),d(y=>({...y,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(be,{className:"w-6 h-6"})})]}),t.jsxs("p",{className:"mt-2 text-gray-600",children:["Submitting to: ",s.name]}),i&&t.jsx("div",{className:"mt-3 flex flex-col gap-2 text-sm",children:t.jsx("div",{className:`px-3 py-2 rounded-lg ${c.alreadySubmittedToPlaylist?"bg-yellow-100 text-yellow-800":c.allowed?"bg-green-100 text-green-800":"bg-red-100 text-red-800"}`,children:c.alreadySubmittedToPlaylist?t.jsxs("div",{className:"flex items-center gap-1",children:[t.jsx(fe,{className:"w-4 h-4"}),"Already submitted to this playlist"]}):c.allowed?t.jsxs("span",{children:[c.remainingSubmissions,"/",as," Submissions Remaining Today"]}):t.jsxs(t.Fragment,{children:[t.jsxs("div",{className:"flex items-center gap-1",children:[t.jsx(fe,{className:"w-4 h-4"}),"Each track can be submitted to up to 10 playlists per day."]}),h&&t.jsxs("div",{className:"text-sm mt-1",children:["(Resets in ",h,")"]})]})})})]}),t.jsxs("form",{onSubmit:v,className:"p-6 space-y-4",children:[t.jsxs("div",{children:[t.jsxs("label",{className:"flex gap-2 text-sm font-medium text-gray-700 mb-1",children:[t.jsx(zs,{className:"w-4 h-4"}),"Search and Select Your Track"]}),t.jsx(Vn,{onTrackSelect:w,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(qt,{className:"w-4 h-4"}),"Artist Name"]}),t.jsx("input",{type:"text",placeholder:"Your artist name",value:n.artistName,onChange:y=>a(P=>({...P,artistName:y.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:y=>a(P=>({...P,email:y.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(Un,{className:"w-4 h-4"}),"Message (Optional)"]}),t.jsx("textarea",{placeholder:"Tell the curator about your track...",value:n.message,onChange:y=>a(P=>({...P,message:y.target.value})),rows:4,className:"w-full p-2 border border-gray-300 rounded-lg focus:ring-2 focus:ring-green-500 focus:border-transparent",disabled:!c.allowed||c.alreadySubmittedToPlaylist})]}),l.submit&&t.jsxs("div",{className:"flex items-center gap-2 text-red-600 text-sm",children:[t.jsx(fe,{className:"w-4 h-4"}),t.jsx("p",{children:l.submit})]}),t.jsxs("div",{className:"flex justify-end gap-3 pt-4",children:[t.jsx("button",{type:"button",onClick:e,className:"px-4 py-2 text-gray-700 hover:bg-gray-100 rounded-lg transition-colors",children:"Cancel"}),t.jsxs("button",{type:"submit",disabled:!c.allowed||c.alreadySubmittedToPlaylist,className:`px-4 py-2 rounded-lg flex items-center gap-2 transition-colors ${!c.allowed||c.alreadySubmittedToPlaylist?"bg-gray-300 text-gray-500 cursor-not-allowed":"bg-green-500 text-white hover:bg-green-600"}`,children:[t.jsx(ve,{className:"w-4 h-4"}),"Submit Track"]})]})]})]})})}const fc=Object.freeze(Object.defineProperty({__proto__:null,SubmissionModal:kt},Symbol.toStringTag,{value:"Module"}));function mc({message:s,type:e,onClose:r}){const[n,a]=b.useState(!1);b.useEffect(()=>{const l=setTimeout(()=>{a(!0)},4700);return()=>clearTimeout(l)},[]),b.useEffect(()=>{if(n){const l=setTimeout(()=>{r()},300);return()=>clearTimeout(l)}},[n,r]);const i={success:"bg-green-500",error:"bg-red-500",info:"bg-blue-500"}[e],o={success:Hs,error:fe,info:fe}[e];return t.jsxs("div",{className:` fixed bottom-4 right-4 ${i} text-white px-4 py-3 rounded-lg shadow-lg flex items-center gap-3 max-w-md transition-all duration-300 ${n?"opacity-0 translate-y-2":"opacity-100 translate-y-0"} `,children:[t.jsx(o,{className:"w-5 h-5 flex-shrink-0"}),t.jsx("p",{className:"flex-1",children:s}),t.jsx("button",{onClick:()=>a(!0),className:"p-1 hover:bg-white/20 rounded-full transition-colors",children:t.jsx(be,{className:"w-4 h-4"})})]})}function qe(s){const[e]=b.useState(()=>{let r=document.getElementById("toast-container");return r||(r=document.createElement("div"),r.id="toast-container",document.body.appendChild(r)),r});return Qr.createPortal(t.jsx(mc,{...s}),e)}function gc({playlist:s,baseUrl:e}){var n;const r={"@context":"https://schema.org","@type":"MusicPlaylist",name:s.name,description:`Get your music featured on ${s.name}, a Spotify playlist curated by ${s.curator_name} with ${s.followers.toLocaleString()} followers. No account needed! Access thousands of playlists and connect with curators on PlaylistPartner.com.`,numTracks:s.track_count,url:`${e}/playlist/${s.spotify_id}`,sameAs:[`https://open.spotify.com/playlist/${s.spotify_id}`],dateModified:s.updated_at,image:s.image_url,author:{"@type":"Person",name:s.curator_name,url:s.curator_profile_url},genre:[s.genre,...((n=s.sub_genres)==null?void 0:n.slice(0,2))||[]].filter(Boolean),interactionStatistic:{"@type":"InteractionCounter",interactionType:"https://schema.org/FollowAction",userInteractionCount:s.followers},isPartOf:{"@id":e}};return t.jsx("script",{type:"application/ld+json",children:JSON.stringify(r)})}function pc(){var S;const{slug:s}=Bt(),e=Xe(),r=it(),[n,a]=b.useState(!1),[i,o]=b.useState(null),[l,d]=b.useState(0),{playlist:c,loading:u,error:h,relatedPlaylists:f,isNotFound:p}=Wl(s||""),[v,w]=b.useState(!1);b.useEffect(()=>{w(!1)},[s]),b.useEffect(()=>{!u&&c&&!h&&!p&&typeof window<"u"&&window.prerenderReady!==void 0&&(window.prerenderReady=!0)},[u,c,h,p]),b.useEffect(()=>{async function N(){if(c!=null&&c.genre){const{count:j}=await W.from("playlist_details").select("*",{count:"exact",head:!0}).eq("genre",c.genre);d(j||0)}}c&&N()},[c]);const x=jt(),y=c&&(x==null?void 0:x.lastTrack)&&Hn(c.id,x.lastTrack.external_urls.spotify),P=()=>{var j;const N=(j=r.state)==null?void 0:j.from;e(N==="genre"?-1:"/")},_=async N=>{try{a(!1),o({type:"success",message:`Track submitted to ${c==null?void 0:c.name}! Watch your inbox for feedback from the curator.`})}catch(j){console.error("Failed to submit track:",j),o({type:"error",message:"Failed to submit track. Please try again."})}};if(u)return t.jsx("div",{className:"container mx-auto px-4 py-8",children:t.jsxs("div",{className:"animate-pulse",children:[t.jsx("div",{className:"h-8 w-48 bg-gray-200 rounded mb-6"}),t.jsx("div",{className:"bg-white shadow-lg",children:t.jsxs("div",{className:"grid md:grid-cols-2",children:[t.jsx("div",{className:"aspect-square bg-gray-200"}),t.jsxs("div",{className:"p-6",children:[t.jsx("div",{className:"h-8 w-3/4 bg-gray-200 rounded mb-4"}),t.jsx("div",{className:"h-4 w-1/2 bg-gray-200 rounded mb-4"}),t.jsx("div",{className:"h-20 bg-gray-200 rounded mb-4"})]})]})})]})});if(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(fe,{className:"w-6 h-6"}),t.jsx("h2",{className:"text-2xl font-bold",children:"Playlist Not Found"})]}),t.jsx("p",{className:"text-gray-600 mb-6",children:"The playlist you're looking for doesn't exist or may have been removed."}),t.jsxs("button",{onClick:P,className:"text-green-600 hover:text-green-700 flex items-center gap-2 mx-auto",children:[t.jsx(We,{className:"w-4 h-4"}),"Back to Playlists"]})]})});if(h)return t.jsx("div",{className:"container mx-auto px-4 py-8",children:t.jsxs("div",{className:"text-center",children:[t.jsxs("div",{className:"flex items-center justify-center gap-2 text-red-600 mb-4",children:[t.jsx(fe,{className:"w-6 h-6"}),t.jsx("h2",{className:"text-2xl font-bold",children:"Error Loading Playlist"})]}),t.jsx("p",{className:"text-gray-600 mb-6",children:h.message||"Something went wrong. Please try again."}),t.jsxs("button",{onClick:P,className:"text-green-600 hover:text-green-700 flex items-center gap-2 mx-auto",children:[t.jsx(We,{className:"w-4 h-4"}),"Back to Playlists"]})]})});const 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(Re,{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(gc,{playlist:c,baseUrl:window.location.origin}),t.jsxs("main",{className:"container mx-auto px-4 py-8",children:[t.jsxs("button",{onClick:P,className:"inline-flex items-center gap-2 text-green-600 hover:text-green-700 mb-6",children:[t.jsx(We,{className:"w-4 h-4"}),"Back to Playlists"]}),t.jsx("div",{className:"bg-white shadow-lg",children:t.jsxs("div",{className:"grid md:grid-cols-2",children:[t.jsx("div",{className:"relative aspect-square bg-gray-100",children:!c.image_url||v?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(Rn,{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:()=>w(!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(qt,{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(J,{to:`/genre/${c.genre_slug}`,className:"flex items-center text-gray-700 hover:text-green-600 transition-colors",children:[t.jsx(ve,{className:"w-5 h-5 mr-2"}),t.jsx("span",{className:"text-lg",children:c.genre})]}),t.jsxs("div",{className:"flex items-center text-gray-700",children:[t.jsx(Gt,{className:"w-5 h-5 mr-2"}),t.jsxs("span",{className:"text-lg",children:[c.followers.toLocaleString()," followers"]})]})]}),((S=c.sub_genres)==null?void 0:S.length)>0&&t.jsx("div",{className:"flex flex-wrap gap-2 mb-6",children:c.sub_genres.map(N=>t.jsx(J,{to:`/genre/${c.genre_slug}/${N.toLowerCase().replace(/\s+/g,"-")}`,className:"px-3 py-1 bg-gray-100 text-gray-700 rounded-full text-sm hover:bg-gray-200 transition-colors",children:N},N))})]}),y?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(In,{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(Bn,{className:"w-5 h-5"}),"Submit Your Track"]})]})]})}),f.length>0&&t.jsxs("div",{className:"mt-12",children:[t.jsx("h2",{className:"text-2xl font-bold mb-6",children:"Related Playlists"}),t.jsx("div",{className:"grid grid-cols-1 md:grid-cols-2 lg:grid-cols-3 xl:grid-cols-4 gap-6",children:f.map(N=>t.jsx(dr,{playlist:N,onSubmit:()=>a(!0),isRelated:!0,hideSubmit:!0},N.id))})]}),n&&c&&t.jsx(kt,{playlist:c,onClose:()=>a(!1),onSubmit:_}),i&&t.jsx(qe,{message:i.message,type:i.type,onClose:()=>o(null)})]})]})}function xc({filters:s,onFilterChange:e,hideGenreFilter:r}){const{genres:n,loading:a}=Fe(),i=n.find(o=>o.name===s.genre);return t.jsx("div",{className:"bg-white shadow-sm -mx-4 px-4",children:t.jsx("div",{className:"max-w-[1400px] mx-auto",children:t.jsxs("div",{className:`grid ${r?"grid-cols-2":"grid-cols-1 md:grid-cols-2 lg:grid-cols-4"} gap-4 py-4`,children:[t.jsxs("div",{className:"relative",children:[t.jsx(ps,{className:"absolute left-3 top-1/2 transform -translate-y-1/2 text-gray-400 w-5 h-5"}),t.jsx("input",{type:"text",placeholder:"Search playlists...",value:s.search,onChange:o=>e({...s,search:o.target.value}),className:"w-full pl-10 pr-4 py-2 border border-gray-300 rounded-lg focus:ring-2 focus:ring-green-500 focus:border-transparent"})]}),!r&&t.jsxs("div",{className:"relative",children:[t.jsx(ve,{className:"absolute left-3 top-1/2 transform -translate-y-1/2 text-gray-400 w-5 h-5"}),t.jsxs("select",{value:s.genre,onChange:o=>e({...s,genre:o.target.value,subGenre:""}),className:"w-full pl-10 pr-4 py-2 border border-gray-300 rounded-lg appearance-none focus:ring-2 focus:ring-green-500 focus:border-transparent disabled:bg-gray-50 disabled:text-gray-500",disabled:a,children:[t.jsx("option",{value:"",children:"All Genres"}),n.map(o=>t.jsx("option",{value:o.name,children:o.name},o.id))]})]}),t.jsx("div",{className:"relative",children:t.jsxs("select",{value:s.subGenre||"",onChange:o=>e({...s,subGenre:o.target.value}),className:`w-full px-4 py-2 border border-gray-300 rounded-lg appearance-none transition-colors ${i?"focus:ring-2 focus:ring-green-500 focus:border-transparent":"bg-gray-50 text-gray-400 cursor-not-allowed"}`,disabled:!i,children:[t.jsx("option",{value:"",children:i?"All Sub-genres":"-- Select a genre first --"}),i==null?void 0:i.subGenres.map(o=>t.jsx("option",{value:o.name,children:o.name},o.id))]})}),t.jsx("div",{className:"relative",children:t.jsxs("select",{value:s.sortBy,onChange:o=>e({...s,sortBy:o.target.value}),className:"w-full px-4 py-2 border border-gray-300 rounded-lg appearance-none focus:ring-2 focus:ring-green-500 focus:border-transparent",children:[t.jsx("option",{value:"default",children:"Default (Most Recent)"}),t.jsx("option",{value:"followers-high",children:"Most Followers"}),t.jsx("option",{value:"followers-low",children:"Least Followers"})]})})]})})})}const Ot="playlist_state";function Kt(s){const[e,r]=b.useState(()=>{try{const w=sessionStorage.getItem(Ot);if(w){const x=JSON.parse(w);if(JSON.stringify(x.filters)===JSON.stringify(s))return x.playlists}return[]}catch{return[]}}),[n,a]=b.useState(!0),[i,o]=b.useState(null),[l,d]=b.useState(!0),[c,u]=b.useState(()=>{try{const w=sessionStorage.getItem(Ot);if(w){const x=JSON.parse(w);if(JSON.stringify(x.filters)===JSON.stringify(s))return x.currentPage}return 1}catch{return 1}}),[h,f]=b.useState(0),p=12;return b.useEffect(()=>{!n&&h>0&&typeof window<"u"&&window.prerenderReady!==void 0&&(window.prerenderReady=!0)},[n,h]),b.useEffect(()=>{(()=>{const x=sessionStorage.getItem(Ot);if(x){const y=JSON.parse(x);return JSON.stringify(y.filters)!==JSON.stringify(s)}return!0})()&&(r([]),u(1),d(!0),sessionStorage.removeItem(Ot))},[s==null?void 0:s.genre,s==null?void 0:s.subGenre,s==null?void 0:s.search,s==null?void 0:s.sortBy]),b.useEffect(()=>{if(e.length>0){const w={playlists:e,currentPage:c,filters:s||{}};sessionStorage.setItem(Ot,JSON.stringify(w))}},[e,c,s]),b.useEffect(()=>{async function w(){try{a(!0),o(null);let x=W.from("playlist_details").select("*",{count:"exact"});if(s!=null&&s.genre&&(x=x.eq("genre",s.genre)),s!=null&&s.subGenre&&(x=x.contains("sub_genres",[s.subGenre])),s!=null&&s.search){const S=`%${s.search}%`;x=x.or(`name.ilike.${S},description.ilike.${S}`)}switch(s==null?void 0:s.sortBy){case"followers-high":x=x.order("followers",{ascending:!1});break;case"followers-low":x=x.order("followers",{ascending:!0});break;default:if(!(s!=null&&s.genre)&&!(s!=null&&s.subGenre)){let S=W.from("playlist_details").select("*").eq("featured",!0).order("created_at",{ascending:!1}).limit(4);if(s!=null&&s.search){const T=`%${s.search}%`;S=S.or(`name.ilike.${T},description.ilike.${T}`)}const{data:N}=await S,j=(c-1)*p;let m=W.from("playlist_details").select("*",{count:"exact"}).eq("featured",!1).order("created_at",{ascending:!1});if(s!=null&&s.search){const T=`%${s.search}%`;m=m.or(`name.ilike.${T},description.ilike.${T}`)}const{data:g,count:k}=await m.range(j,j+p-1);if(c===1){const T=[...N||[],...g||[]];r(T)}else r(T=>{const I=new Set(T.map(K=>K.id)),R=(g||[]).filter(K=>!I.has(K.id));return[...T,...R]});f((k||0)+((N==null?void 0:N.length)||0)),d(j+p<(k||0)),a(!1);return}else{let S=W.from("playlist_details").select("*").eq("featured",!0).eq("genre",s.genre).order("created_at",{ascending:!1}).limit(4);if(s!=null&&s.subGenre&&(S=S.contains("sub_genres",[s.subGenre])),s!=null&&s.search){const T=`%${s.search}%`;S=S.or(`name.ilike.${T},description.ilike.${T}`)}const{data:N}=await S,j=(c-1)*p;let m=W.from("playlist_details").select("*",{count:"exact"}).eq("featured",!1).eq("genre",s.genre).order("created_at",{ascending:!1});if(s!=null&&s.subGenre&&(m=m.contains("sub_genres",[s.subGenre])),s!=null&&s.search){const T=`%${s.search}%`;m=m.or(`name.ilike.${T},description.ilike.${T}`)}const{data:g,count:k}=await m.range(j,j+p-1);if(c===1){const T=[...N||[],...g||[]];r(T)}else r(T=>{const I=new Set(T.map(K=>K.id)),R=(g||[]).filter(K=>!I.has(K.id));return[...T,...R]});f((k||0)+((N==null?void 0:N.length)||0)),d(j+p<(k||0)),a(!1);return}}const y=(c-1)*p;x=x.range(y,y+p-1);const{data:P,error:_,count:A}=await x;if(_)throw _;f(A||0),r(S=>{const N=P||[];if(c===1)return N;const j=new Set(S.map(g=>g.id)),m=N.filter(g=>!j.has(g.id));return[...S,...m]}),d(y+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)}}w()},[c,s==null?void 0:s.genre,s==null?void 0:s.subGenre,s==null?void 0:s.search,s==null?void 0:s.sortBy]),{playlists:e,loading:n,error:i,hasMore:l,loadMore:()=>{!n&&l&&u(w=>w+1)},currentPage:c,totalCount:h,itemsPerPage:p}}function yc(){var N,j;const s=it(),[e,r]=Zr(),[n,a]=b.useState(()=>{var k;const m=(k=s.state)==null?void 0:k.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"}});b.useEffect(()=>{window.scrollTo(0,0)},[]);const{playlists:i,loading:o,error:l,hasMore:d,loadMore:c,currentPage:u,totalCount:h,itemsPerPage:f}=Kt({...n,genre:n.genre||void 0,subGenre:n.subGenre||void 0}),[p,v]=b.useState(null),[w,x]=b.useState(null),y=jt(),[P,_]=b.useState(!0);b.useEffect(()=>{var m;if(!o&&i.length>0&&P){const g=(m=s.state)==null?void 0:m.filters;g!=null&&g.fromSubmission?window.scrollTo(0,0):zn.restorePosition(s.pathname,r),_(!1)}},[o,i.length,s.pathname,s.state,r,P]),b.useEffect(()=>{sessionStorage.setItem("playlist_filters",JSON.stringify(n))},[n]);const A=(u-1)*f+1,S=Math.min(u*f,h);return t.jsxs(t.Fragment,{children:[t.jsx(Re,{}),t.jsxs("main",{children:[t.jsxs("div",{className:"container mx-auto px-4 pb-12",children:[t.jsx(xc,{filters:n,onFilterChange:a}),(y==null?void 0:y.lastTrack)&&t.jsxs("div",{className:"mb-6 flex items-center justify-between bg-white p-4 shadow-sm rounded-lg max-w-[1400px] mx-auto",children:[t.jsxs("div",{className:"flex items-center gap-4",children:[t.jsx("img",{src:(N=y.lastTrack.album.images[2])==null?void 0:N.url,alt:y.lastTrack.name,className:"w-12 h-12 object-cover rounded-md"}),t.jsxs("div",{children:[t.jsx("p",{className:"font-medium",children:y.lastTrack.name}),t.jsx("p",{className:"text-sm text-gray-600",children:(j=y.lastTrack.artists[0])==null?void 0:j.name})]})]}),t.jsx("button",{onClick:()=>{Kn(),window.location.reload()},className:"p-2 hover:bg-gray-100 rounded-full transition-colors",title:"Clear selected track",children:t.jsx(be,{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,"-",S," 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(dr,{playlist:m,onSubmit:k=>v(i.find(T=>T.id===k)||null),priority:g<4},`${m.id}-${g}`))}),o&&t.jsx("div",{className:"flex items-center justify-center py-12",children:t.jsx(me,{className:"w-8 h-8 text-green-500 animate-spin"})}),l&&t.jsx("div",{className:"text-center py-12",children:t.jsx("p",{className:"text-red-500",children:"Failed to load playlists. Please try again."})}),!o&&!l&&i.length===0&&t.jsx("div",{className:"text-center py-12",children:t.jsx("p",{className:"text-gray-500 text-lg",children:"No playlists found matching your criteria."})}),d&&!o&&t.jsx("div",{className:"text-center mt-8",children:t.jsx("button",{onClick:c,className:"px-6 py-3 bg-green-500 text-white rounded-lg hover:bg-green-600 transition-colors",children:"Load More Playlists"})})]})]}),p&&t.jsx(kt,{playlist:p,onClose:()=>v(null),onSubmit:()=>{v(null),x({type:"success",message:`Track submitted to ${p.name}! Watch your inbox for feedback from the curator.`})}}),w&&t.jsx(qe,{message:w.message,type:w.type,onClose:()=>x(null)})]})]})}function bc(){const s=Xe(),[e,r]=b.useState(null);b.useEffect(()=>{typeof window<"u"&&window.prerenderReady!==void 0&&(window.prerenderReady=!0)},[]);const n=a=>{var i;Gn({artistName:((i=a.artists[0])==null?void 0:i.name)||"",email:"",track:a}),s("/submit/genre",{state:{selectedTrack:a}})};return t.jsxs("div",{className:"container mx-auto px-4 py-8 max-w-2xl",children:[t.jsxs("button",{onClick:()=>s("/playlists"),className:"flex items-center gap-2 text-gray-600 hover:text-gray-800 transition-colors mb-6",children:[t.jsx(We,{className:"w-5 h-5"}),"Back to Playlists"]}),t.jsxs("div",{className:"space-y-6",children:[t.jsxs("div",{className:"text-center",children:[t.jsx("h1",{className:"text-3xl font-bold mb-2",children:"Submit Your Track"}),t.jsx("p",{className:"text-gray-600",children:"Search for your track on Spotify to get started"})]}),t.jsx("div",{className:"bg-white p-6 rounded-xl shadow-lg",children:t.jsx(Vn,{onTrackSelect:n,selectedTrack:e,onClearTrack:()=>r(null)})}),e&&t.jsxs("button",{onClick:()=>n(e),className:"w-full flex items-center justify-center gap-2 bg-green-500 text-white p-4 rounded-lg hover:bg-green-600 transition-colors",children:["Continue to Genre Selection",t.jsx(Ut,{className:"w-5 h-5"})]})]})]})}function wc(){const s=Xe(),{genres:e}=Fe(),[r,n]=b.useState(""),[a,i]=b.useState(""),o=e.find(u=>u.id===r),l=(o==null?void 0:o.subGenres)||[],d=u=>{i(u)},c=u=>{if(!r||!o)return;const h=a?l.find(f=>f.id===a):null;window.scrollTo(0,0),s("/playlists",{state:{filters:{genre:o.name,subGenre:(h==null?void 0:h.name)||"",fromSubmission:!0}},replace:!0})};return t.jsx("div",{className:"container mx-auto px-4 py-8 max-w-4xl",children:t.jsxs("div",{className:"space-y-8",children:[t.jsxs("div",{className:"text-center",children:[t.jsx("h1",{className:"text-3xl font-bold mb-2",children:"Select Your Genre"}),t.jsx("p",{className:"text-gray-600",children:"Choose the main category that best fits your track"})]}),t.jsxs("div",{children:[t.jsx("h2",{className:"text-lg font-medium mb-3",children:"Main Genre"}),t.jsx("div",{className:"grid grid-cols-2 sm:grid-cols-3 md:grid-cols-4 gap-3",children:e.map(u=>t.jsxs("button",{onClick:()=>{n(u.id),i("")},className:`p-4 text-center border-2 rounded-lg transition-colors ${r===u.id?"border-green-500 bg-green-50":"border-gray-200 hover:border-green-500 hover:bg-green-50"}`,children:[t.jsx(ve,{className:"w-6 h-6 mx-auto mb-2 text-gray-600"}),t.jsx("span",{className:"font-medium",children:u.name})]},u.id))})]}),r&&l.length>0&&t.jsxs("div",{children:[t.jsx("h2",{className:"text-lg font-medium mb-3",children:"Sub-genre (Optional)"}),t.jsx("div",{className:"grid grid-cols-2 sm:grid-cols-3 md:grid-cols-4 gap-3",children:l.map(u=>t.jsx("button",{onClick:()=>d(u.id),className:`p-3 text-center border-2 rounded-lg transition-colors ${a===u.id?"border-green-500 bg-green-50":"border-gray-200 hover:border-green-500 hover:bg-green-50"}`,children:t.jsx("span",{className:"font-medium",children:u.name})},u.id))})]}),t.jsxs("div",{className:"flex justify-between items-center",children:[t.jsxs("button",{onClick:()=>s("/submit"),className:"flex items-center gap-2 text-gray-600 hover:text-gray-800 transition-colors",children:[t.jsx(We,{className:"w-5 h-5"}),"Back to Track Selection"]}),t.jsxs("button",{onClick:()=>c(),disabled:!r,className:`flex items-center gap-2 px-6 py-3 rounded-lg font-medium transition-colors ${r?"bg-green-500 text-white hover:bg-green-600":"bg-gray-200 text-gray-500 cursor-not-allowed"}`,children:["Continue to Playlists",t.jsx(Ut,{className:"w-5 h-5"})]})]})]})})}function vc(s=4,e,r){const[n,a]=b.useState([]),[i,o]=b.useState(!0),[l,d]=b.useState(null);return b.useEffect(()=>{!i&&n.length>0&&typeof window<"u"&&window.prerenderReady!==void 0&&(window.prerenderReady=!0)},[i,n.length]),b.useEffect(()=>{async function c(){try{o(!0),d(null);let u=W.from("playlist_details").select("*").eq("featured",!0);e&&(u=u.eq("genre",e)),r&&(u=u.contains("sub_genres",[r]));const{data:h,error:f}=await u;if(f)throw f;const p=h||[];if(p.length>=s){const N=Fr(),j=[...p].sort((m,g)=>{const k=mt(`${N}-${m.id}`),T=mt(`${N}-${g.id}`);return k-T});a(j.slice(0,s));return}const v=s-p.length;let w=W.from("playlist_details").select("*").eq("featured",!1);e&&(w=w.eq("genre",e)),r&&(w=w.contains("sub_genres",[r]));const{data:x,error:y}=await w;if(y)throw y;const P=Fr(),_=[...p].sort((N,j)=>{const m=mt(`${P}-featured-${N.id}`),g=mt(`${P}-featured-${j.id}`);return m-g}),A=[...x||[]].sort((N,j)=>{const m=mt(`${P}-nonfeatured-${N.id}`),g=mt(`${P}-nonfeatured-${j.id}`);return m-g}),S=[..._,...A.slice(0,v)];a(S)}catch(u){console.error("Failed to fetch playlists:",u),d(u instanceof Error?u:new Error("Failed to fetch playlists"))}finally{o(!1)}}c()},[s,e,r]),{playlists:n,loading:i,error:l}}function Jn({genre:s,subGenre:e,totalCount:r,onViewAll:n}){const{playlists:a,loading:i}=vc(8,s,e),[o,l]=b.useState(null),[d,c]=b.useState(null);if(i||a.length===0)return null;const h=new Date().toLocaleDateString("en-US",{weekday:"long",month:"long",day:"numeric"}),f=e?`Today's Featured ${e} ${s} Playlists - ${h}`:`Today's Featured ${s} Playlists - ${h}`,p=new URLSearchParams;return p.set("genre",s),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(v=>t.jsx(dr,{playlist:v,onSubmit:w=>l(a.find(x=>x.id===w)||null),priority:!0},v.id))})]}),t.jsx("div",{className:"text-center mb-12",children:t.jsxs("button",{onClick:n,className:"inline-block px-8 py-4 bg-green-500 text-white text-lg font-semibold rounded-lg hover:bg-green-600 transition-all transform hover:scale-105 shadow-lg hover:shadow-xl",children:["View All ",r.toLocaleString()," ",e?`${e} ${s}`:s," Playlists"]})}),o&&t.jsx(kt,{playlist:o,onClose:()=>l(null),onSubmit:()=>{l(null),c({type:"success",message:`Track submitted to ${o.name}! Watch your inbox for feedback from the curator.`})}}),d&&t.jsx(qe,{message:d.message,type:d.type,onClose:()=>c(null)})]})}const jc="https://ftwlzdhkzqfuosdorgjt.supabase.co/storage/v1/object/public/playlistpartner%20public/playlistpartner%20og%20image.png";function _c(){const{genre:s}=Bt(),e=s?decodeURIComponent(s):"",{genres:r,loading:n}=Fe(),a=r.find(y=>y.slug===e),[i,o]=b.useState(null),[l,d]=b.useState(!1),[c,u]=b.useState(null),h=Xe(),{totalCount:f}=Kt({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(me,{className:"w-8 h-8 text-green-500 animate-spin"})})});if(!n&&!a)return t.jsxs("div",{className:"container mx-auto px-4 py-8",children:[t.jsx("h1",{className:"text-2xl font-bold mb-4",children:"Genre Not Found"}),t.jsx(J,{to:"/",className:"text-green-600 hover:text-green-700",children:"Return to Home"})]});const v=`Free ${a.name} Spotify Playlist Submission - No Signup`,w=`Submit your ${a.name} tracks to ${f} Spotify playlists for free. Connect with independent curators and grow your audience — no signup needed.`,x=async y=>{try{d(!1),u({type:"success",message:`Track submitted to ${i==null?void 0:i.name}! Watch your inbox for feedback from the curator.`})}catch(P){console.error("Failed to submit track:",P),u({type:"error",message:"Failed to submit track. Please try again."})}};return t.jsxs(t.Fragment,{children:[t.jsx(Re,{title:v,description:w,image:jc,url:`${window.location.origin}/genre/${a.slug}`,type:"website"}),t.jsxs("main",{className:"container mx-auto px-4 py-8",children:[t.jsxs(J,{to:"/",className:"inline-flex items-center gap-2 text-green-600 hover:text-green-700 mb-6",children:[t.jsx(We,{className:"w-4 h-4"}),"Back to All Genres"]}),t.jsx("div",{className:"bg-white p-6 rounded-lg shadow-sm mb-8",children:t.jsxs("div",{className:"flex items-start gap-4",children:[t.jsx("div",{className:"p-3 bg-green-50 rounded-lg",children:t.jsx(ve,{className:"w-8 h-8 text-green-600"})}),t.jsxs("div",{children:[t.jsxs("h1",{className:"text-3xl font-bold mb-2",children:[a.name," Spotify Playlist Submission"]}),t.jsx("p",{className:"text-gray-600 mb-4",children:a.description}),t.jsx("div",{className:"flex gap-4 text-sm text-gray-600",children:t.jsxs("span",{children:[f," Playlists"]})})]})]})}),t.jsx(Jn,{genre:a.name,totalCount:f,onViewAll:p}),l&&i&&t.jsx(kt,{playlist:i,onClose:()=>{d(!1),o(null)},onSubmit:x}),c&&t.jsx(qe,{message:c.message,type:c.type,onClose:()=>u(null)})]})]})}const Nc="https://ftwlzdhkzqfuosdorgjt.supabase.co/storage/v1/object/public/playlistpartner%20public/playlistpartner%20og%20image.png";function Sc(){const{genre:s,subGenre:e}=Bt(),r=s?decodeURIComponent(s):"",n=e?decodeURIComponent(e):"",{genres:a,loading:i}=Fe(),o=a.find(A=>A.slug===r),l=o==null?void 0:o.subGenres.find(A=>Me(A.name)===n),[d,c]=b.useState(null),[u,h]=b.useState(!1),[f,p]=b.useState(null),v=Xe(),{totalCount:w}=Kt({genre:o==null?void 0:o.name,subGenre:l==null?void 0:l.name}),x=()=>{!o||!l||(window.scrollTo(0,0),v("/playlists",{state:{filters:{genre:o.name,subGenre:l.name,fromSubmission:!0}},replace:!0}))};if(i)return t.jsx("div",{className:"container mx-auto px-4 py-8",children:t.jsx("div",{className:"flex items-center justify-center min-h-[400px]",children:t.jsx(me,{className:"w-8 h-8 text-green-500 animate-spin"})})});if(!i&&(!o||!l))return t.jsxs("div",{className:"container mx-auto px-4 py-8",children:[t.jsx("h1",{className:"text-2xl font-bold mb-4",children:"Sub-Genre Not Found"}),t.jsx(J,{to:"/",className:"text-green-600 hover:text-green-700",children:"Return to Home"})]});const y=`Free ${l.name} Spotify Playlist Submission - No Signup`,P=`Submit your ${l.name} tracks to ${w} Spotify playlists for free. Connect with independent curators and grow your audience — no signup needed.`,_=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(S){console.error("Failed to submit track:",S),p({type:"error",message:"Failed to submit track. Please try again."})}};return t.jsxs(t.Fragment,{children:[t.jsx(Re,{title:y,description:P,image:Nc,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(J,{to:`/genre/${encodeURIComponent(o.slug)}`,className:"inline-flex items-center gap-2 text-green-600 hover:text-green-700 mb-6",children:[t.jsx(We,{className:"w-4 h-4"}),"Back to ",o.name," Playlists"]}),t.jsx("div",{className:"bg-white p-6 rounded-lg shadow-sm mb-8",children:t.jsxs("div",{className:"flex items-start gap-4",children:[t.jsx("div",{className:"p-3 bg-green-50 rounded-lg",children:t.jsx(ve,{className:"w-8 h-8 text-green-600"})}),t.jsxs("div",{children:[t.jsxs("h1",{className:"text-3xl font-bold mb-2",children:[l.name," Spotify Playlist Submission"]}),t.jsx("p",{className:"text-gray-600 mb-4",children:l.description||`Discover curated playlists specializing in ${l.name} ${o.name} music. Submit your tracks to playlist curators who understand and appreciate your specific style.`}),t.jsx("div",{className:"flex gap-4 text-sm text-gray-600",children:t.jsxs("span",{children:[w," Playlists"]})})]})]})}),t.jsx(Jn,{genre:o.name,subGenre:l.name,totalCount:w,onViewAll:x}),u&&d&&t.jsx(kt,{playlist:d,onClose:()=>{h(!1),c(null)},onSubmit:_}),f&&t.jsx(qe,{message:f.message,type:f.type,onClose:()=>p(null)})]})]})}function kc(){const{genres:s,loading:e}=Fe();return b.useEffect(()=>{!e&&s.length>0&&typeof window<"u"&&window.prerenderReady!==void 0&&(window.prerenderReady=!0)},[e,s]),t.jsxs(t.Fragment,{children:[t.jsx(Re,{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(J,{to:"/",className:"inline-flex items-center gap-2 text-green-600 hover:text-green-700 mb-6",children:[t.jsx(We,{className:"w-4 h-4"}),"Back to Home"]}),t.jsxs("div",{className:"bg-white rounded-lg shadow-sm p-6 mb-8",children:[t.jsx("h1",{className:"text-3xl font-bold text-gray-900 mb-2",children:"Spotify Playlist Genres"}),t.jsx("p",{className:"text-gray-600",children:"Discover Spotify playlists in every genre and sub-genre. Submit your music directly to curators for free - from hip-hop to classical, find the perfect playlists for your sound."})]}),e?t.jsx("div",{className:"grid grid-cols-1 md:grid-cols-2 lg:grid-cols-3 gap-6",children:[...Array(6)].map((r,n)=>t.jsxs("div",{className:"bg-white p-6 rounded-lg shadow-sm animate-pulse",children:[t.jsx("div",{className:"h-6 w-1/3 bg-gray-200 rounded mb-4"}),t.jsx("div",{className:"space-y-2",children:[...Array(4)].map((a,i)=>t.jsx("div",{className:"h-4 bg-gray-100 rounded w-2/3"},i))})]},n))}):t.jsx("div",{className:"grid grid-cols-1 md:grid-cols-2 lg:grid-cols-3 gap-6",children:s.map(r=>t.jsxs("div",{className:"bg-white p-6 rounded-lg shadow-sm",children:[t.jsxs(J,{to:`/genre/${Me(r.name)}`,className:"group flex items-center gap-3 mb-4",children:[t.jsx("div",{className:"p-2 bg-gray-50 rounded-lg group-hover:bg-green-50 transition-colors",children:t.jsx(ve,{className:"w-5 h-5 text-gray-500 group-hover:text-green-600"})}),t.jsx("h2",{className:"text-xl font-semibold text-gray-900 group-hover:text-green-600 transition-colors",children:r.name})]}),r.subGenres.length>0&&t.jsx("div",{className:"space-y-1",children:r.subGenres.map(n=>t.jsxs(J,{to:`/genre/${Me(r.name)}/${Me(n.name)}`,className:"block text-gray-600 hover:text-green-600 transition-colors pl-11",children:[n.name,n.description&&t.jsx("p",{className:"text-sm text-gray-500 mt-0.5",children:n.description})]},n.id))})]},r.id))})]})]})}function Ec(){const{totalCount:s}=Kt({});return t.jsxs(t.Fragment,{children:[t.jsx(Re,{title:"About PlaylistPartner - Free Spotify Playlist Submission Platform",description:"Learn about PlaylistPartner, your free platform for submitting music to Spotify playlist curators. No signup required, direct curator connections."}),t.jsx("div",{className:"bg-gradient-to-b from-green-50 to-white",children:t.jsxs("div",{className:"container mx-auto px-4 py-16 md:py-24",children:[t.jsxs("div",{className:"max-w-3xl mx-auto text-center mb-16",children:[t.jsx(gs,{className:"w-12 h-12 text-green-600 mx-auto mb-6"}),t.jsx("h1",{className:"text-4xl font-bold text-gray-900 mb-6",children:"Music Promotion Made Simple"}),t.jsx("p",{className:"text-xl text-gray-600",children:"Submit your music directly to Spotify playlist curators without the typical barriers. No signups, no fees, and no waiting around. Only on PlaylistPartner."})]}),t.jsxs("div",{className:"max-w-5xl mx-auto grid md:grid-cols-3 gap-8 mb-24",children:[t.jsxs("div",{className:"bg-white p-6 rounded-lg shadow-sm text-center",children:[t.jsx(xl,{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(Pl,{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(Gt,{className:"w-8 h-8 text-green-600 mx-auto mb-4"}),t.jsx("h3",{className:"text-lg font-semibold mb-2",children:"Direct Connection"}),t.jsx("p",{className:"text-gray-600",children:"Connect directly with curators in your genre and style. Filter playlists by genre, sub-genre, or search."})]})]}),t.jsxs("div",{className:"max-w-4xl mx-auto mb-24",children:[t.jsx("h2",{className:"text-3xl font-bold text-center mb-12",children:"How It Works"}),t.jsxs("div",{className:"space-y-12",children:[t.jsxs("div",{className:"flex items-start gap-6",children:[t.jsx("div",{className:"w-10 h-10 rounded-full bg-green-100 flex-shrink-0 flex items-center justify-center",children:t.jsx("span",{className:"text-green-600 font-bold",children:"1"})}),t.jsxs("div",{children:[t.jsx("h3",{className:"text-xl font-semibold mb-2",children:"Find Your Playlists"}),t.jsx("p",{className:"text-gray-600",children:"Browse our curated collection of Spotify playlists by genre, sub genre or follower count."})]})]}),t.jsxs("div",{className:"flex items-start gap-6",children:[t.jsx("div",{className:"w-10 h-10 rounded-full bg-green-100 flex-shrink-0 flex items-center justify-center",children:t.jsx("span",{className:"text-green-600 font-bold",children:"2"})}),t.jsxs("div",{children:[t.jsx("h3",{className:"text-xl font-semibold mb-2",children:"Submit Your Track"}),t.jsx("p",{className:"text-gray-600",children:"Select your track from Spotify and submit it to any playlist that matches your style. Add a personal message to the curator to increase your chances."})]})]}),t.jsxs("div",{className:"flex items-start gap-6",children:[t.jsx("div",{className:"w-10 h-10 rounded-full bg-green-100 flex-shrink-0 flex items-center justify-center",children:t.jsx("span",{className:"text-green-600 font-bold",children:"3"})}),t.jsxs("div",{children:[t.jsx("h3",{className:"text-xl font-semibold mb-2",children:"Get Featured"}),t.jsx("p",{className:"text-gray-600",children:"Curators review your submission and add tracks that fit their playlist. Build relationships with curators and grow your audience organically."})]})]})]})]}),t.jsx("div",{className:"max-w-4xl mx-auto border-t border-gray-200 pt-16",children:t.jsxs("div",{className:"grid grid-cols-2 md:grid-cols-4 gap-8",children:[t.jsxs("div",{className:"text-center",children:[t.jsxs("div",{className:"text-3xl font-bold text-green-600 mb-1",children:[s.toLocaleString(),"+"]}),t.jsx("div",{className:"text-sm text-gray-600",children:"Active Playlists"})]}),t.jsxs("div",{className:"text-center",children:[t.jsx("div",{className:"text-3xl font-bold text-green-600 mb-1",children:"15K+"}),t.jsx("div",{className:"text-sm text-gray-600",children:"Monthly Submissions"})]}),t.jsxs("div",{className:"text-center",children:[t.jsx("div",{className:"text-3xl font-bold text-green-600 mb-1",children:"2000+"}),t.jsx("div",{className:"text-sm text-gray-600",children:"Curators"})]}),t.jsxs("div",{className:"text-center",children:[t.jsx("div",{className:"text-3xl font-bold text-green-600 mb-1",children:"100%"}),t.jsx("div",{className:"text-sm text-gray-600",children:"Free"})]})]})}),t.jsxs("div",{className:"max-w-xl mx-auto text-center mt-24",children:[t.jsx("h2",{className:"text-2xl font-bold mb-6",children:"Ready to Share Your Music?"}),t.jsxs("div",{className:"flex flex-col sm:flex-row gap-4 justify-center",children:[t.jsx("a",{href:"/submit",className:"inline-flex items-center justify-center bg-green-500 text-white px-8 py-3 rounded-lg hover:bg-green-600 transition-colors font-medium",children:"Submit Your Music"}),t.jsx("a",{href:"/playlists",className:"inline-flex items-center justify-center bg-white text-gray-700 px-8 py-3 rounded-lg hover:bg-gray-100 transition-colors font-medium border border-gray-200",children:"Browse Playlists"})]})]})]})})]})}function Cc(){const[s,e]=b.useState({name:"",email:"",playlistUrl:""}),[r,n]=b.useState(!1),[a,i]=b.useState(null),[o,l]=b.useState(!1);b.useEffect(()=>{typeof window<"u"&&window.prerenderReady!==void 0&&(window.prerenderReady=!0)},[]);const d=u=>{const h=_t(u,"playlist");if(!h)throw new Error("Please enter a valid Spotify playlist URL");return h},c=async u=>{u.preventDefault(),i(null),n(!0);try{if(!/^[^\s@]+@[^\s@]+\.[^\s@]+$/.test(s.email))throw new Error("Please enter a valid email address");const h=d(s.playlistUrl),{error:f}=await W.from("curator_applications").insert({name:s.name,email:s.email,playlist_url:s.playlistUrl,playlist_id:h});if(f)throw f;l(!0),e({name:"",email:"",playlistUrl:""})}catch(h){console.error("Application submission failed:",h),i(h instanceof Error?h.message:"Failed to submit application")}finally{n(!1)}};return t.jsxs(t.Fragment,{children:[t.jsx(Re,{title:"Become a Curator - PlaylistPartner",description:"Join our network of Spotify playlist curators. Apply to list your playlists and connect with artists in your genre."}),t.jsx("div",{className:"bg-gradient-to-b from-green-50 to-white",children:t.jsx("div",{className:"container mx-auto px-4 py-16 md:py-24",children:t.jsxs("div",{className:"max-w-4xl mx-auto",children:[t.jsxs("div",{className:"text-center mb-16",children:[t.jsx(gs,{className:"w-12 h-12 text-green-600 mx-auto mb-6"}),t.jsx("h1",{className:"text-4xl font-bold text-gray-900 mb-12",children:"Join Our Curator Network"}),t.jsxs("div",{className:"grid md:grid-cols-2 gap-8",children:[t.jsxs("div",{className:"bg-white p-8 rounded-xl shadow-sm",children:[t.jsx("div",{className:"p-3 bg-green-50 rounded-lg w-12 h-12 flex items-center justify-center mx-auto mb-4",children:t.jsx(ml,{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(Gt,{className:"w-6 h-6 text-green-600"})}),t.jsx("h2",{className:"text-xl font-bold mb-4",children:"For Artists"}),t.jsx("p",{className:"text-gray-600",children:"Already making music? List your artist playlists to connect with other independent artists in your genre, expand your network, and build meaningful relationships within your music community."})]})]})]}),t.jsxs("div",{className:"bg-white p-8 rounded-xl shadow-sm mb-12",children:[t.jsx("h2",{className:"text-2xl font-bold mb-6",children:"What We Look For"}),t.jsx("p",{className:"text-gray-600 mb-4",children:"Our curator network maintains high standards to ensure quality. We look for:"}),t.jsxs("ul",{className:"space-y-3 text-gray-600",children:[t.jsxs("li",{className:"flex items-center gap-2",children:[t.jsx(nt,{className:"w-5 h-5 text-green-500 flex-shrink-0"}),"Consistent playlist activity with regular updates"]}),t.jsxs("li",{className:"flex items-center gap-2",children:[t.jsx(nt,{className:"w-5 h-5 text-green-500 flex-shrink-0"}),"Genuine follower engagement"]}),t.jsxs("li",{className:"flex items-center gap-2",children:[t.jsx(nt,{className:"w-5 h-5 text-green-500 flex-shrink-0"}),"Clear genre focus and curation style"]}),t.jsxs("li",{className:"flex items-center gap-2",children:[t.jsx(nt,{className:"w-5 h-5 text-green-500 flex-shrink-0"}),"Professional playlist presentation"]})]})]}),t.jsx("div",{className:"bg-white p-8 rounded-xl shadow-sm",children:o?t.jsxs("div",{className:"text-center py-8",children:[t.jsx(nt,{className:"w-16 h-16 text-green-500 mx-auto mb-4"}),t.jsx("h2",{className:"text-2xl font-bold text-gray-900 mb-4",children:"Application Received!"}),t.jsx("p",{className:"text-gray-600 mb-6",children:"Thank you for your interest in joining PlaylistPartner. We'll review your application and get back to you as soon as possible."}),t.jsx("button",{onClick:()=>l(!1),className:"text-green-600 hover:text-green-700 font-medium",children:"Submit Another Application"})]}):t.jsxs(t.Fragment,{children:[t.jsx("h2",{className:"text-2xl font-bold mb-6",children:"Apply to Join"}),t.jsxs("form",{onSubmit:c,className:"space-y-6",children:[t.jsxs("div",{children:[t.jsx("label",{htmlFor:"name",className:"block text-sm font-medium text-gray-700 mb-1",children:"Your Name"}),t.jsx("input",{type:"text",id:"name",value:s.name,onChange:u=>e(h=>({...h,name:u.target.value})),className:"w-full p-3 border border-gray-300 rounded-lg focus:ring-2 focus:ring-green-500 focus:border-transparent",placeholder:"Enter your name",required:!0,disabled:r})]}),t.jsxs("div",{children:[t.jsx("label",{htmlFor:"email",className:"block text-sm font-medium text-gray-700 mb-1",children:"Email Address"}),t.jsx("input",{type:"email",id:"email",value:s.email,onChange:u=>e(h=>({...h,email:u.target.value})),className:"w-full p-3 border border-gray-300 rounded-lg focus:ring-2 focus:ring-green-500 focus:border-transparent",placeholder:"you@example.com",required:!0,disabled:r})]}),t.jsxs("div",{children:[t.jsx("label",{htmlFor:"playlistUrl",className:"block text-sm font-medium text-gray-700 mb-1",children:"Your Best Playlist"}),t.jsx("input",{type:"url",id:"playlistUrl",value:s.playlistUrl,onChange:u=>e(h=>({...h,playlistUrl:u.target.value})),className:"w-full p-3 border border-gray-300 rounded-lg focus:ring-2 focus:ring-green-500 focus:border-transparent",placeholder:"https://open.spotify.com/playlist/...",required:!0,disabled:r}),t.jsx("p",{className:"mt-1 text-sm text-gray-500",children:"Please provide the Spotify URL of your best performing playlist"})]}),a&&t.jsxs("div",{className:"flex items-center gap-2 text-red-600 bg-red-50 p-3 rounded-lg",children:[t.jsx(fe,{className:"w-5 h-5 flex-shrink-0"}),t.jsx("p",{children:a})]}),t.jsx("button",{type:"submit",disabled:r,className:"w-full flex items-center justify-center gap-2 bg-green-500 text-white p-3 rounded-lg hover:bg-green-600 transition-colors disabled:bg-gray-400 disabled:cursor-not-allowed font-medium",children:r?t.jsxs(t.Fragment,{children:[t.jsx(me,{className:"w-5 h-5 animate-spin"}),"Submitting..."]}):"Submit Application"})]})]})}),t.jsxs("div",{className:"mt-12 bg-white p-8 rounded-xl shadow-sm",children:[t.jsx("h2",{className:"text-2xl font-bold mb-6",children:"What Happens Next?"}),t.jsxs("div",{className:"space-y-6",children:[t.jsxs("div",{className:"flex items-start gap-4",children:[t.jsx("div",{className:"w-8 h-8 bg-green-100 rounded-full flex items-center justify-center flex-shrink-0",children:t.jsx("span",{className:"text-green-600 font-bold",children:"1"})}),t.jsx("div",{children:t.jsx("p",{className:"text-gray-600",children:"Submit your application with links to your playlists"})})]}),t.jsxs("div",{className:"flex items-start gap-4",children:[t.jsx("div",{className:"w-8 h-8 bg-green-100 rounded-full flex items-center justify-center flex-shrink-0",children:t.jsx("span",{className:"text-green-600 font-bold",children:"2"})}),t.jsx("div",{children:t.jsx("p",{className:"text-gray-600",children:"Our team reviews your submission against our quality criteria"})})]}),t.jsxs("div",{className:"flex items-start gap-4",children:[t.jsx("div",{className:"w-8 h-8 bg-green-100 rounded-full flex items-center justify-center flex-shrink-0",children:t.jsx("span",{className:"text-green-600 font-bold",children:"3"})}),t.jsx("div",{children:t.jsx("p",{className:"text-gray-600",children:"If approved, you'll receive instructions for adding your playlists"})})]}),t.jsxs("div",{className:"flex items-start gap-4",children:[t.jsx("div",{className:"w-8 h-8 bg-green-100 rounded-full flex items-center justify-center flex-shrink-0",children:t.jsx("span",{className:"text-green-600 font-bold",children:"4"})}),t.jsx("div",{children:t.jsx("p",{className:"text-gray-600",children:"Start connecting with artists and growing your network"})})]})]})]})]})})})]})}function Tc(){const[s,e]=b.useState([]),[r,n]=b.useState(!0),[a,i]=b.useState(null),[o,l]=b.useState(1),[d,c]=b.useState(0),u=9;b.useEffect(()=>{h()},[o]);async function h(){try{n(!0);const w=(o-1)*u,x=await Dl(u,w);e(x.items),c(x.total)}catch(w){i("Failed to load blog posts. Please try again later."),console.error("Error loading blog posts:",w)}finally{n(!1)}}const f=Math.ceil(d/u);function p(w){return new Date(w).toLocaleDateString("en-US",{year:"numeric",month:"long",day:"numeric"})}function v(w){return w.startsWith("//")?`https:${w}`:w}return t.jsxs(t.Fragment,{children:[t.jsx(Re,{title:"Blog - Music Industry Insights",description:"Stay updated with the latest music industry trends, playlist curation tips, and artist success stories."}),t.jsx("div",{className:"bg-gradient-to-b from-green-50 to-white",children:t.jsxs("section",{className:"max-w-7xl mx-auto px-4 sm:px-6 lg:px-8 py-12 md:py-20",children:[t.jsxs("div",{className:"text-center mb-12",children:[t.jsx("h1",{className:"text-4xl md:text-5xl font-bold text-gray-900 mb-4",children:"Music Industry Insights"}),t.jsx("p",{className:"text-xl text-gray-600 max-w-2xl mx-auto",children:"Discover the latest trends, tips, and success stories from the world of music streaming and playlist curation."})]}),r&&t.jsx("div",{className:"flex justify-center items-center min-h-[400px]",children:t.jsx("div",{className:"animate-spin rounded-full h-12 w-12 border-b-2 border-green-600"})}),a&&t.jsx("div",{className:"text-center py-12",children:t.jsx("p",{className:"text-red-600",children:a})}),!r&&!a&&s.length===0&&t.jsx("div",{className:"text-center py-12",children:t.jsx("p",{className:"text-gray-600",children:"No blog posts available yet. Check back soon!"})}),!r&&!a&&s.length>0&&t.jsxs(t.Fragment,{children:[t.jsx("div",{className:"grid grid-cols-1 md:grid-cols-2 lg:grid-cols-3 gap-8 mb-12",children:s.map(w=>{var x,y,P,_,A;return t.jsxs("article",{className:"bg-white rounded-lg shadow-md overflow-hidden hover:shadow-lg transition-shadow",children:[((P=(y=(x=w.fields.featuredImage)==null?void 0:x.fields)==null?void 0:y.file)==null?void 0:P.url)&&t.jsx(J,{to:`/blog/${((_=w.fields.category)==null?void 0:_.toLowerCase())||"news"}/${w.fields.slug}`,children:t.jsx("img",{src:v(w.fields.featuredImage.fields.file.url),alt:w.fields.featuredImage.fields.title||w.fields.title,className:"w-full aspect-[3/2] object-cover"})}),t.jsxs("div",{className:"p-6",children:[t.jsx(J,{to:`/blog/${((A=w.fields.category)==null?void 0:A.toLowerCase())||"news"}/${w.fields.slug}`,children:t.jsx("h2",{className:"text-xl font-semibold text-gray-900 mb-2 hover:text-green-600 transition-colors",children:w.fields.title})}),w.fields.excerpt&&t.jsx("p",{className:"text-gray-600 mb-4 line-clamp-3",children:w.fields.excerpt}),t.jsxs("div",{className:"flex flex-wrap items-center gap-4 text-sm text-gray-500",children:[t.jsxs("div",{className:"flex items-center gap-1",children:[t.jsx(ms,{className:"w-4 h-4"}),t.jsx("span",{children:p(w.fields.publishDate||w.sys.createdAt)})]}),w.fields.category&&t.jsxs("div",{className:"flex items-center gap-1",children:[t.jsx(Ws,{className:"w-4 h-4"}),t.jsx("span",{children:w.fields.category})]})]})]})]},w.sys.id)})}),f>1&&t.jsxs("div",{className:"flex justify-center gap-2",children:[t.jsx("button",{onClick:()=>l(o-1),disabled:o===1,className:"px-4 py-2 border border-gray-300 rounded-md text-gray-700 hover:bg-gray-50 disabled:opacity-50 disabled:cursor-not-allowed",children:"Previous"}),t.jsx("div",{className:"flex items-center gap-2",children:Array.from({length:f},(w,x)=>x+1).map(w=>t.jsx("button",{onClick:()=>l(w),className:`px-3 py-1 rounded-md ${w===o?"bg-green-600 text-white":"text-gray-700 hover:bg-gray-50"}`,children:w},w))}),t.jsx("button",{onClick:()=>l(o+1),disabled:o===f,className:"px-4 py-2 border border-gray-300 rounded-md text-gray-700 hover:bg-gray-50 disabled:opacity-50 disabled:cursor-not-allowed",children:"Next"})]})]})]})})]})}var Ce={},Pc=s=>{if(Object.prototype.toString.call(s)!=="[object Object]")return!1;const e=Object.getPrototypeOf(s);return e===null||e===Object.prototype};(function(s){var e=Pc;s.BLOCKS=void 0,function(E){E.DOCUMENT="document",E.PARAGRAPH="paragraph",E.HEADING_1="heading-1",E.HEADING_2="heading-2",E.HEADING_3="heading-3",E.HEADING_4="heading-4",E.HEADING_5="heading-5",E.HEADING_6="heading-6",E.OL_LIST="ordered-list",E.UL_LIST="unordered-list",E.LIST_ITEM="list-item",E.HR="hr",E.QUOTE="blockquote",E.EMBEDDED_ENTRY="embedded-entry-block",E.EMBEDDED_ASSET="embedded-asset-block",E.EMBEDDED_RESOURCE="embedded-resource-block",E.TABLE="table",E.TABLE_ROW="table-row",E.TABLE_CELL="table-cell",E.TABLE_HEADER_CELL="table-header-cell"}(s.BLOCKS||(s.BLOCKS={})),s.INLINES=void 0,function(E){E.ASSET_HYPERLINK="asset-hyperlink",E.EMBEDDED_ENTRY="embedded-entry-inline",E.EMBEDDED_RESOURCE="embedded-resource-inline",E.ENTRY_HYPERLINK="entry-hyperlink",E.HYPERLINK="hyperlink",E.RESOURCE_HYPERLINK="resource-hyperlink"}(s.INLINES||(s.INLINES={})),s.MARKS=void 0,function(E){E.BOLD="bold",E.ITALIC="italic",E.UNDERLINE="underline",E.CODE="code",E.SUPERSCRIPT="superscript",E.SUBSCRIPT="subscript",E.STRIKETHROUGH="strikethrough"}(s.MARKS||(s.MARKS={}));var r=function(E,L){return r=Object.setPrototypeOf||{__proto__:[]}instanceof Array&&function(D,C){D.__proto__=C}||function(D,C){for(var O in C)Object.prototype.hasOwnProperty.call(C,O)&&(D[O]=C[O])},r(E,L)};function n(E,L){if(typeof L!="function"&&L!==null)throw new TypeError("Class extends value "+String(L)+" is not a constructor or null");r(E,L);function D(){this.constructor=E}E.prototype=L===null?Object.create(L):(D.prototype=L.prototype,new D)}function a(E,L,D){if(D||arguments.length===2)for(var C=0,O=L.length,$;C<O;C++)($||!(C in L))&&($||($=Array.prototype.slice.call(L,0,C)),$[C]=L[C]);return E.concat($||Array.prototype.slice.call(L))}typeof SuppressedError=="function"&&SuppressedError;var i,o=[s.BLOCKS.PARAGRAPH,s.BLOCKS.HEADING_1,s.BLOCKS.HEADING_2,s.BLOCKS.HEADING_3,s.BLOCKS.HEADING_4,s.BLOCKS.HEADING_5,s.BLOCKS.HEADING_6,s.BLOCKS.OL_LIST,s.BLOCKS.UL_LIST,s.BLOCKS.HR,s.BLOCKS.QUOTE,s.BLOCKS.EMBEDDED_ENTRY,s.BLOCKS.EMBEDDED_ASSET,s.BLOCKS.EMBEDDED_RESOURCE,s.BLOCKS.TABLE],l=[s.BLOCKS.PARAGRAPH,s.BLOCKS.HEADING_1,s.BLOCKS.HEADING_2,s.BLOCKS.HEADING_3,s.BLOCKS.HEADING_4,s.BLOCKS.HEADING_5,s.BLOCKS.HEADING_6,s.BLOCKS.OL_LIST,s.BLOCKS.UL_LIST,s.BLOCKS.HR,s.BLOCKS.QUOTE,s.BLOCKS.EMBEDDED_ENTRY,s.BLOCKS.EMBEDDED_ASSET,s.BLOCKS.EMBEDDED_RESOURCE],d=[s.BLOCKS.TABLE,s.BLOCKS.TABLE_ROW,s.BLOCKS.TABLE_CELL,s.BLOCKS.TABLE_HEADER_CELL],c=[s.BLOCKS.HR,s.BLOCKS.EMBEDDED_ENTRY,s.BLOCKS.EMBEDDED_ASSET,s.BLOCKS.EMBEDDED_RESOURCE],u=(i={},i[s.BLOCKS.OL_LIST]=[s.BLOCKS.LIST_ITEM],i[s.BLOCKS.UL_LIST]=[s.BLOCKS.LIST_ITEM],i[s.BLOCKS.LIST_ITEM]=l,i[s.BLOCKS.QUOTE]=[s.BLOCKS.PARAGRAPH],i[s.BLOCKS.TABLE]=[s.BLOCKS.TABLE_ROW],i[s.BLOCKS.TABLE_ROW]=[s.BLOCKS.TABLE_CELL,s.BLOCKS.TABLE_HEADER_CELL],i[s.BLOCKS.TABLE_CELL]=[s.BLOCKS.PARAGRAPH,s.BLOCKS.UL_LIST,s.BLOCKS.OL_LIST],i[s.BLOCKS.TABLE_HEADER_CELL]=[s.BLOCKS.PARAGRAPH],i),h=[s.BLOCKS.HEADING_1,s.BLOCKS.HEADING_2,s.BLOCKS.HEADING_3,s.BLOCKS.HEADING_4,s.BLOCKS.HEADING_5,s.BLOCKS.HEADING_6],f=a([s.BLOCKS.PARAGRAPH],h,!0),p=[s.BLOCKS.DOCUMENT,s.BLOCKS.PARAGRAPH,s.BLOCKS.HEADING_1,s.BLOCKS.HEADING_2,s.BLOCKS.HEADING_3,s.BLOCKS.HEADING_4,s.BLOCKS.HEADING_5,s.BLOCKS.HEADING_6,s.BLOCKS.OL_LIST,s.BLOCKS.UL_LIST,s.BLOCKS.LIST_ITEM,s.BLOCKS.HR,s.BLOCKS.QUOTE,s.BLOCKS.EMBEDDED_ENTRY,s.BLOCKS.EMBEDDED_ASSET,s.INLINES.HYPERLINK,s.INLINES.ENTRY_HYPERLINK,s.INLINES.ASSET_HYPERLINK,s.INLINES.EMBEDDED_ENTRY,"text"],v=[s.MARKS.BOLD,s.MARKS.CODE,s.MARKS.ITALIC,s.MARKS.UNDERLINE],w={nodeType:s.BLOCKS.DOCUMENT,data:{},content:[{nodeType:s.BLOCKS.PARAGRAPH,data:{},content:[{nodeType:"text",value:"",marks:[],data:{}}]}]};function x(E,L){for(var D=0,C=Object.keys(E);D<C.length;D++){var O=C[D];if(L===E[O])return!0}return!1}function y(E){return x(s.INLINES,E.nodeType)}function P(E){return x(s.BLOCKS,E.nodeType)}function _(E){return E.nodeType==="text"}var A=Object.freeze({__proto__:null,isBlock:P,isInline:y,isText:_}),S=function(E){var L=E.path,D=E.property,C=E.typeName,O=E.value;return{details:'The type of "'.concat(D,'" is incorrect, expected type: ').concat(C),name:"type",path:L.toArray(),type:C,value:O}},N=function(E){var L=E.min,D=E.value,C=E.path;return{name:"size",min:L,path:C.toArray(),details:"Size must be at least ".concat(L),value:D}},j=function(E){var L=E.max,D=E.value,C=E.path;return{name:"size",max:L,path:C.toArray(),details:"Size must be at most ".concat(L),value:D}},m=function(E){var L=E.expected,D=E.value,C=E.path;return{details:"Value must be one of expected values",name:"in",expected:a([],L,!0).sort(),path:C.toArray(),value:D}},g=function(E){var L=E.property,D=E.path;return{details:'The property "'.concat(L,'" is not expected'),name:"unexpected",path:D.toArray()}},k=function(E){var L=E.property,D=E.path;return{details:'The property "'.concat(L,'" is required here'),name:"required",path:D.toArray()}},T=function(){function E(L,D){var C=this;this.obj=L,this.path=D,this._errors=[],this.catch=function(){for(var O,$=[],B=0;B<arguments.length;B++)$[B]=arguments[B];(O=C._errors).push.apply(O,$)},this.exists=function(O){return O in C.obj?!0:(C.catch(k({property:O,path:C.path.of(O)})),!1)},this.object=function(O){var $,B=O?C.obj[O]:C.obj;if(O&&!C.exists(O))return!1;if(e(B))return!0;var Z=O?C.path.of(O):C.path,G=($=O??C.path.last())!==null&&$!==void 0?$:"value";return C.catch(S({typeName:"Object",property:G,path:Z,value:B})),!1},this.string=function(O){var $=C.obj[O];return O&&!C.exists(O)?!1:typeof $=="string"?!0:(C.catch(S({typeName:"String",property:O,path:C.path.of(O),value:$})),!1)},this.number=function(O,$){var B=C.obj[O];return $&&!(O in C.obj)?!0:C.exists(O)?typeof B=="number"&&!Number.isNaN(B)?!0:(C.catch(S({typeName:"Number",property:O,path:C.path.of(O),value:B})),!1):!1},this.array=function(O){var $=C.obj[O];return O&&!C.exists(O)?!1:Array.isArray($)?!0:(C.catch(S({typeName:"Array",property:O,path:C.path.of(O),value:$})),!1)},this.enum=function(O,$){var B=C.obj[O];return typeof B=="string"&&$.includes(B)?!0:(C.catch(m({expected:$,value:B,path:C.path.of(O)})),!1)},this.empty=function(O){if(!C.array(O))return!1;var $=C.obj[O];return $.length===0?!0:(C.catch(j({max:0,value:$,path:C.path.of(O)})),!1)},this.minLength=function(O,$){if(!C.array(O))return!1;var B=C.obj[O];return B.length>=$?!0:(C.catch(N({min:$,value:B,path:C.path.of(O)})),!1)},this.noAdditionalProperties=function(O){var $=Object.keys(C.obj).sort().filter(function(B){return!O.includes(B)});return $.forEach(function(B){return C.catch(g({property:B,path:C.path.of(B)}))}),$.length===0},this.each=function(O,$){if(C.array(O)){var B=C.obj[O],Z=!1;B.forEach(function(G,xe){if(!Z){var V=$(G,C.path.of(O).of(xe));V.length>0&&(Z=!0),C.catch.apply(C,V)}})}}}return Object.defineProperty(E.prototype,"errors",{get:function(){var L=this,D=function(C){return JSON.stringify({details:C.details,path:C.path})};return this._errors.filter(function(C,O){return L._errors.findIndex(function($){return D(C)===D($)})===O})},enumerable:!1,configurable:!0}),E}(),I=[],R=function(){function E(L,D){this.contentRule=L,this.validateData=D}return E.prototype.assert=function(L,D){var C,O,$=new T(L,D);if(!$.object())return $.errors;$.noAdditionalProperties(["nodeType","data","content"]);var B=Array.isArray(this.contentRule)?{nodeTypes:this.contentRule}:this.contentRule(L,D),Z=B.nodeTypes,G=B.min,xe=G===void 0?0:G;if(Z.length===0&&xe>0)throw new Error("Invalid content rule. Cannot have enforce a 'min' of ".concat(xe," with no nodeTypes"));if($.minLength("content",xe),Z.length===0?$.empty("content"):$.each("content",function(de,De){var Pe=new T(de,De);return Pe.object()&&Pe.enum("nodeType",Z),Pe.errors}),$.object("data")){var V=(O=(C=this.validateData)===null||C===void 0?void 0:C.call(this,L.data,D.of("data")))!==null&&O!==void 0?O:[];$.catch.apply($,V)}return $.errors},E}(),K=function(E){n(L,E);function L(D,C){var O=E.call(this,C,function($,B){return O.assertLink($,B)})||this;return O.linkType=D,O.assertLink=function($,B){var Z=new T($,B);if(Z.object("target")){var G=new T($.target.sys,B.of("target").of("sys"));G.object()&&(G.enum("type",[O.type]),G.enum("linkType",[O.linkType]),O.type==="Link"?(G.string("id"),G.noAdditionalProperties(["type","linkType","id"])):O.type==="ResourceLink"&&(G.string("urn"),G.noAdditionalProperties(["type","linkType","urn"]))),Z.catch.apply(Z,G.errors)}return Z.noAdditionalProperties(["target"]),Z.errors},O.type=O.linkType.startsWith("Contentful:")?"ResourceLink":"Link",O}return L}(R),X=function(E){n(L,E);function L(){var D=E.call(this,["text"],function(C,O){return D.assertLink(C,O)})||this;return D.assertLink=function(C,O){var $=new T(C,O);return $.string("uri"),$.noAdditionalProperties(["uri"]),$.errors},D}return L}(R),re=function(E,L){return new R(E,L)},F=function(E,L){return new K(E,L)},ne=function(){function E(L){L===void 0&&(L=[]);var D=this;this.path=L,this.of=function(C){return new E(a(a([],D.path,!0),[C],!1))},this.isRoot=function(){return D.path.length===0},this.last=function(){return D.path[D.path.length-1]},this.toArray=function(){return D.path}}return E}();function H(E,L){var D=new T(E,L);return D.object()&&(D.noAdditionalProperties(["nodeType","data","value","marks"]),D.object("data"),D.each("marks",function(C,O){var $=new T(C,O);return $.object()&&$.string("type"),$.errors}),D.string("value")),D.errors}var U,q=re(a(a([],Object.values(s.INLINES),!0),["text"],!1).sort()),Q=re([s.BLOCKS.LIST_ITEM]),M=F("Entry",I),le=re(function(){return{nodeTypes:[s.BLOCKS.PARAGRAPH],min:1}},function(E,L){var D=new T(E,L);return D.noAdditionalProperties(["colspan","rowspan"]),D.number("colspan",!0),D.number("rowspan",!0),D.errors}),ce=(U={},U[s.BLOCKS.DOCUMENT]=re(o),U[s.BLOCKS.PARAGRAPH]=q,U[s.BLOCKS.HEADING_1]=q,U[s.BLOCKS.HEADING_2]=q,U[s.BLOCKS.HEADING_3]=q,U[s.BLOCKS.HEADING_4]=q,U[s.BLOCKS.HEADING_5]=q,U[s.BLOCKS.HEADING_6]=q,U[s.BLOCKS.QUOTE]=re(u[s.BLOCKS.QUOTE]),U[s.BLOCKS.EMBEDDED_ENTRY]=M,U[s.BLOCKS.EMBEDDED_ASSET]=F("Asset",I),U[s.BLOCKS.EMBEDDED_RESOURCE]=F("Contentful:Entry",I),U[s.BLOCKS.HR]=re(I),U[s.BLOCKS.OL_LIST]=Q,U[s.BLOCKS.UL_LIST]=Q,U[s.BLOCKS.LIST_ITEM]=re(a([],l,!0).sort()),U[s.BLOCKS.TABLE]=re(function(){return{nodeTypes:[s.BLOCKS.TABLE_ROW],min:1}}),U[s.BLOCKS.TABLE_ROW]=re(function(){return{nodeTypes:[s.BLOCKS.TABLE_CELL,s.BLOCKS.TABLE_HEADER_CELL],min:1}}),U[s.BLOCKS.TABLE_CELL]=le,U[s.BLOCKS.TABLE_HEADER_CELL]=le,U[s.INLINES.HYPERLINK]=new X,U[s.INLINES.EMBEDDED_ENTRY]=M,U[s.INLINES.EMBEDDED_RESOURCE]=F("Contentful:Entry",I),U[s.INLINES.ENTRY_HYPERLINK]=F("Entry",["text"]),U[s.INLINES.ASSET_HYPERLINK]=F("Asset",["text"]),U[s.INLINES.RESOURCE_HYPERLINK]=F("Contentful:Entry",["text"]),U);function ue(E,L){if(E.nodeType==="text")return H(E,L);var D=ce[E.nodeType].assert(E,L);if(D.length>0)return D;var C=new T(E,L);return C.each("content",function(O,$){return ue(O,$)}),C.errors}var ae=function(E){var L=new ne,D=new T(E,L);return D.object()&&D.enum("nodeType",[s.BLOCKS.DOCUMENT]),D.errors.length>0?D.errors:ue(E,L)};s.CONTAINERS=u,s.EMPTY_DOCUMENT=w,s.HEADINGS=h,s.LIST_ITEM_BLOCKS=l,s.TABLE_BLOCKS=d,s.TEXT_CONTAINERS=f,s.TOP_LEVEL_BLOCKS=o,s.V1_MARKS=v,s.V1_NODE_TYPES=p,s.VOID_BLOCKS=c,s.helpers=A,s.validateRichTextDocument=ae})(Ce);var se=b,ee=Ce,pt=function(){return pt=Object.assign||function(e){for(var r,n=1,a=arguments.length;n<a;n++){r=arguments[n];for(var i in r)Object.prototype.hasOwnProperty.call(r,i)&&(e[i]=r[i])}return e},pt.apply(this,arguments)};function Ac(s,e){return se.isValidElement(s)&&s.key===null?se.cloneElement(s,{key:e}):s}function Oc(s,e){return s.map(function(r,n){return Ac(Yn(r,e),n)})}function Yn(s,e){var r=e.renderNode,n=e.renderMark,a=e.renderText,i=e.preserveWhitespace;if(ee.helpers.isText(s)){var o=a?a(s.value):s.value;if(i&&!a){o=o.replace(/ {2,}/g,function(u){return" ".repeat(u.length)});var l=o.split(` `),d=[];l.forEach(function(u,h){d.push(u),h!==l.length-1&&d.push(se.createElement("br",null))}),o=d}return s.marks.reduce(function(u,h){return n[h.type]?n[h.type](u):u},o)}else{var c=Oc(s.content,e);return!s.nodeType||!r[s.nodeType]?se.createElement(se.Fragment,null,c):r[s.nodeType](s,c)}}var ie,Ke,Lc=(ie={},ie[ee.BLOCKS.DOCUMENT]=function(s,e){return e},ie[ee.BLOCKS.PARAGRAPH]=function(s,e){return se.createElement("p",null,e)},ie[ee.BLOCKS.HEADING_1]=function(s,e){return se.createElement("h1",null,e)},ie[ee.BLOCKS.HEADING_2]=function(s,e){return se.createElement("h2",null,e)},ie[ee.BLOCKS.HEADING_3]=function(s,e){return se.createElement("h3",null,e)},ie[ee.BLOCKS.HEADING_4]=function(s,e){return se.createElement("h4",null,e)},ie[ee.BLOCKS.HEADING_5]=function(s,e){return se.createElement("h5",null,e)},ie[ee.BLOCKS.HEADING_6]=function(s,e){return se.createElement("h6",null,e)},ie[ee.BLOCKS.EMBEDDED_ENTRY]=function(s,e){return se.createElement("div",null,e)},ie[ee.BLOCKS.EMBEDDED_RESOURCE]=function(s,e){return se.createElement("div",null,e)},ie[ee.BLOCKS.UL_LIST]=function(s,e){return se.createElement("ul",null,e)},ie[ee.BLOCKS.OL_LIST]=function(s,e){return se.createElement("ol",null,e)},ie[ee.BLOCKS.LIST_ITEM]=function(s,e){return se.createElement("li",null,e)},ie[ee.BLOCKS.QUOTE]=function(s,e){return se.createElement("blockquote",null,e)},ie[ee.BLOCKS.HR]=function(){return se.createElement("hr",null)},ie[ee.BLOCKS.TABLE]=function(s,e){return se.createElement("table",null,se.createElement("tbody",null,e))},ie[ee.BLOCKS.TABLE_ROW]=function(s,e){return se.createElement("tr",null,e)},ie[ee.BLOCKS.TABLE_HEADER_CELL]=function(s,e){return se.createElement("th",null,e)},ie[ee.BLOCKS.TABLE_CELL]=function(s,e){return se.createElement("td",null,e)},ie[ee.INLINES.ASSET_HYPERLINK]=function(s){return Ps(ee.INLINES.ASSET_HYPERLINK,s)},ie[ee.INLINES.ENTRY_HYPERLINK]=function(s){return Ps(ee.INLINES.ENTRY_HYPERLINK,s)},ie[ee.INLINES.RESOURCE_HYPERLINK]=function(s){return Wr(ee.INLINES.RESOURCE_HYPERLINK,s)},ie[ee.INLINES.EMBEDDED_ENTRY]=function(s){return Ps(ee.INLINES.EMBEDDED_ENTRY,s)},ie[ee.INLINES.EMBEDDED_RESOURCE]=function(s,e){return Wr(ee.INLINES.EMBEDDED_RESOURCE,s)},ie[ee.INLINES.HYPERLINK]=function(s,e){return se.createElement("a",{href:s.data.uri},e)},ie),Ic=(Ke={},Ke[ee.MARKS.BOLD]=function(s){return se.createElement("b",null,s)},Ke[ee.MARKS.ITALIC]=function(s){return se.createElement("i",null,s)},Ke[ee.MARKS.UNDERLINE]=function(s){return se.createElement("u",null,s)},Ke[ee.MARKS.CODE]=function(s){return se.createElement("code",null,s)},Ke[ee.MARKS.SUPERSCRIPT]=function(s){return se.createElement("sup",null,s)},Ke[ee.MARKS.SUBSCRIPT]=function(s){return se.createElement("sub",null,s)},Ke[ee.MARKS.STRIKETHROUGH]=function(s){return se.createElement("s",null,s)},Ke);function Ps(s,e){return se.createElement("span",{key:e.data.target.sys.id},"type: ",e.nodeType," id: ",e.data.target.sys.id)}function Wr(s,e){return se.createElement("span",{key:e.data.target.sys.urn},"type: ",e.nodeType," urn: ",e.data.target.sys.urn)}function Rc(s,e){return e===void 0&&(e={}),s?Yn(s,{renderNode:pt(pt({},Lc),e.renderNode),renderMark:pt(pt({},Ic),e.renderMark),renderText:e.renderText,preserveWhitespace:e.preserveWhitespace}):null}var Dc=Rc;function $c(){var w,x,y,P;const{category:s,slug:e}=Bt(),[r,n]=b.useState(null),[a,i]=b.useState([]),[o,l]=b.useState(!0),[d,c]=b.useState(null);b.useEffect(()=>{e&&u()},[e,s]);async function u(){try{l(!0);const _=await $l(e);_?(n(_),h(_.fields.category||"News")):c("Blog post not found")}catch(_){c("Failed to load blog post. Please try again later."),console.error("Error loading blog post:",_)}finally{l(!1)}}async function h(_){try{const S=(await cr(_,3,0)).items.filter(N=>N.fields.slug!==e).slice(0,2);i(S)}catch(A){console.error("Error loading related posts:",A)}}function f(_){return new Date(_).toLocaleDateString("en-US",{year:"numeric",month:"long",day:"numeric"})}function p(_){return _.startsWith("//")?`https:${_}`:_}const v={renderNode:{[Ce.BLOCKS.PARAGRAPH]:(_,A)=>t.jsx("p",{className:"mb-6 text-gray-700 leading-relaxed",children:A}),[Ce.BLOCKS.HEADING_1]:(_,A)=>t.jsx("h1",{className:"text-3xl font-bold mb-6 text-gray-900",children:A}),[Ce.BLOCKS.HEADING_2]:(_,A)=>t.jsx("h2",{className:"text-2xl font-semibold mb-4 text-gray-900",children:A}),[Ce.BLOCKS.HEADING_3]:(_,A)=>t.jsx("h3",{className:"text-xl font-semibold mb-3 text-gray-900",children:A}),[Ce.BLOCKS.UL_LIST]:(_,A)=>t.jsx("ul",{className:"list-disc list-inside mb-6 space-y-2",children:A}),[Ce.BLOCKS.OL_LIST]:(_,A)=>t.jsx("ol",{className:"list-decimal list-inside mb-6 space-y-2",children:A}),[Ce.BLOCKS.LIST_ITEM]:(_,A)=>t.jsx("li",{className:"text-gray-700",children:A}),[Ce.BLOCKS.QUOTE]:(_,A)=>t.jsx("blockquote",{className:"border-l-4 border-green-600 pl-4 italic my-6 text-gray-600",children:A}),[Ce.BLOCKS.EMBEDDED_ASSET]:_=>{var N,j;if(!((j=(N=_.data.target)==null?void 0:N.fields)!=null&&j.file))return null;const{file:A,title:S}=_.data.target.fields;return t.jsx("img",{src:p(A.url),alt:S||"",className:"w-full rounded-lg my-6"})},[Ce.INLINES.HYPERLINK]:(_,A)=>t.jsx("a",{href:_.data.uri,target:"_blank",rel:"noopener noreferrer",className:"text-green-600 hover:text-green-700 underline",children:A})}};return o?t.jsx("div",{className:"min-h-screen flex justify-center items-center",children:t.jsx("div",{className:"animate-spin rounded-full h-12 w-12 border-b-2 border-green-600"})}):d||!r?t.jsxs("div",{className:"min-h-screen flex flex-col justify-center items-center",children:[t.jsx("p",{className:"text-red-600 mb-4",children:d||"Post not found"}),t.jsx(J,{to:"/blog",className:"text-green-600 hover:text-green-700",children:"Back to Blog"})]}):t.jsxs(t.Fragment,{children:[t.jsx(Re,{title:`${r.fields.title} - Blog`,description:r.fields.excerpt||`Read ${r.fields.title} on our blog`}),t.jsxs("article",{className:"bg-white",children:[t.jsxs("div",{className:"max-w-4xl mx-auto px-4 sm:px-6 lg:px-8 py-12",children:[t.jsxs(J,{to:"/blog",className:"inline-flex items-center gap-2 text-green-600 hover:text-green-700 mb-8",children:[t.jsx(We,{className:"w-4 h-4"}),"Back to Blog"]}),((y=(x=(w=r.fields.featuredImage)==null?void 0:w.fields)==null?void 0:x.file)==null?void 0:y.url)&&t.jsx("img",{src:p(r.fields.featuredImage.fields.file.url),alt:r.fields.featuredImage.fields.title||r.fields.title,className:"w-full aspect-[3/2] object-cover rounded-lg mb-8"}),t.jsxs("header",{className:"mb-8",children:[t.jsx("h1",{className:"text-4xl md:text-5xl font-bold text-gray-900 mb-4",children:r.fields.title}),t.jsxs("div",{className:"flex flex-wrap items-center gap-6 text-gray-600",children:[t.jsxs("div",{className:"flex items-center gap-2",children:[t.jsx(ms,{className:"w-5 h-5"}),t.jsx("span",{children:f(r.fields.publishDate||r.sys.createdAt)})]}),t.jsxs("div",{className:"flex items-center gap-2",children:[t.jsx(qt,{className:"w-5 h-5"}),t.jsxs("span",{children:["By ",t.jsx(J,{to:"/",className:"hover:text-green-600 transition-colors",children:"Playlist Partner"})]})]}),r.fields.category&&t.jsxs(J,{to:`/blog/${r.fields.category.toLowerCase()}`,className:"inline-flex items-center gap-1 px-3 py-1 bg-green-100 hover:bg-green-200 text-green-800 text-sm font-medium rounded-full transition-colors",children:[t.jsx(Ws,{className:"w-3 h-3"}),r.fields.category]})]})]}),t.jsx("div",{className:"prose prose-lg max-w-none mt-8",children:r.fields.content?Dc(r.fields.content,v):t.jsx("div",{className:"bg-gray-50 p-6 rounded-lg",children:t.jsx("p",{className:"text-gray-600",children:"No content available for this post."})})}),t.jsx("div",{className:"mt-12 pt-8 border-t border-gray-200",children:t.jsxs("div",{className:"flex items-center gap-2 text-sm text-gray-600",children:[t.jsx("span",{children:"Filed under:"}),t.jsxs(J,{to:`/blog/${((P=r.fields.category)==null?void 0:P.toLowerCase())||"news"}`,className:"inline-flex items-center gap-1 px-3 py-1 bg-gray-100 hover:bg-gray-200 rounded-full transition-colors",children:[t.jsx(Ws,{className:"w-3 h-3"}),r.fields.category||"News"]})]})})]}),a.length>0&&t.jsxs("div",{className:"max-w-4xl mx-auto px-4 sm:px-6 lg:px-8 mt-8",children:[t.jsxs("div",{className:"flex items-center gap-3 mb-8",children:[t.jsx(Sl,{className:"w-6 h-6 text-gray-700"}),t.jsx("h2",{className:"text-2xl font-semibold text-gray-900",children:"Related News & Guides"})]}),t.jsx("div",{className:"grid md:grid-cols-2 gap-6 mb-16",children:a.map(_=>{var A,S,N,j;return t.jsxs(J,{to:`/blog/${((A=_.fields.category)==null?void 0:A.toLowerCase())||"news"}/${_.fields.slug}`,className:"bg-white border border-gray-200 rounded-lg shadow-sm hover:shadow-md transition-shadow overflow-hidden group",children:[((j=(N=(S=_.fields.featuredImage)==null?void 0:S.fields)==null?void 0:N.file)==null?void 0:j.url)&&t.jsx("div",{className:"aspect-[3/2] overflow-hidden",children:t.jsx("img",{src:p(_.fields.featuredImage.fields.file.url),alt:_.fields.featuredImage.fields.title||_.fields.title,className:"w-full h-full object-cover group-hover:scale-105 transition-transform duration-300"})}),t.jsxs("div",{className:"p-6",children:[t.jsx("h3",{className:"font-semibold text-gray-900 group-hover:text-green-600 transition-colors line-clamp-2",children:_.fields.title}),_.fields.excerpt&&t.jsx("p",{className:"text-sm text-gray-600 mt-2 line-clamp-2",children:_.fields.excerpt})]})]},_.sys.id)})})]}),t.jsx("section",{className:"bg-gradient-to-r from-green-600 to-green-700 py-12",children:t.jsxs("div",{className:"max-w-4xl mx-auto px-4 sm:px-6 lg:px-8 text-center",children:[t.jsx("h2",{className:"text-3xl font-bold text-white mb-2",children:"Ready to Submit Your Music?"}),t.jsx("p",{className:"text-xl text-green-100 mb-8",children:"Browse 10,000+ curated playlists"}),t.jsxs("div",{className:"flex flex-col sm:flex-row gap-4 justify-center",children:[t.jsx(J,{to:"/playlists",className:"inline-flex items-center justify-center px-6 py-3 bg-white text-green-700 font-semibold rounded-lg hover:bg-gray-100 transition-colors",children:"Browse Playlists"}),t.jsxs(J,{to:"/submit",className:"inline-flex items-center justify-center px-6 py-3 bg-green-800 text-white font-semibold rounded-lg hover:bg-green-900 transition-colors",children:["Submit Track",t.jsx(Ut,{className:"w-5 h-5 ml-2"})]})]})]})})]})]})}function Uc(){const{category:s}=Bt(),[e,r]=b.useState([]),[n,a]=b.useState(!0),[i,o]=b.useState(null),[l,d]=b.useState(1),[c,u]=b.useState(0),h=9;b.useEffect(()=>{f()},[l,s]);async function f(){try{a(!0);const y=(l-1)*h,P=s?s.charAt(0).toUpperCase()+s.slice(1):"News",_=await cr(P,h,y);r(_.items),u(_.total)}catch(y){o("Failed to load blog posts. Please try again later."),console.error("Error loading blog posts:",y)}finally{a(!1)}}const p=Math.ceil(c/h);function v(y){return new Date(y).toLocaleDateString("en-US",{year:"numeric",month:"long",day:"numeric"})}function w(y){return y.startsWith("//")?`https:${y}`:y}function x(y){return y.charAt(0).toUpperCase()+y.slice(1)}return t.jsxs(t.Fragment,{children:[t.jsx(Re,{title:`${x(s||"News")} - Blog`,description:`Read the latest ${s||"news"} articles and updates from Playlist Partner.`}),t.jsx("div",{className:"bg-gradient-to-b from-green-50 to-white",children:t.jsxs("section",{className:"max-w-7xl mx-auto px-4 sm:px-6 lg:px-8 py-12 md:py-20",children:[t.jsxs("div",{className:"text-center mb-12",children:[t.jsx(J,{to:"/blog",className:"text-green-600 hover:text-green-700 text-sm mb-4 inline-block",children:"↠All Blog Posts"}),t.jsx("h1",{className:"text-4xl md:text-5xl font-bold text-gray-900 mb-4",children:x(s||"News")}),t.jsxs("p",{className:"text-xl text-gray-600 max-w-2xl mx-auto",children:["Browse all ",s||"news"," articles and stay updated with the latest insights."]})]}),n&&t.jsx("div",{className:"flex justify-center items-center min-h-[400px]",children:t.jsx("div",{className:"animate-spin rounded-full h-12 w-12 border-b-2 border-green-600"})}),i&&t.jsx("div",{className:"text-center py-12",children:t.jsx("p",{className:"text-red-600",children:i})}),!n&&!i&&e.length===0&&t.jsxs("div",{className:"text-center py-12",children:[t.jsx("p",{className:"text-gray-600",children:"No posts found in this category."}),t.jsx(J,{to:"/blog",className:"text-green-600 hover:text-green-700 mt-4 inline-block",children:"View all posts"})]}),!n&&!i&&e.length>0&&t.jsxs(t.Fragment,{children:[t.jsx("div",{className:"grid grid-cols-1 md:grid-cols-2 lg:grid-cols-3 gap-8 mb-12",children:e.map(y=>{var P,_,A,S,N;return t.jsxs("article",{className:"bg-white rounded-lg shadow-md overflow-hidden hover:shadow-lg transition-shadow",children:[((A=(_=(P=y.fields.featuredImage)==null?void 0:P.fields)==null?void 0:_.file)==null?void 0:A.url)&&t.jsx(J,{to:`/blog/${((S=y.fields.category)==null?void 0:S.toLowerCase())||"news"}/${y.fields.slug}`,children:t.jsx("img",{src:w(y.fields.featuredImage.fields.file.url),alt:y.fields.featuredImage.fields.title||y.fields.title,className:"w-full aspect-[3/2] object-cover"})}),t.jsxs("div",{className:"p-6",children:[t.jsx(J,{to:`/blog/${((N=y.fields.category)==null?void 0:N.toLowerCase())||"news"}/${y.fields.slug}`,children:t.jsx("h2",{className:"text-xl font-semibold text-gray-900 mb-2 hover:text-green-600 transition-colors",children:y.fields.title})}),y.fields.excerpt&&t.jsx("p",{className:"text-gray-600 mb-4 line-clamp-3",children:y.fields.excerpt}),t.jsx("div",{className:"flex flex-wrap items-center gap-4 text-sm text-gray-500",children:t.jsxs("div",{className:"flex items-center gap-1",children:[t.jsx(ms,{className:"w-4 h-4"}),t.jsx("span",{children:v(y.fields.publishDate||y.sys.createdAt)})]})})]})]},y.sys.id)})}),p>1&&t.jsxs("div",{className:"flex justify-center gap-2",children:[t.jsx("button",{onClick:()=>d(l-1),disabled:l===1,className:"px-4 py-2 border border-gray-300 rounded-md text-gray-700 hover:bg-gray-50 disabled:opacity-50 disabled:cursor-not-allowed",children:"Previous"}),t.jsx("div",{className:"flex items-center gap-2",children:Array.from({length:p},(y,P)=>P+1).map(y=>t.jsx("button",{onClick:()=>d(y),className:`px-3 py-1 rounded-md ${y===l?"bg-green-600 text-white":"text-gray-700 hover:bg-gray-50"}`,children:y},y))}),t.jsx("button",{onClick:()=>d(l+1),disabled:l===p,className:"px-4 py-2 border border-gray-300 rounded-md text-gray-700 hover:bg-gray-50 disabled:opacity-50 disabled:cursor-not-allowed",children:"Next"})]})]})]})})]})}function Bc({children:s}){const{user:e,isAdmin:r,loading:n}=nr(),a=it();return n?t.jsx("div",{className:"min-h-screen flex items-center justify-center",children:t.jsx(me,{className:"w-8 h-8 text-green-500 animate-spin"})}):!e||!r?t.jsx(Xr,{to:"/admin/login",state:{from:a},replace:!0}):t.jsx(t.Fragment,{children:s})}function Mc(){const s=it(),e=Xe(),{signOut:r}=nr(),n=[{path:"/admin",icon:wl,label:"Dashboard"},{path:"/admin/playlists",icon:ve,label:"Playlists"},{path:"/admin/submissions",icon:bl,label:"Submissions"},{path:"/admin/genres",icon:vl,label:"Genres"},{path:"/admin/import",icon:rs,label:"Import"},{path:"/admin/settings",icon:Cl,label:"Settings"}],a=async()=>{try{await r(),e("/admin/login")}catch(i){console.error("Failed to log out:",i)}};return t.jsx(Bc,{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(J,{to:i,className:`flex items-center px-4 py-2 text-sm rounded-lg ${s.pathname===i?"bg-green-50 text-green-700":"text-gray-600 hover:bg-gray-50"}`,children:[t.jsx(o,{className:"w-5 h-5 mr-3"}),l]},i))}),t.jsx("div",{className:"p-4 border-t",children:t.jsxs("button",{onClick:a,className:"flex items-center w-full px-4 py-2 text-sm text-red-600 hover:bg-red-50 rounded-lg transition-colors",children:[t.jsx(_l,{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(fa,{})})})]})})})}function Fc({stats:s}){const e=[{label:"Total Playlists",value:(s==null?void 0:s.totalPlaylists.toLocaleString())||"0",icon:ve}];return t.jsx("div",{className:"grid grid-cols-1 gap-6",children:e.map(r=>{const n=r.icon;return t.jsx("div",{className:"bg-white p-6 rounded-lg shadow-sm",children:t.jsxs("div",{className:"flex items-center",children:[t.jsx("div",{className:"p-2 bg-green-50 rounded-lg",children:t.jsx(n,{className:"h-6 w-6 text-green-600"})}),t.jsxs("div",{className:"ml-4",children:[t.jsx("p",{className:"text-sm font-medium text-gray-600",children:r.label}),t.jsx("p",{className:"text-2xl font-semibold text-gray-900",children:r.value})]})]})},r.label)})})}function qc(){const{totalCount:s}=Kt({}),e={totalPlaylists:s};return t.jsxs("div",{children:[t.jsx("h1",{className:"text-2xl font-bold text-gray-900 mb-8",children:"Dashboard"}),t.jsx(Fc,{stats:e})]})}function Gc({playlist:s,onClose:e,onSuccess:r}){const{genres:n,loading:a}=Fe(),[i,o]=b.useState({spotifyUrl:s?`https://open.spotify.com/playlist/${s.spotify_id}`:"",name:(s==null?void 0:s.name)||"",description:(s==null?void 0:s.description)||"",imageUrl:(s==null?void 0:s.image_url)||"",genre:(s==null?void 0:s.genre_id)||"",subGenres:(s==null?void 0:s.sub_genre_ids)||[],followers:(s==null?void 0:s.followers)||0,curatorName:(s==null?void 0:s.curator_name)||"",curatorProfileUrl:(s==null?void 0:s.curator_profile_url)||"",featured:(s==null?void 0:s.featured)||!1}),[l,d]=b.useState(!1),[c,u]=b.useState(null),[h,f]=b.useState(!1),p=n.find(x=>x.id===i.genre),v=async x=>{if(o(y=>({...y,spotifyUrl:x})),!(!x||s)){d(!0),u(null);try{const y=_t(x,"playlist");if(!y)throw new Error("Invalid Spotify playlist URL");const P=await fr(y);if(!P)throw new Error("Playlist not found on Spotify");o(_=>{var A,S,N,j,m;return{..._,name:P.name,description:P.description||_.description,imageUrl:((A=P.images[0])==null?void 0:A.url)||_.imageUrl,followers:((S=P.followers)==null?void 0:S.total)||0,curatorName:((N=P.owner)==null?void 0:N.display_name)||_.curatorName,curatorProfileUrl:((m=(j=P.owner)==null?void 0:j.external_urls)==null?void 0:m.spotify)||_.curatorProfileUrl}})}catch(y){console.error("Failed to fetch Spotify data:",y),u(y instanceof Error?y.message:"Failed to fetch playlist data from Spotify")}finally{d(!1)}}},w=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 y=_t(i.spotifyUrl,"playlist");if(!y)throw new Error("Invalid Spotify playlist URL");const P={spotify_id:y,name:i.name,description:i.description,image_url:i.imageUrl,genre_id:i.genre,sub_genre_ids:i.subGenres,followers:i.followers,curator_name:i.curatorName||null,curator_profile_url:i.curatorProfileUrl||null,featured:i.featured};r(P)}catch(y){console.error("Failed to save playlist:",y),u(y instanceof Error?y.message:"Failed to save playlist"),f(!1)}};return t.jsx("div",{className:"fixed inset-0 bg-black bg-opacity-50 flex items-center justify-center p-4 z-50",children:t.jsxs("div",{className:"bg-white rounded-xl max-w-2xl w-full max-h-[90vh] overflow-y-auto",children:[t.jsx("div",{className:"p-6 border-b border-gray-200",children:t.jsxs("div",{className:"flex justify-between items-center",children:[t.jsx("h2",{className:"text-xl font-bold text-gray-900",children:s?"Edit Playlist":"Add New Playlist"}),t.jsx("button",{onClick:e,className:"text-gray-400 hover:text-gray-500 transition-colors",children:t.jsx(be,{className:"w-6 h-6"})})]})}),t.jsxs("form",{onSubmit:w,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(zs,{className:"w-4 h-4"}),"Spotify Playlist URL"]}),s?t.jsx("input",{type:"text",value:i.spotifyUrl,readOnly:!0,className:"w-full p-2 border border-gray-300 rounded-lg bg-gray-50 text-gray-500"}):t.jsx("input",{type:"text",value:i.spotifyUrl,onChange:x=>v(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(ve,{className:"w-4 h-4"}),"Name"]}),t.jsx("input",{type:"text",value:i.name,onChange:x=>o(y=>({...y,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(Gt,{className:"w-4 h-4"}),"Followers"]}),t.jsx("input",{type:"number",value:i.followers,onChange:x=>o(y=>({...y,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(y=>({...y,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(y=>({...y,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:y=>{y.target.checked?o(P=>({...P,subGenres:[...P.subGenres,x.id]})):o(P=>({...P,subGenres:P.subGenres.filter(_=>_!==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(qt,{className:"w-4 h-4"}),"Curator Name"]}),t.jsx("input",{type:"text",value:i.curatorName,onChange:x=>o(y=>({...y,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(zs,{className:"w-4 h-4"}),"Curator Profile URL"]}),t.jsx("input",{type:"text",value:i.curatorProfileUrl,onChange:x=>o(y=>({...y,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(y=>({...y,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(fe,{className:"w-4 h-4 flex-shrink-0"}),t.jsx("p",{children:c})]}),t.jsxs("div",{className:"flex justify-end gap-3 pt-4",children:[t.jsx("button",{type:"button",onClick:e,className:"px-4 py-2 text-gray-700 hover:bg-gray-100 rounded-lg transition-colors",children:"Cancel"}),t.jsxs("button",{type:"submit",disabled:h||l,className:"px-4 py-2 bg-green-500 text-white rounded-lg hover:bg-green-600 disabled:bg-gray-400 disabled:cursor-not-allowed flex items-center gap-2",children:[(h||l)&&t.jsx(me,{className:"w-5 h-5 animate-spin"}),h?"Saving...":"Save Playlist"]})]})]})]})})}function Kc({isOpen:s,onClose:e,onComplete:r}){const[n,a]=b.useState(!1),[i,o]=b.useState(null),[l,d]=b.useState(null),c=b.useRef(null),u=async()=>{var f;a(!0),o(null),c.current=new AbortController;try{const{data:p,error:v}=await W.from("playlists").select("id, spotify_id").order("created_at",{ascending:!1});if(v)throw v;if(!p||p.length===0)throw new Error("No playlists found to sync");d({current:0,total:p.length,updated:0,failed:0});const w=10;for(let x=0;x<p.length;x+=w){if((f=c.current)!=null&&f.signal.aborted)throw new Error("Sync cancelled");const y=p.slice(x,Math.min(x+w,p.length)),P=await Promise.allSettled(y.map(async S=>{var N,j,m,g,k,T;try{const I=await fr(S.spotify_id);if(!I)throw new Error("Playlist not found on Spotify");return{id:S.id,name:I.name,description:I.description||"",image_url:((N=I.images[0])==null?void 0:N.url)||"",followers:((j=I.followers)==null?void 0:j.total)||0,track_count:((m=I.tracks)==null?void 0:m.total)||0,curator_name:((g=I.owner)==null?void 0:g.display_name)||null,curator_profile_url:((T=(k=I.owner)==null?void 0:k.external_urls)==null?void 0:T.spotify)||null,updated_at:new Date().toISOString()}}catch(I){throw console.error(`Failed to fetch playlist ${S.spotify_id}:`,I),I}}));let _=0,A=0;for(const S of P)if(S.status==="fulfilled"){const{error:N}=await W.from("playlists").update(S.value).eq("id",S.value.id);N?(console.error("Failed to update playlist:",N),A++):_++}else A++;d(S=>S?{...S,current:Math.min(x+w,p.length),updated:S.updated+_,failed:S.failed+A}:null),x+w<p.length&&await new Promise(S=>setTimeout(S,1e3))}r()}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 s?t.jsx("div",{className:"fixed inset-0 bg-black bg-opacity-50 flex items-center justify-center p-4 z-50",children:t.jsxs("div",{className:"bg-white rounded-xl max-w-lg w-full",children:[t.jsx("div",{className:"p-6 border-b border-gray-200",children:t.jsxs("div",{className:"flex justify-between items-center",children:[t.jsx("h2",{className:"text-xl font-bold text-gray-900",children:"Sync Playlists"}),t.jsx("button",{onClick:h,className:"text-gray-400 hover:text-gray-500 transition-colors",children:t.jsx(be,{className:"w-6 h-6"})})]})}),t.jsxs("div",{className:"p-6 space-y-4",children:[!n&&!i&&t.jsx("p",{className:"text-gray-600",children:"This will update playlist metadata including artwork, description, curator details, follower count, and track count from Spotify."}),l&&t.jsxs("div",{className:"space-y-3",children:[t.jsxs("div",{className:"flex items-center justify-between text-sm text-gray-600",children:[t.jsx("span",{children:"Processing playlists..."}),t.jsxs("span",{children:[l.current," of ",l.total]})]}),t.jsx("div",{className:"w-full h-2 bg-gray-100 rounded-full overflow-hidden",children:t.jsx("div",{className:"h-full bg-green-500 transition-all duration-300",style:{width:`${l.current/l.total*100}%`}})}),t.jsxs("div",{className:"flex gap-4 text-sm",children:[t.jsxs("span",{className:"flex items-center gap-1 text-green-600",children:[t.jsx(nt,{className:"w-4 h-4"}),l.updated," updated"]}),l.failed>0&&t.jsxs("span",{className:"flex items-center gap-1 text-red-600",children:[t.jsx(fe,{className:"w-4 h-4"}),l.failed," failed"]})]})]}),i&&t.jsxs("div",{className:"flex items-center gap-2 text-red-600 bg-red-50 p-3 rounded-lg",children:[t.jsx(fe,{className:"w-5 h-5 flex-shrink-0"}),t.jsx("p",{children:i})]}),t.jsxs("div",{className:"flex justify-end gap-3 pt-4",children:[t.jsx("button",{onClick:h,className:"px-4 py-2 text-gray-700 hover:bg-gray-100 rounded-lg transition-colors",children:n?"Cancel":"Close"}),!n&&t.jsxs("button",{onClick:u,className:"flex items-center gap-2 px-4 py-2 bg-green-500 text-white rounded-lg hover:bg-green-600 transition-colors",children:[t.jsx(vt,{className:"w-5 h-5"}),"Start Sync"]})]})]})]})}):null}function Hc(){const[s,e]=b.useState([]),[r,n]=b.useState(!0),[a,i]=b.useState(null),o=async h=>{try{n(!0),i(null);let f=W.from("playlists").select(` *, genres ( id, name, slug ) `);switch(h==null?void 0:h.sortBy){case"followers_asc":f=f.order("followers",{ascending:!0});break;case"followers_desc":f=f.order("followers",{ascending:!1});break;case"featured_desc":f=f.order("featured",{ascending:!1}).order("followers",{ascending:!1});break;default:f=f.order("created_at",{ascending:!1})}const{data:p,error:v}=await f;if(v)throw v;const{data:w,error:x}=await W.from("sub_genres").select("*");if(x)throw x;const y=p.map(P=>({...P,sub_genres:P.sub_genre_ids?P.sub_genre_ids.map(_=>{var A;return(A=w.find(S=>S.id===_))==null?void 0:A.name}).filter(Boolean):[]}));e(y)}catch(f){console.error("Failed to fetch playlists:",f),i(f instanceof Error?f:new Error("Failed to fetch playlists"))}finally{n(!1)}};return b.useEffect(()=>{o()},[]),{playlists:s,loading:r,error:a,refresh:o,createPlaylist:async h=>{try{const{data:f,error:p}=await W.from("playlists").insert([{spotify_id:h.spotify_id,name:h.name,description:h.description,image_url:h.image_url,genre_id:h.genre_id,sub_genre_ids:h.sub_genre_ids||[],followers:h.followers,curator_name:h.curator_name||null,curator_profile_url:h.curator_profile_url||null,created_at:new Date().toISOString(),updated_at:new Date().toISOString()}]).select(` *, genres ( id, name, slug ) `).single();if(p)throw p;const{data:v}=await W.from("sub_genres").select("*").in("id",h.sub_genre_ids||[]),w={...f,sub_genres:(v==null?void 0:v.map(x=>x.name))||[]};return e(x=>[w,...x]),w}catch(f){throw console.error("Failed to create playlist:",f),f}},updatePlaylist:async(h,f)=>{try{const{data:p,error:v}=await W.from("playlists").update({...f,updated_at:new Date().toISOString()}).eq("id",h).select(` *, genres ( id, name, slug ) `).single();if(v)throw v;let w=[];if(f.sub_genre_ids){const{data:y}=await W.from("sub_genres").select("*").in("id",f.sub_genre_ids);w=(y==null?void 0:y.map(P=>P.name))||[]}const x={...p,sub_genres:w};return e(y=>y.map(P=>P.id===h?x:P)),x}catch(p){throw console.error("Failed to update playlist:",p),p}},deletePlaylist:async h=>{try{const{error:f}=await W.from("playlists").delete().eq("id",h);if(f)throw f;e(p=>p.filter(v=>v.id!==h))}catch(f){throw console.error("Failed to delete playlist:",f),f}},toggleFeatured:async(h,f)=>{try{const{error:p}=await W.from("playlists").update({featured:f}).eq("id",h);if(p)throw p;e(v=>v.map(w=>w.id===h?{...w,featured:f}:w))}catch(p){throw console.error("Failed to update featured status:",p),p}}}}function zc(){const[s,e]=b.useState(!1),[r,n]=b.useState(!1),[a,i]=b.useState(null),[o,l]=b.useState(null),[d,c]=b.useState({search:"",genre:"",status:"",sortBy:"created_at_desc"}),{playlists:u,loading:h,error:f,refresh:p,createPlaylist:v,updatePlaylist:w,deletePlaylist:x,toggleFeatured:y}=Hc(),P=()=>{n(!1),l({type:"success",message:"Playlists synced successfully"}),p()},_=async j=>{try{a?(await w(a.id,j),l({type:"success",message:"Playlist updated successfully"})):(await v(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"})}},S=async(j,m)=>{try{await y(j,!m),l({type:"success",message:`Playlist ${m?"removed from":"added to"} featured list`})}catch{l({type:"error",message:"Failed to update featured status"})}},N=u.filter(j=>!(d.search&&!j.name.toLowerCase().includes(d.search.toLowerCase())||d.genre&&j.genre_id!==d.genre||d.status==="claimed"&&!j.claimed||d.status==="unclaimed"&&j.claimed));return f?t.jsx("div",{className:"p-8 text-center",children:t.jsxs("div",{className:"flex items-center justify-center gap-2 text-red-600",children:[t.jsx(fe,{className:"w-5 h-5"}),t.jsx("p",{children:"Failed to load playlists"})]})}):t.jsxs("div",{className:"container mx-auto px-4 py-8",children:[t.jsxs("div",{className:"flex justify-between items-center mb-6",children:[t.jsx("h1",{className:"text-2xl font-bold",children:"Playlists"}),t.jsxs("div",{className:"flex gap-3",children:[t.jsxs("button",{onClick:()=>n(!0),className:"flex items-center gap-2 bg-blue-500 text-white px-4 py-2 rounded-lg hover:bg-blue-600",children:[t.jsx(vt,{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(ar,{className:"w-5 h-5"}),"Add Playlist"]})]})]}),t.jsx("div",{className:"bg-white p-4 rounded-lg shadow-sm mb-6",children:t.jsxs("div",{className:"grid grid-cols-1 md:grid-cols-4 gap-4",children:[t.jsxs("div",{className:"relative",children:[t.jsx(ps,{className:"absolute left-3 top-1/2 transform -translate-y-1/2 text-gray-400 w-5 h-5"}),t.jsx("input",{type:"text",placeholder:"Search playlists...",value:d.search,onChange:j=>c({...d,search:j.target.value}),className:"w-full pl-10 pr-4 py-2 border border-gray-300 rounded-lg"})]}),t.jsxs("select",{value:d.genre,onChange:j=>c({...d,genre:j.target.value}),className:"border border-gray-300 rounded-lg px-4 py-2",children:[t.jsx("option",{value:"",children:"All Genres"}),Array.from(new Set(u.map(j=>j.genre_id))).map(j=>{var g;const m=(g=u.find(k=>k.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(me,{className:"w-6 h-6 text-green-500 animate-spin mx-auto"})})}):N.length===0?t.jsx("tr",{children:t.jsx("td",{colSpan:7,className:"px-6 py-8 text-center text-gray-500",children:"No playlists found"})}):N.map(j=>{var m,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(k=>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:k},k))}),t.jsx("td",{className:"px-6 py-4",children:j.curator_name||"Unclaimed"}),t.jsx("td",{className:"px-6 py-4",children:Al(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:()=>S(j.id,j.featured),className:"p-1 hover:bg-gray-100 rounded",title:j.featured?"Remove from featured":"Add to featured",children:t.jsx(Fn,{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(Mn,{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(ir,{className:"w-4 h-4 text-red-500"})})]})})]},j.id)})})]})}),(s||a)&&t.jsx(Gc,{playlist:a,onClose:()=>{e(!1),i(null)},onSuccess:_}),r&&t.jsx(Kc,{isOpen:r,onClose:()=>n(!1),onComplete:P}),o&&t.jsx(qe,{message:o.message,type:o.type,onClose:()=>l(null)})]})}function Wc(s){const[e,r]=b.useState([]),[n,a]=b.useState(0),[i,o]=b.useState(!0),[l,d]=b.useState(null);return b.useEffect(()=>{async function u(){try{o(!0),d(null);const h=s?await es.getForPlaylist(s):await es.getAll();r(h),a(h.length)}catch(h){console.error("Failed to fetch submissions:",h),d(h instanceof Error?h:new Error("Failed to fetch submissions"))}finally{o(!1)}}u()},[s]),{submissions:e,totalCount:n,loading:i,error:l,updateStatus:async(u,h)=>{try{const f=await es.updateStatus(u,h);return r(p=>p.map(v=>v.id===u?{...v,...f}:v)),f}catch(f){throw console.error("Failed to update submission status:",f),f}}}}function Vc({submission:s,onClose:e}){var r;return t.jsx("div",{className:"fixed inset-0 bg-black bg-opacity-50 flex items-center justify-center p-4 z-50",children:t.jsxs("div",{className:"bg-white rounded-lg max-w-2xl w-full p-6",children:[t.jsxs("div",{className:"flex justify-between items-center mb-6",children:[t.jsx("h3",{className:"text-xl font-semibold",children:"Submission Details"}),t.jsx("button",{onClick:e,className:"text-gray-500 hover:text-gray-700",children:t.jsx(be,{className:"w-5 h-5"})})]}),t.jsxs("div",{className:"space-y-6",children:[t.jsxs("div",{children:[t.jsx("h4",{className:"text-sm font-medium text-gray-500 mb-2",children:"Track Information"}),t.jsxs("div",{className:"bg-gray-50 p-4 rounded-lg space-y-3",children:[t.jsxs("div",{className:"flex items-center gap-2",children:[t.jsx(ve,{className:"w-4 h-4 text-gray-400"}),t.jsx("span",{className:"font-medium",children:s.track_name})]}),t.jsx("div",{className:"flex items-center gap-2",children:t.jsxs("a",{href:s.track_url,target:"_blank",rel:"noopener noreferrer",className:"text-green-600 hover:text-green-700 flex items-center gap-1",children:[t.jsx(gl,{className:"w-4 h-4"}),"Open in Spotify"]})})]})]}),t.jsxs("div",{children:[t.jsx("h4",{className:"text-sm font-medium text-gray-500 mb-2",children:"Artist & Contact"}),t.jsxs("div",{className:"bg-gray-50 p-4 rounded-lg space-y-3",children:[t.jsxs("p",{children:[t.jsx("span",{className:"font-medium",children:"Artist Name:"})," ",s.artist_name]}),t.jsxs("div",{className:"flex items-center gap-2",children:[t.jsx($n,{className:"w-4 h-4 text-gray-400"}),t.jsx("a",{href:`mailto:${s.email}`,className:"text-green-600 hover:text-green-700",children:s.email})]})]})]}),t.jsxs("div",{children:[t.jsx("h4",{className:"text-sm font-medium text-gray-500 mb-2",children:"Playlist"}),t.jsx("div",{className:"bg-gray-50 p-4 rounded-lg",children:t.jsxs("div",{className:"flex items-center gap-2",children:[t.jsx(Dn,{className:"w-4 h-4 text-gray-400"}),t.jsx("span",{className:"font-medium",children:(r=s.playlist)==null?void 0:r.name})]})})]}),s.message&&t.jsxs("div",{children:[t.jsx("h4",{className:"text-sm font-medium text-gray-500 mb-2",children:"Message"}),t.jsx("div",{className:"bg-gray-50 p-4 rounded-lg",children:t.jsx("p",{className:"text-gray-700 whitespace-pre-wrap",children:s.message})})]}),t.jsxs("div",{children:[t.jsx("h4",{className:"text-sm font-medium text-gray-500 mb-2",children:"Timestamps"}),t.jsxs("div",{className:"bg-gray-50 p-4 rounded-lg space-y-2",children:[t.jsxs("div",{className:"flex items-center gap-2",children:[t.jsx(Br,{className:"w-4 h-4 text-gray-400"}),t.jsxs("span",{children:["Submitted: ",new Date(s.created_at).toLocaleString()]})]}),s.reviewed_at&&t.jsxs("div",{className:"flex items-center gap-2",children:[t.jsx(Br,{className:"w-4 h-4 text-gray-400"}),t.jsxs("span",{children:["Reviewed: ",new Date(s.reviewed_at).toLocaleString()]})]})]})]})]})]})})}function Jc(){const[s,e]=b.useState(null),[r,n]=b.useState(null),[a,i]=b.useState({search:"",status:"",startDate:"",endDate:""}),{submissions:o,loading:l,error:d,updateStatus:c}=Wc(),u=async(f,p)=>{try{await c(f,p),e({type:"success",message:`Submission marked as ${p}`})}catch(v){console.error("Failed to update status:",v),e({type:"error",message:"Failed to update submission status"})}},h=o.filter(f=>!(a.search&&!f.track_name.toLowerCase().includes(a.search.toLowerCase())&&!f.artist_name.toLowerCase().includes(a.search.toLowerCase())&&!f.email.toLowerCase().includes(a.search.toLowerCase())||a.status&&f.status!==a.status||a.startDate&&new Date(f.created_at)<new Date(a.startDate)||a.endDate&&new Date(f.created_at)>new Date(a.endDate)));return t.jsxs("div",{className:"container mx-auto px-4 py-8",children:[t.jsx("h1",{className:"text-2xl font-bold mb-6",children:"Submissions"}),t.jsx("div",{className:"bg-white p-4 rounded-lg shadow-sm mb-6",children:t.jsxs("div",{className:"grid grid-cols-1 md:grid-cols-2 lg:grid-cols-4 gap-4",children:[t.jsxs("div",{className:"relative",children:[t.jsx(ps,{className:"absolute left-3 top-1/2 transform -translate-y-1/2 text-gray-400 w-5 h-5"}),t.jsx("input",{type:"text",placeholder:"Search submissions...",value:a.search,onChange:f=>i({...a,search:f.target.value}),className:"w-full pl-10 pr-4 py-2 border border-gray-300 rounded-lg"})]}),t.jsxs("select",{value:a.status,onChange:f=>i({...a,status:f.target.value}),className:"border border-gray-300 rounded-lg px-4 py-2",children:[t.jsx("option",{value:"",children:"All Status"}),t.jsx("option",{value:"pending",children:"Pending"}),t.jsx("option",{value:"approved",children:"Approved"}),t.jsx("option",{value:"rejected",children:"Rejected"})]}),t.jsx("input",{type:"date",value:a.startDate,onChange:f=>i({...a,startDate:f.target.value}),className:"border border-gray-300 rounded-lg px-4 py-2",placeholder:"Start Date"}),t.jsx("input",{type:"date",value:a.endDate,onChange:f=>i({...a,endDate:f.target.value}),className:"border border-gray-300 rounded-lg px-4 py-2",placeholder:"End Date"})]})}),t.jsx("div",{className:"bg-white rounded-lg shadow-sm overflow-hidden",children:t.jsxs("table",{className:"w-full",children:[t.jsx("thead",{children:t.jsxs("tr",{className:"bg-gray-50",children:[t.jsx("th",{className:"px-6 py-3 text-left text-sm font-medium text-gray-500",children:"Track"}),t.jsx("th",{className:"px-6 py-3 text-left text-sm font-medium text-gray-500",children:"Artist"}),t.jsx("th",{className:"px-6 py-3 text-left text-sm font-medium text-gray-500",children:"Email"}),t.jsx("th",{className:"px-6 py-3 text-left text-sm font-medium text-gray-500",children:"Playlist"}),t.jsx("th",{className:"px-6 py-3 text-left text-sm font-medium text-gray-500",children:"Status"}),t.jsx("th",{className:"px-6 py-3 text-left text-sm font-medium text-gray-500",children:"Date"}),t.jsx("th",{className:"px-6 py-3 text-left text-sm font-medium text-gray-500",children:"Actions"})]})}),t.jsx("tbody",{className:"divide-y divide-gray-200",children:l?t.jsx("tr",{children:t.jsx("td",{colSpan:7,className:"px-6 py-8 text-center",children:t.jsx(me,{className:"w-6 h-6 text-green-500 animate-spin mx-auto"})})}):d?t.jsx("tr",{children:t.jsx("td",{colSpan:7,className:"px-6 py-8 text-center",children:t.jsxs("div",{className:"flex items-center justify-center gap-2 text-red-600",children:[t.jsx(fe,{className:"w-5 h-5"}),t.jsx("span",{children:"Failed to load submissions"})]})})}):h.length===0?t.jsx("tr",{children:t.jsx("td",{colSpan:7,className:"px-6 py-8 text-center text-gray-500",children:"No submissions found"})}):h.map(f=>{var 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:v=>v.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:v=>v.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(Hs,{className:"w-3 h-3"}),f.status==="rejected"&&t.jsx(Mr,{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:v=>v.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(Hs,{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(yl,{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(Mr,{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(Un,{className:"w-5 h-5"})})]})})]},f.id)})})]})}),r&&t.jsx(Vc,{submission:r,onClose:()=>n(null)}),s&&t.jsx(qe,{message:s.message,type:s.type,onClose:()=>e(null)})]})}function Yc({genre:s,onClose:e,onSuccess:r}){const[n,a]=b.useState((s==null?void 0:s.name)||""),[i,o]=b.useState((s==null?void 0:s.description)||""),[l,d]=b.useState((s==null?void 0:s.subGenres.map(m=>({name:m.name,description:m.description})))||[]),[c,u]=b.useState({name:"",description:""}),[h,f]=b.useState(null),[p,v]=b.useState(!1),[w,x]=b.useState(null),{createGenre:y,updateGenre:P}=Fe(),_=(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 k=Me(m.name);if(l.filter((I,R)=>R!==g).map(I=>Me(I.name)).includes(k))throw new Error("This sub-genre already exists")},A=async m=>{m.preventDefault(),x(null),v(!0);try{if(!n.trim())throw new Error("Genre name is required");if(!i.trim())throw new Error("Genre description is required");if(new Set(l.map(I=>Me(I.name))).size!==l.length)throw new Error("Duplicate sub-genres are not allowed");const k={name:n.trim(),description:i.trim(),subGenres:l.map(I=>({name:I.name.trim(),description:I.description.trim()}))};let T;s?T=await P(s.id,k):T=await y(k),r(T)}catch(g){console.error("Failed to save genre:",g),x(g instanceof Error?g.message:"Failed to save genre")}finally{v(!1)}},S=()=>{try{_(c),d([...l,{...c}]),u({name:"",description:""}),x(null)}catch(m){x(m instanceof Error?m.message:"Invalid sub-genre")}},N=(m,g)=>{try{const k={...l[m],...g};_(k,m);const T=[...l];T[m]=k,d(T),f(null),x(null)}catch(k){x(k instanceof Error?k.message:"Invalid sub-genre")}},j=m=>{d(l.filter((g,k)=>k!==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:s?"Edit Genre":"Add New Genre"}),t.jsx("button",{onClick:e,className:"text-gray-400 hover:text-gray-500 transition-colors",children:t.jsx(be,{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:S,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(ar,{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:k=>N(g,{name:k.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:k=>N(g,{description:k.target.value}),className:"w-full p-2 border border-gray-300 rounded-lg focus:ring-2 focus:ring-green-500 focus:border-transparent",rows:2}),t.jsxs("div",{className:"flex justify-end gap-2",children:[t.jsx("button",{type:"button",onClick:()=>f(null),className:"px-3 py-1 text-sm text-gray-600 hover:bg-gray-200 rounded",children:"Cancel"}),t.jsx("button",{type:"button",onClick:()=>N(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(kl,{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(ir,{className:"w-4 h-4 text-red-500"})})]})]}),t.jsx("p",{className:"text-sm text-gray-600",children:m.description})]})},g))})]}),w&&t.jsxs("div",{className:"flex items-center gap-2 text-red-600 text-sm",children:[t.jsx(fe,{className:"w-4 h-4 flex-shrink-0"}),t.jsx("span",{children:w})]}),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(me,{className:"w-5 h-5 animate-spin"}),"Saving..."]}):t.jsx(t.Fragment,{children:"Save Genre"})})]})]})]})})}function Qc({id:s,name:e,description:r,subGenres:n,onEdit:a,onDelete:i}){const{attributes:o,listeners:l,setNodeRef:d,transform:c,transition:u,isDragging:h}=ta({id:s}),f={transform:sa.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(pl,{className:"w-5 h-5"})}),t.jsx("div",{className:"p-2 bg-green-50 rounded-lg",children:t.jsx(ve,{className:"w-5 h-5 text-green-600"})}),t.jsxs("div",{children:[t.jsx("h3",{className:"text-lg font-medium",children:e}),t.jsxs("p",{className:"text-sm text-gray-500",children:[n.length," sub-genres"]})]})]}),t.jsxs("div",{className:"flex items-center gap-2",children:[t.jsx("button",{onClick:a,className:"p-2 hover:bg-gray-100 rounded-lg transition-colors",title:"Edit genre",children:t.jsx(Mn,{className:"w-5 h-5 text-gray-600"})}),t.jsx("button",{onClick:i,className:"p-2 hover:bg-red-50 rounded-lg transition-colors",title:"Delete genre",children:t.jsx(ir,{className:"w-5 h-5 text-red-600"})})]})]}),t.jsx("p",{className:"text-gray-600 mb-4",children:r}),n.length>0&&t.jsx("div",{className:"ml-12 space-y-2",children:n.map(p=>t.jsxs("div",{className:"flex items-start gap-2 text-gray-600",children:[t.jsx(fl,{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 Zc(){const{genres:s,loading:e,error:r,deleteGenre:n,updateGenreOrder:a}=Fe(),[i,o]=b.useState(!1),[l,d]=b.useState(null),[c,u]=b.useState(null),h=ra(pr(da),pr(ca,{coordinateGetter:la})),f=async v=>{const{active:w,over:x}=v;if(x&&w.id!==x.id){const y=s.findIndex(_=>_.id===w.id),P=s.findIndex(_=>_.id===x.id);try{await a(y,P),u({type:"success",message:"Genre order updated successfully"})}catch{u({type:"error",message:"Failed to update genre order"})}}},p=async(v,w)=>{if(window.confirm(`Are you sure you want to delete "${w}" and all its sub-genres?`))try{await n(v),u({type:"success",message:`${w} 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(me,{className:"w-8 h-8 text-green-500 animate-spin"})}):r?t.jsxs("div",{className:"flex items-center justify-center min-h-[400px] text-red-600",children:[t.jsx(fe,{className:"w-6 h-6 mr-2"}),t.jsx("span",{children:"Failed to load genres"})]}):t.jsxs("div",{className:"container mx-auto px-4 py-8",children:[t.jsxs("div",{className:"flex justify-between items-center mb-6",children:[t.jsx("h1",{className:"text-2xl font-bold",children:"Genres & Sub-genres"}),t.jsxs("button",{onClick:()=>o(!0),className:"flex items-center gap-2 bg-green-500 text-white px-4 py-2 rounded-lg hover:bg-green-600",children:[t.jsx(ar,{className:"w-5 h-5"}),"Add Genre"]})]}),t.jsxs("div",{className:"space-y-4",children:[t.jsx(na,{sensors:h,collisionDetection:aa,onDragEnd:f,children:t.jsx(ia,{items:s.map(v=>v.id),strategy:oa,children:s.map(v=>t.jsx(Qc,{id:v.id,name:v.name,subGenres:v.subGenres,onEdit:()=>d({id:v.id,name:v.name,subGenres:v.subGenres}),onDelete:()=>p(v.id,v.name)},v.id))})}),s.length===0&&t.jsxs("div",{className:"text-center py-12 bg-white rounded-lg",children:[t.jsx(ve,{className:"w-12 h-12 text-gray-400 mx-auto mb-4"}),t.jsx("p",{className:"text-gray-500",children:"No genres added yet"})]})]}),(i||l)&&t.jsx(Yc,{genre:l,onClose:()=>{o(!1),d(null)},onSuccess:v=>{o(!1),d(null),u({type:"success",message:`Genre ${l?"updated":"created"} successfully`})}}),c&&t.jsx(qe,{message:c.message,type:c.type,onClose:()=>u(null)})]})}const Xc=ua,Qn=b.forwardRef(({className:s,...e},r)=>t.jsx(Vr,{ref:r,className:"inline-flex h-10 items-center justify-center rounded-lg bg-gray-100 p-1 text-gray-500 mb-4",...e}));Qn.displayName=Vr.displayName;const Ys=b.forwardRef(({className:s,...e},r)=>t.jsx(Jr,{ref:r,className:"inline-flex items-center justify-center whitespace-nowrap rounded-md px-3 py-1.5 text-sm font-medium ring-offset-white transition-all focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-gray-400 focus-visible:ring-offset-2 disabled:pointer-events-none disabled:opacity-50 data-[state=active]:bg-white data-[state=active]:text-gray-950 data-[state=active]:shadow-sm",...e}));Ys.displayName=Jr.displayName;const Qs=b.forwardRef(({className:s,...e},r)=>t.jsx(Yr,{ref:r,className:"mt-2 ring-offset-white focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-gray-400 focus-visible:ring-offset-2",...e}));Qs.displayName=Yr.displayName;function ed({onSuccess:s}){const[e,r]=b.useState(!1),[n,a]=b.useState(null),[i,o]=b.useState(null),[l,d]=b.useState(null),[c,u]=b.useState(null),h=async()=>{if(!i||!l){a("Please select both genre and sub-genre files");return}r(!0),a(null),u({stage:"Reading files",current:0,total:2});try{const w=(await i.text()).split(` `),x=w[0].split(",").map(R=>R.trim()),P=["Name","Slug","Description"].filter(R=>!x.includes(R));if(P.length>0)throw new Error(`Missing required columns in genres file: ${P.join(", ")}`);const _=[];for(let R=1;R<w.length;R++){if(!w[R].trim())continue;const K=w[R].split(",").map(X=>X.trim());_.push({Name:K[x.indexOf("Name")],Slug:K[x.indexOf("Slug")],Description:K[x.indexOf("Description")]})}u({stage:"Processing genres",current:1,total:2});const S=(await l.text()).split(` `),N=S[0].split(",").map(R=>R.trim()),m=["Name","Slug","Description"].filter(R=>!N.includes(R));if(m.length>0)throw new Error(`Missing required columns in sub-genres file: ${m.join(", ")}`);const g=[];for(let R=1;R<S.length;R++){if(!S[R].trim())continue;const K=S[R].split(",").map(X=>X.trim());g.push({Name:K[N.indexOf("Name")],Slug:K[N.indexOf("Slug")],Description:K[N.indexOf("Description")]})}u({stage:"Importing data",current:0,total:_.length+g.length});for(const R of _){const{error:K}=await W.from("genres").insert({name:R.Name,slug:R.Slug||Me(R.Name),description:R.Description});if(K&&K.code!=="23505")throw K;u(X=>X?{...X,current:X.current+1}:null)}const{data:k,error:T}=await W.from("genres").select("id, name, slug");if(T)throw T;const I=new Map(k.map(R=>[R.name.toLowerCase(),R.id]));for(const R of g){const K=k.find(X=>R.Slug.includes(X.slug)||R.Name.toLowerCase().includes(X.name.toLowerCase()));if(K){const{error:X}=await W.from("sub_genres").insert({name:R.Name,slug:R.Slug||Me(R.Name),description:R.Description,genre_id:K.id});if(X&&X.code!=="23505")throw X}u(X=>X?{...X,current:X.current+1}:null)}s()}catch(v){console.error("Import failed:",v),a(v instanceof Error?v.message:"Failed to import data")}finally{r(!1),u(null),o(null),d(null)}},f=v=>{if(!v.name.endsWith(".csv")){a("Please select a CSV file");return}o(v),a(null)},p=v=>{if(!v.name.endsWith(".csv")){a("Please select a CSV file");return}d(v),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:v=>v.preventDefault(),onDrop:v=>{v.preventDefault();const w=v.dataTransfer.files[0];w&&f(w)},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(be,{className:"w-4 h-4 text-gray-500"})})]}):t.jsxs(t.Fragment,{children:[t.jsx(rs,{className:"w-8 h-8 text-gray-400 mx-auto mb-2"}),t.jsx("p",{className:"text-sm text-gray-600 mb-2",children:"Drop genres CSV file here"}),t.jsx("input",{type:"file",accept:".csv",onChange:v=>{var x;const w=(x=v.target.files)==null?void 0:x[0];w&&f(w)},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:v=>v.preventDefault(),onDrop:v=>{v.preventDefault();const w=v.dataTransfer.files[0];w&&p(w)},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(be,{className:"w-4 h-4 text-gray-500"})})]}):t.jsxs(t.Fragment,{children:[t.jsx(rs,{className:"w-8 h-8 text-gray-400 mx-auto mb-2"}),t.jsx("p",{className:"text-sm text-gray-600 mb-2",children:"Drop sub-genres CSV file here"}),t.jsx("input",{type:"file",accept:".csv",onChange:v=>{var x;const w=(x=v.target.files)==null?void 0:x[0];w&&p(w)},className:"hidden",id:"sub-genres-file",disabled:e}),t.jsx("label",{htmlFor:"sub-genres-file",className:"inline-block px-3 py-1 text-sm bg-green-500 text-white rounded hover:bg-green-600 transition-colors cursor-pointer",children:"Select File"})]})})]})]}),n&&t.jsxs("div",{className:"p-3 bg-red-50 text-red-700 rounded-lg flex items-center gap-2",children:[t.jsx(fe,{className:"w-5 h-5 flex-shrink-0"}),t.jsx("p",{className:"flex-1",children:n}),t.jsx("button",{onClick:()=>a(null),children:t.jsx(be,{className:"w-5 h-5"})})]}),c&&t.jsxs("div",{className:"bg-white p-4 rounded-lg shadow-sm",children:[t.jsxs("div",{className:"flex items-center gap-3 mb-2",children:[t.jsx(me,{className:"w-5 h-5 text-green-500 animate-spin"}),t.jsxs("span",{className:"text-gray-600",children:[c.stage,"..."]})]}),t.jsx("div",{className:"w-full h-2 bg-gray-100 rounded-full",children:t.jsx("div",{className:"h-full bg-green-500 rounded-full transition-all",style:{width:`${c.current/c.total*100}%`}})})]}),t.jsx("button",{onClick:h,disabled:!i||!l||e,className:`w-full py-2 rounded-lg text-white transition-colors ${!i||!l||e?"bg-gray-300 cursor-not-allowed":"bg-green-500 hover:bg-green-600"}`,children:e?"Importing...":"Import Data"}),t.jsxs("div",{className:"text-sm text-gray-500",children:[t.jsx("p",{className:"font-medium mb-2",children:"CSV Format Requirements:"}),t.jsxs("ul",{className:"list-disc list-inside space-y-1",children:[t.jsx("li",{children:"Files must be in CSV format"}),t.jsx("li",{children:"First row must contain headers"}),t.jsx("li",{children:"Required columns: Name, Slug, Description"}),t.jsx("li",{children:"Values containing commas must be enclosed in quotes"})]})]})]})}const td={async importPlaylists(s,e){try{if(!Array.isArray(s)||s.length===0)throw new Error("No playlists provided");const r={current:0,total:s.length,processed:0,skipped:0,failed:0,unmatchedCategories:new Set,recentErrors:[],skippedDetails:{genreNotFound:0,duplicates:0,invalidData:0,details:[]}},{data:n,error:a}=await W.from("genres").select("*").order("name");if(a)throw a;if(!(n!=null&&n.length))throw new Error("No genres found. Please set up genres first.");const{data:i,error:o}=await W.from("sub_genres").select("*").order("name");if(o)throw o;const l=50;for(let d=0;d<s.length;d+=l){const c=s.slice(d,Math.min(d+l,s.length)),u=[];for(const h of c)try{const f=n.find(x=>x.name.toLowerCase()===h.Category.toLowerCase()||h.Category.toLowerCase().includes(x.name.toLowerCase()));if(!f){r.skippedDetails.genreNotFound++,r.skippedDetails.details.push({row:d+c.indexOf(h)+1,name:h.Name,reason:"No matching genre found",details:`Category: ${h.Category}`}),r.unmatchedCategories.add(h.Category),r.failed++;continue}const p=h["Sub Genres"].split(";").map(x=>x.trim()).filter(Boolean),v=(i==null?void 0:i.filter(x=>x.genre_id===f.id&&p.some(y=>y.toLowerCase().includes(x.name.toLowerCase())||x.name.toLowerCase().includes(y.toLowerCase()))).map(x=>x.id))||[],{data:w}=await W.from("playlists").select("id").eq("spotify_id",h.URL.split("/").pop()).single();if(w){r.skippedDetails.duplicates++,r.skippedDetails.details.push({row:d+c.indexOf(h)+1,name:h.Name,reason:"Duplicate playlist",details:`Spotify ID: ${h.URL.split("/").pop()}`}),r.skipped++;continue}u.push({spotify_id:h.URL.split("/").pop(),name:h.Name,description:h.Description,image_url:h["Cover URL"],followers:parseInt(h.Followers.replace(/,/g,""),10),track_count:parseInt(h.Tracks.replace(/,/g,""),10),genre_id:f.id,sub_genre_ids:v,curator_name:h.Curator,curator_profile_url:h["Curator URL"],created_at:new Date().toISOString(),updated_at:new Date().toISOString()}),r.processed++}catch(f){r.skippedDetails.invalidData++,r.skippedDetails.details.push({row:d+c.indexOf(h)+1,name:h.Name,reason:"Invalid data",details:f instanceof Error?f.message:"Unknown error"}),r.failed++,r.recentErrors.push({row:d+c.indexOf(h)+1,message:f instanceof Error?f.message:"Failed to process playlist"})}if(u.length>0){const{error:h}=await W.from("playlists").insert(u);h&&(console.error("Failed to insert batch:",h),r.failed+=u.length,r.processed-=u.length)}r.current=d+c.length,e&&e({...r}),d+l<s.length&&await new Promise(h=>setTimeout(h,1e3))}return{successCount:r.processed,skipCount:r.skipped,unmatchedCategories:Array.from(r.unmatchedCategories),errors:r.recentErrors,skippedDetails:r.skippedDetails}}catch(r){throw console.error("Import failed:",r),r instanceof Error?r:new Error("Failed to import playlists")}}};var Zn={exports:{}};/* @license Papa Parse v5.5.3 https://github.com/mholt/PapaParse License: MIT */(function(s,e){((r,n)=>{s.exports=n()})(Ee,function r(){var n=typeof self<"u"?self:typeof window<"u"?window:n!==void 0?n:{},a,i=!n.document&&!!n.postMessage,o=n.IS_PAPA_WORKER||!1,l={},d=0,c={};function u(m){this._handle=null,this._finished=!1,this._completed=!1,this._halted=!1,this._input=null,this._baseIndex=0,this._partialLine="",this._rowCount=0,this._start=0,this._nextChunk=null,this.isFirstChunk=!0,this._completeResults={data:[],errors:[],meta:{}},(function(g){var k=S(g);k.chunkSize=parseInt(k.chunkSize),g.step||g.chunk||(k.chunkSize=null),this._handle=new w(k),(this._handle.streamer=this)._config=k}).call(this,m),this.parseChunk=function(g,k){var T=parseInt(this._config.skipFirstNLines)||0;if(this.isFirstChunk&&0<T){let R=this._config.newline;R||(I=this._config.quoteChar||'"',R=this._handle.guessLineEndings(g,I)),g=[...g.split(R).slice(T)].join(R)}this.isFirstChunk&&j(this._config.beforeFirstChunk)&&(I=this._config.beforeFirstChunk(g))!==void 0&&(g=I),this.isFirstChunk=!1,this._halted=!1;var T=this._partialLine+g,I=(this._partialLine="",this._handle.parse(T,this._baseIndex,!this._finished));if(!this._handle.paused()&&!this._handle.aborted()){if(g=I.meta.cursor,T=(this._finished||(this._partialLine=T.substring(g-this._baseIndex),this._baseIndex=g),I&&I.data&&(this._rowCount+=I.data.length),this._finished||this._config.preview&&this._rowCount>=this._config.preview),o)n.postMessage({results:I,workerId:c.WORKER_ID,finished:T});else if(j(this._config.chunk)&&!k){if(this._config.chunk(I,this._handle),this._handle.paused()||this._handle.aborted())return void(this._halted=!0);this._completeResults=I=void 0}return this._config.step||this._config.chunk||(this._completeResults.data=this._completeResults.data.concat(I.data),this._completeResults.errors=this._completeResults.errors.concat(I.errors),this._completeResults.meta=I.meta),this._completed||!T||!j(this._config.complete)||I&&I.meta.aborted||(this._config.complete(this._completeResults,this._input),this._completed=!0),T||I&&I.meta.paused||this._nextChunk(),I}this._halted=!0},this._sendError=function(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(k){this._input=k,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=N(this._chunkLoaded,this),g.onerror=N(this._chunkError,this)),g.open(this._config.downloadRequestBody?"POST":"GET",this._input,!i),this._config.downloadRequestHeaders){var k,T=this._config.downloadRequestHeaders;for(k in T)g.setRequestHeader(k,T[k])}var I;this._config.chunkSize&&(I=this._start+this._config.chunkSize-1,g.setRequestHeader("Range","bytes="+this._start+"-"+I));try{g.send(this._config.downloadRequestBody)}catch(R){this._chunkError(R.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>=(k=>(k=k.getResponseHeader("Content-Range"))!==null?parseInt(k.substring(k.lastIndexOf("/")+1)):-1)(g),this.parseChunk(g.responseText)))},this._chunkError=function(k){k=g.statusText||k,this._sendError(new Error(k))}}function f(m){(m=m||{}).chunkSize||(m.chunkSize=c.LocalChunkSize),u.call(this,m);var g,k,T=typeof FileReader<"u";this.stream=function(I){this._input=I,k=I.slice||I.webkitSlice||I.mozSlice,T?((g=new FileReader).onload=N(this._chunkLoaded,this),g.onerror=N(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 I=this._input,R=(this._config.chunkSize&&(R=Math.min(this._start+this._config.chunkSize,this._input.size),I=k.call(I,this._start,R)),g.readAsText(I,this._config.encoding));T||this._chunkLoaded({target:{result:R}})},this._chunkLoaded=function(I){this._start+=this._config.chunkSize,this._finished=!this._config.chunkSize||this._start>=this._input.size,this.parseChunk(I.target.result)},this._chunkError=function(){this._sendError(g.error)}}function p(m){var g;u.call(this,m=m||{}),this.stream=function(k){return g=k,this._nextChunk()},this._nextChunk=function(){var k,T;if(!this._finished)return k=this._config.chunkSize,g=k?(T=g.substring(0,k),g.substring(k)):(T=g,""),this._finished=!g,this.parseChunk(T)}}function v(m){u.call(this,m=m||{});var g=[],k=!0,T=!1;this.pause=function(){u.prototype.pause.apply(this,arguments),this._input.pause()},this.resume=function(){u.prototype.resume.apply(this,arguments),this._input.resume()},this.stream=function(I){this._input=I,this._input.on("data",this._streamData),this._input.on("end",this._streamEnd),this._input.on("error",this._streamError)},this._checkIsFinished=function(){T&&g.length===1&&(this._finished=!0)},this._nextChunk=function(){this._checkIsFinished(),g.length?this.parseChunk(g.shift()):k=!0},this._streamData=N(function(I){try{g.push(typeof I=="string"?I:I.toString(this._config.encoding)),k&&(k=!1,this._checkIsFinished(),this.parseChunk(g.shift()))}catch(R){this._streamError(R)}},this),this._streamError=N(function(I){this._streamCleanUp(),this._sendError(I)},this),this._streamEnd=N(function(){this._streamCleanUp(),T=!0,this._streamData("")},this),this._streamCleanUp=N(function(){this._input.removeListener("data",this._streamData),this._input.removeListener("end",this._streamEnd),this._input.removeListener("error",this._streamError)},this)}function w(m){var g,k,T,I,R=Math.pow(2,53),K=-R,X=/^\s*-?(\d+\.?|\.\d+|\d+\.\d+)([eE][-+]?\d+)?\s*$/,re=/^((\d{4}-[01]\d-[0-3]\dT[0-2]\d:[0-5]\d:[0-5]\d\.\d+([+-][0-2]\d:[0-5]\d|Z))|(\d{4}-[01]\d-[0-3]\dT[0-2]\d:[0-5]\d:[0-5]\d([+-][0-2]\d:[0-5]\d|Z))|(\d{4}-[01]\d-[0-3]\dT[0-2]\d:[0-5]\d([+-][0-2]\d:[0-5]\d|Z)))$/,F=this,ne=0,H=0,U=!1,q=!1,Q=[],M={data:[],errors:[],meta:{}};function le(E){return m.skipEmptyLines==="greedy"?E.join("").trim()==="":E.length===1&&E[0].length===0}function ce(){if(M&&T&&(ae("Delimiter","UndetectableDelimiter","Unable to auto-detect delimiting character; defaulted to '"+c.DefaultDelimiter+"'"),T=!1),m.skipEmptyLines&&(M.data=M.data.filter(function(C){return!le(C)})),ue()){let C=function(O,$){j(m.transformHeader)&&(O=m.transformHeader(O,$)),Q.push(O)};if(M)if(Array.isArray(M.data[0])){for(var E=0;ue()&&E<M.data.length;E++)M.data[E].forEach(C);M.data.splice(0,1)}else M.data.forEach(C)}function L(C,O){for(var $=m.header?{}:[],B=0;B<C.length;B++){var Z=B,G=C[B],G=((xe,V)=>(de=>(m.dynamicTypingFunction&&m.dynamicTyping[de]===void 0&&(m.dynamicTyping[de]=m.dynamicTypingFunction(de)),(m.dynamicTyping[de]||m.dynamicTyping)===!0))(xe)?V==="true"||V==="TRUE"||V!=="false"&&V!=="FALSE"&&((de=>{if(X.test(de)&&(de=parseFloat(de),K<de&&de<R))return 1})(V)?parseFloat(V):re.test(V)?new Date(V):V===""?null:V):V)(Z=m.header?B>=Q.length?"__parsed_extra":Q[B]:Z,G=m.transform?m.transform(G,Z):G);Z==="__parsed_extra"?($[Z]=$[Z]||[],$[Z].push(G)):$[Z]=G}return m.header&&(B>Q.length?ae("FieldMismatch","TooManyFields","Too many fields: expected "+Q.length+" fields but parsed "+B,H+O):B<Q.length&&ae("FieldMismatch","TooFewFields","Too few fields: expected "+Q.length+" fields but parsed "+B,H+O)),$}var D;M&&(m.header||m.dynamicTyping||m.transform)&&(D=1,!M.data.length||Array.isArray(M.data[0])?(M.data=M.data.map(L),D=M.data.length):M.data=L(M.data,0),m.header&&M.meta&&(M.meta.fields=Q),H+=D)}function ue(){return m.header&&Q.length===0}function ae(E,L,D,C){E={type:E,code:L,message:D},C!==void 0&&(E.row=C),M.errors.push(E)}j(m.step)&&(I=m.step,m.step=function(E){M=E,ue()?ce():(ce(),M.data.length!==0&&(ne+=E.data.length,m.preview&&ne>m.preview?k.abort():(M.data=M.data[0],I(M,F))))}),this.parse=function(E,L,D){var C=m.quoteChar||'"',C=(m.newline||(m.newline=this.guessLineEndings(E,C)),T=!1,m.delimiter?j(m.delimiter)&&(m.delimiter=m.delimiter(E),M.meta.delimiter=m.delimiter):((C=((O,$,B,Z,G)=>{var xe,V,de,De;G=G||[","," ","|",";",c.RECORD_SEP,c.UNIT_SEP];for(var Pe=0;Pe<G.length;Pe++){for(var $e,Et=G[Pe],ye=0,Ue=0,ge=0,je=(de=void 0,new y({comments:Z,delimiter:Et,newline:$,preview:10}).parse(O)),Ge=0;Ge<je.data.length;Ge++)B&&le(je.data[Ge])?ge++:($e=je.data[Ge].length,Ue+=$e,de===void 0?de=$e:0<$e&&(ye+=Math.abs($e-de),de=$e));0<je.data.length&&(Ue/=je.data.length-ge),(V===void 0||ye<=V)&&(De===void 0||De<Ue)&&1.99<Ue&&(V=ye,xe=Et,De=Ue)}return{successful:!!(m.delimiter=xe),bestDelimiter:xe}})(E,m.newline,m.skipEmptyLines,m.comments,m.delimitersToGuess)).successful?m.delimiter=C.bestDelimiter:(T=!0,m.delimiter=c.DefaultDelimiter),M.meta.delimiter=m.delimiter),S(m));return m.preview&&m.header&&C.preview++,g=E,k=new y(C),M=k.parse(g,L,D),ce(),U?{meta:{paused:!0}}:M||{meta:{paused:!1}}},this.paused=function(){return U},this.pause=function(){U=!0,k.abort(),g=j(m.chunk)?"":g.substring(k.getCharIndex())},this.resume=function(){F.streamer._halted?(U=!1,F.streamer.parseChunk(g,!0)):setTimeout(F.resume,3)},this.aborted=function(){return q},this.abort=function(){q=!0,k.abort(),M.meta.aborted=!0,j(m.complete)&&m.complete(M),g=""},this.guessLineEndings=function(O,C){O=O.substring(0,1048576);var C=new RegExp(x(C)+"([^]*?)"+x(C),"gm"),D=(O=O.replace(C,"")).split("\r"),C=O.split(` `),O=1<C.length&&C[0].length<D[0].length;if(D.length===1||O)return` `;for(var $=0,B=0;B<D.length;B++)D[B][0]===` `&&$++;return $>=D.length/2?`\r `:"\r"}}function x(m){return m.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}function y(m){var g=(m=m||{}).delimiter,k=m.newline,T=m.comments,I=m.step,R=m.preview,K=m.fastMode,X=null,re=!1,F=m.quoteChar==null?'"':m.quoteChar,ne=F;if(m.escapeChar!==void 0&&(ne=m.escapeChar),(typeof g!="string"||-1<c.BAD_DELIMITERS.indexOf(g))&&(g=","),T===g)throw new Error("Comment character same as delimiter");T===!0?T="#":(typeof T!="string"||-1<c.BAD_DELIMITERS.indexOf(T))&&(T=!1),k!==` `&&k!=="\r"&&k!==`\r `&&(k=` `);var H=0,U=!1;this.parse=function(q,Q,M){if(typeof q!="string")throw new Error("Input must be a string");var le=q.length,ce=g.length,ue=k.length,ae=T.length,E=j(I),L=[],D=[],C=[],O=H=0;if(!q)return ye();if(K||K!==!1&&q.indexOf(F)===-1){for(var $=q.split(k),B=0;B<$.length;B++){if(C=$[B],H+=C.length,B!==$.length-1)H+=k.length;else if(M)return ye();if(!T||C.substring(0,ae)!==T){if(E){if(L=[],De(C.split(g)),Ue(),U)return ye()}else De(C.split(g));if(R&&R<=B)return L=L.slice(0,R),ye(!0)}}return ye()}for(var Z=q.indexOf(g,H),G=q.indexOf(k,H),xe=new RegExp(x(ne)+x(F),"g"),V=q.indexOf(F,H);;)if(q[H]===F)for(V=H,H++;;){if((V=q.indexOf(F,V+1))===-1)return M||D.push({type:"Quotes",code:"MissingQuotes",message:"Quoted field unterminated",row:L.length,index:H}),$e();if(V===le-1)return $e(q.substring(H,V).replace(xe,F));if(F===ne&&q[V+1]===ne)V++;else if(F===ne||V===0||q[V-1]!==ne){Z!==-1&&Z<V+1&&(Z=q.indexOf(g,V+1));var de=Pe((G=G!==-1&&G<V+1?q.indexOf(k,V+1):G)===-1?Z:Math.min(Z,G));if(q.substr(V+1+de,ce)===g){C.push(q.substring(H,V).replace(xe,F)),q[H=V+1+de+ce]!==F&&(V=q.indexOf(F,H)),Z=q.indexOf(g,H),G=q.indexOf(k,H);break}if(de=Pe(G),q.substring(V+1+de,V+1+de+ue)===k){if(C.push(q.substring(H,V).replace(xe,F)),Et(V+1+de+ue),Z=q.indexOf(g,H),V=q.indexOf(F,H),E&&(Ue(),U))return ye();if(R&&L.length>=R)return ye(!0);break}D.push({type:"Quotes",code:"InvalidQuotes",message:"Trailing quote on quoted field is malformed",row:L.length,index:H}),V++}}else if(T&&C.length===0&&q.substring(H,H+ae)===T){if(G===-1)return ye();H=G+ue,G=q.indexOf(k,H),Z=q.indexOf(g,H)}else if(Z!==-1&&(Z<G||G===-1))C.push(q.substring(H,Z)),H=Z+ce,Z=q.indexOf(g,H);else{if(G===-1)break;if(C.push(q.substring(H,G)),Et(G+ue),E&&(Ue(),U))return ye();if(R&&L.length>=R)return ye(!0)}return $e();function De(ge){L.push(ge),O=H}function Pe(ge){var je=0;return je=ge!==-1&&(ge=q.substring(V+1,ge))&&ge.trim()===""?ge.length:je}function $e(ge){return M||(ge===void 0&&(ge=q.substring(H)),C.push(ge),H=le,De(C),E&&Ue()),ye()}function Et(ge){H=ge,De(C),C=[],G=q.indexOf(k,H)}function ye(ge){if(m.header&&!Q&&L.length&&!re){var je=L[0],Ge=Object.create(null),ys=new Set(je);let mr=!1;for(let lt=0;lt<je.length;lt++){let Be=je[lt];if(Ge[Be=j(m.transformHeader)?m.transformHeader(Be,lt):Be]){let Ct,gr=Ge[Be];for(;Ct=Be+"_"+gr,gr++,ys.has(Ct););ys.add(Ct),je[lt]=Ct,Ge[Be]++,mr=!0,(X=X===null?{}:X)[Ct]=Be}else Ge[Be]=1,je[lt]=Be;ys.add(Be)}mr&&console.warn("Duplicate headers found and renamed."),re=!0}return{data:L,errors:D,meta:{delimiter:g,linebreak:k,aborted:U,truncated:!!ge,cursor:O+(Q||0),renamedHeaders:X}}}function Ue(){I(ye()),L=[],D=[]}},this.abort=function(){U=!0},this.getCharIndex=function(){return H}}function P(m){var g=m.data,k=l[g.workerId],T=!1;if(g.error)k.userError(g.error,g.file);else if(g.results&&g.results.data){var I={abort:function(){T=!0,_(g.workerId,{data:[],errors:[],meta:{aborted:!0}})},pause:A,resume:A};if(j(k.userStep)){for(var R=0;R<g.results.data.length&&(k.userStep({data:g.results.data[R],errors:g.results.errors,meta:g.results.meta},I),!T);R++);delete g.results}else j(k.userChunk)&&(k.userChunk(g.results,I,g.file),delete g.results)}g.finished&&!T&&_(g.workerId,g.results)}function _(m,g){var k=l[m];j(k.userComplete)&&k.userComplete(g),k.terminate(),delete l[m]}function A(){throw new Error("Not implemented.")}function S(m){if(typeof m!="object"||m===null)return m;var g,k=Array.isArray(m)?[]:{};for(g in m)k[g]=S(m[g]);return k}function N(m,g){return function(){m.apply(g,arguments)}}function j(m){return typeof m=="function"}return c.parse=function(m,g){var k=(g=g||{}).dynamicTyping||!1;if(j(k)&&(g.dynamicTypingFunction=k,k={}),g.dynamicTyping=k,g.transform=!!j(g.transform)&&g.transform,!g.worker||!c.WORKERS_SUPPORTED)return k=null,c.NODE_STREAM_INPUT,typeof m=="string"?(m=(T=>T.charCodeAt(0)!==65279?T:T.slice(1))(m),k=new(g.download?h:p)(g)):m.readable===!0&&j(m.read)&&j(m.on)?k=new v(g):(n.File&&m instanceof File||m instanceof Object)&&(k=new f(g)),k.stream(m);(k=(()=>{var T;return!!c.WORKERS_SUPPORTED&&(T=(()=>{var I=n.URL||n.webkitURL||null,R=r.toString();return c.BLOB_URL||(c.BLOB_URL=I.createObjectURL(new Blob(["var global = (function() { if (typeof self !== 'undefined') { return self; } if (typeof window !== 'undefined') { return window; } if (typeof global !== 'undefined') { return global; } return {}; })(); global.IS_PAPA_WORKER=true; ","(",R,")();"],{type:"text/javascript"})))})(),(T=new n.Worker(T)).onmessage=P,T.id=d++,l[T.id]=T)})()).userStep=g.step,k.userChunk=g.chunk,k.userComplete=g.complete,k.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,k.postMessage({input:m,config:g,workerId:k.id})},c.unparse=function(m,g){var k=!1,T=!0,I=",",R=`\r `,K='"',X=K+K,re=!1,F=null,ne=!1,H=((()=>{if(typeof g=="object"){if(typeof g.delimiter!="string"||c.BAD_DELIMITERS.filter(function(Q){return g.delimiter.indexOf(Q)!==-1}).length||(I=g.delimiter),typeof g.quotes!="boolean"&&typeof g.quotes!="function"&&!Array.isArray(g.quotes)||(k=g.quotes),typeof g.skipEmptyLines!="boolean"&&typeof g.skipEmptyLines!="string"||(re=g.skipEmptyLines),typeof g.newline=="string"&&(R=g.newline),typeof g.quoteChar=="string"&&(K=g.quoteChar),typeof g.header=="boolean"&&(T=g.header),Array.isArray(g.columns)){if(g.columns.length===0)throw new Error("Option columns is empty");F=g.columns}g.escapeChar!==void 0&&(X=g.escapeChar+K),g.escapeFormulae instanceof RegExp?ne=g.escapeFormulae:typeof g.escapeFormulae=="boolean"&&g.escapeFormulae&&(ne=/^[=+\-@\t\r].*$/)}})(),new RegExp(x(K),"g"));if(typeof m=="string"&&(m=JSON.parse(m)),Array.isArray(m)){if(!m.length||Array.isArray(m[0]))return U(null,m,re);if(typeof m[0]=="object")return U(F||Object.keys(m[0]),m,re)}else if(typeof m=="object")return typeof m.data=="string"&&(m.data=JSON.parse(m.data)),Array.isArray(m.data)&&(m.fields||(m.fields=m.meta&&m.meta.fields||F),m.fields||(m.fields=Array.isArray(m.data[0])?m.fields:typeof m.data[0]=="object"?Object.keys(m.data[0]):[]),Array.isArray(m.data[0])||typeof m.data[0]=="object"||(m.data=[m.data])),U(m.fields||[],m.data||[],re);throw new Error("Unable to serialize unrecognized input");function U(Q,M,le){var ce="",ue=(typeof Q=="string"&&(Q=JSON.parse(Q)),typeof M=="string"&&(M=JSON.parse(M)),Array.isArray(Q)&&0<Q.length),ae=!Array.isArray(M[0]);if(ue&&T){for(var E=0;E<Q.length;E++)0<E&&(ce+=I),ce+=q(Q[E],E);0<M.length&&(ce+=R)}for(var L=0;L<M.length;L++){var D=(ue?Q:M[L]).length,C=!1,O=ue?Object.keys(M[L]).length===0:M[L].length===0;if(le&&!ue&&(C=le==="greedy"?M[L].join("").trim()==="":M[L].length===1&&M[L][0].length===0),le==="greedy"&&ue){for(var $=[],B=0;B<D;B++){var Z=ae?Q[B]:B;$.push(M[L][Z])}C=$.join("").trim()===""}if(!C){for(var G=0;G<D;G++){0<G&&!O&&(ce+=I);var xe=ue&&ae?Q[G]:G;ce+=q(M[L][xe],G)}L<M.length-1&&(!le||0<D&&!O)&&(ce+=R)}}return ce}function q(Q,M){var le,ce;return Q==null?"":Q.constructor===Date?JSON.stringify(Q).slice(1,25):(ce=!1,ne&&typeof Q=="string"&&ne.test(Q)&&(Q="'"+Q,ce=!0),le=Q.toString().replace(H,X),(ce=ce||k===!0||typeof k=="function"&&k(Q,M)||Array.isArray(k)&&k[M]||((ue,ae)=>{for(var E=0;E<ae.length;E++)if(-1<ue.indexOf(ae[E]))return!0;return!1})(le,c.BAD_DELIMITERS)||-1<le.indexOf(I)||le.charAt(0)===" "||le.charAt(le.length-1)===" ")?K+le+K:le)}},c.RECORD_SEP="",c.UNIT_SEP="",c.BYTE_ORDER_MARK="\uFEFF",c.BAD_DELIMITERS=["\r",` `,'"',c.BYTE_ORDER_MARK],c.WORKERS_SUPPORTED=!i&&!!n.Worker,c.NODE_STREAM_INPUT=1,c.LocalChunkSize=10485760,c.RemoteChunkSize=5242880,c.DefaultDelimiter=",",c.Parser=y,c.ParserHandle=w,c.NetworkStreamer=h,c.FileStreamer=f,c.StringStreamer=p,c.ReadableStreamStreamer=v,n.jQuery&&((a=n.jQuery).fn.parse=function(m){var g=m.config||{},k=[];return this.each(function(R){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 K=0;K<this.files.length;K++)k.push({file:this.files[K],inputElem:this,instanceConfig:a.extend({},g)})}),T(),this;function T(){if(k.length===0)j(m.complete)&&m.complete();else{var R,K,X,re,F=k[0];if(j(m.before)){var ne=m.before(F.file,F.inputElem);if(typeof ne=="object"){if(ne.action==="abort")return R="AbortError",K=F.file,X=F.inputElem,re=ne.reason,void(j(m.error)&&m.error({name:R},K,X,re));if(ne.action==="skip")return void I();typeof ne.config=="object"&&(F.instanceConfig=a.extend(F.instanceConfig,ne.config))}else if(ne==="skip")return void I()}var H=F.instanceConfig.complete;F.instanceConfig.complete=function(U){j(H)&&H(U,F.file,F.inputElem),I()},c.parse(F.file,F.instanceConfig)}}function I(){k.splice(0,1),T()}}),o&&(n.onmessage=function(m){m=m.data,c.WORKER_ID===void 0&&m&&(c.WORKER_ID=m.workerId),typeof m.input=="string"?n.postMessage({workerId:c.WORKER_ID,results:c.parse(m.input,m.config),finished:!0}):(n.File&&m.input instanceof File||m.input instanceof Object)&&(m=c.parse(m.input,m.config))&&n.postMessage({workerId:c.WORKER_ID,results:m,finished:!0})}),(h.prototype=Object.create(u.prototype)).constructor=h,(f.prototype=Object.create(u.prototype)).constructor=f,(p.prototype=Object.create(p.prototype)).constructor=p,(v.prototype=Object.create(u.prototype)).constructor=v,c})})(Zn);var sd=Zn.exports;const rd=is(sd),nd=({onSuccess:s})=>{const[e,r]=b.useState(!1),[n,a]=b.useState(null),[i,o]=b.useState([]),[l,d]=b.useState(!1),[c,u]=b.useState(null),[h,f]=b.useState(!1),[p,v]=b.useState(null),w=async()=>{try{r(!0),a(null),v(null);const S=await td.importPlaylists(i,N=>{u({total:N.total,processed:N.processed,successCount:N.processed-N.failed,skipCount:N.skipped,unmatchedCategories:Array.from(N.unmatchedCategories),errors:N.recentErrors.map(j=>({row:j.row,error:j.message}))})});v(S),S.successCount>0&&s()}catch(S){a("Error importing playlists"),console.error("Import error:",S)}finally{r(!1)}},x=async S=>{try{if(r(!0),a(null),u(null),!S.name.endsWith(".csv")){a("Please upload a CSV file");return}const N=new FileReader;N.onload=async j=>{var T;const m=(T=j.target)==null?void 0:T.result,{data:g,errors:k}=rd.parse(m,{header:!0,skipEmptyLines:!0});if(k.length>0){a("Error parsing CSV file");return}o(g),d(!0)},N.readAsText(S)}catch{a("Error processing file")}finally{r(!1)}},y=b.useCallback(S=>{S.preventDefault(),S.stopPropagation(),f(!0)},[]),P=b.useCallback(S=>{S.preventDefault(),S.stopPropagation(),f(!1)},[]),_=b.useCallback(S=>{S.preventDefault(),S.stopPropagation(),f(!1);const N=S.dataTransfer.files[0];N&&x(N)},[]),A=S=>{var j;const N=(j=S.target.files)==null?void 0:j[0];N&&x(N),S.target.value=""};return t.jsxs("div",{className:"space-y-4",children:[t.jsx("div",{onDragOver:y,onDragLeave:P,onDrop:_,className:` border-2 border-dashed rounded-lg p-8 text-center transition-colors ${h?"border-green-500 bg-green-50":"border-gray-300 hover:border-green-500"} ${e?"opacity-50 cursor-not-allowed":"cursor-pointer"} `,children:e?t.jsxs("div",{className:"space-y-4",children:[t.jsx(me,{className:"w-8 h-8 text-green-500 animate-spin mx-auto"}),c&&t.jsxs("div",{className:"text-sm text-gray-600",children:["Processing ",c.processed," of ",c.total," playlists...",c.successCount>0&&t.jsxs("div",{className:"text-green-600",children:[c.successCount," playlists imported successfully"]}),c.skipCount>0&&t.jsxs("div",{className:"text-yellow-600",children:[c.skipCount," playlists skipped"]})]})]}):t.jsxs(t.Fragment,{children:[t.jsx(rs,{className:"w-8 h-8 text-gray-400 mx-auto mb-3"}),t.jsx("p",{className:"text-gray-600 mb-2",children:"Drag and drop your CSV file here, or click to select"}),t.jsx("input",{type:"file",accept:".csv",onChange: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(fe,{className:"w-5 h-5 flex-shrink-0"}),t.jsx("p",{className:"flex-1",children:n}),t.jsx("button",{onClick:()=>a(null),children:t.jsx(be,{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:w,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((S,N)=>t.jsxs("tr",{children:[t.jsx("td",{className:"px-6 py-4 whitespace-nowrap text-sm text-gray-900",children:S.Name}),t.jsx("td",{className:"px-6 py-4 whitespace-nowrap text-sm text-gray-500",children:S.Category}),t.jsx("td",{className:"px-6 py-4 whitespace-nowrap text-sm text-gray-500",children:S.Curator})]},N)),i.length>5&&t.jsx("tr",{children:t.jsxs("td",{colSpan:3,className:"px-6 py-4 text-sm text-gray-500 text-center",children:["+ ",i.length-5," more playlists"]})})]})]})})]}),p&&!e&&t.jsx(ad,{result:p})]})},ad=({result:s})=>t.jsx("div",{className:"mt-4",children:t.jsxs("div",{className:"bg-white rounded-lg shadow-sm p-4 border border-gray-200",children:[t.jsx("h3",{className:"text-lg font-medium mb-4",children:"Import Results"}),t.jsxs("div",{className:"grid grid-cols-3 gap-4 mb-4",children:[t.jsxs("div",{className:"bg-green-50 p-3 rounded-lg",children:[t.jsx("div",{className:"text-2xl font-semibold text-green-600",children:s.successCount}),t.jsx("div",{className:"text-sm text-green-700",children:"Successfully imported"})]}),t.jsxs("div",{className:"bg-yellow-50 p-3 rounded-lg",children:[t.jsx("div",{className:"text-2xl font-semibold text-yellow-600",children:s.skipCount}),t.jsx("div",{className:"text-sm text-yellow-700",children:"Skipped"})]}),t.jsxs("div",{className:"bg-blue-50 p-3 rounded-lg",children:[t.jsx("div",{className:"text-2xl font-semibold text-blue-600",children:s.unmatchedCategories.length}),t.jsx("div",{className:"text-sm text-blue-700",children:"Unmatched categories"})]})]}),s.unmatchedCategories.length>0&&t.jsxs("div",{className:"mb-4",children:[t.jsx("h4",{className:"font-medium mb-2 text-sm text-gray-700",children:"Unmatched Categories:"}),t.jsx("div",{className:"flex flex-wrap gap-2",children:s.unmatchedCategories.map((e,r)=>t.jsx("span",{className:"inline-flex items-center px-2 py-1 rounded-full text-xs font-medium bg-blue-100 text-blue-800",children:e},r))})]}),s.errors.length>0&&t.jsxs("div",{children:[t.jsx("h4",{className:"font-medium mb-2 text-sm text-gray-700",children:"Errors:"}),t.jsx("div",{className:"max-h-60 overflow-y-auto rounded-lg border border-gray-200",children:t.jsxs("table",{className:"min-w-full divide-y divide-gray-200",children:[t.jsx("thead",{className:"bg-gray-50",children:t.jsxs("tr",{children:[t.jsx("th",{className:"px-4 py-2 text-left text-xs font-medium text-gray-500",children:"Row"}),t.jsx("th",{className:"px-4 py-2 text-left text-xs font-medium text-gray-500",children:"Error"})]})}),t.jsx("tbody",{className:"bg-white divide-y divide-gray-200",children:s.errors.map((e,r)=>t.jsxs("tr",{children:[t.jsxs("td",{className:"px-4 py-2 whitespace-nowrap text-sm text-gray-500",children:["Row ",e.row]}),t.jsx("td",{className:"px-4 py-2 text-sm text-gray-500",children:e.error})]},r))})]})})]})]})});function id({onClose:s,onComplete:e}){const[r,n]=b.useState(!1),[a,i]=b.useState(!1),[o,l]=b.useState(null),[d,c]=b.useState(null),u=b.useRef(null),h=async()=>{var v,w;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:y,error:P}=await W.from("playlists").select("*",{count:"exact",head:!0}).or(`last_synced_at.is.null,last_synced_at.lt.${x}`);if(P)throw console.error("Error getting playlist count:",P),P;if(!y||y===0)throw new Error("No playlists need syncing");console.log(`Total playlists to sync: ${y}`),c({current:0,total:y,updated:0,failed:0});const _=1e3,A=5,S=1e3,N=3e4;let j=S,m=0,g=null;for(;m<y;){if((v=u.current)!=null&&v.signal.aborted)throw new Error("Sync cancelled");console.log(`Fetching page of playlists${g?` after ID ${g}`:""}...`);let k=W.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(_);g&&(k=k.gt("id",g));const{data:T,error:I}=await k;if(I)throw console.error("Error fetching playlists:",I),I;if(!T||T.length===0){console.log("No more playlists to process");break}console.log(`Processing page of ${T.length} playlists${g?` after ID ${g}`:""}`),g=T[T.length-1].id;for(let R=0;R<T.length;R+=A){if((w=u.current)!=null&&w.signal.aborted)throw new Error("Sync cancelled");const K=T.slice(R,Math.min(R+A,T.length)),X=Math.floor((m+R)/A)+1,re=Math.ceil(y/A);console.log(`Processing batch ${X} of ${re}`);try{const F=await Promise.allSettled(K.map(async U=>{var q,Q,M,le,ce,ue;try{console.log(`Fetching details for playlist ${U.spotify_id}`);const ae=await fr(U.spotify_id);if(!ae)throw console.error(`No data returned for playlist ${U.spotify_id}`),new Error("Playlist not found on Spotify");return console.log(`Successfully fetched details for playlist ${U.spotify_id}`),{id:U.id,name:ae.name,description:ae.description||"",image_url:((q=ae.images[0])==null?void 0:q.url)||"",followers:((Q=ae.followers)==null?void 0:Q.total)||0,track_count:((M=ae.tracks)==null?void 0:M.total)||0,curator_name:((le=ae.owner)==null?void 0:le.display_name)||null,curator_profile_url:((ue=(ce=ae.owner)==null?void 0:ce.external_urls)==null?void 0:ue.spotify)||null,curator_email:ae.curator_email||null,last_synced_at:new Date().toISOString(),updated_at:new Date().toISOString()}}catch(ae){throw console.error(`Failed to fetch playlist ${U.spotify_id}:`,ae),ae}}));j=S;let ne=0,H=0;for(const U of F)if(U.status==="fulfilled"){const{error:q}=await W.from("playlists").update(U.value).eq("id",U.value.id);q?(console.error("Failed to update playlist:",q),H++):(console.log(`Successfully updated playlist ${U.value.id}`),ne++)}else{console.error("Batch update failed:",U.reason);const q=U.reason instanceof Error?U.reason.message:"Unknown error";console.error("Detailed error:",{message:q,fullError:U.reason}),H++}c(U=>({current:m+R+K.length,updated:((U==null?void 0:U.updated)||0)+ne,failed:((U==null?void 0:U.failed)||0)+H,total:y}))}catch(F){if(F instanceof Error&&F.message.includes("rate limit")){console.log(`Rate limit hit. Waiting ${j/1e3} seconds before retrying...`),await new Promise(ne=>setTimeout(ne,j)),j=Math.min(j*2,N),R-=A;continue}throw F}await new Promise(F=>setTimeout(F,j))}m+=T.length}e(),n(!1)}catch(x){console.error("Sync failed:",x);const y=x instanceof Error?x.message:"Failed to sync playlists";console.error("Detailed error:",{error:x,message:y}),l(y)}finally{i(!1),u.current=null}},f=()=>{var v;a?(v=u.current)==null||v.abort():(n(!1),s==null||s())},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(vt,{className:"w-5 h-5"}),"Start Sync"]})]})}),r&&t.jsx("div",{className:"fixed inset-0 bg-black bg-opacity-50 flex items-center justify-center p-4 z-50",children:t.jsxs("div",{className:"bg-white rounded-xl max-w-lg w-full",children:[t.jsx("div",{className:"p-6 border-b border-gray-200",children:t.jsxs("div",{className:"flex justify-between items-center",children:[t.jsx("h2",{className:"text-xl font-bold text-gray-900",children:"Sync Playlists"}),t.jsx("button",{onClick:f,className:"text-gray-400 hover:text-gray-500 transition-colors",children:t.jsx(be,{className:"w-6 h-6"})})]})}),t.jsxs("div",{className:"p-6 space-y-4",children:[!a&&!o&&t.jsx("p",{className:"text-gray-600",children:"This will update playlist metadata including artwork, description, curator details, follower count, and track count from Spotify."}),d&&t.jsxs("div",{className:"space-y-3",children:[t.jsxs("div",{className:"flex items-center justify-between text-sm text-gray-600",children:[t.jsx("span",{children:"Processing playlists..."}),t.jsxs("span",{children:[d.current," of ",d.total," (",Math.round(d.current/d.total*100),"%)"]})]}),t.jsx("div",{className:"w-full h-2 bg-gray-100 rounded-full overflow-hidden",children:t.jsx("div",{className:"h-full bg-green-500 transition-all duration-300",style:{width:`${d.current/d.total*100}%`}})}),t.jsxs("div",{className:"flex gap-4 text-sm",children:[t.jsxs("span",{className:"flex items-center gap-1 text-green-600",children:[t.jsx(nt,{className:"w-4 h-4"}),d.updated," updated (",Math.round(d.updated/d.total*100),"%)"]}),d.failed>0&&t.jsxs("span",{className:"flex items-center gap-1 text-red-600",children:[t.jsx(fe,{className:"w-4 h-4"}),d.failed," failed (",Math.round(d.failed/d.total*100),"%)"]})]})]}),o&&t.jsxs("div",{className:"flex items-center gap-2 text-red-600 bg-red-50 p-3 rounded-lg",children:[t.jsx(fe,{className:"w-5 h-5 flex-shrink-0"}),t.jsx("p",{children:o})]}),t.jsxs("div",{className:"flex justify-end gap-3 pt-4",children:[t.jsx("button",{onClick:f,className:"px-4 py-2 text-gray-700 hover:bg-gray-100 rounded-lg transition-colors",children:a?"Cancel":"Close"}),!a&&!o&&t.jsxs("button",{onClick:h,className:"flex items-center gap-2 px-4 py-2 bg-green-500 text-white rounded-lg hover:bg-green-600 transition-colors",children:[t.jsx(vt,{className:"w-5 h-5"}),"Start Sync"]})]})]})]})})]})}function od(){const[s,e]=b.useState(null);return t.jsxs("div",{className:"container mx-auto px-4 py-8",children:[t.jsx("h1",{className:"text-2xl font-bold mb-6",children:"Import & Sync Data"}),t.jsxs("div",{className:"space-y-6",children:[t.jsx(id,{onComplete:()=>e({type:"success",message:"Successfully synced playlists with Spotify"})}),t.jsxs(Xc,{defaultValue:"playlists",className:"space-y-6",children:[t.jsxs(Qn,{children:[t.jsx(Ys,{value:"playlists",children:"Playlists"}),t.jsx(Ys,{value:"genres",children:"Genres & Sub-genres"})]}),t.jsx(Qs,{value:"playlists",children:t.jsx(nd,{onSuccess:()=>e({type:"success",message:"Successfully imported playlists"})})}),t.jsx(Qs,{value:"genres",children:t.jsx(ed,{onSuccess:()=>e({type:"success",message:"Successfully imported genres and sub-genres"})})})]})]}),s&&t.jsx(qe,{message:s.message,type:s.type,onClose:()=>e(null)})]})}function ld({isOpen:s,onClose:e,onConfirm:r,isCleaning:n,progress:a}){if(!s)return null;const i=a?Math.round(a.processed/a.total*100):0;return t.jsx("div",{className:"fixed inset-0 bg-black bg-opacity-50 flex items-center justify-center z-50",children:t.jsxs("div",{className:"bg-white rounded-lg p-6 max-w-md w-full mx-4",children:[t.jsxs("div",{className:"flex justify-between items-center mb-4",children:[t.jsx("h2",{className:"text-xl font-semibold",children:n?"Cleaning Descriptions":"Confirm Clean Descriptions"}),t.jsx("button",{onClick:e,className:"text-gray-500 hover:text-gray-700",disabled:n,children:t.jsx(be,{className:"w-5 h-5"})})]}),n?t.jsxs("div",{className:"space-y-4",children:[t.jsxs("div",{className:"space-y-2",children:[t.jsxs("div",{className:"flex justify-between text-sm",children:[t.jsx("span",{children:"Progress"}),t.jsxs("span",{children:[i,"%"]})]}),t.jsx("div",{className:"w-full bg-gray-200 rounded-full h-2.5",children:t.jsx("div",{className:"bg-blue-500 h-2.5 rounded-full transition-all duration-300",style:{width:`${i}%`}})})]}),t.jsxs("div",{className:"grid grid-cols-2 gap-4 text-sm",children:[t.jsxs("div",{children:[t.jsx("span",{className:"text-gray-500",children:"Processed:"}),t.jsx("span",{className:"ml-2 font-medium",children:(a==null?void 0:a.processed)||0})]}),t.jsxs("div",{children:[t.jsx("span",{className:"text-gray-500",children:"Updated:"}),t.jsx("span",{className:"ml-2 font-medium",children:(a==null?void 0:a.updated)||0})]}),t.jsxs("div",{children:[t.jsx("span",{className:"text-gray-500",children:"Total:"}),t.jsx("span",{className:"ml-2 font-medium",children:(a==null?void 0:a.total)||0})]})]}),t.jsxs("div",{className:"flex items-center justify-center text-blue-500",children:[t.jsx(me,{className:"w-6 h-6 animate-spin"}),t.jsx("span",{className:"ml-2",children:"Cleaning in progress..."})]})]}):t.jsxs("div",{className:"space-y-4",children:[t.jsx("p",{className:"text-gray-600",children:"This will clean all playlist descriptions by removing HTML, URLs, and extracting curator emails. Existing emails will be preserved unless new ones are found."}),t.jsxs("div",{className:"flex justify-end gap-3",children:[t.jsx("button",{onClick:e,className:"px-4 py-2 text-gray-600 hover:text-gray-800",children:"Cancel"}),t.jsx("button",{onClick:r,className:"px-4 py-2 bg-blue-500 text-white rounded-lg hover:bg-blue-600",children:"Start Cleaning"})]})]})]})})}async function cd(){return{success:!0}}function dd(){const[s,e]=b.useState(""),[r,n]=b.useState(""),[a,i]=b.useState(""),[o,l]=b.useState(!1),[d,c]=b.useState(!1),[u,h]=b.useState(!1),[f,p]=b.useState(!1),[v,w]=b.useState(null),[x,y]=b.useState(null),P=async N=>{if(N.preventDefault(),r!==a){w({type:"error",message:"New passwords do not match"});return}l(!0);try{w({type:"success",message:"Password updated successfully"}),e(""),n(""),i("")}catch(j){console.error("Failed to update password:",j),w({type:"error",message:"Failed to update password"})}finally{l(!1)}},_=async()=>{c(!0);try{await cd(),w({type:"success",message:"Genres and sub-genres have been set up successfully"})}catch(N){console.error("Failed to setup genres:",N),w({type:"error",message:"Failed to setup genres and sub-genres"})}finally{c(!1)}},A=async()=>{p(!0)},S=async()=>{h(!0),p(!0);try{const{count:N,error:j}=await W.from("playlists").select("*",{count:"exact",head:!0});if(j)throw j;if(!N)throw new Error("No playlists found");y({total:N,processed:0,updated:0});let m=!0,g=0;const k=50;for(;m;){const{data:T,error:I}=await W.from("playlists").select("id, description").range(g,g+k-1);if(I)throw I;if(!T||T.length===0){m=!1;break}for(const R of T){const{description:K,extractedEmail:X}=Wn(R.description);if(K!==R.description||X){const{error:re}=await W.from("playlists").update({description:K,curator_email:X,updated_at:new Date().toISOString()}).eq("id",R.id);if(re){console.error(`Failed to update playlist ${R.id}:`,re);continue}y(F=>F?{...F,updated:F.updated+1}:null)}y(re=>re?{...re,processed:re.processed+1}:null)}g+=k}w({type:"success",message:`Processed ${x==null?void 0:x.processed} playlists, updated ${x==null?void 0:x.updated} descriptions`})}catch(N){console.error("Failed to clean descriptions:",N),w({type:"error",message:N instanceof Error?N.message:"Failed to clean descriptions"})}finally{h(!1),p(!1),y(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:_,disabled:d,className:"flex items-center gap-2 bg-green-500 text-white px-4 py-2 rounded-lg hover:bg-green-600 disabled:bg-gray-400 disabled:cursor-not-allowed",children:[d?t.jsx(me,{className:"w-5 h-5 animate-spin"}):t.jsx(vt,{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(me,{className:"w-5 h-5 animate-spin"}):t.jsx(Tl,{className:"w-5 h-5"}),u?"Cleaning...":"Clean All Descriptions"]}),t.jsx("p",{className:"mt-2 text-sm text-gray-600",children:"This will clean all playlist descriptions by removing HTML, URLs, and extracting curator emails."})]}),t.jsxs("div",{className:"bg-white p-6 rounded-lg shadow-sm",children:[t.jsx("h2",{className:"text-lg font-medium mb-4",children:"Change Password"}),t.jsxs("form",{onSubmit:P,className:"space-y-4",children:[t.jsxs("div",{children:[t.jsx("label",{htmlFor:"currentPassword",className:"block text-sm font-medium text-gray-700 mb-1",children:"Current Password"}),t.jsx("input",{type:"password",id:"currentPassword",value:s,onChange:N=>e(N.target.value),required:!0,className:"w-full px-3 py-2 border border-gray-300 rounded-lg focus:ring-2 focus:ring-green-500 focus:border-transparent"})]}),t.jsxs("div",{children:[t.jsx("label",{htmlFor:"newPassword",className:"block text-sm font-medium text-gray-700 mb-1",children:"New Password"}),t.jsx("input",{type:"password",id:"newPassword",value:r,onChange:N=>n(N.target.value),required:!0,className:"w-full px-3 py-2 border border-gray-300 rounded-lg focus:ring-2 focus:ring-green-500 focus:border-transparent"})]}),t.jsxs("div",{children:[t.jsx("label",{htmlFor:"confirmPassword",className:"block text-sm font-medium text-gray-700 mb-1",children:"Confirm New Password"}),t.jsx("input",{type:"password",id:"confirmPassword",value:a,onChange:N=>i(N.target.value),required:!0,className:"w-full px-3 py-2 border border-gray-300 rounded-lg focus:ring-2 focus:ring-green-500 focus:border-transparent"})]}),t.jsxs("button",{type:"submit",disabled:o,className:"w-full flex items-center justify-center gap-2 bg-green-500 text-white px-4 py-2 rounded-lg hover:bg-green-600 disabled:bg-gray-400",children:[o?t.jsx(me,{className:"w-5 h-5 animate-spin"}):t.jsx(El,{className:"w-5 h-5"}),o?"Updating...":"Update Password"]})]})]})]}),t.jsx(ld,{isOpen:f,onClose:()=>p(!1),onConfirm:S,isCleaning:u,progress:x}),v&&t.jsx(qe,{message:v.message,type:v.type,onClose:()=>w(null)})]})}function ud(){var p,v;const[s,e]=b.useState(""),[r,n]=b.useState(""),[a,i]=b.useState(""),[o,l]=b.useState(!1),d=Xe(),c=it(),{signIn:u}=nr(),h=((v=(p=c.state)==null?void 0:p.from)==null?void 0:v.pathname)||"/admin",f=async w=>{w.preventDefault(),i(""),l(!0);try{await u(s.trim(),r),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(jl,{className:"h-6 w-6 text-green-600"})}),t.jsx("h2",{className:"mt-6 text-3xl font-extrabold text-gray-900",children:"Admin Login"}),t.jsx("p",{className:"mt-2 text-sm text-gray-600",children:"Sign in to access the admin dashboard"})]}),t.jsxs("form",{className:"mt-8 space-y-6",onSubmit:f,children:[t.jsxs("div",{className:"space-y-4",children:[t.jsxs("div",{children:[t.jsx("label",{htmlFor:"email",className:"block text-sm font-medium text-gray-700",children:"Email"}),t.jsx("input",{id:"email",type:"email",required:!0,value:s,onChange:w=>e(w.target.value),className:"mt-1 block w-full px-3 py-2 border border-gray-300 rounded-lg shadow-sm focus:ring-green-500 focus:border-green-500",placeholder:"admin@example.com",disabled:o})]}),t.jsxs("div",{children:[t.jsx("label",{htmlFor:"password",className:"block text-sm font-medium text-gray-700",children:"Password"}),t.jsx("input",{id:"password",type:"password",required:!0,value:r,onChange:w=>n(w.target.value),className:"mt-1 block w-full px-3 py-2 border border-gray-300 rounded-lg shadow-sm focus:ring-green-500 focus:border-green-500",placeholder:"Enter your password",disabled:o})]})]}),a&&t.jsxs("div",{className:"flex items-center gap-2 text-red-600 text-sm",children:[t.jsx(fe,{className:"w-4 h-4"}),a]}),t.jsx("button",{type:"submit",disabled:o,className:"w-full flex justify-center py-2 px-4 border border-transparent rounded-lg shadow-sm text-sm font-medium text-white bg-green-600 hover:bg-green-700 focus:outline-none focus:ring-2 focus:ring-offset-2 focus:ring-green-500 disabled:opacity-50 disabled:cursor-not-allowed",children:o?t.jsx(me,{className:"w-5 h-5 animate-spin"}):"Sign in"})]})]})})}function hd(){return t.jsx(qn,{children:t.jsx("div",{className:"min-h-screen flex flex-col",children:t.jsxs(ma,{children:[t.jsx(he,{path:"/",element:t.jsxs(t.Fragment,{children:[t.jsx(Se,{}),t.jsx(Kl,{}),t.jsx(ke,{})]})}),t.jsx(he,{path:"/playlists",element:t.jsxs(t.Fragment,{children:[t.jsx(Se,{}),t.jsx(yc,{}),t.jsx(ke,{})]})}),t.jsx(he,{path:"/submit",element:t.jsxs(t.Fragment,{children:[t.jsx(Se,{}),t.jsx(bc,{}),t.jsx(ke,{})]})}),t.jsx(he,{path:"/submit/genre",element:t.jsxs(t.Fragment,{children:[t.jsx(Se,{}),t.jsx(wc,{}),t.jsx(ke,{})]})}),t.jsx(he,{path:"/playlist/:slug/*",element:t.jsxs(t.Fragment,{children:[t.jsx(Se,{}),t.jsx(pc,{}),t.jsx(ke,{})]})}),t.jsx(he,{path:"/genres",element:t.jsxs(t.Fragment,{children:[t.jsx(Se,{}),t.jsx(kc,{}),t.jsx(ke,{})]})}),t.jsx(he,{path:"/genre/:genre",element:t.jsxs(t.Fragment,{children:[t.jsx(Se,{}),t.jsx(_c,{}),t.jsx(ke,{})]})}),t.jsx(he,{path:"/genre/:genre/:subGenre",element:t.jsxs(t.Fragment,{children:[t.jsx(Se,{}),t.jsx(Sc,{}),t.jsx(ke,{})]})}),t.jsx(he,{path:"/about",element:t.jsxs(t.Fragment,{children:[t.jsx(Se,{}),t.jsx(Ec,{}),t.jsx(ke,{})]})}),t.jsx(he,{path:"/for-curators",element:t.jsxs(t.Fragment,{children:[t.jsx(Se,{}),t.jsx(Cc,{}),t.jsx(ke,{})]})}),t.jsx(he,{path:"/blog",element:t.jsxs(t.Fragment,{children:[t.jsx(Se,{}),t.jsx(Tc,{}),t.jsx(ke,{})]})}),t.jsx(he,{path:"/blog/:category",element:t.jsxs(t.Fragment,{children:[t.jsx(Se,{}),t.jsx(Uc,{}),t.jsx(ke,{})]})}),t.jsx(he,{path:"/blog/:category/:slug",element:t.jsxs(t.Fragment,{children:[t.jsx(Se,{}),t.jsx($c,{}),t.jsx(ke,{})]})}),t.jsx(he,{path:"/admin/login",element:t.jsx(ud,{})}),t.jsxs(he,{path:"/admin",element:t.jsx(Mc,{}),children:[t.jsx(he,{index:!0,element:t.jsx(qc,{})}),t.jsx(he,{path:"playlists",element:t.jsx(zc,{})}),t.jsx(he,{path:"submissions",element:t.jsx(Jc,{})}),t.jsx(he,{path:"genres",element:t.jsx(Zc,{})}),t.jsx(he,{path:"import",element:t.jsx(od,{})}),t.jsx(he,{path:"settings",element:t.jsx(dd,{})})]}),t.jsx(he,{path:"*",element:t.jsx(Xr,{to:"/",replace:!0})})]})})})}const fd={};en(document.getElementById("root")).render(t.jsx(b.StrictMode,{children:t.jsx(ln,{context:fd,children:t.jsx(ga,{children:t.jsx(cl,{children:t.jsx(qn,{children:t.jsx(hd,{})})})})})}));export{me as L,dr as P,kt as S,qe as T,vc as u}; //# sourceMappingURL=index-CC9wZD_D.js.map