5 lines
207 KiB
JavaScript
5 lines
207 KiB
JavaScript
const __vite__mapDeps=(i,m=__vite__mapDeps,d=(m.f||(m.f=["assets/vendor-fFnFILYR.js","assets/vendor-react-YMhRUmcb.js","assets/vendor-BD_zwJK7.css","assets/DashboardPage-BMNaRTjt.js","assets/vendor-tanstack-CoFNL2zy.js","assets/chatStore-VE5eaeTh.js","assets/vendor-router-DX94Iu-2.js","assets/vendor-icons-DINCNwpk.js","assets/vendor-utils-4BWoYre8.js","assets/ChatPage-BO6K8M83.js","assets/input-DL1WY4HG.js","assets/Select-So_RP28r.js","assets/dropdown-DLDDI8f2.js","assets/useIsRateLimited-C43yhDlJ.js","assets/confirmation-dialog-O1mUMh9e.js","assets/LibraryPage-DJ1eADn5.js","assets/tracks-C_h6xkxF.js","assets/progress-CWjxseYI.js","assets/alert-COAUu9KR.js","assets/UserProfilePage-B2tC81y7.js","assets/users-DDt25V_U.js","assets/PlaylistCard-Due74KZ6.js","assets/features-CKIBrJL0.js","assets/socialService-rJN8QISo.js","assets/avatar-DwZKme3D.js","assets/Tabs-C8UCeQNW.js","assets/SettingsPage-DSklKTTs.js","assets/checkbox-Cwr-kRad.js","assets/LoginPage-6ERIsPFb.js","assets/AuthInput-CLUfktvv.js","assets/AuthButton-C1maCyAI.js","assets/AuthLayout-CeiHDQMs.js","assets/RegisterPage-Dikw454Q.js","assets/PasswordStrengthIndicator-foHQcebK.js","assets/ForgotPasswordPage-wIZ3bMJo.js","assets/usePasswordReset-BHItX07X.js","assets/VerifyEmailPage-Cj8MYc6s.js","assets/ResetPasswordPage-Doc7zcwQ.js","assets/SessionsPage-BJ02ofFg.js","assets/NotFoundPage-DoPT3V64.js","assets/ServerErrorPage-CZyfhQKe.js","assets/RolesPage-Ba5bJq9j.js","assets/textarea-DfK27c18.js","assets/TrackDetailPage-CoaPghB_.js","assets/Spinner-DMondT4l.js","assets/routes-CJBS24ox.js","assets/skeleton-BPDNnZ8E.js","assets/Pagination-DXc0wGeY.js","assets/useDebounce-zqwECu1l.js","assets/routes-B3giLbLK.css","assets/AdminDashboardView-CvscVmHo.js","assets/AnalyticsView-B3o6WIlr.js","assets/StatCard-Xzk79Siz.js","assets/WebhooksView-B5i4t7Y2.js","assets/webhookService-BUZkpEvD.js","assets/DesignSystemDemo-C_pcj_EH.js","assets/SocialView-C_G9BXzk.js","assets/GearView-BL2JvPVu.js","assets/LiveView-DSSm3dtG.js","assets/EducationView-Dgv2lm_h.js","assets/QueueView-q1taT2la.js","assets/DeveloperDashboardView-Dkv7ps0m.js","assets/NotificationsView-n_qp2i9l.js","assets/MarketplaceHome-DBtdadsi.js","assets/marketplaceService-BwlLR1ZR.js","assets/cartStore-C2PNCAMv.js","assets/SearchPage-77y10iyI.js","assets/SellerDashboardView-ymVO9IBa.js","assets/commerceService-bs-xd9qB.js","assets/WishlistView-BrN3xAjD.js","assets/PurchasesView-B_mVTOu6.js"])))=>i.map(i=>d[i]);
|
|
import{a as f,j as s,c as Kr,d as Hr,R as Wr}from"./vendor-react-YMhRUmcb.js";import{N as Ge,u as et,L as Ye,a as Gr,R as Yr,b as be,B as Xr}from"./vendor-router-DX94Iu-2.js";import{u as Jt,a as St,b as qt,Q as Jr,c as Zr}from"./vendor-tanstack-CoFNL2zy.js";import{k as Pe,l as Le,n as qe,q as tt,t as Zt,u as es,v as ts,S as rs,w as er,x as ss,y as as,z as tr,B as ns,C as is}from"./vendor-fFnFILYR.js";import{s as b,o as T,Z as Nt,r as De,b as re,e as se,a as me,n as z,c as ne,f as os,d as ls}from"./vendor-utils-4BWoYre8.js";import{X as _e,I as rt,A as ye,a as st,C as cs,B as us,b as ds,c as rr,d as ms,e as Ce,T as fs,f as hs,W as ps,L as Dt,g as Me,R as gs,h as sr,i as ys,j as vs,M as xs,S as bs,U as ws,k as ar,l as nr,m as ks,n as Es,o as _s,p as Ss,q as Ns,r as Ts,H as js,s as Cs,t as Rs,u as As,v as Ps,w as Is,x as Ls,y as qs,z as Ds,G as Ms,D as Os,E as Tt,F as zs,J as ir,K as Fs,N as Vs,O as Us,P as or,Q as lr,V as cr,Y as ur,Z as dr,_ as mr,$ as $s,a0 as Qs,a1 as Bs,a2 as Ks,a3 as Mt,a4 as Hs,a5 as Ws}from"./vendor-icons-DINCNwpk.js";(function(){const t=document.createElement("link").relList;if(t&&t.supports&&t.supports("modulepreload"))return;for(const n of document.querySelectorAll('link[rel="modulepreload"]'))a(n);new MutationObserver(n=>{for(const i of n)if(i.type==="childList")for(const o of i.addedNodes)o.tagName==="LINK"&&o.rel==="modulepreload"&&a(o)}).observe(document,{childList:!0,subtree:!0});function r(n){const i={};return n.integrity&&(i.integrity=n.integrity),n.referrerPolicy&&(i.referrerPolicy=n.referrerPolicy),n.crossOrigin==="use-credentials"?i.credentials="include":n.crossOrigin==="anonymous"?i.credentials="omit":i.credentials="same-origin",i}function a(n){if(n.ep)return;n.ep=!0;const i=r(n);fetch(n.href,i)}})();const Gs="modulepreload",Ys=function(e){return"/"+e},Ot={},N=function(t,r,a){let n=Promise.resolve();if(r&&r.length>0){let l=function(p){return Promise.all(p.map(u=>Promise.resolve(u).then(d=>({status:"fulfilled",value:d}),d=>({status:"rejected",reason:d}))))};document.getElementsByTagName("link");const o=document.querySelector("meta[property=csp-nonce]"),c=o?.nonce||o?.getAttribute("nonce");n=l(r.map(p=>{if(p=Ys(p),p in Ot)return;Ot[p]=!0;const u=p.endsWith(".css"),d=u?'[rel="stylesheet"]':"";if(document.querySelector(`link[href="${p}"]${d}`))return;const h=document.createElement("link");if(h.rel=u?"stylesheet":Gs,u||(h.as="script"),h.crossOrigin="",h.href=p,c&&h.setAttribute("nonce",c),document.head.appendChild(h),u)return new Promise((v,y)=>{h.addEventListener("load",v),h.addEventListener("error",()=>y(new Error(`Unable to preload CSS for ${p}`)))})}))}function i(o){const c=new Event("vite:preloadError",{cancelable:!0});if(c.payload=o,window.dispatchEvent(c),!c.defaultPrevented)throw o}return n.then(o=>{for(const c of o||[])c.status==="rejected"&&i(c.reason);return t().catch(i)})};let fr=null;function Xs(e){fr=e}function Js(){return fr}const Zs=f.lazy(()=>N(()=>import("./vendor-fFnFILYR.js").then(e=>e.Y),__vite__mapDeps([0,1,2])).then(e=>({default:e.Toaster})));function ea(e){return s.jsx(f.Suspense,{fallback:null,children:s.jsx(Zs,{...e})})}const zt="veza_access_token",Ft="veza_refresh_token";class ee{static setTokens(t,r){try{localStorage.removeItem(zt),localStorage.removeItem(Ft)}catch{}}static getAccessToken(){return null}static getRefreshToken(){return null}static clearTokens(){try{localStorage.removeItem(zt),localStorage.removeItem(Ft)}catch{}}static hasTokens(){return!1}}const ta="WARN".toUpperCase();let Xe={};function Vt(e){Xe={...Xe,...e}}function ra(){return{...Xe}}function $e(e,t,r,...a){const n={...Xe,...r},i=new Date().toISOString();{const o={timestamp:i,level:e,message:t,...n,...a.length>0&&{data:a}},c=JSON.stringify(o);console.log(c);const l="https://api.veza.com/api/v1/logs/frontend";l&&sa(l,o).catch(()=>{})}}async function sa(e,t){try{if(navigator.sendBeacon){const r=new Blob([JSON.stringify(t)],{type:"application/json"});navigator.sendBeacon(e,r)}else await fetch(e,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(t),keepalive:!0})}catch{}}function Qe(e){const t=["DEBUG","INFO","WARN","ERROR"],r=t.indexOf(ta),a=t.indexOf(e);return r===-1||a===-1?!0:a>=r}const g={debug:(e,t,...r)=>{Qe("DEBUG")&&$e("DEBUG",e,t,...r)},info:(e,t,...r)=>{Qe("INFO")&&$e("INFO",e,t,...r)},warn:(e,t,...r)=>{Qe("WARN")&&$e("WARN",e,t,...r)},error:(e,t,...r)=>{Qe("ERROR")&&$e("ERROR",e,t,...r)}},ue=N(()=>import("./vendor-fFnFILYR.js").then(e=>e.Y),__vite__mapDeps([0,1,2]));let We=null,xt=!1;ue.then(e=>{We=e,xt=!0}).catch(()=>{xt=!0});function Ut(){return!We&&xt?(g.error("Toast module failed to load"),{success:()=>{},error:()=>{},loading:()=>{},custom:()=>{},dismiss:()=>{},remove:()=>{},promise:()=>Promise.resolve()}):We?We.default:{success:(...e)=>{ue.then(t=>t.default.success(...e))},error:(...e)=>{ue.then(t=>t.default.error(...e))},loading:(...e)=>{ue.then(t=>t.default.loading(...e))},custom:(...e)=>{ue.then(t=>t.default.custom(...e))},dismiss:(...e)=>{ue.then(t=>t.default.dismiss(...e))},remove:(...e)=>{ue.then(t=>t.default.remove(...e))},promise:(...e)=>ue.then(t=>t.default.promise(...e))}}const te=new Proxy({},{get(e,t){const r=Ut();if(t in r){const a=r[t];return typeof a=="function"?a.bind(r):a}},apply(e,t,r){const a=Ut();return typeof a=="function"?a(...r):ue.then(n=>n.default(...r))}});let ht=null;const aa=60*1e3,na=240*1e3;let Re=null,Ee=null;function ia(){return ht||(ht=Pe.create({baseURL:"https://api.veza.com/api/v1",timeout:1e4,headers:{"Content-Type":"application/json"},withCredentials:!0})),ht}async function Ie(){try{const t=await ia().post("/auth/refresh",{});let r;if(t.data?.success&&t.data?.data)r=t.data.data.expires_in;else if(t.data?.access_token)r=t.data.expires_in||3600;else throw new Error(`Invalid refresh response format. Expected { success: true, data: { access_token, refresh_token, expires_in } } or { access_token, refresh_token, expires_in }, got: ${JSON.stringify(t.data)}`);ee.setTokens("","cookie-based"),hr(r)}catch(e){throw ee.clearTokens(),at(),e}}function hr(e=300){at(),oa();const t=e*1e3,r=Math.max(0,t-aa);if(r<=0){Ie().catch(a=>{g.warn("Proactive token refresh failed",{error:a instanceof Error?a.message:String(a),stack:a instanceof Error?a.stack:void 0})});return}Re=setTimeout(()=>{Ie().catch(a=>{g.warn("Proactive token refresh failed",{error:a instanceof Error?a.message:String(a),stack:a instanceof Error?a.stack:void 0})}),Re=null},r)}function oa(){Ee&&clearInterval(Ee),Ee=setInterval(()=>{Ie().catch(e=>{g.warn("Periodic token refresh failed",{error:e instanceof Error?e.message:String(e),stack:e instanceof Error?e.stack:void 0}),at()})},na)}function at(){Re&&(clearTimeout(Re),Re=null),Ee&&(clearInterval(Ee),Ee=null)}function jt(){hr(300)}function pr(){at()}const la=Object.freeze(Object.defineProperty({__proto__:null,cleanupProactiveRefresh:pr,initializeProactiveRefresh:jt,refreshToken:Ie},Symbol.toStringTag,{value:"Module"})),Be=b().refine(e=>{if(!e)return!1;if(/^https?:\/\//.test(e)||/^wss?:\/\//.test(e))try{return new URL(e),!0}catch{return!1}return e.startsWith("/")},{message:"Must be a valid URL or a path starting with /"}),ca=T({VITE_API_URL:Be.default("/api/v1"),VITE_WS_URL:Be.default("/ws"),VITE_STREAM_URL:Be.default("/stream"),VITE_UPLOAD_URL:Be.default("/upload"),VITE_APP_NAME:b().default("Veza"),VITE_API_VERSION:b().default("v1"),VITE_DEBUG:b().transform(e=>e==="true"||e==="1").default("false"),VITE_USE_MSW:b().transform(e=>e==="1"||e==="true").default("0"),VITE_FCM_VAPID_KEY:b().optional(),VITE_SENTRY_DSN:b().url().optional()}),ua=()=>{try{return ca.parse({VITE_API_URL:"https://api.veza.com/api/v1",VITE_WS_URL:"wss://api.veza.com/ws",VITE_STREAM_URL:"https://api.veza.com/stream",VITE_UPLOAD_URL:"https://api.veza.com/upload",VITE_APP_NAME:void 0,VITE_API_VERSION:"v1",VITE_DEBUG:void 0,VITE_USE_MSW:void 0,VITE_FCM_VAPID_KEY:void 0,VITE_SENTRY_DSN:void 0})}catch(e){throw e instanceof Nt?(g.error("❌ Invalid environment variables",{errors:e.errors}),new Error(`Environment variables validation failed: ${e.errors.map(t=>`${t.path.join(".")}: ${t.message}`).join(", ")}`)):e}},le=ua(),nt={API_URL:le.VITE_API_URL,WS_URL:le.VITE_WS_URL,STREAM_URL:le.VITE_STREAM_URL,UPLOAD_URL:le.VITE_UPLOAD_URL,APP_NAME:le.VITE_APP_NAME,API_VERSION:le.VITE_API_VERSION,DEBUG:le.VITE_DEBUG,USE_MSW:le.VITE_USE_MSW,FCM_VAPID_KEY:le.VITE_FCM_VAPID_KEY,SENTRY_DSN:le.VITE_SENTRY_DSN},ae={400:"La requête est invalide. Veuillez vérifier les informations fournies.",401:"Vous devez être connecté pour effectuer cette action.",403:"Vous n'avez pas les permissions nécessaires pour effectuer cette action.",404:"La ressource demandée est introuvable.",409:"Un conflit est survenu. Cette ressource existe déjà ou a été modifiée.",422:"Les données fournies ne sont pas valides.",429:"Trop de requêtes. Veuillez patienter quelques instants avant de réessayer.",500:"Une erreur serveur s'est produite. Veuillez réessayer plus tard.",502:"Erreur de communication avec le serveur. Veuillez réessayer plus tard.",503:"Service temporairement indisponible. Veuillez réessayer dans quelques instants.",504:"Le serveur met trop de temps à répondre. Veuillez réessayer plus tard.",NETWORK:"Erreur de connexion. Vérifiez votre connexion internet et réessayez. Si le problème persiste, le serveur pourrait être temporairement indisponible.",TIMEOUT:"La requête a expiré. Vérifiez votre connexion internet et réessayez.",UNKNOWN:"Une erreur inattendue s'est produite. Veuillez réessayer."},da={auth:{login:"Échec de la connexion. Vérifiez vos identifiants.",logout:"Erreur lors de la déconnexion.",register:"Erreur lors de l'inscription. Veuillez réessayer.",tokenExpired:"Votre session a expiré. Veuillez vous reconnecter."},upload:{fileTooLarge:"Le fichier est trop volumineux.",invalidFormat:"Le format de fichier n'est pas supporté.",uploadFailed:"L'upload a échoué. Veuillez réessayer.",networkError:"Erreur réseau lors de l'upload. Vérifiez votre connexion."},playlist:{notFound:"La playlist est introuvable.",accessDenied:"Vous n'avez pas accès à cette playlist.",createFailed:"Erreur lors de la création de la playlist.",updateFailed:"Erreur lors de la mise à jour de la playlist.",deleteFailed:"Erreur lors de la suppression de la playlist."},track:{notFound:"Le morceau est introuvable.",playFailed:"Impossible de lire le morceau. Vérifiez votre connexion.",uploadFailed:"Erreur lors de l'upload du morceau.",deleteFailed:"Erreur lors de la suppression du morceau."},conversation:{notFound:"La conversation est introuvable.",accessDenied:"Vous n'avez pas accès à cette conversation.",createFailed:"Erreur lors de la création de la conversation.",sendMessageFailed:"Erreur lors de l'envoi du message."},search:{failed:"La recherche a échoué. Veuillez réessayer.",timeout:"La recherche a pris trop de temps. Veuillez réessayer.",invalidQuery:"La requête de recherche est invalide."}};function ma(e,t){return e in ae?ae[e]:t||ae.UNKNOWN}function fa(e,t,r){const a=da[e];return a&&t in a?a[t]:r||ae.UNKNOWN}function gr(e,t,r=!1){if(e&&typeof e=="object"&&"code"in e&&"message"in e){const a=e,n=typeof a.code=="number"?a.code:0;if(t&&n>=400&&n<500){const i=ha(a.message),o=fa(t,i,void 0);if(o!==ae.UNKNOWN)return o}if(n>0){const i=ma(n,a.message);if(r&&a.details&&Array.isArray(a.details)){const o=a.details.map(c=>c.message||c.field).filter(Boolean).join(", ");if(o)return`${i} (${o})`}return i}return a.message||ae.UNKNOWN}if(e instanceof Error)return e.message||ae.UNKNOWN;if(e&&typeof e=="object"&&"code"in e){const a=e.code;if(a==="ECONNABORTED"||a==="ETIMEDOUT")return ae.TIMEOUT;if(a==="ERR_NETWORK"||!e.response)return ae.NETWORK}return ae.UNKNOWN}function ha(e){const t=e.toLowerCase();return t.includes("login")||t.includes("connexion")?"login":t.includes("logout")||t.includes("déconnexion")?"logout":t.includes("register")||t.includes("inscription")?"register":t.includes("upload")||t.includes("téléchargement")?t.includes("large")||t.includes("volumineux")?"fileTooLarge":t.includes("format")||t.includes("type")?"invalidFormat":"uploadFailed":t.includes("not found")||t.includes("introuvable")?"notFound":t.includes("access denied")||t.includes("permission")?"accessDenied":t.includes("create")||t.includes("créer")?"createFailed":t.includes("update")||t.includes("mise à jour")?"updateFailed":t.includes("delete")||t.includes("suppression")?"deleteFailed":""}const yr={timeout:ae.TIMEOUT};function pa(e){if(e instanceof Error)return e.message===yr.timeout||e.message.includes("timeout")||e.message.includes("expired")||e.name==="TimeoutError";if(e&&typeof e=="object"&&"code"in e){const t=e.code;return t==="ECONNABORTED"||t==="ETIMEDOUT"}return!1}function ga(){return typeof navigator>"u"?!0:navigator.onLine}function ya(){return!ga()}function B(e){if(xa(e))return e;if(ba(e)){const t=e,r=t.response?.data,a=l=>typeof l=="object"&&l!==null&&"success"in l&&l.success===!1&&"error"in l,n=l=>typeof l=="object"&&l!==null&&"error"in l&&typeof l.error=="object",i=l=>typeof l=="object"&&l!==null&&"code"in l&&"message"in l;if(r){if(a(r))return pt(r.error);if(n(r)){const l=r.error;if(l&&("code"in l||"message"in l))return pt(l)}if(i(r))return pt(r)}if(t.request&&!t.response)return pa(t)?{code:0,message:yr.timeout,timestamp:new Date().toISOString()}:t.code==="ECONNREFUSED"||t.code==="ERR_CONNECTION_REFUSED"?{code:0,message:"Connection refused: The server is not responding. Please try again later.",timestamp:new Date().toISOString()}:t.code==="ENETUNREACH"||t.code==="ERR_NETWORK"||t.code==="ERR_INTERNET_DISCONNECTED"||ya()?{code:0,message:"No internet connection: Please check your network settings and try again.",timestamp:new Date().toISOString()}:{code:0,message:"Network error: Unable to connect to server. Please check your connection and try again.",timestamp:new Date().toISOString()};const o=t.response?.status;if(o===429){const l=t.response?.headers||{},p=r,u=l["x-ratelimit-limit"]?parseInt(String(l["x-ratelimit-limit"]),10):void 0,d=l["x-ratelimit-remaining"]?parseInt(String(l["x-ratelimit-remaining"]),10):void 0,h=l["x-ratelimit-reset"]?parseInt(String(l["x-ratelimit-reset"]),10):void 0,v=l["retry-after"]?parseInt(String(l["retry-after"]),10):p?.error?.retry_after||60,y=h?new Date(h*1e3):void 0,k=y?Math.max(0,Math.ceil((y.getTime()-Date.now())/1e3)):v;return{code:429,message:p?.error?.message||"Trop de requêtes. Veuillez patienter avant de réessayer.",timestamp:new Date().toISOString(),details:[{field:"rate_limit",message:`Limite de ${u||"N/A"} requêtes atteinte. Réessayez dans ${k} seconde${k>1?"s":""}.`},...d!==void 0?[{field:"remaining",message:`${d} requête${d>1?"s":""} restante${d>1?"s":""}`}]:[]],retry_after:k}}if(o===503){const l=r;return{code:503,message:l?.message||"Service temporairement indisponible. Veuillez réessayer dans quelques instants.",timestamp:new Date().toISOString(),details:bt(l?.details)}}if(o===502){const l=r;return{code:502,message:l?.message||"Erreur de communication avec le serveur. Veuillez réessayer plus tard.",timestamp:new Date().toISOString(),details:bt(l?.details)}}return o===423?{code:423,message:r?.message||"This action cannot be completed right now. The resource may be locked or your account may be temporarily restricted. Please try again later.",timestamp:new Date().toISOString()}:{code:o||0,message:r?.message||t.message||"An unexpected error occurred",timestamp:new Date().toISOString()}}return e instanceof Error?{code:0,message:e.message||"An unexpected error occurred",timestamp:new Date().toISOString()}:{code:0,message:"An unexpected error occurred",timestamp:new Date().toISOString()}}function bt(e){if(!Array.isArray(e))return;const t=e.filter(r=>typeof r=="object"&&r!==null&&"field"in r&&"message"in r&&typeof r.field=="string"&&typeof r.message=="string");return t.length>0?t:void 0}function va(e){if(typeof e=="object"&&e!==null&&!Array.isArray(e))return e}function pt(e){const t=e;return{code:typeof t.code=="number"?t.code:parseInt(String(t.code||0),10),message:typeof t.message=="string"?t.message:"An error occurred",details:bt(t.details),request_id:typeof t.request_id=="string"?t.request_id:void 0,timestamp:typeof t.timestamp=="string"?t.timestamp:new Date().toISOString(),context:va(t.context)}}function dl(e,t=!1){const r=typeof e.message=="string"?e.message:"An error occurred";let a=r;if(e.details&&Array.isArray(e.details)&&e.details.length>0){const n=e.details.map(i=>{const o=typeof i.field=="string"?i.field:String(i.field),c=typeof i.message=="string"?i.message:String(i.message);return`${o}: ${c}`}).join(", ");a=`${r} (${n})`}return t&&e.request_id&&(a=`${a} [Request ID: ${e.request_id}]`),a}function it(e){if(e&&typeof e=="object"&&"isAxiosError"in e){const t=e;if(!t.response&&t.request)return"network";if(t.code==="ECONNABORTED"||t.code==="ETIMEDOUT")return"timeout"}if(e&&typeof e=="object"&&"code"in e){const t=e,r=typeof t.code=="number"?t.code:parseInt(String(t.code||0),10);if(r===0)return"network";if(r>=400&&r<500)return r===401?"authentication":r===403?"authorization":r===404?"not_found":r===422?(t.details&&Array.isArray(t.details)&&t.details.length>0,"validation"):r===429?"rate_limit":"validation";if(r>=500&&r<600)return r===504||r===408?"timeout":"server_error"}if(e instanceof Error){const t=e.message.toLowerCase(),r=e.name.toLowerCase();if(t.includes("network")||t.includes("fetch")||t.includes("connection")||t.includes("offline")||r==="networkerror"||r==="typeerror")return"network";if(t.includes("timeout")||r==="timeouterror")return"timeout";if(t.includes("abort")||r==="aborterror")return"network"}return"unknown"}function xa(e){return typeof e=="object"&&e!==null&&"code"in e&&"message"in e&&typeof e.code=="number"&&typeof e.message=="string"}function ba(e){return typeof e=="object"&&e!==null&&"isAxiosError"in e&&e.isAxiosError===!0}class wa{token=null;refreshPromise=null;async refreshToken(){return this.refreshPromise?this.refreshPromise:(this.refreshPromise=(async()=>{try{const r=(await D.get("/csrf-token")).data;return this.token=r.csrf_token,this.token}catch(t){throw g.error("Failed to fetch CSRF token:",{error:t}),t}finally{this.refreshPromise=null}})(),this.refreshPromise)}getToken(){return this.token}async ensureToken(){return this.token?this.token:this.refreshToken()}clearToken(){this.token=null,this.refreshPromise=null}clearCsrfToken(){this.clearToken()}async refreshCsrfToken(){return this.refreshToken()}getCsrfHeaders(){const t=this.getToken();return t?{"X-CSRF-Token":t}:{}}}const G=new wa;class ka{queue=[];isProcessing=!1;maxQueueSize=100;defaultMaxRetries=3;defaultRetryDelay=1e3;constructor(){this.loadQueue(),typeof window<"u"&&(window.addEventListener("online",()=>{g.info("[OfflineQueue] Connection restored, processing queue"),this.processQueue()}),navigator.onLine&&this.queue.length>0&&setTimeout(()=>{this.processQueue()},1e3))}isOffline(){return typeof navigator>"u"?!1:!navigator.onLine}generateRequestId(){return`req_${Date.now()}_${Math.random().toString(36).substr(2,9)}`}async queueRequest(t,r={}){const{priority:a="normal"}=r;if(this.queue.length>=this.maxQueueSize){const c=this.queue.findIndex(l=>l.priority==="low");c!==-1?this.queue.splice(c,1):this.queue.shift()}const n={id:this.generateRequestId(),config:t,timestamp:Date.now(),retryCount:0,priority:a},i={high:0,normal:1,low:2},o=this.queue.findIndex(c=>i[c.priority]>i[a]);return o===-1?this.queue.push(n):this.queue.splice(o,0,n),await this.saveQueue(),g.info(`[OfflineQueue] Request queued: ${t.method?.toUpperCase()} ${t.url}`,{requestId:n.id,priority:a,queueSize:this.queue.length}),n.id}async processQueue(){if(!(this.isProcessing||this.isOffline()||this.queue.length===0)){for(this.isProcessing=!0,g.info(`[OfflineQueue] Processing ${this.queue.length} queued requests`);this.queue.length>0&&!this.isOffline();){const t=this.queue[0];try{await D.request(t.config),this.queue.shift(),await this.saveQueue(),g.info(`[OfflineQueue] Request succeeded: ${t.config.method?.toUpperCase()} ${t.config.url}`,{requestId:t.id}),await new Promise(r=>setTimeout(r,100))}catch(r){t.retryCount++;const a=this.defaultMaxRetries;if(t.retryCount>=a?(g.error(`[OfflineQueue] Request failed after ${a} retries: ${t.config.method?.toUpperCase()} ${t.config.url}`,{requestId:t.id,error:r}),this.queue.shift(),await this.saveQueue()):(this.queue.shift(),this.queue.push(t),await this.saveQueue(),await new Promise(n=>setTimeout(n,this.defaultRetryDelay*t.retryCount))),this.isOffline()){g.warn("[OfflineQueue] Connection lost, stopping queue processing");break}}}this.isProcessing=!1,this.queue.length>0?g.info(`[OfflineQueue] Queue processing complete, ${this.queue.length} requests remaining`):g.info("[OfflineQueue] All queued requests processed successfully")}}getQueueSize(){return this.queue.length}getQueue(){return[...this.queue]}async clearQueue(){this.queue=[],await this.saveQueue(),g.info("[OfflineQueue] Queue cleared")}async removeRequest(t){const r=this.queue.findIndex(a=>a.id===t);return r!==-1?(this.queue.splice(r,1),await this.saveQueue(),g.info(`[OfflineQueue] Request removed from queue: ${t}`),!0):!1}async saveQueue(){try{if(typeof window<"u"&&window.localStorage){const t=JSON.stringify(this.queue);localStorage.setItem("veza_offline_queue",t)}}catch(t){g.error("[OfflineQueue] Failed to save queue to localStorage",{error:t})}}async loadQueue(){try{if(typeof window<"u"&&window.localStorage){const t=localStorage.getItem("veza_offline_queue");if(t){const r=JSON.parse(t),a=Date.now()-1440*60*1e3;this.queue=r.filter(n=>n.timestamp>a),this.queue.length!==r.length&&await this.saveQueue(),g.info(`[OfflineQueue] Loaded ${this.queue.length} requests from storage`)}}}catch(t){g.error("[OfflineQueue] Failed to load queue from localStorage",{error:t}),this.queue=[]}}shouldQueueRequest(t){const r=t.method?.toUpperCase();return r==="GET"?!1:["POST","PUT","DELETE","PATCH"].includes(r||"")}}const de=new ka;class Ea{cache=new Map;defaultCacheTime=1e3;generateRequestKey(t){const r=(t.method||"GET").toUpperCase(),a=t.url||"",n=t.baseURL||"",i=a.startsWith("http")?a:`${n}${a}`,o=t.params?Object.keys(t.params).sort().map(l=>`${l}=${JSON.stringify(t.params[l])}`).join("&"):"";let c="";if(t.data)if(t.data instanceof FormData)c="[FormData]";else try{c=JSON.stringify(t.data)}catch{c=String(t.data)}return`${r}:${i}${o?`?${o}`:""}${c?`|${c}`:""}`}shouldDeduplicate(t){const r=(t.method||"GET").toUpperCase();if(["GET","HEAD","OPTIONS"].includes(r))return!0;const a=t?._enableDeduplication!==!1;return t?._disableDeduplication===!0?!1:a}async getOrCreateRequest(t,r,a={}){const{enabled:n=!0,cacheTime:i=this.defaultCacheTime}=a;if(!n||!this.shouldDeduplicate(t))return r();const o=this.generateRequestKey(t),c=this.cache.get(o);if(c)return c.resolveCount++,g.debug(`[RequestDeduplication] Reusing request: ${t.method?.toUpperCase()} ${t.url}`,{key:o,resolveCount:c.resolveCount}),c.promise;const l=r().then(p=>(setTimeout(()=>{const u=this.cache.get(o);u&&u.promise===l&&(this.cache.delete(o),g.debug(`[RequestDeduplication] Removed from cache: ${o}`))},i),p)).catch(p=>{const u=this.cache.get(o);throw u&&u.promise===l&&(this.cache.delete(o),g.debug(`[RequestDeduplication] Removed from cache (error): ${o}`)),p});return this.cache.set(o,{promise:l,timestamp:Date.now(),resolveCount:1}),g.debug(`[RequestDeduplication] New request: ${t.method?.toUpperCase()} ${t.url}`,{key:o,cacheSize:this.cache.size}),l}clearCache(){const t=this.cache.size;this.cache.clear(),g.info(`[RequestDeduplication] Cache cleared (${t} entries)`)}getCacheStats(){const t=Array.from(this.cache.entries()).map(([r,a])=>({key:r,resolveCount:a.resolveCount,age:Date.now()-a.timestamp}));return{size:this.cache.size,entries:t}}cleanup(t=6e4){const r=Date.now();let a=0;for(const[n,i]of this.cache.entries())r-i.timestamp>t&&(this.cache.delete(n),a++);a>0&&g.debug(`[RequestDeduplication] Cleaned up ${a} old cache entries`)}}const _a=new Ea;typeof window<"u"&&setInterval(()=>{_a.cleanup(6e4)},300*1e3);class Sa{cache=new Map;defaultTTL=300*1e3;maxSize=100;respectCacheControl=!0;enableETag=!0;constructor(t={}){this.defaultTTL=t.defaultTTL||this.defaultTTL,this.maxSize=t.maxSize||this.maxSize,this.respectCacheControl=t.respectCacheControl!==!1,this.enableETag=t.enableETag!==!1}generateCacheKey(t){const r=(t.method||"GET").toUpperCase(),a=t.url||"",n=t.baseURL||"",i=a.startsWith("http")?a:`${n}${a}`,o=t.params?Object.keys(t.params).sort().map(l=>`${l}=${JSON.stringify(t.params[l])}`).join("&"):"",c=t.headers?.Authorization||"";return`${r}:${i}${o?`?${o}`:""}:${c}`}parseCacheControl(t){if(!t)return{};const r={},a=t.split(",").map(n=>n.trim());for(const n of a)if(n.includes("=")){const[i,o]=n.split("=").map(c=>c.trim());r[i.toLowerCase()]=o}else r[n.toLowerCase()]=!0;return{maxAge:r["max-age"]?parseInt(String(r["max-age"]),10):void 0,noCache:r["no-cache"]===!0,noStore:r["no-store"]===!0,mustRevalidate:r["must-revalidate"]===!0}}isCacheValid(t,r){const n=Date.now()-t.timestamp;if(t.maxAge){const i=t.maxAge*1e3;if(n>i)return!1}else if(n>this.defaultTTL)return!1;if(this.enableETag&&t.etag){const i=r.headers?.["If-None-Match"];if(i&&i!==t.etag)return!1}if(t.lastModified){const i=r.headers?.["If-Modified-Since"];if(i){const o=new Date(t.lastModified).getTime(),c=new Date(i).getTime();if(o<c)return!1}}return!0}get(t){if((t.method||"GET").toUpperCase()!=="GET"||t?._disableCache===!0)return null;const a=this.generateCacheKey(t),n=this.cache.get(a);if(!n)return null;if(!this.isCacheValid(n,t))return this.cache.delete(a),g.debug(`[ResponseCache] Cache expired: ${t.url}`),null;const i={data:n.data,status:n.status,statusText:n.statusText,headers:n.headers,config:t,request:{}};return g.debug(`[ResponseCache] Cache hit: ${t.url}`,{key:a,age:Date.now()-n.timestamp}),i}set(t,r){if((t.method||"GET").toUpperCase()!=="GET"||t?._disableCache===!0)return;const n=r.headers["cache-control"]||r.headers["Cache-Control"],i=this.parseCacheControl(n);if(i.noStore||i.noCache){g.debug(`[ResponseCache] Not caching (no-store/no-cache): ${t.url}`);return}let o;this.respectCacheControl&&i.maxAge?o=i.maxAge:o=Math.floor(this.defaultTTL/1e3);const c=r.headers.etag||r.headers.ETag,l=r.headers["last-modified"]||r.headers["Last-Modified"],p=this.generateCacheKey(t);if(this.cache.size>=this.maxSize&&!this.cache.has(p)){const u=this.cache.keys().next().value;u&&this.cache.delete(u)}this.cache.set(p,{data:r.data,headers:r.headers,status:r.status,statusText:r.statusText,timestamp:Date.now(),etag:c,lastModified:l,maxAge:o}),g.debug(`[ResponseCache] Cached: ${t.url}`,{key:p,maxAge:o,etag:c?"present":"none"})}invalidate(t){let r=0;for(const a of this.cache.keys())(typeof t=="string"?a.includes(t):t.test(a))&&(this.cache.delete(a),r++);return r>0&&g.info(`[ResponseCache] Invalidated ${r} cache entries for pattern: ${t}`),r}clear(){const t=this.cache.size;this.cache.clear(),g.info(`[ResponseCache] Cache cleared (${t} entries)`)}getStats(){const t=Array.from(this.cache.entries()).map(([r,a])=>({key:r,age:Date.now()-a.timestamp,maxAge:a.maxAge}));return{size:this.cache.size,maxSize:this.maxSize,entries:t}}cleanup(){const t=Date.now();let r=0;for(const[a,n]of this.cache.entries()){const i=t-n.timestamp,o=(n.maxAge||Math.floor(this.defaultTTL/1e3))*1e3;i>o&&(this.cache.delete(a),r++)}return r>0&&g.debug(`[ResponseCache] Cleaned up ${r} expired cache entries`),r}}const ge=new Sa({defaultTTL:300*1e3,maxSize:100,respectCacheControl:!0,enableETag:!0});typeof window<"u"&&setInterval(()=>{ge.cleanup()},60*1e3);function $t(e={}){const{target:t="all",resourceType:r,resourceId:a,invalidateAll:n=!1,queryKeys:i=[],storeNames:o=[]}=e;try{(t==="cache"||t==="all")&&(n?(ge.clear(),g.debug("[StateInvalidation] Cleared all response cache")):r&&Na(r,a)),(t==="queries"||t==="all")&&Ta(i,r,a),(t==="stores"||t==="all")&&ja(o,r,a),g.debug("[StateInvalidation] State invalidated",{target:t,resourceType:r,resourceId:a,invalidateAll:n})}catch(c){g.error("[StateInvalidation] Error invalidating state",{error:String(c)})}}function Na(e,t){const r={tracks:["/tracks","/library/tracks"],playlists:["/playlists"],users:["/users","/auth/me"],conversations:["/conversations"],roles:["/roles"],library:["/library","/tracks"],auth:["/auth"],ui:[],all:[]};if(e==="all"){ge.clear();return}const a=r[e]||[];for(const n of a)ge.invalidate(n);if(t)for(const n of a)ge.invalidate(`${n}/${t}`)}function Ta(e,t,r){const a=Js();if(!a){if(g.warn("[StateInvalidation] QueryClient not available, falling back to event system"),typeof window<"u"){const n=new CustomEvent("veza:invalidate-queries",{detail:{queryKeys:e,resourceType:t,resourceId:r}});window.dispatchEvent(n)}return}if(e&&e.length>0)for(const n of e)a.invalidateQueries({queryKey:n});if(t){const i={tracks:[["tracks"],["track"],["library"]],playlists:[["playlists"],["playlist"]],users:[["users"],["user"],["auth"],["userProfile"]],conversations:[["conversations"],["conversation"],["chat"],["chatConversations"]],roles:[["roles"],["role"]],library:[["library"],["tracks"],["favorites"],["libraryItems"]],auth:[["auth"],["user"]],ui:[],all:[]}[t]||[];for(const o of i)a.invalidateQueries({queryKey:r?[...o,r]:o})}g.debug("[StateInvalidation] Invalidated React Query cache",{queryKeys:e,resourceType:t,resourceId:r})}function ja(e,t,r){const a={tracks:["library"],playlists:["library"],users:["auth"],conversations:["chat"],roles:[],library:["library"],auth:["auth"],ui:["ui"],all:["auth","library","chat","ui"]},n=e.length>0?e:t?a[t]||[]:[];for(const i of n)Ca(i).catch(o=>{g.warn(`[StateInvalidation] Failed to invalidate store ${i}`,{error:String(o)})})}async function Ca(e,t,r){try{switch(e){case"auth":{const{useAuthStore:a}=await N(async()=>{const{useAuthStore:n}=await Promise.resolve().then(()=>we);return{useAuthStore:n}},void 0);a.getState().refreshUser?.();break}case"library":break;case"chat":break;case"ui":break;default:g.warn(`[StateInvalidation] Unknown store: ${e}`)}}catch(a){g.error(`[StateInvalidation] Error invalidating store ${e}`,{error:String(a)})}}function Ra(e,t){if(!e)return;let r,a;if(e.includes("/tracks/")){r="tracks";const n=e.match(/\/tracks\/([^/]+)/);a=n?n[1]:void 0}else if(e.includes("/playlists/")){r="playlists";const n=e.match(/\/playlists\/([^/]+)/);a=n?n[1]:void 0}else if(e.includes("/users/")||e.includes("/auth/")){r="users";const n=e.match(/\/(users|auth)\/([^/]+)/);a=n?n[2]:void 0}else if(e.includes("/conversations/")){r="conversations";const n=e.match(/\/conversations\/([^/]+)/);a=n?n[1]:void 0}else if(e.includes("/roles/")){r="roles";const n=e.match(/\/roles\/([^/]+)/);a=n?n[1]:void 0}$t(r?{resourceType:r,resourceId:a,target:"all"}:{target:"cache",invalidateAll:!0})}function Aa(e){if(e!=null)return typeof e=="string"?e:String(e)}function wt(e,t=["id","user_id","track_id","playlist_id","conversation_id","message_id","sender_id","creator_id","created_by","parent_id","parent_message_id"]){if(!e||typeof e!="object")return e;const r={...e};for(const[a,n]of Object.entries(r))t.includes(a)?r[a]=Aa(n):n&&typeof n=="object"&&!Array.isArray(n)&&!(n instanceof Date)?r[a]=wt(n,t):Array.isArray(n)&&n.length>0&&typeof n[0]=="object"&&(r[a]=n.map(i=>typeof i=="object"&&i!==null?wt(i,t):i));return r}const Se="1.2.0";function Oe(e,t=Se,r){return Object.defineProperty(e,"_version",{value:t,enumerable:!1,writable:!1}),r&&Object.defineProperty(e,"_description",{value:r,enumerable:!1,writable:!1}),e}const R=b().uuid("Invalid UUID format"),Q=b().datetime({message:"Invalid ISO8601 date format"}),ze=Oe(T({id:R,username:b().min(1),slug:b().optional(),email:b().email(),first_name:b().optional().nullable(),last_name:b().optional().nullable(),avatar:b().optional().nullable(),bio:b().optional().nullable(),location:b().optional().nullable(),birthdate:Q.optional().nullable(),gender:b().optional().nullable(),username_changed_at:Q.optional().nullable(),role:se(["user","admin","super_admin"]),is_active:re(),is_verified:re(),is_banned:re().optional(),is_admin:re(),is_public:re(),last_login_at:Q.optional().nullable(),created_at:Q,updated_at:Q,is_2fa_enabled:re().optional(),social_links:De(me()).optional().nullable()}),Se,"User response schema - matches backend User model"),Pa=T({id:R,conversation_id:R,sender_id:R,content:b(),message_type:se(["text","image","audio","file"]),attachment_url:b().url().optional(),created_at:Q,updated_at:Q,sender:ze.optional()});T({id:R,name:b(),type:se(["direct","group"]),creator_id:R,created_at:Q,updated_at:Q,participants:ne(ze).optional(),last_message:Pa.optional(),unread_count:z().int().nonnegative().optional()});const vr=Oe(T({id:R,creator_id:R,file_id:R.optional().nullable(),title:b().min(1),artist:b().min(1),album:b(),duration:z().int().nonnegative(),genre:b(),year:z().int().min(1900).max(2100),file_path:b(),file_size:z().nonnegative(),format:b(),bitrate:z().nonnegative(),sample_rate:z().nonnegative(),waveform_path:b().optional().nullable(),cover_art_path:b().optional().nullable(),is_public:re(),status:se(["uploading","processing","completed","failed"]),status_message:b().optional().nullable(),stream_status:se(["pending","processing","ready","error"]),stream_manifest_url:b().url().optional().nullable(),play_count:z().int().nonnegative(),like_count:z().int().nonnegative(),created_at:Q,updated_at:Q,user:ze.optional(),is_premium:re().optional(),lyrics:ne(T({time:z(),text:b()})).optional(),waveform_data:ne(z()).optional(),tags:ne(b()).optional()}),Se,"Track response schema - matches backend Track model");Oe(T({id:R,user_id:R,title:b().min(1),description:b().optional().nullable(),visibility:se(["public","private","unlisted"]).optional(),is_public:re(),cover_url:b().url().optional().nullable(),track_count:z().int().nonnegative(),follower_count:z().int().nonnegative(),created_at:Q,updated_at:Q,tracks:ne(vr).optional(),user:ze.optional(),playlist_tracks:ne(me()).optional(),collaborators:ne(me()).optional()}),Se,"Playlist response schema - matches backend Playlist model");T({id:R,user_id:R,ip_address:b(),user_agent:b(),revoked_at:Q.optional().nullable(),expires_at:Q,created_at:Q});T({id:R,user_id:R.optional().nullable(),action:b(),resource:b(),resource_id:R.optional().nullable(),metadata:De(me()).optional().nullable(),ip_address:b().optional().nullable(),user_agent:b().optional().nullable(),timestamp:Q});Oe(T({code:z().int(),message:b(),details:ne(T({field:b(),message:b(),value:b().optional()})).optional(),request_id:b().optional(),timestamp:Q,context:De(me()).optional(),retry_after:z().int().positive().optional()}),Se,"API Error response schema - matches backend error format");Oe(T({page:z().int().positive(),limit:z().int().positive(),total:z().int().nonnegative(),total_pages:z().int().nonnegative(),has_next:re(),has_prev:re(),next_cursor:b().optional(),prev_cursor:b().optional()}),Se,"Pagination metadata schema");T({id:R,user_id:R,type:se(["new_message","track_uploaded","user_mentioned","system"]),content:b(),read:re(),created_at:Q});T({id:R,playlist_id:R,track_id:R,position:z().int().nonnegative(),added_by:R,added_at:Q,track:vr.optional()});T({id:R,playlist_id:R,user_id:R,role:se(["owner","editor","viewer"]),created_at:Q,user:ze.optional()});function Ia(e,t,r={}){const{normalizeIds:a=!0}=r;let n=t;return a&&typeof t=="object"&&t!==null&&(n=wt(t)),e.parse(n)}function Qt(e,t,r={}){try{return{success:!0,data:Ia(e,t,r)}}catch(a){if(a instanceof Nt)return{success:!1,error:a};throw a}}const Fe=b().email("Invalid email format"),ot=b().min(8,"Password must be at least 8 characters"),lt=b().min(3,"Username must be at least 3 characters").max(30,"Username must be at most 30 characters").regex(/^[a-zA-Z0-9_]+$/,"Username can only contain letters, numbers, and underscores");T({email:Fe,password:b().min(1,"Password is required")});T({username:lt,email:Fe,password:ot,first_name:b().max(100).optional(),last_name:b().max(100).optional()});T({code:b().min(6,"TOTP code must be at least 6 characters").max(6,"TOTP code must be exactly 6 characters"),secret:b().min(1,"Secret is required")});T({password:ot});T({username:lt,email:Fe,password:ot});T({username:lt.optional(),email:Fe.optional(),password:ot.optional()});T({first_name:b().max(100).optional(),last_name:b().max(100).optional(),username:lt.optional(),bio:b().max(500).optional(),location:b().max(100).optional(),birthdate:b().regex(/^\d{4}-\d{2}-\d{2}$/,"Invalid date format. Use YYYY-MM-DD").optional(),gender:se(["Male","Female","Other","Prefer not to say"]).optional()});T({conversation_id:R,content:b().min(1,"Message content is required"),message_type:se(["text","image","audio","file"]).optional(),attachment_url:b().url().optional()});T({content:b().min(1,"Message content is required").optional()});T({name:b().min(1,"Conversation name is required"),type:se(["direct","group"]),participant_ids:ne(R).min(1,"At least one participant is required")});T({name:b().min(1,"Conversation name is required").optional()});T({track_ids:ne(R).min(1,"At least one track ID is required")});T({filename:b().min(1,"Filename is required"),total_chunks:z().int().min(1,"Total chunks must be at least 1"),total_size:z().int().min(1,"Total size must be at least 1")});T({upload_id:b().min(1,"Upload ID is required")});T({upload_id:b().min(1,"Upload ID is required"),chunk_number:z().int().min(0,"Chunk number must be non-negative"),total_chunks:z().int().min(1,"Total chunks must be at least 1"),total_size:z().int().min(1,"Total size must be at least 1"),filename:b().min(1,"Filename is required")});T({event_name:b().min(1,"Event name is required").max(100,"Event name must be at most 100 characters"),payload:De(me()).optional()});T({url:b().url("Invalid webhook URL"),events:ne(b()).min(1,"At least one event is required"),secret:b().min(1,"Secret is required").optional()});T({level:b().optional(),message:b().optional(),context:De(me()).optional(),timestamp:b().optional(),data:me().optional()});T({email:Fe});T({title:b().min(1,"Track title is required"),artist_id:R,album_id:R.optional(),genre:b().min(1,"Genre is required")});T({title:b().min(1,"Track title is required").optional(),artist_id:R.optional(),album_id:R.optional(),genre:b().min(1,"Genre is required").optional()});const Ve=T({page:z().int().positive().optional(),limit:z().int().positive().max(100).optional(),cursor:b().optional()});Ve.extend({query:b().optional()});Ve.extend({conversation_id:R});Ve.extend({query:b().optional()});Ve.extend({artist:b().optional(),genre:b().optional()});Ve.extend({query:b().min(1,"Search query is required")});T({type:se(["image","audio","document"])});function La(e,t){return e.parse(t)}function qa(e,t){try{return{success:!0,data:La(e,t)}}catch(r){if(r instanceof Nt)return{success:!1,error:r};throw r}}const Bt={limit:null,remaining:null,reset:null,retryAfter:null,isLimited:!1,lastUpdated:null},kt=Le()(qe(e=>({...Bt,updateRateLimit:t=>{const r=t.limit!==null&&t.limit!==void 0?typeof t.limit=="string"?parseInt(t.limit,10):t.limit:null,a=t.remaining!==null&&t.remaining!==void 0?typeof t.remaining=="string"?parseInt(t.remaining,10):t.remaining:null,n=t.reset!==null&&t.reset!==void 0?typeof t.reset=="string"?parseInt(t.reset,10):t.reset:null,i=t.retryAfter!==null&&t.retryAfter!==void 0?typeof t.retryAfter=="string"?parseInt(t.retryAfter,10):t.retryAfter:null,o=a!==null&&a<=0||i!==null;e({limit:r,remaining:a,reset:n,retryAfter:i,isLimited:o,lastUpdated:Date.now()})},clearRateLimit:()=>{e(Bt)}}),{name:"rate-limit-storage",partialize:e=>({limit:e.limit,remaining:e.remaining,reset:e.reset,retryAfter:e.retryAfter,isLimited:e.isLimited,lastUpdated:null})}));class Da{metrics={totalValidations:0,successfulValidations:0,failedValidations:0,failureRate:0,failuresByEndpoint:{}};recordSuccess(t){this.metrics.totalValidations++,this.metrics.successfulValidations++,this.metrics.lastSuccessTime=new Date().toISOString(),this.updateFailureRate()}recordFailure(t){if(this.metrics.totalValidations++,this.metrics.failedValidations++,this.metrics.lastFailureTime=new Date().toISOString(),t){const r=this.normalizeEndpoint(t);this.metrics.failuresByEndpoint[r]=(this.metrics.failuresByEndpoint[r]||0)+1}this.updateFailureRate()}updateFailureRate(){this.metrics.totalValidations>0&&(this.metrics.failureRate=this.metrics.failedValidations/this.metrics.totalValidations*100)}normalizeEndpoint(t){if(!t)return"unknown";try{return new URL(t,"http://localhost").pathname.replace(/\/[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}/gi,"/:id").replace(/\/\d+/g,"/:id")}catch{return t.split("?")[0]||"unknown"}}getMetrics(){return{...this.metrics}}reset(){this.metrics={totalValidations:0,successfulValidations:0,failedValidations:0,failureRate:0,failuresByEndpoint:{}}}}const Je=new Da,Kt={failureRateThreshold:5,minValidationsForAlert:10,checkInterval:300*1e3};class Ma{config=Kt;checkIntervalId=null;lastAlertTime=0;alertCooldown=900*1e3;start(t){this.checkIntervalId&&this.stop(),this.config={...Kt,...t},typeof window<"u"&&(setTimeout(()=>this.checkMetrics(),60*1e3),this.checkIntervalId=setInterval(()=>this.checkMetrics(),this.config.checkInterval))}stop(){this.checkIntervalId&&(clearInterval(this.checkIntervalId),this.checkIntervalId=null)}checkMetrics(){const t=Je.getMetrics();if(!(t.totalValidations<this.config.minValidationsForAlert)&&t.failureRate>this.config.failureRateThreshold){const r=Date.now();if(r-this.lastAlertTime<this.alertCooldown)return;this.lastAlertTime=r,g.error("[API Validation Alert] High validation failure rate detected",{alert_type:"high_validation_failure_rate",failure_rate:t.failureRate.toFixed(2),threshold:this.config.failureRateThreshold,total_validations:t.totalValidations,failed_validations:t.failedValidations,successful_validations:t.successfulValidations,last_failure_time:t.lastFailureTime,failures_by_endpoint:t.failuresByEndpoint,timestamp:new Date().toISOString()})}}updateConfig(t){this.config={...this.config,...t}}}const xr=new Ma;typeof window<"u"&&xr.start();const br={DEFAULT:1e4,UPLOAD:3e5,LONG_POLLING:3e4},Et=1e3,D=Pe.create({baseURL:nt.API_URL,timeout:br.DEFAULT,headers:{"Content-Type":"application/json"},withCredentials:!0});let Ke=!1,fe=0;const gt=3;let ke=[];const Oa=e=>new Promise(t=>setTimeout(t,e)),he={maxRetries:3,baseDelay:1e3,maxDelay:1e4,retryableStatusCodes:[500,502,503,504],retryableNetworkErrors:["ECONNABORTED","ETIMEDOUT","ENOTFOUND","ECONNREFUSED","ECONNRESET","EAI_AGAIN","Network Error"]},_t=e=>e?["GET","HEAD","OPTIONS"].includes(e.toUpperCase()):!1;class za{recentRequests=[];windowSize=10;windowMs=3e4;recordRequest(t){const r=Date.now();this.recentRequests.push({success:t,timestamp:r}),this.recentRequests=this.recentRequests.filter(a=>r-a.timestamp<this.windowMs),this.recentRequests.length>this.windowSize&&(this.recentRequests=this.recentRequests.slice(-this.windowSize))}isPartialFailure(){if(this.recentRequests.length===0)return!1;const t=this.recentRequests.filter(a=>a.success).length,r=this.recentRequests.filter(a=>!a.success).length;return t>0&&r>0}isCompleteFailure(){return this.recentRequests.length===0?!1:this.recentRequests.every(t=>!t.success)}reset(){this.recentRequests=[]}}const Ct=new za,wr=e=>!!(e.response?.status===206||e.code==="ECONNABORTED"&&e.message?.toLowerCase().includes("timeout")&&e.request||e.code==="ECONNRESET"&&e.response||Ct.isPartialFailure()),Fa=e=>!!(!e.response&&!e.request||e.code==="ECONNREFUSED"||e.code==="ERR_CONNECTION_REFUSED"||e.code==="ENETUNREACH"||e.code==="ERR_NETWORK"||e.code==="ERR_INTERNET_DISCONNECTED"||Ct.isCompleteFailure()),Va=(e,t=he)=>{if(Pe.isCancel(e)||e.config?._disableRetry)return!1;if(wr(e))return _t(e.config?.method);if(e.response?.status)return t.retryableStatusCodes.includes(e.response.status);if(e.code)return t.retryableNetworkErrors.includes(e.code);if(e.message){const r=e.message.toLowerCase();return["network","timeout","connection","econn","etimedout","enotfound"].some(n=>r.includes(n))}return!e.response&&e.request?_t(e.config?.method):!1},Ua=(e,t,r=he.baseDelay,a=he.maxDelay)=>{const n=e.response?.headers["retry-after"]||e.response?.headers["Retry-After"];if(n){const c=parseInt(String(n),10);if(!isNaN(c)&&c>0)return Math.min(c*1e3,a)}const i=r*Math.pow(2,t),o=Math.random()*r;return Math.min(i+o,a)},pe=e=>{if(!e||typeof e!="object")return e;const t=["password","token","access_token","refresh_token","secret","authorization","x-csrf-token"],r=Array.isArray(e)?[...e]:{...e};for(const a in r){const n=a.toLowerCase();t.some(i=>n.includes(i))?r[a]="[REDACTED]":typeof r[a]=="object"&&r[a]!==null&&(r[a]=pe(r[a]))}return r},Ae=e=>{const t=e.headers?.["X-Request-ID"]||e.headers?.["x-request-id"]||`req_${Date.now()}_${Math.random().toString(36).substr(2,9)}`;return e._requestId=t,t},yt=e=>{ke.forEach(t=>{e?t.reject(e):t.resolve(void 0)}),ke=[]};D.interceptors.request.use(async e=>{const t=Date.now();e._requestStartTime=t,e._isSlowRequest=!1,e.headers&&(e.headers["X-API-Version"]=nt.API_VERSION),e.data instanceof FormData&&e.headers&&delete e.headers["Content-Type"];const r=e.method?.toUpperCase(),a=["POST","PUT","DELETE","PATCH"].includes(r||""),n=e.url?.includes("/auth/login")||e.url?.includes("/auth/register"),i=e.url?.includes("/csrf-token");if(a&&!i&&!n&&e.headers){let c=G.getToken();if(!c)try{c=await G.ensureToken()}catch{g.warn("[API] Failed to fetch CSRF token before request, will retry on 403",{url:e.url,method:e.method})}c&&e.headers&&(e.headers["X-CSRF-Token"]=c)}!e.signal&&e.cancelToken;const o=e?._requestSchema;if(o&&e.data!==void 0&&e.data!==null&&!(e.data instanceof FormData)){const c=qa(o,e.data);if(!c.success){const l=Ae(e);g.warn("[API Request Validation Error]",{request_id:l,url:e.url,method:e.method?.toUpperCase(),errors:c.error?.errors.map(u=>({path:u.path.join("."),message:u.message,code:u.code}))},c.error);const p=c.error?.errors.map(u=>`${u.path.join(".")}: ${u.message}`).join(", ")||"Request validation failed";throw new Error(`Request validation failed: ${p}`)}e.data=c.data}if(e._requestStartTime=Date.now(),e?._enableLogging){const c=Ae(e),l=pe({...e.headers}),p=pe(e.data);g.debug(`[API Request] ${r||"GET"} ${e.url}`,{request_id:c,method:r||"GET",url:e.url,baseURL:e.baseURL,headers:l,params:e.params,data:p,timeout:e.timeout,signal:e.signal?"AbortController":void 0})}return e},e=>Promise.reject(e));D.interceptors.response.use(e=>{Ct.recordRequest(!0);const t=e.config?._requestStartTime;if(t){const h=Date.now()-t;h>Et&&(e.config._isSlowRequest=!0,e.config._requestDuration=h,e.config?._enableLogging&&g.debug(`[API Slow Request] ${e.config?.method?.toUpperCase()} ${e.config?.url} took ${h}ms`,{duration:h,threshold:Et}))}const a=e.headers["x-request-id"]||e.headers["X-Request-ID"]||e.config?._requestId;a&&Vt({request_id:a});const n=e.headers["x-ratelimit-limit"]||e.headers["X-RateLimit-Limit"],i=e.headers["x-ratelimit-remaining"]||e.headers["X-RateLimit-Remaining"],o=e.headers["x-ratelimit-reset"]||e.headers["X-RateLimit-Reset"];if((n||i||o)&&kt.getState().updateRateLimit({limit:n,remaining:i,reset:o,retryAfter:null}),e.config?._enableLogging){const h=pe(e.data),v=pe(e.headers);g.debug(`[API Response] ${e.config.method?.toUpperCase()||"GET"} ${e.config.url} ${e.status}`,{request_id:a,status:e.status,statusText:e.statusText,headers:v,data:h,duration:e.config?._requestStartTime?Date.now()-e.config._requestStartTime:void 0})}if((e.headers["x-api-deprecated"]||e.headers["X-API-Deprecated"])==="true"){const h="api_deprecation_warning_shown";if(typeof window<"u"&&!sessionStorage.getItem(h)){const v=e.headers.sunset||e.headers.Sunset,y=v?`This API version is deprecated and will be removed on ${v}. Please update to the latest version.`:"This API version is deprecated. Please update to the latest version.";te(y,{icon:"⚠️",duration:1e4}),sessionStorage.setItem(h,"true"),g.warn("[API] Deprecated API version detected",{url:e.config.url,version:e.headers["x-api-version"]||e.headers["X-API-Version"],sunset_date:v})}}if(!e.data||typeof e.data!="object")return e;const p=e.config.method?.toUpperCase(),u=["POST","PUT","PATCH","DELETE"].includes(p||"");if(u&&e.config?._showSuccessToast&&typeof window<"u"){const h=e.config?._successMessage||e.data?.message||$a(p||"");h&&te.success(h)}if(p==="GET"&&!e.config?._disableCache&&ge.set(e.config,e),u){const h=e.config.url||"";e.config.method,Ra(h)}if("success"in e.data){if(e.data.success===!0){const h=e.data.data!==void 0?e.data.data:null,v=e.config?._responseSchema;if(v&&h!==null){const y=Qt(v,h);if(y.success){const k=Ae(e.config);g.debug("[API Response Validation Success]",{request_id:k,url:e.config.url}),Je.recordSuccess(e.config.url)}else{const k=Ae(e.config),S={request_id:k,url:e.config.url,method:e.config.method?.toUpperCase(),status:e.status,error_type:"api_response_validation_failed",validation_errors:y.error?.errors.map(m=>({path:m.path.join("."),message:m.message,code:m.code,received:m.code==="invalid_type"?m.received:void 0,expected:m.code==="invalid_type"?m.expected:void 0})),response_data_preview:JSON.stringify(h).substring(0,200),schema_provided:!!v,timestamp:new Date().toISOString()};g.error("[API Response Validation Failed]",S,y.error),Je.recordFailure(e.config.url);const _=e.config?._validationRecovery,E=_?.useCache!==!1,I=_?.retry===!0,M=_?.notifyUser!==!1;if(E&&p==="GET"){const m=ge.get(e.config);if(m){let x=m.data;if(x&&typeof x=="object"&&"success"in x&&x.success===!0&&(x=x.data!==void 0?x.data:null),x!==null&&Qt(v,x).success)return g.warn("[API Validation Recovery] Using cached response due to validation failure",{request_id:k,url:e.config.url,recovery_type:"cache_fallback"}),M&&typeof window<"u"&&te("Data may be outdated. Please refresh if issues persist.",{icon:"⚠️",duration:5e3}),{...m,data:x}}}if(I&&!e.config?._validationRetryAttempted)return e.config._validationRetryAttempted=!0,g.warn("[API Validation Recovery] Retrying request due to validation failure",{request_id:k,url:e.config.url,recovery_type:"retry"}),D.request(e.config);M&&typeof window<"u"&&te("Some data may be incomplete. Please refresh if issues persist.",{icon:"⚠️",duration:5e3})}}return{...e,data:h}}if(e.data.success===!1){const h=e.data.error||e.data;g.error("[API] Response with success=false:",{url:e.config.url,error:h});const v=new tt(h?.message||"Request failed","API_ERROR",e.config,e.request,{...e,status:e.status||400,statusText:e.statusText||"Bad Request",data:{success:!1,error:h}});return Promise.reject(v)}}if(e.data&&typeof e.data=="object"&&!("success"in e.data)){const h=Ae(e.config);g.warn("[API] Received non-wrapped response format (unexpected)",{request_id:h,url:e.config.url,method:e.config.method?.toUpperCase(),status:e.status,response_preview:JSON.stringify(e.data).substring(0,200),timestamp:new Date().toISOString()})}return e},async e=>{if(Pe.isCancel(e)){const m=e.config?._requestId;return e.config?._enableLogging&&g.debug(`[API Request Cancelled] ${e.config?.method?.toUpperCase()||"GET"} ${e.config?.url}`,{request_id:m}),Promise.reject(e)}const t=e.config;let r=t?._requestId;if(e.response?.headers){const m=e.response.headers["x-request-id"]||e.response.headers["X-Request-ID"];m&&(r=m,Vt({request_id:r}));const x=e.response.headers["x-ratelimit-limit"]||e.response.headers["X-RateLimit-Limit"],j=e.response.headers["x-ratelimit-remaining"]||e.response.headers["X-RateLimit-Remaining"],F=e.response.headers["x-ratelimit-reset"]||e.response.headers["X-RateLimit-Reset"],$=e.response.headers["retry-after"]||e.response.headers["Retry-After"];(x||j||F||$)&&kt.getState().updateRateLimit({limit:x,remaining:j,reset:F,retryAfter:$})}const a=t?._enableLogging;if(a&&e.response){const m=pe(e.response.data),x=pe(e.response.headers);g.error(`[API Error Response] ${t?.method?.toUpperCase()||"GET"} ${t?.url} ${e.response.status}`,{request_id:r,status:e.response.status,statusText:e.response.statusText,headers:x,data:m,duration:t?._requestStartTime?Date.now()-t._requestStartTime:void 0})}else a&&e.request&&!e.response&&g.error(`[API Network Error] ${t?.method?.toUpperCase()||"GET"} ${t?.url}`,{request_id:r,message:e.message,code:e.code,duration:t?._requestStartTime?Date.now()-t._requestStartTime:void 0});const n=t?.url?.includes("/csrf-token"),i=t?.url?.includes("/auth/login")||t?.url?.includes("/auth/register");if(e.response?.status===403&&t&&!t._csrfRetry&&!n&&!i){const m=e.response?.data,x=(typeof m?.error=="string"?m.error:m?.message||"").toLowerCase();if(x.includes("csrf")||x.includes("token")||x.includes("forbidden")){t._csrfRetry=!0,g.info("[API] CSRF token invalid (403), refreshing and retrying",{request_id:r,url:t?.url,method:t?.method});try{const F=await G.ensureToken();return t.headers&&(t.headers["X-CSRF-Token"]=F),g.debug("[API] CSRF token refreshed, retrying request",{request_id:r,url:t?.url}),D.request(t)}catch(F){g.error("[API] CSRF token refresh failed",{request_id:r,url:t?.url,error:F})}}}const o=t?.url?.includes("/auth/refresh"),c=t?.url?.includes("/auth/logout"),l=t?.url?.includes("/auth/me");if((e.response?.status===401||e.response?.status===400)&&o)return g.error(`[API] ${e.response?.status} on /auth/refresh - refresh token expired/revoked/invalid, logging out`,{request_id:r,url:t?.url,status:e.response?.status}),ee.clearTokens(),G.clearToken(),typeof window<"u"&&(N(async()=>{const{useAuthStore:m}=await Promise.resolve().then(()=>we);return{useAuthStore:m}},void 0).then(({useAuthStore:m})=>{m.getState().logoutLocal()}).catch(m=>{g.error("[API] Failed to import auth store for logout",{error:m})}),sessionStorage.setItem("auth_error","Votre session a expiré. Veuillez vous reconnecter."),window.location.href="/login"),Promise.reject(B(e));if(e.response?.status===401&&c)return g.warn("[API] 401 on /auth/logout - token expired/invalid, clearing tokens locally",{request_id:r,url:t?.url}),ee.clearTokens(),G.clearToken(),typeof window<"u"&&N(async()=>{const{useAuthStore:m}=await Promise.resolve().then(()=>we);return{useAuthStore:m}},void 0).then(({useAuthStore:m})=>{m.getState().logoutLocal()}).catch(m=>{g.error("[API] Failed to import auth store for logout",{error:m})}),Promise.reject(B(e));if(e.response?.status===401&&t&&!t._retry&&!o&&!c&&!l){if(Ke)return g.debug("[API] Refresh already in progress, queuing request",{request_id:r,url:t?.url,queue_size:ke.length}),new Promise((m,x)=>{ke.push({resolve:m,reject:x})}).then(()=>(g.debug("[API] Replaying queued request after successful refresh",{request_id:r,url:t?.url}),D(t))).catch(m=>(g.error("[API] Queued request failed after refresh",{request_id:r,url:t?.url,error:m}),Promise.reject(m)));if(t._retry=!0,Ke=!0,g.info("[API] Starting token refresh due to 401",{request_id:r,url:t?.url,method:t?.method}),fe>=gt)return g.error("[API] Max refresh attempts reached, logging out",{request_id:r,attempts:fe,max_attempts:gt}),fe=0,Ke=!1,ee.clearTokens(),G.clearToken(),typeof window<"u"&&(N(async()=>{const{useAuthStore:m}=await Promise.resolve().then(()=>we);return{useAuthStore:m}},void 0).then(({useAuthStore:m})=>{m.getState().logoutLocal()}).catch(m=>{g.error("[API] Failed to import auth store for logout",{error:m})}),sessionStorage.setItem("auth_error","Votre session a expiré après plusieurs tentatives. Veuillez vous reconnecter."),window.location.href="/login"),yt(new Error("Max refresh attempts reached")),Promise.reject(B(e));fe++;try{return await Ie(),g.info("[API] Token refresh successful, retrying original request",{request_id:r,url:t?.url,queue_size:ke.length,attempt:fe}),fe=0,yt(null),D(t)}catch(m){return g.error("[API] Token refresh failed",{attempt:fe,max_attempts:gt,request_id:r,error:m,queue_size:ke.length}),yt(m),ee.clearTokens(),G.clearToken(),typeof window<"u"&&(N(async()=>{const{useAuthStore:x}=await Promise.resolve().then(()=>we);return{useAuthStore:x}},void 0).then(({useAuthStore:x})=>{x.getState().logoutLocal()}).catch(x=>{g.error("[API] Failed to import auth store for logout",{error:x})}),sessionStorage.setItem("auth_error","Votre session a expiré. Veuillez vous reconnecter."),window.location.href="/login"),Promise.reject(m)}finally{Ke=!1,g.debug("[API] Token refresh process completed",{request_id:r,is_refreshing:!1})}}if(e.response?.status===403&&t&&!t?._csrfRetry&&e.response?.data&&typeof e.response.data=="object"&&(e.response.data?.error?.message?.toLowerCase().includes("csrf")||e.response.data?.message?.toLowerCase().includes("csrf"))){const m=t.method?.toUpperCase();if(["POST","PUT","DELETE","PATCH"].includes(m||"")){t._csrfRetry=!0;try{const j=await G.refreshToken();return t.headers&&j&&(t.headers["X-CSRF-Token"]=j),D(t)}catch(j){g.error("[API] Failed to refresh CSRF token after CSRF error",{error:j});const F=B(e);return Promise.reject(F)}}}const u=e.response?.status,d=t?._retryCount||0,h=he.maxRetries;if(u===429){const m=B(e),x=e.response?.headers["retry-after"]||e.response?.headers["Retry-After"],j=x?parseInt(x,10):60;return g.warn("[API] Rate limit exceeded, not retrying",{url:t?.url,retry_after:j,request_id:m.request_id}),m.message&&te.error(m.message,{duration:j*1e3}),Promise.reject(m)}const y=h,k=t?.url?.includes("/marketplace/products");if(u===500&&k){g.warn("[API] 500 error on marketplace/products, not retrying (likely empty state)",{url:t?.url,retry_count:d,request_id:B(e).request_id});const m=B(e);return m.httpStatus=u,Promise.reject(m)}if(Va(e,he)&&t&&d<y){const m=t.method?.toUpperCase(),x=_t(m);if(!x&&u&&u!==500&&u!==502&&u!==503&&u!==504){const U=B(e);return Promise.reject(U)}t._retryCount=d+1;const j=Ua(e,d,he.baseDelay,he.maxDelay),F=B(e),$=u?`HTTP ${u}`:e.code||"Network Error";return F.request_id?g.warn(`[API Retry] ${$} error, retrying (${d+1}/${y}) - Request ID: ${F.request_id}`,{status:u||"N/A",error_code:e.code||"N/A",retry_count:d+1,max_retries:y,delay_ms:Math.round(j),request_id:F.request_id,url:t?.url,method:t?.method,is_idempotent:x}):g.warn(`[API Retry] ${$} error, retrying (${d+1}/${y})`,{status:u||"N/A",error_code:e.code||"N/A",retry_count:d+1,max_retries:y,delay_ms:Math.round(j),url:t?.url,method:t?.method,is_idempotent:x}),Oa(j).then(()=>D(t))}if(d>=y){const m=B(e),x=u?`HTTP ${u}`:e.code||"Network Error";return m.request_id?g.error(`[API Error] ${x} error after ${h} retries - Request ID: ${m.request_id}`,{code:m.code,message:m.message,request_id:m.request_id,timestamp:m.timestamp,url:t?.url,method:t?.method}):g.error(`[API Error] ${x} error after ${h} retries`,{code:m.code,message:m.message,timestamp:m.timestamp,url:t?.url,method:t?.method}),Promise.reject(m)}const _=B(e);u===401&&!o&&!c&&!l&&typeof window<"u"&&it(_)==="authentication"&&(ee.clearTokens(),G.clearToken(),N(async()=>{const{useAuthStore:x}=await Promise.resolve().then(()=>we);return{useAuthStore:x}},void 0).then(({useAuthStore:x})=>{x.getState().logoutLocal()}).catch(x=>{g.error("[API] Failed to import auth store for logout",{error:x})}),sessionStorage.setItem("auth_error","Votre session a expiré. Veuillez vous reconnecter."),window.location.href="/login");const E=!t?._disableToast&&u!==401&&u!==404&&!Pe.isCancel(e),I=!e.response;if(I){const{recordNetworkError:m}=await N(async()=>{const{recordNetworkError:x}=await Promise.resolve().then(()=>mn);return{recordNetworkError:x}},void 0);m(_)}const M=I?"network-error-toast":void 0;if(E&&typeof window<"u"){const m=t?.url||"";let x;m.includes("/auth/")?x="auth":m.includes("/tracks")||m.includes("/track/")?x="track":m.includes("/playlists")||m.includes("/playlist/")?x="playlist":m.includes("/upload")?x="upload":m.includes("/conversations")||m.includes("/chat")?x="conversation":m.includes("/search")&&(x="search");const F=gr(_,x,u===422);if(!e.response&&t&&de.shouldQueueRequest(t)&&(typeof navigator<"u"&&!navigator.onLine||!e.response&&e.request)){const H=t.method?.toUpperCase(),K=H==="DELETE"?"low":H==="POST"?"high":"normal";try{await de.queueRequest(t,{priority:K}),te.success("Requête mise en file d'attente. Elle sera envoyée à la reconnexion.",{duration:4e3,id:"offline-queue-toast"})}catch(W){g.error("[API] Failed to queue request for offline replay",{error:W})}}const $=wr(e),U=Fa(e);let Y=F;I&&($?Y=`${F} ⚠️ Connexion intermittente détectée. Certaines requêtes réussissent, d'autres échouent. La connexion devrait se rétablir automatiquement.`:U?Y=`${F} ❌ Aucune connexion réseau. Vérifiez votre connexion internet et réessayez.`:Y=`${F} 💡 Vérifiez votre connexion internet. Si le problème persiste, le serveur pourrait être temporairement indisponible.`),($||U)&&g.warn("[API] Network failure detected",{request_id:r,is_partial_failure:$,is_complete_failure:U,url:t?.url,method:t?.method,error_code:e.code,error_message:e.message}),te.error(Y,{duration:8e3,id:M})}return g.error(`[API Error] ${_.message}`,{request_id:_.request_id||r,code:_.code,message:_.message,timestamp:_.timestamp,details:_.details,context:_.context,url:t?.url,method:t?.method}),Promise.reject(_)});function $a(e){switch(e){case"POST":return"Opération réussie";case"PUT":case"PATCH":return"Modification réussie";case"DELETE":return"Suppression réussie";default:return""}}const ml=Object.freeze(Object.defineProperty({__proto__:null,API_TIMEOUTS:br,SLOW_REQUEST_THRESHOLD:Et,apiClient:D,validationAlerting:xr,validationMetrics:Je},Symbol.toStringTag,{value:"Module"}));async function kr(e){try{const t=await D.post("/auth/register",{email:e.email,password:e.password,password_confirmation:e.password_confirm,username:e.username});let r,a,n,i;if(t.data?.token?.access_token?(r=t.data.token.access_token,a=t.data.token.refresh_token||"",n=t.data.token.expires_in,i=t.data.user):t.data?.access_token?(r=t.data.access_token,a=t.data.refresh_token||"",n=t.data.expires_in,i=t.data.user):t.data?.Token?.AccessToken?(r=t.data.Token.AccessToken,a=t.data.Token.RefreshToken||"",n=t.data.Token.ExpiresIn,i=t.data.User||t.data.user):(t.data?.User||t.data?.user)&&(i=t.data.User||t.data.user),r&&(ee.setTokens(r,a||""),jt()),!i)throw new Error("Registration response missing user data");if(!r||n===void 0)throw new Error("Registration response missing tokens. Email verification may be required.");return{user:i,token:{access_token:r,refresh_token:a||"",expires_in:n}}}catch(t){throw B(t)}}async function Er(e){try{const t=await D.post("/auth/login",{email:e.email,password:e.password,remember_me:e.remember_me||!1});let r,a,n,i;if(t.data?.token?.access_token?(r=t.data.token.access_token,a=t.data.token.refresh_token||"",n=t.data.token.expires_in,i=t.data.user):t.data?.access_token?(r=t.data.access_token,a=t.data.refresh_token||"",n=t.data.expires_in,i=t.data.user):t.data?.Token?.AccessToken&&(r=t.data.Token.AccessToken,a=t.data.Token.RefreshToken||"",n=t.data.Token.ExpiresIn,i=t.data.User||t.data.user),t.data?.requires_2fa){if(i||(i=t.data.user||t.data.User),!i)throw new Error("Login response missing user data");return{user:i,token:{access_token:"",refresh_token:"",expires_in:0},requires_2fa:!0}}if(r)ee.setTokens(r,a||""),e.remember_me?localStorage.setItem("remember_me","true"):localStorage.removeItem("remember_me"),jt();else throw g.error("[AUTH] Tokens not found in login response",{responseData:t.data}),new Error("Login response missing tokens");return{user:i,token:{access_token:r,refresh_token:a||"",expires_in:n||3600},requires_2fa:t.data?.requires_2fa}}catch(t){throw B(t)}}async function _r(){try{await D.post("/auth/logout",{},{_disableToast:!0})}catch(e){e?.response?.status===400&&(e?.response?.data?.error?.includes("RefreshToken")||e?.response?.data?.message?.includes("RefreshToken"))||g.warn("Logout API call failed, but tokens will be cleared locally",{error:e instanceof Error?e.message:String(e),stack:e instanceof Error?e.stack:void 0})}finally{pr(),ee.clearTokens()}}async function Rt(){try{return(await D.get("/auth/me")).data}catch(e){throw B(e)}}const fl={login:Er,register:kr,logout:_r,getMe:Rt,refresh:async e=>{const{data:t}=await D.post("/auth/refresh",{refresh_token:e});return t},verifyEmail:async e=>{const{data:t}=await D.post("/auth/verify-email",void 0,{params:{token:e.token}});return t},resendVerification:async e=>{const{data:t}=await D.post("/auth/resend-verification",e);return t},checkUsername:async e=>{const{data:t}=await D.get("/auth/check-username",{params:{username:e.username}});return t},requestPasswordReset:async e=>{const{data:t}=await D.post("/auth/password/reset-request",e);return t},resetPassword:async e=>{const{data:t}=await D.post("/auth/password/reset",e);return t},getOAuthProviders:async()=>{const{data:e}=await D.get("/auth/oauth/providers");return e},initiateOAuth:e=>{window.location.href=`${nt.API_URL}/auth/oauth/${e}`},setup2FA:async()=>{const{data:e}=await D.post("/auth/2fa/setup");return e},verify2FA:async e=>{const{data:t}=await D.post("/auth/2fa/verify",{code:e});return t},disable2FA:async e=>{const{data:t}=await D.post("/auth/2fa/disable",{code:e});return t},get2FAStatus:async()=>{const{data:e}=await D.get("/auth/2fa/status");return e}};function Qa(e){if(typeof window>"u"||!window.BroadcastChannel)return g.warn("[BroadcastSync] BroadcastChannel not supported in this environment"),null;try{return new BroadcastChannel(`veza-store-${e}`)}catch(t){return g.warn(`[BroadcastSync] Failed to create BroadcastChannel for ${e}`,{error:t instanceof Error?t.message:String(t),stack:t instanceof Error?t.stack:void 0,storeName:e}),null}}function Sr(e,t={}){return(r,a,n)=>{const i=t.channelName||"default-store",o=t.enabled!==!1,c=t.shouldSync||(()=>!0),l=t.onStateSync;let p=null,u=!1,d=null,h=0;const v=new Set,y=[];if(o&&(p=Qa(i),p)){const S=()=>{if(y.length===0||u)return;y.sort((E,I)=>I.timestamp-E.timestamp);const _=y.shift();_&&_.timestamp>h&&(u=!0,r(_.state),d=_.state,h=_.timestamp,v.size>100&&Array.from(v).slice(0,50).forEach(I=>v.delete(I)),setTimeout(()=>{u=!1,S()},50))};p.onmessage=_=>{const E=_.data;if(!E||typeof E!="object"||!E.type||!E.storeName||typeof E.timestamp!="number"||E.type!=="state-update"&&E.type!=="state-request"&&E.type!=="state-response"||E.storeName!==i)return;const I=E.messageId||`${E.type}-${E.timestamp}-${Math.random()}`;if(!v.has(I)){if(E.type==="state-update"&&E.state){if(u){y.push({state:E.state,timestamp:E.timestamp,messageId:I}),S();return}if(E.timestamp<=h){v.add(I);return}if(c(E.state,d)){v.add(I),u=!0;const M=d;r(E.state);const m=E.state;if(d=m,h=E.timestamp,l)try{l(m,M)}catch(x){g.warn("[BroadcastSync] Error in onStateSync callback",{error:x instanceof Error?x.message:String(x),stack:x instanceof Error?x.stack:void 0,storeName:i})}setTimeout(()=>{u=!1,S()},50)}else v.add(I)}else if(E.type==="state-request"){const M=a(),m=JSON.parse(JSON.stringify(M));p&&p.postMessage({type:"state-response",storeName:i,state:m,timestamp:Date.now()})}else if(E.type==="state-response"&&E.state)if(!d||E.timestamp>h){v.add(I),u=!0;const M=d;r(E.state);const m=E.state;if(d=m,h=E.timestamp,l)try{l(m,M)}catch(x){g.warn("[BroadcastSync] Error in onStateSync callback",{error:x instanceof Error?x.message:String(x),stack:x instanceof Error?x.stack:void 0,storeName:i})}setTimeout(()=>{u=!1,S()},50)}else v.add(I)}},p.postMessage({type:"state-request",storeName:i,timestamp:Date.now()})}return e((...S)=>{if(u)r(...S);else if(r(...S),p&&o){const _=a();if(c(_,d)){const E=Date.now(),I=`update-${E}-${Math.random()}`,M=JSON.parse(JSON.stringify(_));if(p.postMessage({type:"state-update",storeName:i,state:M,timestamp:E,messageId:I}),l)try{l(_,d)}catch(m){g.warn("[BroadcastSync] Error in onStateSync callback",{error:m instanceof Error?m.message:String(m),stack:m instanceof Error?m.stack:void 0,storeName:i})}d=_,h=E}}},a,n)}}const Z=Le()(qe(Sr(e=>({isAuthenticated:!1,isLoading:!1,error:null,login:async t=>{e({isLoading:!0,error:null});try{const r=await Er(t);return e({isAuthenticated:!0,isLoading:!1,error:null}),G.refreshToken().catch(a=>{g.warn("Failed to fetch CSRF token after login",{error:a instanceof Error?a.message:String(a),stack:a instanceof Error?a.stack:void 0})}),r}catch(r){throw e({error:B(r),isLoading:!1,isAuthenticated:!1}),r}},register:async t=>{e({isLoading:!0,error:null});try{const a=!!(await kr(t)).token?.access_token;e({isAuthenticated:a,isLoading:!1,error:null}),a&&G.refreshToken().catch(n=>{g.warn("Failed to fetch CSRF token after register",{error:n instanceof Error?n.message:String(n),stack:n instanceof Error?n.stack:void 0})})}catch(r){throw e({error:B(r),isLoading:!1,isAuthenticated:!1}),r}},logout:async()=>{e({isLoading:!0});try{await _r()}catch(t){g.error("Logout error",{error:t instanceof Error?t.message:String(t),stack:t instanceof Error?t.stack:void 0})}finally{e({isAuthenticated:!1,isLoading:!1,error:null}),G.clearToken()}},logoutLocal:()=>{g.info("[Auth] Performing local logout (no API call)",{}),ee.clearTokens(),N(async()=>{const{cleanupProactiveRefresh:t}=await Promise.resolve().then(()=>la);return{cleanupProactiveRefresh:t}},void 0).then(({cleanupProactiveRefresh:t})=>{t()}).catch(t=>{g.warn("Failed to cleanup proactive refresh",{error:t instanceof Error?t.message:String(t)})}),G.clearToken(),e({isAuthenticated:!1,isLoading:!1,error:null})},refreshUser:async()=>{const r=Z.getState().isAuthenticated;e({isLoading:!0});try{await Rt(),e({isAuthenticated:!0,isLoading:!1,error:null}),G.refreshToken().catch(a=>{g.warn("Failed to fetch CSRF token after refresh user",{error:a instanceof Error?a.message:String(a),stack:a instanceof Error?a.stack:void 0})})}catch(a){const n=B(a),i=typeof n.code=="number"?n.code:0;i===401||i===1001||i===1002?(ee.clearTokens(),e({error:n,isLoading:!1,isAuthenticated:!1})):e({error:n,isLoading:!1,isAuthenticated:!!r})}},checkAuthStatus:async()=>{{Z.getState().isAuthenticated||e({isAuthenticated:!1,isLoading:!1});return}},clearError:()=>e({error:null}),setLoading:t=>e({isLoading:t})}),{channelName:"auth-store",enabled:!0,shouldSync:(e,t)=>{const r=e,a=t;return r.isAuthenticated!==a?.isAuthenticated}}),{name:"auth-storage",partialize:e=>({isAuthenticated:e.isAuthenticated})})),we=Object.freeze(Object.defineProperty({__proto__:null,useAuthStore:Z},Symbol.toStringTag,{value:"Module"})),xe=Le()(Zt(qe(Sr(e=>({theme:"dark",language:"en",sidebarOpen:!0,notifications:[],setTheme:t=>{e({theme:t});const r=document.documentElement;if(t==="system"){const a=window.matchMedia("(prefers-color-scheme: dark)").matches;r.classList.remove("light","dark"),r.classList.add(a?"dark":"light"),r.setAttribute("data-theme",a?"dark":"light")}else r.classList.remove("light","dark"),r.classList.add(t),r.setAttribute("data-theme",t)},setLanguage:t=>{e({language:t}),typeof window<"u"&&window.i18n&&window.i18n.changeLanguage(t)},setSidebarOpen:t=>e({sidebarOpen:t}),addNotification:t=>{const r={...t,id:crypto.randomUUID(),timestamp:new Date().toISOString()};e(a=>({notifications:[...a.notifications,r]}))},removeNotification:t=>{e(r=>({notifications:r.notifications.filter(a=>a.id!==t)}))},markNotificationAsRead:t=>{e(r=>({notifications:r.notifications.map(a=>a.id===t?{...a,read:!0}:a)}))},clearNotifications:()=>e({notifications:[]})}),{channelName:"ui-store",enabled:!0,shouldSync:(e,t)=>e.theme!==t?.theme||e.language!==t?.language||e.sidebarOpen!==t?.sidebarOpen}),{name:"ui-storage",partialize:e=>({theme:e.theme,language:e.language,sidebarOpen:e.sidebarOpen})}),{name:"UIStore",enabled:!1}));function w(...e){return es(ts(e))}const Ba=er("inline-flex items-center justify-center whitespace-nowrap rounded-full text-sm font-medium tracking-tight transition-[color,transform,box-shadow,border-color,background-color] duration-[var(--duration-normal)] ease-out focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring focus-visible:ring-offset-2 focus-visible:ring-offset-background disabled:pointer-events-none disabled:opacity-50 gap-2 active:scale-95",{variants:{variant:{default:"bg-primary text-primary-foreground hover:bg-primary/90 hover:shadow-[0_0_20px_var(--primary)/0.25] border border-transparent font-semibold",primary:"bg-primary text-primary-foreground hover:bg-primary/90 hover:shadow-[0_0_20px_var(--primary)/0.25] border border-transparent font-semibold",destructive:"bg-destructive/10 text-destructive hover:bg-destructive/20 border border-destructive/30 hover:border-destructive/50",outline:"border border-border bg-transparent text-foreground hover:bg-muted/50 hover:border-border",secondary:"bg-muted text-foreground hover:bg-muted/80 border border-border",ghost:"hover:bg-muted/50 text-foreground",gaming:"bg-muted border border-warning/40 text-warning hover:bg-warning/10 hover:border-warning font-bold tracking-wider uppercase",terminal:"bg-card border border-border text-muted-foreground font-mono text-xs hover:border-primary hover:text-primary",nature:"bg-muted border border-success/30 text-success hover:bg-success/10 hover:border-success/50",glass:"bg-white/5 backdrop-blur-md border border-white/10 text-foreground hover:bg-white/10 hover:border-white/20 shadow-lg"},size:{default:"h-10 px-4 py-2",sm:"h-9 rounded-full px-4 text-xs",lg:"h-12 rounded-full px-8 text-base",icon:"h-10 w-10 rounded-full"}},defaultVariants:{variant:"default",size:"default"}}),P=f.forwardRef(({className:e,variant:t,size:r,asChild:a=!1,icon:n,children:i,...o},c)=>{const l=a?rs:"button";return s.jsx(l,{className:w(Ba({variant:t,size:r,className:e})),ref:c,...o,children:a?i:s.jsxs(s.Fragment,{children:[n&&s.jsx("span",{className:"flex items-center justify-center pointer-events-none",children:n}),i]})})});P.displayName="Button";const Ka=er("flex flex-col rounded-[var(--radius-xl)] text-card-foreground transition-[box-shadow,background-color,border-color,transform] duration-[var(--duration-normal)] ease-out relative overflow-hidden",{variants:{variant:{default:"bg-card border border-border shadow-lg shadow-black/10 hover:shadow-xl hover:shadow-black/15",elevated:"bg-card border border-border shadow-lg hover:shadow-xl",ghost:"bg-transparent border-0",outline:"bg-transparent border border-border",muted:"bg-muted/50 border border-border",glass:"glass border border-white/10 hover:bg-[var(--glass-bg)] hover:border-white/15",interactive:"bg-card border-0 shadow-lg shadow-black/5 cursor-pointer hover:shadow-xl hover:-translate-y-0.5",glow:"bg-card border-0 shadow-lg hover:shadow-[0_0_30px_oklch(0.75_0.18_195_/_0.15)]",glowMagenta:"bg-card border-0 shadow-lg hover:shadow-[0_0_30px_oklch(0.65_0.25_330_/_0.15)]",spotlight:"bg-black/40 border border-white/10 hover:border-white/20",surface:"bg-card border border-white/5 shadow-none hover:bg-card/90 hover:border-white/10 hover:shadow-[0_8px_30px_rgba(0,0,0,0.25)] transition-all duration-[var(--duration-immersive)] ease-in-out"},padding:{none:"",sm:"p-4",default:"p-6",lg:"p-8"}},defaultVariants:{variant:"default",padding:"none"}});function Nr({className:e,variant:t,padding:r,spotlight:a,spotlightColor:n="rgba(255, 255, 255, 0.1)",...i}){const o=f.useRef(null),[c,l]=f.useState({x:0,y:0}),[p,u]=f.useState(0),d=k=>{if(!o.current||t!=="spotlight"&&!a)return;const _=o.current.getBoundingClientRect();l({x:k.clientX-_.left,y:k.clientY-_.top})},h=()=>{u(1)},v=()=>{u(0)},y=t==="spotlight"||a;return s.jsxs("div",{ref:o,onMouseMove:d,onMouseEnter:h,onMouseLeave:v,"data-slot":"card",className:w(Ka({variant:t,padding:r}),e),...i,children:[y&&s.jsx("div",{className:"pointer-events-none absolute -inset-px opacity-0 transition duration-300",style:{opacity:p,background:`radial-gradient(600px circle at ${c.x}px ${c.y}px, ${n}, transparent 40%)`}}),s.jsx("div",{className:"relative z-10 w-full h-full flex flex-col",children:i.children})]})}function hl({className:e,...t}){return s.jsx("div",{"data-slot":"card-header",className:w("flex flex-col gap-1.5 p-6 pb-0",e),...t})}function pl({className:e,...t}){return s.jsx("h3",{"data-slot":"card-title",className:w("text-lg font-semibold leading-tight tracking-tight text-foreground",e),...t})}function gl({className:e,...t}){return s.jsx("p",{"data-slot":"card-description",className:w("text-sm text-muted-foreground/90",e),...t})}function Ha({className:e,...t}){return s.jsx("div",{"data-slot":"card-content",className:w("p-6 pt-4",e),...t})}function yl({className:e,...t}){return s.jsx("div",{"data-slot":"card-footer",className:w("flex items-center gap-3 p-6 pt-0",e),...t})}function Tr({children:e,active:t=!0,onEscape:r}){const a=f.useRef(null),n=f.useRef(null);return f.useEffect(()=>{if(!t||!a.current)return;n.current=document.activeElement;const i=a.current.querySelectorAll('button, [href], input, select, textarea, [tabindex]:not([tabindex="-1"])'),o=i[0],c=i[i.length-1];o&&o.focus();const l=p=>{if(p.key==="Escape"){r?.();return}p.key==="Tab"&&(p.shiftKey?document.activeElement===o&&(p.preventDefault(),c?.focus()):document.activeElement===c&&(p.preventDefault(),o?.focus()))};return document.addEventListener("keydown",l),()=>{document.removeEventListener("keydown",l),n.current instanceof HTMLElement&&n.current.focus()}},[t,r]),s.jsx("div",{ref:a,tabIndex:-1,children:e})}const Wa={sm:"max-w-sm",md:"max-w-md",lg:"max-w-2xl",xl:"max-w-4xl",full:"max-w-full m-4 h-[calc(100vh-2rem)]"};function Ga({open:e,onClose:t,children:r,title:a,closeOnOverlayClick:n=!0,closeOnEscape:i=!0,size:o="md",className:c,footer:l}){const p=f.useRef(null);if(f.useEffect(()=>{if(e)return document.body.style.overflow="hidden",()=>{document.body.style.overflow=""}},[e]),f.useEffect(()=>{if(!i||!e)return;const d=h=>{h.key==="Escape"&&t()};return document.addEventListener("keydown",d),()=>document.removeEventListener("keydown",d)},[e,i,t]),!e)return null;const u=d=>{n&&d.target===d.currentTarget&&t()};return Kr.createPortal(s.jsxs("div",{className:"fixed inset-0 z-[100] flex items-center justify-center p-4",onClick:u,children:[s.jsx("div",{className:"absolute inset-0 bg-kodo-void/90 backdrop-blur-sm animate-fadeIn"}),s.jsx(Tr,{children:s.jsxs("div",{ref:p,className:w("relative w-full bg-kodo-graphite border border-kodo-steel rounded-xl shadow-2xl flex flex-col overflow-hidden animate-scaleIn",Wa[o],c),onClick:d=>d.stopPropagation(),children:[a&&s.jsxs("div",{className:"p-4 border-b border-kodo-steel bg-kodo-ink flex justify-between items-center shrink-0",children:[s.jsx("h3",{className:"font-bold text-white text-lg font-display",children:a}),s.jsx(P,{variant:"ghost",size:"icon",onClick:t,className:"ml-auto",children:s.jsx(_e,{className:"w-5 h-5"})})]}),s.jsx("div",{className:"p-8 overflow-y-auto custom-scrollbar flex-1",children:r}),l&&s.jsx("div",{className:"p-4 border-t border-kodo-steel bg-kodo-ink shrink-0 flex justify-end gap-4",children:l})]})})]}),document.body)}const Ya={alert:ye,confirm:ye,info:rt,default:void 0},Xa={alert:"text-destructive",confirm:"text-primary",info:"text-muted-foreground",default:""};function At({open:e,onClose:t,onOpenChange:r,title:a,children:n,footer:i,variant:o="default",onConfirm:c,onCancel:l,confirmLabel:p="Confirm",cancelLabel:u="Cancel",showCancel:d=!0,size:h="md"}){const v=()=>{r?r(!1):t&&t()},y=async()=>{c&&await c(),v()},k=()=>{l&&l(),v()},S=Ya[o],_=Xa[o];return s.jsxs(Ga,{open:e,onClose:v,size:h,closeOnOverlayClick:o==="default",title:a,footer:i||c||l?i||s.jsxs("div",{className:"flex justify-end gap-2",children:[d&&s.jsx(P,{variant:"outline",onClick:k,children:u}),c&&s.jsx(P,{variant:o==="alert"?"destructive":"default",onClick:y,children:p})]}):void 0,children:[a&&S&&s.jsx("div",{className:"flex items-center gap-4 mb-4",children:s.jsx(S,{className:w("h-5 w-5",_)})}),n]})}function Ja(e,t){const r=B(e),a=it(r),n=typeof navigator<"u"?navigator.userAgent:"Unknown",i=typeof window<"u"?window.location.href:"Unknown",o=new Date().toISOString(),c=`[${a.toUpperCase()}] ${r.message||"Unknown error"}`,l=[];l.push("## 🐞 Error Details"),l.push(""),l.push(`**Message:** ${r.message||"No message provided"}`),r.code!==void 0&&l.push(`**Error Code:** ${r.code}`),r.status!==void 0&&l.push(`**HTTP Status:** ${r.status}`),r.request_id&&l.push(`**Request ID:** \`${r.request_id}\``),l.push(`**Category:** ${a}`),l.push(`**Timestamp:** ${o}`),l.push(""),t&&(l.push("## 📍 Context"),l.push(""),t.component&&l.push(`**Component:** ${t.component}`),t.action&&l.push(`**Action:** ${t.action}`),t.userId&&l.push(`**User ID:** ${t.userId}`),t.additionalInfo&&Object.keys(t.additionalInfo).length>0&&(l.push("**Additional Info:**"),l.push("```json"),l.push(JSON.stringify(t.additionalInfo,null,2)),l.push("```")),l.push("")),r.details&&(l.push("## 🔍 Error Details"),l.push(""),l.push("```json"),l.push(JSON.stringify(r.details,null,2)),l.push("```"),l.push("")),r.errors&&Object.keys(r.errors).length>0&&(l.push("## ⚠️ Validation Errors"),l.push(""),Object.entries(r.errors).forEach(([u,d])=>{l.push(`- **${u}:** ${Array.isArray(d)?d.join(", "):d}`)}),l.push("")),l.push("## 💻 Environment"),l.push(""),l.push(`**URL:** ${i}`),l.push(`**User Agent:** ${n}`),l.push(`**Browser:** ${tn(n)}`),l.push(`**Platform:** ${rn(n)}`),typeof window<"u"&&(l.push(`**Screen:** ${window.screen.width}x${window.screen.height}`),l.push(`**Viewport:** ${window.innerWidth}x${window.innerHeight}`)),l.push(""),l.push("## 🔁 Steps to Reproduce"),l.push(""),l.push("1. [Describe step 1]"),l.push("2. [Describe step 2]"),l.push("3. [Describe step 3]"),l.push(""),l.push("## ✅ Expected Behavior"),l.push(""),l.push("[Describe what should have happened]"),l.push("");const p=l.join(`
|
|
`);return{title:c,body:p,metadata:{requestId:r.request_id,errorCode:r.code,statusCode:r.status,category:a,timestamp:o,userAgent:n,url:i}}}async function jr(e){const t=`${e.title}
|
|
|
|
${e.body}`;if(typeof navigator<"u"&&navigator.clipboard&&navigator.clipboard.writeText)try{await navigator.clipboard.writeText(t);return}catch{}const r=document.createElement("textarea");r.value=t,r.style.position="fixed",r.style.opacity="0",document.body.appendChild(r),r.select();try{document.execCommand("copy")}finally{document.body.removeChild(r)}}function Za(e,t){const r=en();if(!r){jr(e);return}const a=new URLSearchParams({title:e.title,body:e.body}),n=`${r}/issues/new?${a.toString()}`;window.open(n,"_blank")}function en(){return null}function tn(e){return e.includes("Chrome")&&!e.includes("Edg")?"Chrome":e.includes("Firefox")?"Firefox":e.includes("Safari")&&!e.includes("Chrome")?"Safari":e.includes("Edg")?"Edge":e.includes("Opera")||e.includes("OPR")?"Opera":"Unknown"}function rn(e){return e.includes("Windows")?"Windows":e.includes("Mac")?"macOS":e.includes("Linux")?"Linux":e.includes("Android")?"Android":e.includes("iOS")||e.includes("iPhone")||e.includes("iPad")?"iOS":"Unknown"}function sn(e){if(typeof e=="string")return{message:e};if(e instanceof Error)return{message:e.message,stack:e.stack};if(e&&typeof e=="object")try{const t=B(e);return{message:t.message||"An error occurred",code:t.code,status:typeof t.code=="number"?t.code:void 0,details:t.details}}catch{return{message:e.message||String(e),code:e.code,status:e.status,details:e.details}}return{message:String(e)}}const Cr=f.forwardRef(({error:e,onRetry:t,onDismiss:r,showDetails:a,context:n,variant:i="inline",severity:o="error",size:c="md",className:l,dismissible:p,title:u,icon:d,actions:h=[],...v},y)=>{const[k,S]=f.useState(!1),[_,E]=f.useState(!1),[I,M]=f.useState(!0),m=f.useMemo(()=>sn(e),[e]),x=f.useMemo(()=>B(e),[e]),j=f.useMemo(()=>it(x),[x]),F=f.useMemo(()=>j==="server_error"||m.status!==void 0&&m.status>=500,[j,e]),U=a??!1,Y=f.useMemo(()=>{if(m.message)try{return gr(m,n?.resource,!1)}catch{return m.message}return"An unexpected error occurred"},[m,n]),X=f.useMemo(()=>{if(u)return u;if(n?.action)return`Error ${n.action}`;switch(o){case"error":return"Error";case"warning":return"Warning";case"info":return"Information";default:return"Error"}},[u,n,o]),H=f.useMemo(()=>{if(d)return d;const O=c==="sm"?"w-4 h-4":c==="lg"?"w-6 h-6":"w-5 h-5";switch(o){case"error":return s.jsx(ye,{className:w(O,"text-destructive")});case"warning":return s.jsx(st,{className:w(O,"text-warning")});case"info":return s.jsx(rt,{className:w(O,"text-info")});default:return s.jsx(ye,{className:w(O,"text-destructive")})}},[d,o,c]),K=f.useMemo(()=>{switch(o){case"error":return{bg:"bg-destructive/10",border:"border-destructive/30",text:"text-destructive",icon:"text-destructive"};case"warning":return{bg:"bg-warning/10",border:"border-warning/30",text:"text-warning",icon:"text-warning"};case"info":return{bg:"bg-info/10",border:"border-info/30",text:"text-info",icon:"text-info"};default:return{bg:"bg-destructive/10",border:"border-destructive/30",text:"text-destructive",icon:"text-destructive"}}},[o]),W=f.useMemo(()=>{switch(c){case"sm":return{padding:"p-4",text:"text-xs",title:"text-sm",gap:"gap-2"};case"lg":return{padding:"p-6",text:"text-base",title:"text-lg",gap:"gap-4"};default:return{padding:"p-4",text:"text-sm",title:"text-base",gap:"gap-4"}}},[c]),ie=f.useCallback(async()=>{if(!(!t||_)){E(!0);try{await t()}finally{E(!1)}}},[t,_]),Ne=f.useCallback(()=>{r&&r(),i==="modal"&&M(!1)},[r,i]),ct=f.useCallback(async()=>{try{const O=Ja(e,{component:n?.resource,action:n?.action,userId:n?.userId,additionalInfo:n});try{Za(O),te.success("Opening GitHub issue...")}catch{await jr(O),te.success("Issue report copied to clipboard")}}catch{te.error("Failed to generate issue report")}},[e,n]),ut=f.useCallback(async()=>{if(x.request_id)try{await navigator.clipboard.writeText(x.request_id),te.success("Request ID copied to clipboard")}catch{te.error("Failed to copy request ID")}},[x.request_id]),dt=p??(r!==void 0||i==="modal"),Ue=()=>{if(!U||!k)return null;const O=[];return x.request_id&&O.push({label:"Request ID",value:x.request_id}),m.code&&O.push({label:"Error Code",value:String(m.code)}),m.status&&O.push({label:"HTTP Status",value:String(m.status)}),m.details&&O.push({label:"Details",value:JSON.stringify(m.details,null,2)}),m.stack&&O.push({label:"Stack Trace",value:m.stack}),n&&O.push({label:"Context",value:JSON.stringify(n,null,2)}),O.length===0?null:s.jsx("div",{className:"mt-4 pt-4 border-t border-white/10",children:s.jsx("div",{className:"space-y-2",children:O.map((oe,mt)=>s.jsxs("div",{className:"text-xs",children:[s.jsxs("span",{className:"font-semibold opacity-70",children:[oe.label,":"]}),s.jsx("pre",{className:"mt-1 p-2 bg-black/20 rounded text-xs overflow-x-auto",children:typeof oe.value=="string"?oe.value:JSON.stringify(oe.value,null,2)})]},mt))})})},Te=s.jsxs("div",{ref:y,role:"alert","aria-live":"polite",className:w("rounded-lg border flex shadow-[0_0_15px_rgba(0,0,0,0.1)]",K.bg,K.border,K.text,W.padding,W.gap,l),...v,children:[s.jsx("div",{className:"flex-shrink-0 pt-0.5",children:H}),s.jsxs("div",{className:"flex-1 min-w-0",children:[s.jsx("div",{className:w("font-semibold mb-1",W.title),children:X}),s.jsx("div",{className:w("opacity-90",W.text),children:Y}),Ue(),(t||h.length>0||F||U&&(m.code||m.details||m.stack||n))&&s.jsxs("div",{className:"mt-4 flex flex-wrap gap-2 items-center",children:[t&&s.jsx(P,{variant:"outline",size:c==="sm"?"sm":"default",onClick:ie,disabled:_,className:"border-current text-current hover:bg-current/10 bg-transparent",children:_?"Retrying...":"Retry"}),F&&x.request_id&&s.jsxs(s.Fragment,{children:[s.jsxs(P,{variant:"outline",size:c==="sm"?"sm":"default",onClick:ut,className:"border-current text-current hover:bg-current/10 bg-transparent",title:"Copy Request ID",children:[s.jsx(cs,{className:"w-4 h-4 mr-1.5"}),"Copy ID"]}),s.jsxs(P,{variant:"outline",size:c==="sm"?"sm":"default",onClick:ct,className:"border-current text-current hover:bg-current/10 bg-transparent",children:[s.jsx(us,{className:"w-4 h-4 mr-1.5"}),"Report"]})]}),h.map((O,oe)=>s.jsx(P,{variant:O.variant||"outline",size:c==="sm"?"sm":"default",onClick:O.onClick,className:"border-current text-current hover:bg-current/10 bg-transparent",children:O.label},oe)),U&&(m.code||m.details||m.stack||n)&&s.jsx(P,{variant:"ghost",size:c==="sm"?"sm":"default",onClick:()=>S(!k),className:"text-current hover:bg-current/10 hover:text-current",children:k?s.jsxs(s.Fragment,{children:[s.jsx(ds,{className:"w-4 h-4 mr-1"}),"Hide Details"]}):s.jsxs(s.Fragment,{children:[s.jsx(rr,{className:"w-4 h-4 mr-1"}),"Show Details"]})})]})]}),dt&&s.jsx("button",{onClick:Ne,className:"opacity-70 hover:opacity-100 transition-opacity flex-shrink-0 self-start","aria-label":"Dismiss error",children:s.jsx(_e,{className:w(c==="sm"?"w-4 h-4":"w-5 h-5")})})]});switch(i){case"banner":return s.jsx("div",{className:"w-full",children:Te});case"card":return s.jsx(Nr,{className:w(K.border,l,"glass"),children:s.jsx(Ha,{className:w(W.padding,"pt-6"),children:Te})});case"modal":return s.jsx(At,{open:I,onClose:Ne,title:X,variant:o==="error"?"alert":"default",footer:s.jsxs("div",{className:"flex gap-2 justify-end",children:[t&&s.jsx(P,{variant:"outline",onClick:ie,disabled:_,children:_?"Retrying...":"Retry"}),h.map((O,oe)=>s.jsx(P,{variant:O.variant||"outline",onClick:O.onClick,children:O.label},oe)),s.jsx(P,{variant:"default",onClick:Ne,children:t?"Close":"Dismiss"})]}),children:s.jsxs("div",{className:w(K.text),children:[s.jsx("div",{className:w("opacity-90 mb-4",W.text),children:Y}),Ue()]})});default:return Te}});Cr.displayName="ErrorDisplay";class ve extends f.Component{constructor(t){super(t),this.state={hasError:!1}}static getDerivedStateFromError(t){return{hasError:!0,error:t}}componentDidCatch(t,r){this.setState({error:t,errorInfo:r});const a=ra(),n={...a,component:"ErrorBoundary",errorType:t.name||"Error",errorMessage:t.message,stack:t.stack,componentStack:r.componentStack,url:typeof window<"u"?window.location.href:void 0,userAgent:typeof navigator<"u"?navigator.userAgent:void 0,timestamp:new Date().toISOString()};g.error("[ErrorBoundary] React error caught",n),typeof window<"u"&&ss(t,{contexts:{react:{componentStack:r.componentStack},application:{...a,url:window.location.href,userAgent:navigator.userAgent}},tags:{error_boundary:!0,error_type:t.name||"Error",...a.request_id?{request_id:String(a.request_id)}:{}},level:"error"})}handleReset=()=>{this.setState({hasError:!1,error:void 0,errorInfo:void 0})};render(){return this.state.hasError?this.props.fallback?this.props.fallback:s.jsxs("div",{className:"min-h-screen flex items-center justify-center bg-background p-4 relative overflow-hidden",children:[s.jsx("div",{className:"absolute inset-0 bg-[radial-gradient(ellipse_at_center,_var(--tw-gradient-stops))] from-primary/5 via-background to-background pointer-events-none"}),s.jsx("div",{className:"w-full max-w-md relative z-10",children:s.jsx(Cr,{error:this.state.error||new Error("An unexpected error occurred"),variant:"card",severity:"error",size:"lg",showDetails:!1,context:{component:"ErrorBoundary",action:"rendering component",componentStack:this.state.errorInfo?.componentStack},onRetry:this.handleReset,actions:[{label:"Return Home",onClick:()=>{window.location.href="/"},variant:"outline"}]})})]}):this.props.children}}const an={success:ms,error:ye,warning:st,info:rt},Ht={success:"border-lime-500/30 bg-lime-500/10 text-lime-500",error:"border-destructive/30 bg-destructive/10 text-destructive",warning:"border-warning/30 bg-warning/10 text-warning",info:"border-info/30 bg-info/10 text-info"},Wt=5e3;function nn({toast:e,onDismiss:t}){const[r,a]=f.useState(!1),[n,i]=f.useState(!1),o=f.useCallback(()=>{i(!0),setTimeout(()=>{t(e.id)},300)},[e.id,t]);f.useEffect(()=>{requestAnimationFrame(()=>a(!0));const p=e.duration??Wt;let u=null;return p>0&&(u=setTimeout(()=>{o()},p)),()=>{u&&clearTimeout(u)}},[e.duration,e.id,o]);const c=e.type?an[e.type]:rt,l=e.type?Ht[e.type]:Ht.info;return s.jsxs(Nr,{variant:"glass",className:w("relative flex min-w-[320px] max-w-sm items-start gap-4 p-4 shadow-[0_4px_20px_rgba(0,0,0,0.2)] transition-all duration-300 transform",l,r&&!n?"opacity-100 translate-x-0 translate-y-0 scale-100":"opacity-0 translate-x-full scale-95","backdrop-blur-xl"),role:"alert","data-testid":"toast-alert","aria-live":"polite",children:[s.jsx(c,{className:"h-5 w-5 flex-shrink-0 animate-[pulse-ring_2s_infinite]"}),s.jsx("div",{className:"flex-1",children:s.jsx("p",{className:"text-sm font-medium leading-relaxed font-sans",children:e.message})}),s.jsx("button",{onClick:o,className:"flex-shrink-0 rounded-md p-1 opacity-60 transition-opacity hover:opacity-100 hover:bg-black/10 focus:outline-none focus:ring-1 focus:ring-current","aria-label":"Close",children:s.jsx(_e,{className:"h-4 w-4"})}),s.jsx("div",{className:w("absolute bottom-0 left-0 h-0.5 bg-current opacity-20 transition-all ease-linear",r&&!n?"w-full":"w-0"),style:{transitionDuration:`${(e.duration||Wt)-300}ms`}})]})}const Rr=f.createContext(void 0);function Ar(){const e=f.useContext(Rr);if(!e)throw new Error("useToastContext must be used within ToastProvider");return e}function vl(){const e=Ar();return{...e,addToast:(r,a)=>{typeof r=="string"?e.addToast({message:r,type:a||"info"}):e.addToast(r)}}}const on={"top-right":"top-4 right-4","top-left":"top-4 left-4","bottom-right":"bottom-4 right-4","bottom-left":"bottom-4 left-4","top-center":"top-4 left-1/2 -translate-x-1/2","bottom-center":"bottom-4 left-1/2 -translate-x-1/2"};function ln({children:e,position:t="top-right",className:r}){const[a,n]=f.useState([]),i=f.useCallback(l=>{const p=`toast-${Date.now()}-${Math.random().toString(36).substr(2,9)}`,u={...l,id:p};n(d=>[...d,u])},[]),o=f.useCallback(l=>{n(p=>p.filter(u=>u.id!==l))},[]),c={toasts:a,addToast:i,removeToast:o};return s.jsxs(Rr.Provider,{value:c,children:[e,s.jsx("div",{className:w("fixed z-50 flex flex-col gap-2",on[t],r),children:a.map(l=>s.jsx(nn,{toast:l,onDismiss:o},l.id))})]})}function Pr(){const e=f.useRef(null),{theme:t}=xe();return f.useEffect(()=>{const r=e.current;if(!r)return;const a=r.getContext("2d");if(!a)return;const n=document.documentElement.classList.contains("light");let i,o=[];const c=window.innerWidth<768?20:50,l=150,p=n?"14, 165, 233":"102, 252, 241",u=n?"148, 163, 184":"102, 252, 241",d=()=>{r.width=window.innerWidth,r.height=window.innerHeight},h=()=>{o=[];for(let y=0;y<c;y++)o.push({x:Math.random()*r.width,y:Math.random()*r.height,size:Math.random()*(n?3:2),speedX:(Math.random()-.5)*.2,speedY:(Math.random()-.5)*.2,opacity:Math.random()*.5+.1})},v=()=>{a.clearRect(0,0,r.width,r.height),o.forEach((y,k)=>{y.x+=y.speedX,y.y+=y.speedY,y.x<0&&(y.x=r.width),y.x>r.width&&(y.x=0),y.y<0&&(y.y=r.height),y.y>r.height&&(y.y=0),a.beginPath(),a.arc(y.x,y.y,y.size,0,Math.PI*2),a.fillStyle=`rgba(${p}, ${y.opacity})`,a.fill();for(let S=k+1;S<o.length;S++){const _=o[S],E=y.x-_.x,I=y.y-_.y,M=Math.sqrt(E*E+I*I);if(M<l){a.beginPath();const m=n?.05:.1;a.strokeStyle=`rgba(${u}, ${m*(1-M/l)})`,a.lineWidth=.5,a.moveTo(y.x,y.y),a.lineTo(_.x,_.y),a.stroke()}}}),i=requestAnimationFrame(v)};return window.addEventListener("resize",d),d(),h(),v(),()=>{window.removeEventListener("resize",d),cancelAnimationFrame(i)}},[t]),s.jsxs("div",{className:"fixed inset-0 z-0 pointer-events-none overflow-hidden transition-colors duration-700",children:[s.jsx("div",{className:"absolute inset-0 bg-background transition-colors duration-700"}),s.jsx("div",{className:"absolute inset-0 bg-gradient-to-b from-transparent via-transparent to-black/20 dark:to-black/80"}),s.jsx("div",{className:"absolute top-[-20%] left-[-10%] w-[60%] h-[60%] rounded-full bg-cyan/5 dark:bg-cyan/5 blur-[120px] animate-pulse"}),s.jsx("div",{className:"absolute bottom-[-20%] right-[-10%] w-[60%] h-[60%] rounded-full bg-magenta/5 dark:bg-magenta/5 blur-[120px] animate-pulse",style:{animationDelay:"2s"}}),s.jsx("canvas",{ref:e,className:"absolute inset-0 opacity-60 dark:opacity-40"}),s.jsx("div",{className:"absolute inset-0 opacity-[0.02] dark:opacity-[0.03]",style:{backgroundImage:"linear-gradient(rgb(var(--sidebar-border)) 1px, transparent 1px)",backgroundSize:"100px 100px"}})]})}function cn(){const[e,t]=f.useState(()=>typeof navigator<"u"?navigator.onLine:!0);return f.useEffect(()=>{const r=()=>t(!0),a=()=>t(!1);return window.addEventListener("online",r),window.addEventListener("offline",a),()=>{window.removeEventListener("online",r),window.removeEventListener("offline",a)}},[]),e}let Pt=null,Ze=null;const un=3e4;function dn(e){const t=it(e);(t==="network"||t==="timeout")&&(Pt=e instanceof Error||e&&typeof e=="object"&&"message"in e?e:new Error(String(e)),Ze=Date.now())}function Ir(){Pt=null,Ze=null}function Lr(){return!Pt||!Ze?!1:Date.now()-Ze>un?(Ir(),!1):!0}const mn=Object.freeze(Object.defineProperty({__proto__:null,clearNetworkError:Ir,hasRecentNetworkError:Lr,recordNetworkError:dn},Symbol.toStringTag,{value:"Module"}));function fn(e){return new Date(e).toLocaleString()}function hn(e){const t=e.config.method?.toUpperCase()||"UNKNOWN",r=e.config.url||"Unknown URL";return`${t} ${r}`}function pn(e){switch(e){case"high":return"bg-kodo-red/20 text-kodo-red border-kodo-red/30";case"normal":return"bg-kodo-steel/20 text-kodo-steel border-kodo-steel/30";case"low":return"bg-kodo-steel/30 text-kodo-secondary border-kodo-steel/50";default:return"bg-kodo-steel/30 text-kodo-secondary border-kodo-steel/50"}}function Gt({open:e,onClose:t}){const[r,a]=f.useState([]),[n,i]=f.useState(null),[o,c]=f.useState(!1);f.useEffect(()=>{if(!e)return;const u=()=>{a(de.getQueue())};u();const d=setInterval(u,1e3);return()=>clearInterval(d)},[e]);const l=async u=>{i(u);try{await de.removeRequest(u),a(de.getQueue())}catch(d){g.error("Failed to remove request",{error:d instanceof Error?d.message:String(d),stack:d instanceof Error?d.stack:void 0,requestId:u})}finally{i(null)}},p=async()=>{c(!0);try{await de.clearQueue(),a([]),t()}catch(u){g.error("Failed to clear queue",{error:u instanceof Error?u.message:String(u),stack:u instanceof Error?u.stack:void 0})}finally{c(!1)}};return s.jsx(At,{open:e,onClose:t,title:"Offline Queue Manager",size:"lg",variant:"info",children:s.jsxs("div",{className:"space-y-4",children:[s.jsxs("div",{className:"flex items-center justify-between p-4 bg-kodo-ink/50 rounded-lg border border-kodo-steel",children:[s.jsxs("div",{className:"flex items-center gap-2",children:[s.jsx(Ce,{className:"w-5 h-5 text-kodo-steel"}),s.jsx("span",{className:"text-sm text-kodo-secondary",children:r.length===0?"No queued requests":`${r.length} ${r.length===1?"request":"requests"} queued`})]}),r.length>0&&s.jsxs(P,{variant:"destructive",size:"sm",onClick:p,disabled:o,children:[s.jsx(fs,{className:"w-4 h-4 mr-2"}),"Clear All"]})]}),r.length===0?s.jsxs("div",{className:"text-center py-8 text-kodo-secondary",children:[s.jsx(hs,{className:"w-12 h-12 mx-auto mb-4 text-kodo-cyan/50"}),s.jsx("p",{className:"text-sm",children:"All requests have been processed"})]}):s.jsx("div",{className:"space-y-2 max-h-[400px] overflow-y-auto custom-scrollbar",children:r.map(u=>s.jsx("div",{className:"p-4 bg-kodo-ink/30 rounded-lg border border-kodo-steel hover:border-kodo-steel/50 transition-colors",children:s.jsxs("div",{className:"flex items-start justify-between gap-4",children:[s.jsxs("div",{className:"flex-1 min-w-0",children:[s.jsx("div",{className:"flex items-center gap-2 mb-2",children:s.jsx("span",{className:"font-mono text-sm font-semibold text-white truncate",children:hn(u)})}),s.jsxs("div",{className:"flex items-center gap-4 flex-wrap text-xs text-kodo-secondary",children:[s.jsx("span",{className:w("px-2 py-0.5 rounded border",pn(u.priority)),children:u.priority}),s.jsxs("span",{className:"flex items-center gap-1",children:[s.jsx(Ce,{className:"w-3 h-3"}),fn(u.timestamp)]}),u.retryCount>0&&s.jsxs("span",{className:"flex items-center gap-1 text-kodo-red",children:[s.jsx(ye,{className:"w-3 h-3"}),u.retryCount," retry",u.retryCount>1?"ies":""]})]})]}),s.jsx(P,{variant:"ghost",size:"icon",onClick:()=>l(u.id),disabled:n===u.id,className:"shrink-0",children:n===u.id?s.jsx(Ce,{className:"w-4 h-4 animate-spin"}):s.jsx(_e,{className:"w-4 h-4"})})]})},u.id))}),r.length>0&&s.jsx("div",{className:"p-4 bg-kodo-steel/10 border border-kodo-steel/20 rounded-lg text-xs text-kodo-secondary",children:s.jsx("p",{children:"Queued requests will be automatically processed when you're back online. You can remove individual requests or clear the entire queue."})})]})})}function gn(){const e=cn(),[t,r]=f.useState(0),[a,n]=f.useState(!1),[i,o]=f.useState(!1),[c,l]=f.useState(!1),[p,u]=f.useState(!1);return f.useEffect(()=>{const d=()=>{const v=de.getQueueSize();r(v)};d();const h=setInterval(d,1e3);return()=>clearInterval(h)},[]),f.useEffect(()=>{if(e&&t>0){n(!0);const d=setInterval(()=>{de.getQueueSize()===0&&(n(!1),clearInterval(d))},500);return()=>clearInterval(d)}else{n(!1);return}},[e,t]),f.useEffect(()=>{const d=()=>{o(Lr())};d();const h=setInterval(d,2e3);return()=>clearInterval(h)},[]),f.useEffect(()=>{if(a&&t>0&&e){const d=setTimeout(()=>{u(!0)},500);return()=>{clearTimeout(d),u(!1)}}else{u(!1);return}},[a,t,e]),e&&t===0&&!a&&!i?null:!e||i?s.jsxs(s.Fragment,{children:[s.jsxs("div",{className:"fixed top-0 left-0 right-0 bg-kodo-red/90 backdrop-blur-sm text-white px-4 py-2.5 text-sm z-50 flex items-center justify-center gap-2 shadow-lg border-b border-kodo-red",children:[s.jsx(ps,{className:"w-4 h-4"}),s.jsxs("span",{children:["Mode hors ligne",t>0&&s.jsxs("span",{className:"ml-2 font-semibold",children:["- ",t," ",t===1?"requête":"requêtes"," en attente"]})]}),t>0&&s.jsxs("button",{onClick:()=>l(!0),className:"ml-3 px-2 py-1 bg-white/10 hover:bg-white/20 rounded border border-white/20 transition-colors flex items-center gap-1.5 text-xs font-medium",title:"View queued requests",children:[s.jsx(Dt,{className:"w-3.5 h-3.5"}),"View Queue"]})]}),s.jsx(Gt,{open:c,onClose:()=>l(!1)})]}):a&&t>0&&p?s.jsxs(s.Fragment,{children:[s.jsxs("div",{className:"fixed top-0 left-0 right-0 bg-kodo-cyan/90 backdrop-blur-sm text-kodo-void px-4 py-2.5 text-sm z-50 flex items-center justify-center gap-2 shadow-lg border-b border-kodo-steel",children:[s.jsx(Me,{className:"w-4 h-4 animate-spin"}),s.jsxs("span",{children:["Synchronisation en cours",t>0&&s.jsxs("span",{className:"ml-2 font-semibold",children:["- ",t," ",t===1?"requête":"requêtes"," restante",t>1?"s":""]})]}),t>0&&s.jsxs(s.Fragment,{children:[s.jsx("button",{onClick:async()=>{await de.clearQueue(),r(0)},className:"ml-2 px-2 py-1 bg-kodo-red/20 hover:bg-kodo-red/30 rounded border border-kodo-red/30 transition-colors flex items-center gap-1.5 text-xs font-medium",title:"Clear queued requests",children:"Clear Queue"}),s.jsxs("button",{onClick:()=>l(!0),className:"ml-2 px-2 py-1 bg-kodo-void/20 hover:bg-kodo-void/30 rounded border border-kodo-void/30 transition-colors flex items-center gap-1.5 text-xs font-medium",title:"View queued requests",children:[s.jsx(Dt,{className:"w-3.5 h-3.5"}),"View Queue"]})]})]}),s.jsx(Gt,{open:c,onClose:()=>l(!1)})]}):null}function qr(){const{isAuthenticated:e}=Z();return Jt({queryKey:["user","me"],queryFn:Rt,enabled:e,retry:!1,staleTime:300*1e3,gcTime:600*1e3})}const Dr=()=>{const{isAuthenticated:e,logout:t}=Z(),{data:r}=qr();return{user:r??null,accessToken:null,refreshToken:null,isAuthenticated:e,logout:async()=>{await t()}}};function yn({children:e}){const{isAuthenticated:t}=Dr(),[r,a]=f.useState(!0),n=!1,{isLoading:i}=Z();return f.useEffect(()=>{const c=setTimeout(()=>{a(!1)},200);return()=>clearTimeout(c)},[]),r||i?null:t||n?s.jsx(s.Fragment,{children:e}):s.jsx(Ge,{to:"/login",replace:!0})}function vn(e){try{return e?typeof e=="string"?e:e instanceof Error?e.message:String(e):"Currently unable to access this component. Please check your connection."}catch{return"An unknown error occurred."}}function Mr({pageName:e,error:t,onRetry:r}){return s.jsx("div",{className:"flex flex-col items-center justify-center min-h-layout-page-sm p-8 text-center animate-in fade-in zoom-in duration-300",children:s.jsxs("div",{className:"bg-kodo-ink/50 border border-kodo-steel/30 rounded-xl p-8 max-w-md w-full shadow-lg backdrop-blur-sm",children:[s.jsx("div",{className:"w-16 h-16 bg-kodo-red/10 rounded-full flex items-center justify-center mx-auto mb-6",children:s.jsx(st,{className:"h-8 w-8 text-kodo-red"})}),s.jsxs("h2",{className:"text-xl font-bold mb-2",children:["Failed to load ",e]}),s.jsx("p",{className:"text-kodo-content-dim mb-6 text-sm",children:vn(t)}),s.jsxs("div",{className:"flex flex-col gap-3",children:[r&&s.jsxs(P,{onClick:r,variant:"outline",className:"w-full flex items-center justify-center gap-2",children:[s.jsx(gs,{className:"h-4 w-4"}),"Try Again"]}),s.jsx(P,{onClick:()=>window.location.reload(),variant:"default",className:"w-full flex items-center justify-center gap-2",children:"Refresh Page"})]})]})})}class xn extends f.Component{constructor(t){super(t),this.state={hasError:!1}}static getDerivedStateFromError(t){return{hasError:!0,error:t}}componentDidCatch(t,r){g.error("[LazyComponent] Failed to load lazy component",{pageName:this.props.pageName,error:t instanceof Error?t.message:String(t),stack:t instanceof Error?t.stack:void 0,componentStack:r.componentStack}),this.props.onError?.(t,r)}handleRetry=()=>{this.setState({hasError:!1,error:void 0})};render(){return this.state.hasError?s.jsx(Mr,{pageName:this.props.pageName,error:this.state.error,onRetry:this.handleRetry}):this.props.children}}function bn({size:e="md",className:t,text:r}){const a={sm:"h-4 w-4",md:"h-8 w-8",lg:"h-12 w-12"};return s.jsxs("div",{className:w("flex flex-col items-center justify-center min-h-[200px]",t),children:[s.jsx("div",{className:w("animate-spin rounded-full border-2 border-kodo-steel border-t-blue-600",a[e]),role:"status","aria-label":"Chargement en cours",children:s.jsx("span",{className:"sr-only",children:"Chargement..."})}),r&&s.jsx("p",{className:"mt-2 text-sm text-kodo-content-dim dark:text-kodo-content-dim",children:r})]})}function wn(e,t){return e().then(r=>r).catch(r=>{const a=r instanceof Error?r.message:String(r);return g.error("[LazyComponent] Failed to import lazy component",{pageName:t,error:a,stack:r instanceof Error?r.stack:void 0}),Promise.resolve({default:()=>s.jsx(Mr,{pageName:t,error:r instanceof Error?r:new Error(a)})})})}function A(e,t,r){const a=r?()=>wn(e,r):e,n=f.lazy(a);return function(o){const{fallback:c,...l}=o,p=s.jsx(f.Suspense,{fallback:s.jsx(bn,{}),children:s.jsx(n,{...l})});return r?s.jsx(xn,{pageName:r,children:p}):p}}const kn=A(()=>N(()=>import("./DashboardPage-BMNaRTjt.js"),__vite__mapDeps([3,1,0,2,4,5,6,7,8])),void 0,"Dashboard"),En=A(()=>N(()=>import("./ChatPage-BO6K8M83.js"),__vite__mapDeps([9,1,0,2,4,10,7,11,12,5,13,14,6,8])).then(e=>({default:e.ChatPage})),void 0,"Chat"),_n=A(()=>N(()=>import("./LibraryPage-DJ1eADn5.js"),__vite__mapDeps([15,1,0,2,4,16,13,12,7,17,18,10,8,6])).then(e=>({default:e.LibraryPage})),void 0,"Library"),Sn=A(()=>N(()=>import("./UserProfilePage-B2tC81y7.js"),__vite__mapDeps([19,1,0,2,4,20,16,21,22,6,7,23,8,24,25])).then(e=>({default:e.UserProfilePage})),void 0,"Profile"),Nn=A(()=>N(()=>import("./SettingsPage-DSklKTTs.js"),__vite__mapDeps([26,1,0,2,20,25,10,7,11,12,27,18,22,8,6,4])).then(e=>({default:e.SettingsPage})),void 0,"Settings"),Tn=A(()=>N(()=>import("./LoginPage-6ERIsPFb.js"),__vite__mapDeps([28,1,0,2,6,29,30,4,31,7,8])),void 0,"Login"),jn=A(()=>N(()=>import("./RegisterPage-Dikw454Q.js"),__vite__mapDeps([32,1,0,2,31,6,4,10,7,27,33,8])),void 0,"Register"),Cn=A(()=>N(()=>import("./ForgotPasswordPage-wIZ3bMJo.js"),__vite__mapDeps([34,1,0,2,6,31,29,30,35,4,8,7])),void 0,"Forgot Password"),Rn=A(()=>N(()=>import("./VerifyEmailPage-Cj8MYc6s.js"),__vite__mapDeps([36,1,0,2,6,31,30,4,8,7])),void 0,"Verify Email"),An=A(()=>N(()=>import("./ResetPasswordPage-Doc7zcwQ.js"),__vite__mapDeps([37,1,0,2,6,31,29,30,33,35,4,8,7])),void 0,"Reset Password"),Pn=A(()=>N(()=>import("./SessionsPage-BJ02ofFg.js"),__vite__mapDeps([38,1,0,2,14,7,6,4,8])),void 0,"Sessions"),In=A(()=>N(()=>import("./NotFoundPage-DoPT3V64.js"),__vite__mapDeps([39,1,0,2,6,7,4,8])),void 0,"Not Found"),Ln=A(()=>N(()=>import("./ServerErrorPage-CZyfhQKe.js"),__vite__mapDeps([40,1,0,2,6,7,4,8])),void 0,"Server Error"),qn=A(()=>N(()=>import("./UserProfilePage-B2tC81y7.js"),__vite__mapDeps([19,1,0,2,4,20,16,21,22,6,7,23,8,24,25])).then(e=>({default:e.UserProfilePage})),void 0,"User Profile"),Dn=A(()=>N(()=>import("./RolesPage-Ba5bJq9j.js"),__vite__mapDeps([41,1,0,2,22,10,7,42,11,12,6,4,8])).then(e=>({default:e.RolesPage})),void 0,"Roles"),Mn=A(()=>N(()=>import("./TrackDetailPage-CoaPghB_.js"),__vite__mapDeps([43,1,0,2,7,25,4,13,12,24,10,44,14,8,16,18,6])).then(e=>({default:e.TrackDetailPage})),void 0,"Track Detail"),On=A(()=>N(()=>import("./routes-CJBS24ox.js"),__vite__mapDeps([45,1,0,2,4,21,22,6,7,46,44,47,8,10,42,27,11,12,24,14,25,48,49])).then(e=>({default:e.PlaylistRoutes})),void 0,"Playlists"),zn=A(()=>N(()=>import("./AdminDashboardView-CvscVmHo.js"),__vite__mapDeps([50,1,0,2,7,25,46,6,4,8])).then(e=>({default:e.AdminDashboardView})),void 0,"Admin Dashboard"),Fn=A(()=>N(()=>import("./AnalyticsView-B3o6WIlr.js"),__vite__mapDeps([51,1,0,2,7,52,46,6,4,8])).then(e=>({default:e.AnalyticsView})),void 0,"Analytics"),Vn=A(()=>N(()=>import("./WebhooksView-B5i4t7Y2.js"),__vite__mapDeps([53,1,0,2,10,7,54,6,4,8])).then(e=>({default:e.WebhooksView})),void 0,"Webhooks"),Un=A(()=>N(()=>import("./DesignSystemDemo-C_pcj_EH.js"),__vite__mapDeps([55,1,0,2])).then(e=>({default:e.DesignSystemDemo})),void 0,"Design System Demo"),$n=A(()=>N(()=>import("./SocialView-C_G9BXzk.js"),__vite__mapDeps([56,1,0,2,7,46,6,4,8])).then(e=>({default:e.SocialView})),void 0,"Social"),Qn=A(()=>N(()=>import("./GearView-BL2JvPVu.js"),__vite__mapDeps([57,1,0,2,46,7,10,6,4,8])).then(e=>({default:e.GearView})),void 0,"Gear"),Bn=A(()=>N(()=>import("./LiveView-DSSm3dtG.js"),__vite__mapDeps([58,1,0,2,7,46,6,4,8])).then(e=>({default:e.LiveView})),void 0,"Live"),Kn=A(()=>N(()=>import("./EducationView-Dgv2lm_h.js"),__vite__mapDeps([59,1,0,2,17,7,10,46,6,4,8])).then(e=>({default:e.EducationView})),void 0,"Education"),Hn=A(()=>N(()=>import("./QueueView-q1taT2la.js"),__vite__mapDeps([60,1,0,2,10,7,6,4,8])).then(e=>({default:e.QueueView})),void 0,"Queue"),Wn=A(()=>N(()=>import("./DeveloperDashboardView-Dkv7ps0m.js"),__vite__mapDeps([61,1,0,2,52,7,10,54,25,6,4,8])).then(e=>({default:e.DeveloperDashboardView})),void 0,"Developer"),Gn=A(()=>N(()=>import("./NotificationsView-n_qp2i9l.js"),__vite__mapDeps([62,1,0,2,7,46,23,6,4,8])).then(e=>({default:e.NotificationsView})),void 0,"Notifications"),Yn=A(()=>N(()=>import("./MarketplaceHome-DBtdadsi.js"),__vite__mapDeps([63,1,0,2,64,7,10,65,47,6,4,8])).then(e=>({default:e.MarketplaceHome})),void 0,"Marketplace"),Xn=A(()=>N(()=>import("./SearchPage-77y10iyI.js"),__vite__mapDeps([66,1,0,2,6,48,7,25,24,8,4])).then(e=>({default:e.SearchPage})),void 0,"Search"),Jn=A(()=>N(()=>import("./SellerDashboardView-ymVO9IBa.js"),__vite__mapDeps([67,1,0,2,7,64,68,6,4,8])).then(e=>({default:e.SellerDashboardView})),void 0,"Seller Dashboard"),Zn=A(()=>N(()=>import("./WishlistView-BrN3xAjD.js"),__vite__mapDeps([69,1,0,2,65,7,6,4,8])).then(e=>({default:e.WishlistView})),void 0,"Wishlist"),ei=A(()=>N(()=>import("./PurchasesView-B_mVTOu6.js"),__vite__mapDeps([70,1,0,2,7,68,10,46,6,4,8])).then(e=>({default:e.PurchasesView})),void 0,"Purchases");function ti({children:e}){const{isAuthenticated:t}=Dr(),r=!1,{isLoading:a}=Z();return a?null:t||r?s.jsx(Ge,{to:"/dashboard",replace:!0}):s.jsx(s.Fragment,{children:e})}function Or(){const{i18n:e,t}=as(),{language:r,setLanguage:a}=xe(),n=i=>{e.changeLanguage(i),a(i)};return{t,i18n:{...e,changeLanguage:async i=>{await e.changeLanguage(i)},isInitialized:e.isInitialized},language:r,changeLanguage:n,isReady:e.isInitialized}}function ri({verified:e}){return e?s.jsx("span",{className:"inline-flex items-center px-2 py-1 rounded-full text-xs font-medium bg-success/20 text-success",children:"✓ Email Verified"}):s.jsx("span",{className:"inline-flex items-center px-2 py-1 rounded-full text-xs font-medium bg-warning/20 text-warning",children:"⚠ Email Not Verified"})}async function si(e){try{const t=new URLSearchParams;e?.read!==void 0&&t.append("read",e.read.toString()),e?.type&&t.append("type",e.type),e?.page&&t.append("page",e.page.toString()),e?.limit&&t.append("limit",e.limit.toString());const r=await D.get(`/notifications?${t.toString()}`);return{notifications:r.data.notifications||[],total:r.data.total,page:r.data.page||e?.page||1,limit:r.data.limit||e?.limit||20,totalPages:r.data.totalPages,unreadCount:r.data.unread_count}}catch(t){throw t instanceof tt?new Error(t.response?.data?.error||t.message||"Failed to fetch notifications"):t}}async function ai(e){try{await D.post(`/notifications/${e}/read`)}catch(t){throw t instanceof tt?new Error(t.response?.data?.error||t.message||"Failed to mark notification as read"):t}}async function ni(){try{await D.post("/notifications/read-all")}catch(e){throw e instanceof tt?new Error(e.response?.data?.error||e.message||"Failed to mark all notifications as read"):e}}function ii(){const{addToast:e}=Ar();return{success:(t,r)=>e({message:t,type:"success",duration:r}),error:(t,r)=>e({message:t,type:"error",duration:r}),warning:(t,r)=>e({message:t,type:"warning",duration:r}),info:(t,r)=>e({message:t,type:"info",duration:r}),toast:t=>e(t)}}const oi=3e4,li=50;function ci(e){const[t,r]=f.useState(!1),a=f.useRef(null),n=et(),i=St(),{success:o,error:c}=ii(),l=Jt({queryKey:["notifications","menu"],queryFn:()=>si({limit:li}),refetchInterval:oi,staleTime:1e4,enabled:e?.notificationsOverride===void 0&&e?.isLoadingOverride===void 0&&e?.errorOverride===void 0}),p=e?.notificationsOverride!==void 0?e.notificationsOverride??[]:l.data?.notifications??[],u=e?.isLoadingOverride??l.isLoading,d=e?.errorOverride!==void 0?e.errorOverride:l.error?String(l.error):null,h=p.filter(m=>!m.read).length,v=l.refetch,y=["notifications","menu"],k=qt({mutationFn:ai,onMutate:async m=>{await i.cancelQueries({queryKey:y});const x=i.getQueryData(y);return x&&i.setQueryData(y,{...x,notifications:x.notifications.map(j=>j.id===m?{...j,read:!0}:j),unreadCount:Math.max((x.unreadCount??1)-1,0)}),{previous:x}},onError:(m,x,j)=>{j?.previous&&i.setQueryData(y,j.previous),c("Erreur lors du marquage")},onSuccess:()=>{i.invalidateQueries({queryKey:y})}}),S=qt({mutationFn:ni,onMutate:async()=>{await i.cancelQueries({queryKey:y});const m=i.getQueryData(y);return m&&i.setQueryData(y,{...m,notifications:m.notifications.map(x=>({...x,read:!0})),unreadCount:0}),{previous:m}},onError:(m,x,j)=>{j?.previous&&i.setQueryData(y,j.previous),c("Erreur lors du marquage")},onSuccess:()=>{i.invalidateQueries({queryKey:y}),o("Toutes les notifications ont été marquées comme lues")}});f.useEffect(()=>{function m(x){a.current&&!a.current.contains(x.target)&&r(!1)}return t&&document.addEventListener("mousedown",m),()=>document.removeEventListener("mousedown",m)},[t]),f.useEffect(()=>{t&&v()},[t,v]);const _=f.useCallback(m=>k.mutate(m),[k]),E=f.useCallback(()=>S.mutate(),[S]),I=f.useCallback(m=>{m.read||_(m.id),m.link&&(n(m.link),r(!1))},[_,n]),M=f.useCallback(()=>{n("/notifications"),r(!1)},[n]);return{menuRef:a,isOpen:t,setIsOpen:r,notifications:p,isLoading:u,error:d,unreadCount:h,handleMarkAsRead:_,handleMarkAllAsRead:E,handleNotificationClick:I,handleViewAll:M,markAsReadMutation:k,markAllAsReadMutation:S}}function ui({isOpen:e,unreadCount:t,onClick:r}){return s.jsxs(P,{variant:"ghost",size:"icon",className:"relative",onClick:r,"aria-label":"Notifications","aria-expanded":e,"aria-haspopup":"true",children:[s.jsx(sr,{className:"h-5 w-5"}),t>0&&s.jsx("span",{className:"absolute -top-1 -right-1 h-5 w-5 bg-destructive rounded-full text-xs text-destructive-foreground flex items-center justify-center font-semibold","aria-label":`${t} notifications non lues`,children:t>9?"9+":t})]})}function di({notification:e,onMarkAsRead:t,onClick:r,isMarking:a}){return s.jsx("div",{role:"button",tabIndex:0,className:w("p-4 hover:bg-accent transition-colors cursor-pointer",!e.read&&"bg-accent/50"),onClick:()=>r(e),onKeyDown:n=>{(n.key==="Enter"||n.key===" ")&&(n.preventDefault(),r(e))},children:s.jsxs("div",{className:"flex items-start justify-between gap-2",children:[s.jsxs("div",{className:"flex-1 min-w-0",children:[s.jsxs("div",{className:"flex items-center space-x-2 mb-1",children:[!e.read&&s.jsx("span",{className:"h-2 w-2 bg-primary rounded-full flex-shrink-0 mt-1.5"}),s.jsx("p",{className:w("text-sm font-medium",!e.read&&"font-semibold"),children:e.title})]}),e.content&&s.jsx("p",{className:"text-sm text-muted-foreground mb-2 line-clamp-2",children:e.content}),s.jsx("p",{className:"text-xs text-muted-foreground",children:os(new Date(e.created_at),{addSuffix:!0,locale:ls})})]}),s.jsx("div",{className:"flex items-center space-x-1 ml-2 shrink-0",children:!e.read&&s.jsx(P,{variant:"ghost",size:"icon",className:"h-6 w-6",onClick:n=>{n.stopPropagation(),t(e.id)},"aria-label":"Marquer comme lu",disabled:a,children:a?s.jsx(Me,{className:"h-3 w-3 animate-spin"}):s.jsx(ys,{className:"h-3 w-3"})})})]})})}function mi({isLoading:e,error:t,notifications:r,onMarkAsRead:a,onNotificationClick:n,isMarkingAsRead:i}){return t?s.jsx("div",{className:"p-4 text-center text-destructive text-sm",children:t}):e?s.jsx("div",{className:"flex items-center justify-center py-8",children:s.jsx(Me,{className:"h-6 w-6 animate-spin text-muted-foreground"})}):r.length===0?s.jsxs("div",{className:"p-8 text-center text-muted-foreground",children:[s.jsx(sr,{className:"h-12 w-12 mx-auto mb-2 opacity-50"}),s.jsx("p",{className:"text-sm",children:"Aucune notification"})]}):s.jsx("div",{className:"divide-y",children:r.map(o=>s.jsx(di,{notification:o,onMarkAsRead:a,onClick:n,isMarking:i},o.id))})}function fi({unreadCount:e,notifications:t,isLoading:r,onMarkAllAsRead:a,onMarkAsRead:n,onNotificationClick:i,onViewAll:o,markAllPending:c,markPending:l,error:p}){return s.jsxs("div",{className:"absolute right-0 mt-2 w-80 bg-background border rounded-lg shadow-lg z-50 max-h-96 flex flex-col",children:[s.jsxs("div",{className:"p-4 border-b flex items-center justify-between shrink-0",children:[s.jsx("h3",{className:"font-semibold text-sm",children:"Notifications"}),s.jsx("div",{className:"flex items-center space-x-2",children:e>0&&s.jsxs(P,{variant:"ghost",size:"sm",onClick:a,className:"h-7 text-xs",disabled:c,children:[c?s.jsx(Me,{className:"h-3 w-3 mr-1 animate-spin"}):s.jsx(vs,{className:"h-3 w-3 mr-1"}),"Tout marquer comme lu"]})})]}),s.jsx("div",{className:"overflow-y-auto flex-1 min-h-0",children:s.jsx(mi,{isLoading:r,error:p,notifications:t,onMarkAsRead:n,onNotificationClick:i,isMarkingAsRead:l})}),t.length>0&&s.jsx("div",{className:"p-4 border-t shrink-0",children:s.jsx(P,{variant:"ghost",size:"sm",className:"w-full",onClick:o,children:"Voir toutes les notifications"})})]})}function hi({isLoadingOverride:e,errorOverride:t,notificationsOverride:r}={}){const{menuRef:a,isOpen:n,setIsOpen:i,notifications:o,isLoading:c,error:l,unreadCount:p,handleMarkAsRead:u,handleMarkAllAsRead:d,handleNotificationClick:h,handleViewAll:v,markAsReadMutation:y,markAllAsReadMutation:k}=ci({isLoadingOverride:e,errorOverride:t,notificationsOverride:r??void 0});return s.jsxs("div",{className:"relative",ref:a,children:[s.jsx(ui,{isOpen:n,unreadCount:p,onClick:()=>i(!n)}),n&&s.jsx(fi,{unreadCount:p,notifications:o,isLoading:c,error:l,onMarkAllAsRead:d,onMarkAsRead:u,onNotificationClick:h,onViewAll:v,markAllPending:k.isPending,markPending:y.isPending})]})}function pi(){const{limit:e,remaining:t,reset:r,isLimited:a}=kt(),[n,i]=f.useState(null);f.useEffect(()=>{if(!r){i(null);return}const u=()=>{const h=Math.floor(Date.now()/1e3),v=r-h;i(v>0?v:0)};u();const d=setInterval(u,1e3);return()=>clearInterval(d)},[r]);const o=e!==null&&t!==null&&e>0?t/e*100:null;if(!(a||e!==null&&t!==null&&o!==null&&o<20)||e===null)return null;const l=u=>{if(u<=0)return"0s";if(u<60)return`${u}s`;const d=Math.floor(u/60),h=u%60;if(d<60)return h>0?`${d}m ${h}s`:`${d}m`;const v=Math.floor(d/60),y=d%60;return y>0?`${v}h ${y}m`:`${v}h`},p=a||t!==null&&t<=0;return s.jsxs("div",{className:w("flex items-center gap-2 px-4 py-1.5 rounded-lg text-xs font-medium transition-all",p?"bg-kodo-red/10 text-kodo-red border border-kodo-red/30":"bg-kodo-gold/10 text-kodo-gold border border-kodo-gold/30"),role:"alert","aria-live":"polite",children:[s.jsx(st,{className:"w-4 h-4 flex-shrink-0"}),s.jsx("div",{className:"flex items-center gap-2",children:a?s.jsxs(s.Fragment,{children:[s.jsx("span",{children:"Rate limit exceeded"}),n!==null&&s.jsxs("span",{className:"flex items-center gap-1",children:[s.jsx(Ce,{className:"w-3 h-3"}),l(n)]})]}):s.jsxs(s.Fragment,{children:[s.jsx("span",{children:t!==null?`${t}/${e} requests`:`${e} requests`}),n!==null&&s.jsxs("span",{className:"flex items-center gap-1 opacity-75",children:[s.jsx(Ce,{className:"w-3 h-3"}),"resets in ",l(n)]})]})})]})}function gi(e,t,r,a){const[n,i]=f.useState(!1),[o,c]=f.useState(!1),[l,p]=f.useState(e),[u,d]=f.useState({}),h=f.useRef(null),v=f.useRef(null),y=f.useRef(null),k=f.useRef(null),S=f.useCallback(()=>{if(!y.current||!k.current||!n)return;const m=y.current.getBoundingClientRect(),x=k.current.getBoundingClientRect(),j=window.innerWidth,F=window.innerHeight,$=8;let U=e,Y=0,X=0;switch(e){case"top":m.top-x.height-$<0&&(U="bottom");break;case"bottom":m.bottom+x.height+$>F&&(U="top");break;case"left":m.left-x.width-$<0&&(U="right");break;case"right":m.right+x.width+$>j&&(U="left");break}if(U==="top"||U==="bottom"){const H=m.left+m.width/2,K=x.width/2,W=$,ie=j-$;H-K<W?Y=W-(H-K):H+K>ie&&(Y=ie-(H+K))}else{const H=m.top+m.height/2,K=x.height/2,W=$,ie=F-$;H-K<W?X=W-(H-K):H+K>ie&&(X=ie-(H+K))}p(U),d({...Y!==0&&{transform:`translate(calc(-50% + ${Y}px), 0)`},...X!==0&&{transform:`translate(0, calc(-50% + ${X}px))`}})},[e,n]);f.useEffect(()=>{n&&S()},[n,S]),f.useEffect(()=>{o&&n&&S()},[o,n,S]);const _=f.useCallback(()=>{h.current&&clearTimeout(h.current),h.current=setTimeout(()=>{i(!0),c(!0)},r)},[r]),E=f.useCallback(()=>{h.current&&clearTimeout(h.current),v.current&&clearTimeout(v.current),v.current=setTimeout(()=>{i(!1)},100)},[]),I=f.useCallback(()=>{t==="click"&&i(m=>{const x=!m;return x&&c(!0),x})},[t]),M=t==="hover"?{onMouseEnter:_,onMouseLeave:E}:t==="click"?{onClick:I}:{onFocus:_,onBlur:E};return f.useEffect(()=>()=>{h.current&&clearTimeout(h.current),v.current&&clearTimeout(v.current)},[]),{visible:n,isMounted:o,calculatedPosition:l,tooltipStyle:u,wrapperRef:y,tooltipRef:k,triggerProps:a?{}:M}}const yi={top:"bottom-full left-1/2 -translate-x-1/2 mb-2",bottom:"top-full left-1/2 -translate-x-1/2 mt-2",left:"right-full top-1/2 -translate-y-1/2 mr-2",right:"left-full top-1/2 -translate-y-1/2 ml-2"},vi={top:"top-full left-1/2 -translate-x-1/2 border-t-card border-l-transparent border-r-transparent border-b-transparent",bottom:"bottom-full left-1/2 -translate-x-1/2 border-b-card border-l-transparent border-r-transparent border-t-transparent",left:"left-full top-1/2 -translate-y-1/2 border-l-card border-t-transparent border-b-transparent border-r-transparent",right:"right-full top-1/2 -translate-y-1/2 border-r-card border-t-transparent border-b-transparent border-l-transparent"};function xi({content:e,visible:t,calculatedPosition:r,tooltipStyle:a,tooltipRef:n,showArrow:i,maxWidth:o,className:c}){return s.jsxs("div",{ref:n,className:w("absolute z-50 max-w-xs px-4 py-1.5 text-sm text-foreground bg-card rounded-xl shadow-lg","border border-border pointer-events-none","transition-all duration-[var(--duration-normal)]",yi[r],t?"opacity-100 scale-100":"opacity-0 scale-95",c),role:"tooltip",style:{...o!=null&&{maxWidth:`${o}px`},...a},children:[e,i&&s.jsx("div",{className:w("absolute w-0 h-0 border-4",vi[r])})]})}function bi({content:e,children:t,position:r="top",trigger:a="hover",delay:n=200,showArrow:i=!0,maxWidth:o,disabled:c=!1,className:l}){const{visible:p,isMounted:u,calculatedPosition:d,tooltipStyle:h,wrapperRef:v,tooltipRef:y,triggerProps:k}=gi(r,a,n,c);if(c)return s.jsx(s.Fragment,{children:t});const S=a==="hover",_=S?k:{},E=!S&&f.isValidElement(t)&&f.Children.only(t)?f.cloneElement(t,k):t;return s.jsxs("div",{ref:v,className:"relative inline-block",..._,children:[E,u&&s.jsx(xi,{content:e,visible:p,calculatedPosition:d,tooltipStyle:h,tooltipRef:y,showArrow:i,maxWidth:o,className:l})]})}function wi(e){const[t,r]=f.useState(!1),{logout:a}=Z(),{data:n}=qr(),{theme:i,setTheme:o,sidebarOpen:c,setSidebarOpen:l}=xe(),{t:p}=Or(),u=et(),d=async()=>{await a(),u("/login")},h=()=>{o(i==="light"?"dark":i==="dark"?"system":"light")},v=()=>{switch(i){case"light":return s.jsx(_s,{className:"h-4 w-4"});case"dark":return s.jsx(Es,{className:"h-4 w-4"});default:return s.jsx(ks,{className:"h-4 w-4"})}};return s.jsx("header",{className:"fixed top-0 left-0 right-0 h-20 z-50 pointer-events-none",children:s.jsxs("div",{className:w("absolute top-0 right-0 h-20 bg-gradient-to-b from-background/90 via-background/80 to-transparent backdrop-blur-md flex items-center justify-between px-6 pointer-events-auto transition-all duration-[var(--duration-immersive)] ease-in-out",c?"left-72":"left-20","max-lg:left-0"),children:[s.jsx("button",{onClick:()=>l(!c),className:"lg:hidden p-2 rounded-xl hover:bg-muted text-muted-foreground hover:text-foreground mr-4",children:s.jsx(xs,{className:"w-5 h-5"})}),s.jsx("div",{className:"flex-1 max-w-xl relative hidden md:block group",children:s.jsxs("div",{className:"relative flex items-center group/search",children:[s.jsx(bs,{className:"absolute left-4 w-4 h-4 text-muted-foreground group-hover/search:text-primary transition-colors duration-[var(--duration-normal)]"}),s.jsx("input",{type:"text",placeholder:"Search Network...",className:"w-full h-11 pl-12 pr-16 bg-card border border-white/10 rounded-xl text-sm text-foreground placeholder:text-muted-foreground focus:outline-none focus:border-primary/40 focus:ring-4 focus:ring-primary/10 transition-all duration-[var(--duration-normal)] shadow-inner"}),s.jsx("div",{className:"absolute right-3 px-2 py-1 rounded-md bg-white/5 border border-white/5 text-[10px] font-mono font-bold text-muted-foreground group-hover/search:text-foreground group-hover/search:bg-white/10 transition-colors",children:"CMD+K"})]})}),s.jsxs("div",{className:"flex items-center gap-3 ml-4",children:[s.jsxs("div",{className:"hidden xl:flex items-center gap-2 mr-4 px-3 py-1.5 rounded-full bg-primary/10 border border-primary/20",children:[s.jsx("div",{className:"w-1.5 h-1.5 rounded-full bg-primary animate-pulse shadow-[0_0_8px_hsl(var(--primary)/0.5)]"}),s.jsx("span",{className:"text-[10px] font-mono text-primary uppercase font-bold tracking-tight",children:"Network Stable"})]}),s.jsx(hi,{}),s.jsx(pi,{}),s.jsx("div",{className:"h-8 w-px bg-gradient-to-b from-transparent via-white/10 to-transparent mx-2"}),s.jsx(bi,{content:p("common.changeTheme"),children:s.jsx(P,{variant:"ghost",size:"icon",onClick:h,className:"w-9 h-9 rounded-xl hover:bg-muted hover:text-foreground text-muted-foreground",children:v()})}),s.jsxs("div",{className:"relative ml-2",children:[s.jsxs("button",{onClick:()=>r(!t),className:"flex items-center gap-3 p-1.5 pr-4 rounded-full hover:bg-white/5 transition-all border border-transparent focus:outline-none focus:ring-2 focus:ring-primary/50 group",children:[s.jsx("div",{className:"w-9 h-9 rounded-full bg-gradient-to-br from-primary to-primary/80 p-0.5 shadow-lg shadow-primary/10 group-hover:shadow-primary/30 transition-shadow duration-300",children:s.jsx("div",{className:"w-full h-full rounded-full bg-card flex items-center justify-center overflow-hidden",children:s.jsx("span",{className:"text-xs font-bold text-white group-hover:scale-110 transition-transform duration-300",children:n?.username?.substring(0,2).toUpperCase()||"VZ"})})}),s.jsxs("div",{className:"hidden lg:block text-left",children:[s.jsx("div",{className:"text-xs font-bold text-white leading-none mb-1 group-hover:text-primary transition-colors",children:n?.username}),s.jsx("div",{className:"text-[9px] text-muted-foreground uppercase tracking-wider font-mono",children:"LVL. 01"})]})]}),t&&s.jsx(Tr,{active:t,onEscape:()=>r(!1),children:s.jsxs("div",{className:"absolute right-0 top-full mt-2 w-64 bg-card/95 backdrop-blur-xl border border-white/10 rounded-2xl shadow-2xl p-2 z-50 animate-scaleIn origin-top-right",children:[s.jsxs("div",{className:"px-3 py-3 border-b border-white/5 mb-1",children:[s.jsx("p",{className:"text-sm font-bold text-white truncate text-center mb-1",children:n?.username}),s.jsx("p",{className:"text-xs text-muted-foreground truncate text-center font-mono",children:n?.email}),!n?.is_verified&&s.jsx("div",{className:"mt-2 flex justify-center",children:s.jsx(ri,{verified:!1})})]}),s.jsxs("div",{className:"p-1 space-y-0.5",children:[s.jsxs(Ye,{to:"/profile",className:"flex items-center gap-3 px-3 py-2.5 text-sm text-muted-foreground hover:text-foreground hover:bg-muted rounded-xl transition-colors",children:[s.jsx(ws,{className:"w-4 h-4"})," Profil"]}),s.jsxs(Ye,{to:"/settings",className:"flex items-center gap-3 px-3 py-2.5 text-sm text-muted-foreground hover:text-foreground hover:bg-muted rounded-xl transition-colors",children:[s.jsx(ar,{className:"w-4 h-4"})," Paramètres"]})]}),s.jsx("div",{className:"h-px bg-white/5 my-1"}),s.jsx("div",{className:"p-1",children:s.jsxs("button",{onClick:d,className:"w-full flex items-center gap-3 px-3 py-2.5 text-sm text-destructive hover:bg-destructive/10 rounded-xl transition-colors",children:[s.jsx(nr,{className:"w-4 h-4"})," Déconnexion"]})})]})})]})]})]})})}const ki=[{section:"My Studio",items:[{id:"dashboard",label:"Command Center",icon:s.jsx(js,{className:"w-4 h-4"})},{id:"studio",label:"Cloud Files",icon:s.jsx(Cs,{className:"w-4 h-4"})},{id:"tracks",label:"Projects",icon:s.jsx(Rs,{className:"w-4 h-4"})},{id:"gear",label:"Gear Locker",icon:s.jsx(As,{className:"w-4 h-4"})},{id:"analytics",label:"Performance",icon:s.jsx(Ps,{className:"w-4 h-4"})}]},{section:"Veza Network",items:[{id:"social",label:"Community Feed",icon:s.jsx(Is,{className:"w-4 h-4"})},{id:"marketplace",label:"Marketplace",icon:s.jsx(Ls,{className:"w-4 h-4"})},{id:"live",label:"Live Sessions",icon:s.jsx(qs,{className:"w-4 h-4"}),badge:3},{id:"chat",label:"Channels",icon:s.jsx(Ds,{className:"w-4 h-4"}),badge:12},{id:"education",label:"Academy",icon:s.jsx(Ms,{className:"w-4 h-4"})}]},{section:"Commerce",items:[{id:"sell",label:"Seller Dashboard",icon:s.jsx(Os,{className:"w-4 h-4"})},{id:"wishlist",label:"Wishlist",icon:s.jsx(Tt,{className:"w-4 h-4"})},{id:"purchases",label:"Purchases",icon:s.jsx(zs,{className:"w-4 h-4"})}]},{section:"Library",items:[{id:"playlists",label:"Playlists",icon:s.jsx(ir,{className:"w-4 h-4"})},{id:"queue",label:"Play Queue",icon:s.jsx(Fs,{className:"w-4 h-4"})}]},{section:"System",items:[{id:"developer",label:"Developer API",icon:s.jsx(Vs,{className:"w-4 h-4"})},{id:"admin",label:"Admin Panel",icon:s.jsx(Us,{className:"w-4 h-4"})}]}],vt={dashboard:"/dashboard",studio:"/library",tracks:"/library",gear:"/gear",analytics:"/analytics",social:"/social",marketplace:"/marketplace",live:"/live",chat:"/chat",education:"/education",sell:"/sell",wishlist:"/wishlist",purchases:"/purchases",playlists:"/playlists",queue:"/queue",developer:"/developer",admin:"/admin",settings:"/settings"},Ei=({currentView:e,onNavigate:t,onLogout:r})=>{const a=et(),n=Gr(),{logout:i}=Z(),{sidebarOpen:o,setSidebarOpen:c}=xe(),l=()=>{window.innerWidth<1024&&c(!1)},p=e||Object.keys(vt).find(d=>vt[d]===n.pathname)||"dashboard",u=()=>{i(),a("/login"),r?.()};return s.jsxs(s.Fragment,{children:[o&&s.jsx("div",{className:"fixed inset-0 bg-black/60 backdrop-blur-sm lg:hidden z-[90]",onClick:()=>c(!1),"aria-hidden":"true"}),s.jsxs("aside",{className:w("fixed left-6 bottom-6 top-24 rounded-xl flex flex-col transition-all duration-500 ease-[cubic-bezier(0.33,1,0.68,1)] z-[95] overflow-hidden border border-white/5 bg-[var(--sidebar)] backdrop-blur-md",o?"w-64 translate-x-0 opacity-100":"-translate-x-full lg:translate-x-0 lg:opacity-100 lg:w-20"),children:[s.jsxs("div",{className:"p-6 border-b border-white/5 flex items-center gap-4 relative",children:[s.jsx("div",{className:"w-8 h-8 rounded-lg bg-muted/20 flex items-center justify-center border border-white/10 shadow-[0_0_15px_rgba(0,0,0,0.5)] flex-shrink-0",children:s.jsx(Ss,{className:"w-4 h-4 text-muted-foreground"})}),s.jsxs("div",{className:w("transition-all duration-300 overflow-hidden",o?"w-auto opacity-100":"w-0 opacity-0"),children:[s.jsx("h2",{className:"text-xs font-display font-bold text-foreground tracking-widest uppercase whitespace-nowrap",children:"System Hub"}),s.jsxs("div",{className:"flex items-center gap-1.5 mt-0.5",children:[s.jsx("span",{className:"w-1.5 h-1.5 rounded-full bg-primary animate-pulse shadow-[0_0_8px_var(--color-primary)]"}),s.jsx("span",{className:"text-[9px] font-mono text-primary opacity-90 uppercase whitespace-nowrap tracking-wider",children:"Online"})]})]}),s.jsx(P,{variant:"ghost",size:"icon",onClick:()=>c(!o),className:w("ml-auto text-muted-foreground hover:text-white hidden lg:flex hover:bg-white/5",!o&&"absolute left-1/2 -translate-x-1/2 top-1/2 -translate-y-1/2"),children:o?s.jsx(Ns,{className:"w-4 h-4"}):s.jsx(Ts,{className:"w-4 h-4"})})]}),s.jsx("div",{className:"flex-1 overflow-y-auto custom-scrollbar p-3 space-y-8",children:ki.map((d,h)=>s.jsxs("div",{children:[s.jsx("h3",{className:w("text-[9px] font-mono font-bold text-muted-foreground/50 uppercase tracking-[0.2em] mb-3 mt-1 px-3 transition-all duration-300",!o&&"opacity-0 h-0 overflow-hidden mb-0 mt-0"),children:d.section}),s.jsx("div",{className:"space-y-1",children:d.items.map(v=>{const y=vt[v.id]||"/dashboard",k=p===v.id;return s.jsxs(Ye,{to:y,onClick:()=>{l(),t?.(v.id)},className:w("w-full flex items-center px-3 py-2.5 rounded-xl text-sm font-medium transition-all duration-[var(--duration-immersive)] ease-in-out group relative overflow-hidden",k?"bg-primary/10 text-foreground shadow-[inset_2px_0_0_0_var(--color-primary)]":"text-muted-foreground/60 hover:text-primary hover:bg-white/5",!o&&"justify-center px-0"),title:o?void 0:v.label,children:[k&&s.jsx("div",{className:"absolute inset-0 bg-gradient-to-r from-primary/10 to-transparent opacity-50 pointer-events-none"}),s.jsxs("div",{className:w("flex items-center gap-3 relative z-10",!o&&"justify-center"),children:[s.jsx("span",{className:w("transition-colors duration-[var(--duration-immersive)] ease-in-out",k?"text-primary":"text-muted-foreground/60 group-hover:text-primary"),children:v.icon}),s.jsx("span",{className:w("transition-all duration-300 whitespace-nowrap origin-left font-sans text-[13px]",o?"w-auto opacity-100 scale-100":"w-0 opacity-0 scale-95 hidden"),children:v.label})]}),v.badge&&o&&s.jsx("span",{className:"ml-auto bg-primary/20 text-primary text-[9px] px-1.5 py-0.5 rounded font-mono font-bold border border-primary/30",children:v.badge}),v.badge&&!o&&s.jsx("span",{className:"absolute top-2 right-2 w-1.5 h-1.5 rounded-full bg-primary shadow-[0_0_5px_var(--color-primary)]"})]},v.id)})})]},h))}),s.jsxs("div",{className:"p-3 border-t border-white/5 bg-black/20 backdrop-blur-sm",children:[s.jsxs(Ye,{to:"/settings",onClick:()=>{l(),t?.("settings")},className:w("flex items-center gap-3 px-3 py-2.5 rounded-xl text-sm transition-all duration-[var(--duration-immersive)] ease-in-out",p==="settings"?"bg-primary/10 text-primary":"text-muted-foreground/60 hover:text-primary hover:bg-white/5",!o&&"justify-center"),children:[s.jsx(ar,{className:"w-4 h-4"}),s.jsx("span",{className:w("transition-all duration-300 whitespace-nowrap",o?"opacity-100":"w-0 opacity-0 hidden"),children:"Settings"})]}),s.jsxs(P,{variant:"ghost",onClick:u,className:w("w-full text-destructive/80 hover:text-destructive hover:bg-destructive/10 mt-1 gap-3 justify-start",!o&&"justify-center px-0"),children:[s.jsx(nr,{className:"w-4 h-4"}),s.jsx("span",{className:w("transition-all duration-300 whitespace-nowrap",o?"opacity-100":"w-0 opacity-0 hidden"),children:"Sign Out"})]})]})]})]})},It=Le()(qe((e,t)=>({currentTrack:null,isPlaying:!1,currentTime:0,duration:0,volume:100,muted:!1,queue:[],currentIndex:-1,repeat:"off",shuffle:!1,play:r=>{if(!r){e({isPlaying:!0});return}const{queue:a}=t(),n=a.findIndex(i=>i.id===r.id);if(n>=0)e({currentTrack:r,currentIndex:n,isPlaying:!0,currentTime:0});else{const i=[...a,r];e({currentTrack:r,currentIndex:i.length-1,queue:i,isPlaying:!0,currentTime:0})}},pause:()=>{e({isPlaying:!1})},resume:()=>{e({isPlaying:!0})},stop:()=>{e({isPlaying:!1,currentTime:0})},next:()=>{const{queue:r,currentIndex:a,repeat:n,shuffle:i}=t();if(r.length===0)return;let o=a;if(i)o=Math.floor(Math.random()*r.length);else if(a<r.length-1)o=a+1;else if(n==="playlist")o=0;else return;o!==a&&o<r.length&&e({currentIndex:o,currentTrack:r[o],currentTime:0,isPlaying:!0})},previous:()=>{const{queue:r,currentIndex:a}=t();if(r.length===0||a<=0)return;const n=a-1;e({currentIndex:n,currentTrack:r[n],currentTime:0,isPlaying:!0})},seek:r=>{const{duration:a}=t(),n=Math.max(0,Math.min(r,a||0));e({currentTime:n})},setCurrentTime:r=>{const{duration:a}=t(),n=Math.max(0,Math.min(r,a||0));e({currentTime:n})},setDuration:r=>{e({duration:Math.max(0,r)})},setVolume:r=>{const a=Math.max(0,Math.min(100,r));e({volume:a})},toggleMute:()=>{e({muted:!t().muted})},toggleShuffle:()=>{e({shuffle:!t().shuffle})},setRepeat:r=>{e({repeat:r})},addToQueue:r=>{const{queue:a}=t(),n=[...a,...r];e({queue:n})},removeFromQueue:r=>{const{queue:a,currentIndex:n}=t();if(r<0||r>=a.length)return;const i=a.filter((c,l)=>l!==r);let o=n;if(r<n)o=n-1;else if(r===n)if(i.length>0){o=Math.min(o,i.length-1),e({queue:i,currentIndex:o,currentTrack:i[o]||null,isPlaying:i[o]?t().isPlaying:!1});return}else{o=-1,e({queue:i,currentIndex:o,currentTrack:null,isPlaying:!1});return}e({queue:i,currentIndex:o})},reorderQueue:(r,a)=>{const{queue:n,currentIndex:i}=t();if(r<0||r>=n.length||a<0||a>=n.length||r===a)return;const o=[...n],[c]=o.splice(r,1);o.splice(a,0,c);let l=i;r===i?l=a:r<i&&a>=i?l=i-1:r>i&&a<=i&&(l=i+1),e({queue:o,currentIndex:l})},clearQueue:()=>{e({queue:[],currentIndex:-1,currentTrack:null,isPlaying:!1,currentTime:0})}}),{name:"player-storage",partialize:e=>({volume:e.volume,muted:e.muted,repeat:e.repeat,shuffle:e.shuffle,queue:e.queue,currentIndex:e.currentIndex,currentTrack:e.currentTrack})}));function _i(e){return e?!!(e.id&&e.title&&e.url):!1}class Si{audioElement=null;timeUpdateCallback=null;durationChangeCallback=null;endedCallback=null;errorCallback=null;playCallback=null;pauseCallback=null;initialize(t){this.audioElement=t,this.setupEventListeners()}setupEventListeners(){this.audioElement&&(this.audioElement.addEventListener("timeupdate",this.handleTimeUpdate),this.audioElement.addEventListener("loadedmetadata",this.handleLoadedMetadata),this.audioElement.addEventListener("durationchange",this.handleDurationChange),this.audioElement.addEventListener("ended",this.handleEnded),this.audioElement.addEventListener("error",this.handleError),this.audioElement.addEventListener("play",this.handlePlay),this.audioElement.addEventListener("pause",this.handlePause))}cleanup(){this.audioElement&&(this.audioElement.removeEventListener("timeupdate",this.handleTimeUpdate),this.audioElement.removeEventListener("loadedmetadata",this.handleLoadedMetadata),this.audioElement.removeEventListener("durationchange",this.handleDurationChange),this.audioElement.removeEventListener("ended",this.handleEnded),this.audioElement.removeEventListener("error",this.handleError),this.audioElement.removeEventListener("play",this.handlePlay),this.audioElement.removeEventListener("pause",this.handlePause),this.audioElement=null)}async loadTrack(t){if(!this.audioElement)throw new Error("Audio element not initialized");if(!t){this.audioElement.src="";return}if(!_i(t))throw new Error("Invalid track");this.audioElement.src=t.url,this.audioElement.load()}async play(){if(!this.audioElement)throw new Error("Audio element not initialized");try{await this.audioElement.play()}catch(t){throw new Error(`Failed to play audio: ${t}`)}}pause(){if(!this.audioElement)throw new Error("Audio element not initialized");this.audioElement.pause()}stop(){if(!this.audioElement)throw new Error("Audio element not initialized");this.audioElement.pause(),this.audioElement.currentTime=0}seek(t){if(!this.audioElement)throw new Error("Audio element not initialized");const r=this.audioElement.duration||0,a=Math.max(0,Math.min(t,r));this.audioElement.currentTime=a}setVolume(t){if(!this.audioElement)throw new Error("Audio element not initialized");const r=Math.max(0,Math.min(1,t));this.audioElement.volume=r}setMuted(t){if(!this.audioElement)throw new Error("Audio element not initialized");this.audioElement.muted=t}getCurrentTime(){return this.audioElement&&this.audioElement.currentTime||0}getDuration(){return this.audioElement&&this.audioElement.duration||0}getVolume(){return this.audioElement?this.audioElement.volume:1}isPlaying(){return this.audioElement?!this.audioElement.paused&&!this.audioElement.ended:!1}isMuted(){return this.audioElement?this.audioElement.muted:!1}handleTimeUpdate=()=>{this.timeUpdateCallback&&this.audioElement&&this.timeUpdateCallback(this.audioElement.currentTime)};handleLoadedMetadata=()=>{this.durationChangeCallback&&this.audioElement&&this.durationChangeCallback(this.audioElement.duration)};handleDurationChange=()=>{this.durationChangeCallback&&this.audioElement&&this.durationChangeCallback(this.audioElement.duration)};handleEnded=()=>{this.endedCallback&&this.endedCallback()};handleError=()=>{if(this.errorCallback&&this.audioElement){const t=new Error(this.audioElement.error?.message||"Unknown audio error");this.errorCallback(t)}};handlePlay=()=>{this.playCallback&&this.playCallback()};handlePause=()=>{this.pauseCallback&&this.pauseCallback()};onTimeUpdate(t){this.timeUpdateCallback=t}onDurationChange(t){this.durationChangeCallback=t}onEnded(t){this.endedCallback=t}onError(t){this.errorCallback=t}onPlay(t){this.playCallback=t}onPause(t){this.pauseCallback=t}}const q=new Si;function Ni(e){const t=It(),r=f.useRef(null),a=e?.current||r.current;f.useEffect(()=>{if(a)return q.initialize(a),()=>{q.cleanup()}},[a]),f.useEffect(()=>{if(!a)return;const d=t.muted?0:t.volume/100;q.setVolume(d),q.setMuted(t.muted)},[a,t.volume,t.muted]),f.useEffect(()=>{if(!a)return;(async()=>{try{await q.loadTrack(t.currentTrack)}catch(h){g.error("Failed to load track:",{error:h})}})()},[a,t.currentTrack]),f.useEffect(()=>{if(!a)return;(async()=>{try{t.isPlaying?await q.play():q.pause()}catch(h){g.error("Failed to sync playback:",{error:h}),t.pause()}})()},[a,t.isPlaying,t]),f.useEffect(()=>{if(a)return q.onTimeUpdate(d=>{t.setCurrentTime(d)}),q.onDurationChange(d=>{t.setDuration(d)}),q.onEnded(()=>{t.repeat==="track"?(q.seek(0),q.play().catch(d=>g.error("Failed to reply track:",{error:d}))):t.next()}),q.onError(d=>{g.error("Audio playback error:",{error:d}),t.pause()}),q.onPlay(()=>{t.isPlaying||t.resume()}),q.onPause(()=>{t.isPlaying&&t.pause()}),()=>{q.onTimeUpdate(null),q.onDurationChange(null),q.onEnded(null),q.onError(null),q.onPlay(null),q.onPause(null)}},[a,t]);const n=f.useCallback(async d=>{if(t.play(d),d&&a)try{await q.loadTrack(d),await q.play()}catch(h){g.error("Failed to play track:",{error:h}),t.pause()}},[t,a]),i=f.useCallback(()=>{t.pause(),a&&q.pause()},[t,a]),o=f.useCallback(async()=>{if(t.resume(),a)try{await q.play()}catch(d){g.error("Failed to resume playback:",{error:d}),t.pause()}},[t,a]),c=f.useCallback(()=>{t.stop(),a&&q.stop()},[t,a]),l=f.useCallback(d=>{t.seek(d),a&&q.seek(d)},[t,a]),p=f.useCallback(d=>{if(t.setVolume(d),a){const h=t.muted?0:d/100;q.setVolume(h)}},[t,a]),u=f.useCallback(()=>{t.toggleMute(),a&&q.setMuted(!t.muted)},[t,a]);return{currentTrack:t.currentTrack,isPlaying:t.isPlaying,currentTime:t.currentTime,duration:t.duration,volume:t.volume,muted:t.muted,queue:t.queue,currentIndex:t.currentIndex,repeat:t.repeat,shuffle:t.shuffle,play:n,pause:i,resume:o,stop:c,next:t.next,previous:t.previous,seek:l,setVolume:p,toggleMute:u,toggleShuffle:t.toggleShuffle,setRepeat:t.setRepeat,addToQueue:t.addToQueue,clearQueue:t.clearQueue}}const Ti=5,ji=5;function Ci(e,t={}){const{enabled:r=!0,seekStep:a=Ti,volumeStep:n=ji,preventDefault:i=!0}=t,o=f.useCallback(c=>{if(!r)return;const l=c.target;if(!(l&&(l.tagName==="INPUT"||l.tagName==="TEXTAREA"||l.isContentEditable===!0)))switch(c.code){case"Space":{i&&c.preventDefault(),e.isPlaying?e.pause():e.resume();break}case"ArrowLeft":{i&&c.preventDefault();const p=Math.max(0,e.currentTime-a);e.seek(p);break}case"ArrowRight":{i&&c.preventDefault();const p=Math.min(e.duration||0,e.currentTime+a);e.seek(p);break}case"ArrowUp":{i&&c.preventDefault();const p=Math.min(100,e.volume+n);e.setVolume(p);break}case"ArrowDown":{i&&c.preventDefault();const p=Math.max(0,e.volume-n);e.setVolume(p);break}}},[r,i,a,n,e.isPlaying,e.currentTime,e.duration,e.volume,e.pause,e.resume,e.seek,e.setVolume]);f.useEffect(()=>{if(r)return window.addEventListener("keydown",o),()=>{window.removeEventListener("keydown",o)}},[r,o])}const Lt=f.forwardRef(({className:e,value:t=[0],onValueChange:r,min:a=0,max:n=100,step:i=1,disabled:o,"aria-label":c,"aria-labelledby":l,...p},u)=>{const d=v=>{const y=[Number(v.target.value)];r&&r(y)},h=(t[0]-a)/(n-a)*100;return s.jsxs("div",{className:w("relative flex w-full touch-none select-none items-center",e),children:[s.jsx("div",{className:"relative h-2 w-full grow overflow-hidden rounded-full bg-muted",children:s.jsx("div",{className:"absolute h-full bg-primary transition-all shadow-[0_0_10px_oklch(0.75_0.18_195_/_0.5)]",style:{width:`${h}%`}})}),s.jsx("input",{ref:u,type:"range",min:a,max:n,step:i,value:t[0],onChange:d,disabled:o,className:"absolute inset-0 w-full h-full opacity-0 cursor-pointer disabled:cursor-not-allowed","aria-label":c,"aria-labelledby":l,"aria-valuenow":t[0],"aria-valuemin":a,"aria-valuemax":n,...p}),s.jsx("div",{className:w("absolute h-5 w-5 rounded-full border-2 border-primary bg-background ring-offset-background transition-transform pointer-events-none shadow-[0_0_10px_oklch(0.75_0.18_195_/_0.5)]",o&&"opacity-50"),style:{left:`calc(${h}% - 10px)`}})]})});Lt.displayName="Slider";function Ri({isPlaying:e,onPlayPause:t,onNext:r,onPrevious:a,onShuffle:n,onRepeat:i,shuffle:o,repeat:c,isExpanded:l=!1}){return s.jsxs("div",{className:w("flex items-center gap-4 md:gap-6",l&&"gap-8"),children:[s.jsx("button",{onClick:n,className:w("p-2 rounded-full transition-all duration-300",o?"text-primary bg-primary/10 shadow-[0_0_10px_rgba(var(--cyan-500),0.3)]":"text-muted-foreground hover:text-white hover:bg-white/5"),title:"Shuffle",children:s.jsx(or,{className:w("w-4 h-4",l&&"w-5 h-5")})}),s.jsx("button",{onClick:a,className:"text-white hover:text-primary transition-colors p-2 active:scale-95 hover:bg-white/5 rounded-full",children:s.jsx(lr,{className:w("w-5 h-5 fill-current",l&&"w-6 h-6")})}),s.jsx("button",{onClick:t,className:w("rounded-full bg-primary text-black flex items-center justify-center hover:scale-105 active:scale-95 transition-all shadow-[0_0_20px_rgba(var(--cyan-500),0.5)] hover:shadow-[0_0_30px_rgba(var(--cyan-500),0.8)]",l?"w-16 h-16":"w-12 h-12"),children:e?s.jsx(cr,{className:w("fill-current",l?"w-8 h-8":"w-6 h-6")}):s.jsx(ur,{className:w("fill-current ml-1",l?"w-8 h-8":"w-6 h-6")})}),s.jsx("button",{onClick:r,className:"text-white hover:text-primary transition-colors p-2 active:scale-95 hover:bg-white/5 rounded-full",children:s.jsx(dr,{className:w("w-5 h-5 fill-current",l&&"w-6 h-6")})}),s.jsxs("button",{onClick:i,className:w("p-2 rounded-full transition-all duration-300 relative",c!=="off"?"text-primary bg-primary/10 shadow-[0_0_10px_rgba(var(--cyan-500),0.3)]":"text-muted-foreground hover:text-white hover:bg-white/5"),title:"Repeat",children:[s.jsx(mr,{className:w("w-4 h-4",l&&"w-5 h-5")}),c==="track"&&s.jsx("span",{className:"absolute -top-1 -right-1 text-[8px] font-bold bg-primary text-black px-1 rounded-full",children:"1"})]})]})}const zr=f.forwardRef(({label:e,variant:t="cyan",icon:r,size:a="md",dot:n,count:i,children:o,className:c,...l},p)=>{const d={default:"cyan",primary:"cyan",success:"lime",warning:"gold",error:"magenta",secondary:"magenta"}[t]||t,h={cyan:"bg-kodo-steel/10 text-kodo-steel border-kodo-steel/30",magenta:"bg-kodo-magenta/10 text-kodo-magenta border-kodo-magenta/30",lime:"bg-kodo-lime/10 text-kodo-lime border-kodo-lime/30",gold:"bg-kodo-gold/10 text-kodo-gold border-kodo-gold/30",terminal:"bg-kodo-terminal/10 text-kodo-terminal border-kodo-terminal/30 font-mono"},v={sm:"px-2 py-0.5 text-[10px]",md:"px-2.5 py-0.5 text-[10px]",lg:"px-4 py-1 text-xs"},y=e||o,k=d;return s.jsxs("span",{ref:p,className:w("inline-flex items-center gap-1.5 rounded-full font-bold uppercase tracking-widest border",h[k]||h.cyan,v[a],c),...l,children:[n&&s.jsx("span",{className:"w-3 h-3 rounded-full bg-current"}),r&&s.jsx("span",{className:"w-3 h-3",children:r}),y,i!==void 0&&i>0&&s.jsx("span",{className:"ml-1 px-1.5 py-0.5 rounded-full bg-current/20 text-[10px]",children:i})]})});zr.displayName="Badge";const Fr=f.forwardRef(({className:e,children:t,...r},a)=>s.jsx("div",{ref:a,className:w("relative overflow-auto custom-scrollbar",e),...r,children:t}));Fr.displayName="ScrollArea";const Ai=f.forwardRef(({className:e,...t},r)=>s.jsx("div",{ref:r,className:w("flex touch-none select-none transition-colors",e),...t}));Ai.displayName="ScrollBar";function Pi({isOpen:e,onClose:t,currentTrackId:r,onPlay:a}){const{queue:n,currentIndex:i,removeFromQueue:o,clearQueue:c}=It();return e?s.jsxs("div",{className:w("fixed inset-x-0 bottom-24 mx-auto max-w-4xl w-full z-40 transition-all duration-300 ease-in-out transform",e?"translate-y-0 opacity-100":"translate-y-10 opacity-0 pointer-events-none"),children:[s.jsxs("div",{className:"mx-4 md:mx-0 bg-black/80 backdrop-blur-2xl border border-white/10 rounded-2xl shadow-2xl overflow-hidden max-h-[60vh] flex flex-col",children:[s.jsxs("div",{className:"flex items-center justify-between p-4 border-b border-white/5 bg-white/5",children:[s.jsxs("div",{className:"flex items-center gap-2",children:[s.jsx("h3",{className:"text-white font-bold font-display tracking-wide",children:"Play Queue"}),s.jsxs(zr,{variant:"outline",className:"border-primary/20 text-primary bg-primary/10",children:[n.length," Tracks"]})]}),s.jsxs("div",{className:"flex items-center gap-2",children:[s.jsx("button",{onClick:c,className:"px-3 py-1.5 text-xs text-muted-foreground hover:text-white hover:bg-white/10 rounded-md transition-colors",children:"Clear"}),s.jsx("button",{onClick:t,className:"p-1.5 text-muted-foreground hover:text-white hover:bg-white/10 rounded-full transition-colors",children:s.jsx(_e,{className:"w-5 h-5"})})]})]}),s.jsx("div",{className:"flex-1 overflow-hidden relative",children:n.length===0?s.jsxs("div",{className:"flex flex-col items-center justify-center h-48 text-muted-foreground p-8 text-center",children:[s.jsx(ye,{className:"w-8 h-8 mb-3 opacity-20"}),s.jsx("p",{children:"Your queue is empty."}),s.jsx("p",{className:"text-xs opacity-50 mt-1",children:"Add tracks to keep the vibe going."})]}):s.jsx(Fr,{className:"h-full max-h-[400px]",children:s.jsx("div",{className:"p-2 space-y-1",children:n.map((l,p)=>{const u=p===i,d=p<i;return s.jsxs("div",{className:w("group flex items-center gap-3 p-2 rounded-lg transition-all duration-200 border border-transparent",u?"bg-primary/10 border-primary/20 shadow-[0_0_15px_rgba(var(--cyan-500),0.1)]":"hover:bg-white/5 hover:border-white/5",d&&"opacity-50"),children:[s.jsx("div",{className:"text-white/20 group-hover:text-white/40 cursor-grab px-1",children:s.jsx($s,{className:"w-4 h-4"})}),s.jsx("div",{className:"w-6 text-center text-xs font-mono text-muted-foreground",children:u?s.jsx("div",{className:"w-2 h-2 rounded-full bg-primary mx-auto animate-pulse shadow-[0_0_8px_rgba(var(--cyan-500),0.8)]"}):p+1}),s.jsxs("div",{className:"flex-1 min-w-0 cursor-pointer",onClick:()=>!u&&a(l),children:[s.jsx("h4",{className:w("text-sm font-medium truncate transition-colors",u?"text-primary":"text-white group-hover:text-white"),children:l.title}),s.jsx("p",{className:"text-xs text-muted-foreground truncate opacity-70 group-hover:opacity-100",children:l.artist})]}),s.jsx("button",{onClick:h=>{h.stopPropagation(),o(p)},className:"opacity-0 group-hover:opacity-100 p-2 text-muted-foreground hover:text-red-400 hover:bg-red-400/10 rounded-full transition-all",children:s.jsx(_e,{className:"w-3 h-3"})})]},`${l.id}-${p}`)})})})})]}),s.jsx("div",{className:"fixed inset-0 bg-black/20 -z-10 backdrop-blur-sm md:hidden",onClick:t})]}):null}function Ii({isPlaying:e,isLoading:t=!1,size:r="md",variant:a="default",className:n,disabled:i,onClick:o,...c}){const l={sm:"h-8 w-8",md:"h-10 w-10",lg:"h-12 w-12"},p={sm:"h-4 w-4",md:"h-5 w-5",lg:"h-6 w-6"},u={default:"bg-primary text-primary-foreground hover:bg-primary focus:ring-primary",ghost:"bg-transparent text-foreground hover:bg-muted focus:ring-primary",outline:"border border-border bg-card text-foreground hover:bg-muted focus:ring-muted"},d=h=>{i||t||o?.(h)};return s.jsx("button",{type:"button",className:w("rounded-full flex items-center justify-center transition-colors focus:outline-none focus:ring-2 focus:ring-offset-2",l[r],u[a],(i||t)&&"opacity-50 cursor-not-allowed",n),disabled:i||t,onClick:d,"aria-label":e?"Mettre en pause":"Lire","aria-busy":t,...c,children:t?s.jsxs(s.Fragment,{children:[s.jsx(Me,{className:w(p[r],"animate-spin"),"aria-hidden":"true"}),s.jsx("span",{className:"sr-only",children:"Chargement..."})]}):e?s.jsxs(s.Fragment,{children:[s.jsx(cr,{className:p[r],"aria-hidden":"true"}),s.jsx("span",{className:"sr-only",children:"Mettre en pause"})]}):s.jsxs(s.Fragment,{children:[s.jsx(ur,{className:w(p[r],"ml-0.5"),"aria-hidden":"true"}),s.jsx("span",{className:"sr-only",children:"Lire"})]})})}function Yt({onNext:e,onPrevious:t,canGoNext:r,canGoPrevious:a,size:n="md",variant:i="ghost",className:o,disabled:c=!1}){const l={sm:"h-8 w-8",md:"h-10 w-10",lg:"h-12 w-12"},p={sm:"h-4 w-4",md:"h-5 w-5",lg:"h-6 w-6"},u={default:"bg-primary text-primary-foreground hover:bg-primary focus:ring-primary",ghost:"bg-transparent text-foreground hover:bg-muted focus:ring-primary",outline:"border border-border bg-card text-foreground hover:bg-muted focus:ring-muted"},d=c||!a,h=c||!r;return s.jsxs("div",{className:w("flex items-center gap-2",o),children:[s.jsxs("button",{type:"button",onClick:t,disabled:d,className:w("rounded-full flex items-center justify-center transition-colors focus:outline-none focus:ring-2 focus:ring-offset-2",l[n],u[i],d&&"opacity-50 cursor-not-allowed"),"aria-label":"Piste précédente","aria-disabled":d,children:[s.jsx(lr,{className:p[n],"aria-hidden":"true"}),s.jsx("span",{className:"sr-only",children:"Piste précédente"})]}),s.jsxs("button",{type:"button",onClick:e,disabled:h,className:w("rounded-full flex items-center justify-center transition-colors focus:outline-none focus:ring-2 focus:ring-offset-2",l[n],u[i],h&&"opacity-50 cursor-not-allowed"),"aria-label":"Piste suivante","aria-disabled":h,children:[s.jsx(dr,{className:p[n],"aria-hidden":"true"}),s.jsx("span",{className:"sr-only",children:"Piste suivante"})]})]})}function Li({repeat:e,shuffle:t,onRepeatChange:r,onShuffleToggle:a,className:n,disabled:i=!1,size:o="md",variant:c="ghost"}){const l={sm:"h-8 w-8",md:"h-10 w-10",lg:"h-12 w-12"},p={sm:"h-4 w-4",md:"h-5 w-5",lg:"h-6 w-6"},u={default:"bg-primary text-primary-foreground hover:bg-primary focus:ring-primary",ghost:"bg-transparent text-foreground hover:bg-muted focus:ring-muted",outline:"border border-border bg-card text-foreground hover:bg-muted focus:ring-muted"},d=()=>{i||r(e==="off"?"track":e==="track"?"playlist":"off")},h=()=>{switch(e){case"track":return"Répéter la piste";case"playlist":return"Répéter la playlist";default:return"Répéter désactivé"}},v=()=>{switch(e){case"track":return"Répéter la piste (actif)";case"playlist":return"Répéter la playlist (actif)";default:return"Répéter désactivé"}};return s.jsxs("div",{className:w("flex items-center gap-2",n),children:[s.jsxs("button",{type:"button",onClick:d,disabled:i,className:w("rounded-full flex items-center justify-center transition-colors focus:outline-none focus:ring-2 focus:ring-offset-2 relative",l[o],u[c],e!=="off"&&"bg-primary text-primary-foreground hover:bg-primary",i&&"opacity-50 cursor-not-allowed"),"aria-label":v(),"aria-pressed":e!=="off","aria-disabled":i,title:h(),children:[s.jsx(mr,{className:w(p[o],e==="track"&&"fill-current"),"aria-hidden":"true"}),e==="playlist"&&s.jsx("span",{className:"absolute bottom-0 right-0 text-[8px] font-bold leading-none bg-primary rounded-full w-3 h-3 flex items-center justify-center","aria-hidden":"true",children:"1"}),s.jsx("span",{className:"sr-only",children:h()})]}),s.jsxs("button",{type:"button",onClick:a,disabled:i,className:w("rounded-full flex items-center justify-center transition-colors focus:outline-none focus:ring-2 focus:ring-offset-2",l[o],u[c],t&&"bg-primary text-primary-foreground hover:bg-primary",i&&"opacity-50 cursor-not-allowed"),"aria-label":t?"Mélanger activé":"Mélanger désactivé","aria-pressed":t,"aria-disabled":i,title:t?"Mélanger activé":"Mélanger désactivé",children:[s.jsx(or,{className:w(p[o],t&&"fill-current"),"aria-hidden":"true"}),s.jsx("span",{className:"sr-only",children:t?"Mélanger activé":"Mélanger désactivé"})]})]})}function qi({isOpen:e,onClose:t,currentTime:r,duration:a,onSeek:n,player:i}){const{currentTrack:o}=It();if(!e||!o)return null;const c=l=>{if(!l&&l!==0)return"0:00";const p=Math.floor(l/60),u=Math.floor(l%60);return`${p}:${u.toString().padStart(2,"0")}`};return s.jsxs("div",{className:w("fixed inset-0 z-[110] bg-black/95 backdrop-blur-3xl overflow-hidden flex flex-col transition-all duration-500",e?"opacity-100 translate-y-0":"opacity-0 translate-y-full pointer-events-none"),children:[s.jsxs("div",{className:"absolute inset-0 overflow-hidden pointer-events-none",children:[s.jsx("div",{className:"absolute inset-0 bg-cover bg-center opacity-30 blur-[100px] scale-110 transition-all duration-1000",style:{backgroundImage:`url(${o.cover||"/placeholder.svg"})`}}),s.jsx("div",{className:"absolute inset-0 bg-gradient-to-b from-black/20 via-black/60 to-black/90"})]}),s.jsxs("div",{className:"relative z-10 flex items-center justify-between p-6",children:[s.jsx(P,{variant:"ghost",className:"text-white hover:bg-white/10 rounded-full",onClick:t,children:s.jsx(rr,{className:"w-6 h-6"})}),s.jsx("span",{className:"text-xs font-bold tracking-widest uppercase text-white/50",children:"Following the Signal"}),s.jsx(P,{variant:"ghost",className:"text-white hover:bg-white/10 rounded-full",children:s.jsx(Qs,{className:"w-6 h-6"})})]}),s.jsxs("div",{className:"flex-1 flex flex-col md:flex-row items-center justify-center gap-12 px-8 pb-12 relative z-10 max-w-7xl mx-auto w-full",children:[s.jsxs("div",{className:"w-full max-w-md md:max-w-xl aspect-square relative group",children:[s.jsx("div",{className:"absolute inset-0 bg-gradient-to-br from-cyan-500/20 to-magenta-500/20 rounded-xl blur-2xl transform group-hover:scale-105 transition-transform duration-700"}),s.jsx("img",{src:o.cover||"/placeholder.svg",alt:o.title,className:"w-full h-full object-cover rounded-xl shadow-[0_20px_50px_rgba(0,0,0,0.5)] relative z-10 border border-white/10"})]}),s.jsxs("div",{className:"w-full max-w-xl flex flex-col justify-end space-y-8",children:[s.jsxs("div",{className:"flex items-end justify-between",children:[s.jsxs("div",{className:"space-y-2",children:[s.jsx("h2",{className:"text-4xl md:text-5xl font-display font-bold text-white leading-tight",children:o.title}),s.jsx("p",{className:"text-xl md:text-2xl text-muted-foreground font-medium",children:o.artist})]}),s.jsx(P,{size:"icon",variant:"ghost",className:"text-muted-foreground hover:text-red-500 hover:bg-red-500/10 rounded-full h-12 w-12 transition-all",children:s.jsx(Tt,{className:"w-6 h-6"})})]}),s.jsxs("div",{className:"space-y-4 group/progress",children:[s.jsx(Lt,{value:[r],onValueChange:l=>n(l[0]),max:a||100,step:.1,className:"py-2"}),s.jsxs("div",{className:"flex items-center justify-between text-xs font-mono text-muted-foreground",children:[s.jsx("span",{children:c(r)}),s.jsx("span",{children:c(a)})]})]}),s.jsxs("div",{className:"flex items-center justify-between",children:[s.jsx("div",{className:"flex items-center gap-4",children:s.jsx(Li,{repeat:i.repeat,shuffle:i.shuffle,onRepeatChange:i.setRepeat,onShuffleToggle:i.toggleShuffle,size:"lg"})}),s.jsxs("div",{className:"flex items-center gap-6 md:gap-8",children:[s.jsx(Yt,{onNext:i.next,onPrevious:i.previous,canGoNext:!0,canGoPrevious:!0,size:"lg"}),s.jsx(Ii,{isPlaying:i.isPlaying,onClick:()=>i.isPlaying?i.pause():i.resume(),size:"xl",className:"scale-125"}),s.jsx(Yt,{onNext:i.next,onPrevious:i.previous,canGoNext:!0,canGoPrevious:!0,size:"lg",className:"hidden"})]}),s.jsxs("div",{className:"flex items-center gap-4",children:[s.jsx(P,{size:"icon",variant:"ghost",className:"text-muted-foreground hover:text-white",children:s.jsx(Bs,{className:"w-5 h-5"})}),s.jsx(P,{size:"icon",variant:"ghost",className:"text-muted-foreground hover:text-white",children:s.jsx(Ks,{className:"w-5 h-5"})})]})]})]})]})]})}const Di=({playing:e})=>s.jsx("div",{className:"flex items-center gap-[3px] h-8 opacity-60",children:Array.from({length:24}).map((t,r)=>s.jsx("div",{className:w("w-[3px] bg-gradient-to-t from-cyan-500 to-magenta-500 rounded-full transition-all duration-300",e?"animate-[eq-bounce_0.5s_ease-in-out_infinite]":"h-1"),style:{height:e?`${20+Math.random()*80}%`:"15%",animationDelay:`${Math.random()*.5}s`,animationDuration:`${.4+Math.random()*.4}s`}},r))});function Mi(){const e=f.useRef(null),t=Ni(e);Ci(t);const[r,a]=f.useState(!1),[n,i]=f.useState(!1),[o,c]=f.useState(!1),l=v=>{if(!v&&v!==0)return"0:00";const y=Math.floor(v/60),k=Math.floor(v%60);return`${y}:${k.toString().padStart(2,"0")}`},p=t.currentTrack,d=p||{title:"System Online",artist:"Select a track to play",cover:""},h=!p;return s.jsxs(s.Fragment,{children:[s.jsx("audio",{ref:e,onEnded:()=>{}}),s.jsx(qi,{isOpen:n,onClose:()=>i(!1),currentTime:t.currentTime,duration:t.duration,onSeek:t.seek,player:t}),s.jsx(Pi,{isOpen:o,onClose:()=>c(!1),currentTrackId:p?.id,onPlay:v=>t.play(v)}),s.jsx("div",{className:w("fixed bottom-6 left-4 right-4 md:left-1/2 md:-translate-x-1/2 md:w-full md:max-w-5xl z-[100] transition-all duration-500 ease-[cubic-bezier(0.32,0.72,0,1)]",n?"translate-y-[200%] opacity-0":"translate-y-0 opacity-100"),onMouseEnter:()=>a(!0),onMouseLeave:()=>a(!1),children:s.jsxs("div",{className:w("relative rounded-2xl overflow-hidden backdrop-blur-2xl transition-all duration-300 group shadow-2xl","bg-black/80 border border-white/10",r?"shadow-[0_0_50px_rgba(var(--cyan-500),0.15)] border-primary/30":"box-shadow-[0_8px_32px_rgba(0,0,0,0.5)]"),children:[s.jsx("div",{className:w("absolute top-0 left-0 right-0 h-[2px] bg-white/5 z-20 transition-all",!h&&"group-hover:h-[4px] cursor-pointer"),onClick:v=>{if(h)return;const y=v.currentTarget.getBoundingClientRect(),S=(v.clientX-y.left)/y.width;t.seek(S*t.duration)},children:s.jsx("div",{className:w("h-full bg-gradient-to-r from-cyan-500 via-blue-500 to-magenta-500 relative",h&&"w-0 opacity-0"),style:{width:h?"0%":`${t.currentTime/(t.duration||1)*100}%`},children:s.jsx("div",{className:"absolute right-0 top-1/2 -translate-y-1/2 w-3 h-3 bg-white rounded-full shadow-[0_0_10px_white] opacity-0 group-hover:opacity-100 transition-opacity scale-0 group-hover:scale-100"})})}),s.jsxs("div",{className:"flex items-center justify-between h-20 md:h-24 px-4 md:px-6 relative z-10",children:[s.jsxs("div",{className:"flex items-center gap-4 flex-1 min-w-0",children:[s.jsxs("div",{className:w("relative w-12 h-12 md:w-14 md:h-14 rounded-lg overflow-hidden group/art",!h&&"cursor-pointer"),onClick:()=>!h&&i(!0),children:[d.cover?s.jsx("img",{src:d.cover,alt:d.title,className:w("w-full h-full object-cover transition-transform duration-700",t.isPlaying&&"scale-110")}):s.jsx("div",{className:"w-full h-full bg-white/5 flex items-center justify-center",children:s.jsx(Mt,{className:w("w-6 h-6 text-muted-foreground",h&&"opacity-20")})}),!h&&s.jsx("div",{className:"absolute inset-0 bg-black/50 flex items-center justify-center opacity-0 group-hover/art:opacity-100 transition-opacity",children:s.jsx(Mt,{className:"w-5 h-5 text-white"})})]}),s.jsxs("div",{className:"flex flex-col justify-center min-w-0",children:[s.jsxs("div",{className:"flex items-center gap-2",children:[s.jsx("h3",{className:w("font-display font-bold text-sm md:text-base text-white truncate transition-colors",!h&&"hover:text-primary cursor-pointer"),onClick:()=>!h&&i(!0),children:d.title}),!h&&s.jsx("span",{className:"hidden md:inline-flex px-1.5 py-0.5 rounded text-[9px] font-mono bg-white/5 text-muted-foreground border border-white/10 uppercase tracking-wider",children:"HQ"})]}),s.jsx("p",{className:w("text-xs text-muted-foreground truncate transition-colors",!h&&"hover:text-white cursor-pointer"),onClick:()=>!h&&i(!0),children:d.artist||"Unknown Artist"})]})]}),s.jsxs("div",{className:"absolute left-1/2 top-1/2 -translate-x-1/2 -translate-y-1/2 flex flex-col items-center justify-center gap-1 min-w-[300px]",children:[s.jsx(Ri,{isPlaying:t.isPlaying,onPlayPause:()=>{t.isPlaying?t.pause():h||t.resume()},onNext:t.next,onPrevious:t.previous,onShuffle:t.toggleShuffle,onRepeat:()=>{const v=["off","track","playlist"],y=v[(v.indexOf(t.repeat)+1)%v.length];t.setRepeat(y)},shuffle:t.shuffle,repeat:t.repeat}),s.jsxs("div",{className:w("hidden md:flex items-center gap-2 text-[10px] font-mono text-muted-foreground w-full justify-center transition-opacity",h?"opacity-0":"opacity-0 group-hover:opacity-100"),children:[s.jsx("span",{children:l(t.currentTime)}),s.jsx("span",{className:"opacity-30",children:"/"}),s.jsx("span",{children:l(t.duration)})]})]}),s.jsxs("div",{className:"flex items-center justify-end gap-3 md:gap-4 flex-1",children:[s.jsx("div",{className:"hidden lg:block w-24 mr-2",children:s.jsx(Di,{playing:t.isPlaying})}),s.jsxs("div",{className:"hidden md:flex items-center gap-2 group/volume",children:[s.jsx(P,{variant:"ghost",size:"icon",className:"w-8 h-8 text-muted-foreground hover:text-white",onClick:t.toggleMute,children:t.muted||t.volume===0?s.jsx(Hs,{className:"w-4 h-4"}):s.jsx(Ws,{className:"w-4 h-4"})}),s.jsx("div",{className:"w-0 group-hover/volume:w-24 overflow-hidden transition-all duration-300",children:s.jsx(Lt,{value:[t.muted?0:t.volume],onValueChange:v=>t.setVolume(v[0]),max:100,className:"w-20"})})]}),s.jsx("div",{className:"w-px h-8 bg-white/10 hidden md:block"}),s.jsx(P,{variant:"ghost",size:"icon",className:w("w-9 h-9 rounded-full",o?"text-primary bg-primary/10":"text-muted-foreground hover:text-white"),onClick:()=>c(!o),children:s.jsx(ir,{className:"w-4 h-4"})}),s.jsx(P,{variant:"ghost",size:"icon",className:"w-9 h-9 rounded-full text-muted-foreground hover:text-magenta-500 hover:bg-magenta-500/10",children:s.jsx(Tt,{className:"w-4 h-4"})})]})]}),s.jsx("div",{className:"absolute inset-0 bg-gradient-to-r from-cyan-500/5 via-primary/5 to-magenta-500/5 opacity-0 group-hover:opacity-100 transition-opacity duration-700 pointer-events-none -z-10"})]})})]})}function Oi({children:e}){const{sidebarOpen:t}=xe();return s.jsxs("div",{className:"flex h-screen w-full overflow-hidden relative bg-background",children:[s.jsx(Pr,{}),s.jsx(Ei,{}),s.jsxs("div",{className:w("flex-1 flex flex-col h-full relative z-10 transition-all duration-500 ease-in-out",t?"lg:ml-72":"lg:ml-28","ml-0"),children:[s.jsx(wi,{}),s.jsx("main",{className:"flex-1 overflow-y-auto overflow-x-hidden pt-24 pb-32 px-4 md:px-8 custom-scrollbar",id:"main-scroll-container",children:s.jsx("div",{className:"max-w-layout-content mx-auto w-full",children:e})}),s.jsx("div",{className:"absolute bottom-0 left-0 right-0 z-50",children:s.jsx(Mi,{})})]})]})}function zi({children:e}){return s.jsx(Oi,{children:e})}function je(e){return s.jsx(ti,{children:s.jsx(ve,{children:e})})}function V(e){return s.jsx(yn,{children:s.jsx(zi,{children:s.jsx(ve,{children:e})})})}function Fi(){return[{path:"/login",element:je(s.jsx(Tn,{}))},{path:"/register",element:je(s.jsx(jn,{}))},{path:"/forgot-password",element:je(s.jsx(Cn,{}))},{path:"/verify-email",element:je(s.jsx(Rn,{}))},{path:"/reset-password",element:je(s.jsx(An,{}))}]}function Vi(){return[{path:"/design-system",element:s.jsx(ve,{children:s.jsx(Un,{})})},{path:"/u/:username",element:s.jsx(ve,{children:s.jsx(qn,{})})}]}function Ui(){return[{path:"/dashboard",element:V(s.jsx(kn,{}))},{path:"/marketplace",element:V(s.jsx(Yn,{}))},{path:"/sell",element:V(s.jsx(Jn,{onCreateProduct:()=>{}}))},{path:"/wishlist",element:V(s.jsx(Zn,{}))},{path:"/purchases",element:V(s.jsx(ei,{}))},{path:"/chat",element:V(s.jsx(En,{}))},{path:"/library",element:V(s.jsx(_n,{}))},{path:"/profile",element:V(s.jsx(Sn,{}))},{path:"/settings",element:V(s.jsx(Nn,{}))},{path:"/settings/sessions",element:V(s.jsx(Pn,{}))},{path:"/admin/roles",element:V(s.jsx(Dn,{}))},{path:"/tracks/:id",element:V(s.jsx(Mn,{}))},{path:"/playlists/*",element:V(s.jsx(On,{}))},{path:"/search",element:V(s.jsx(Xn,{}))},{path:"/notifications",element:V(s.jsx(Gn,{}))},{path:"/analytics",element:V(s.jsx(Fn,{onNavigateTrack:()=>{}}))},{path:"/webhooks",element:V(s.jsx(Vn,{}))},{path:"/admin",element:V(s.jsx(zn,{}))},{path:"/social",element:V(s.jsx($n,{onViewProfile:()=>{}}))},{path:"/gear",element:V(s.jsx(Qn,{}))},{path:"/live",element:V(s.jsx(Bn,{}))},{path:"/education",element:V(s.jsx(Kn,{}))},{path:"/queue",element:V(s.jsx(Hn,{}))},{path:"/developer",element:V(s.jsx(Wn,{}))}]}function $i(){return[{path:"/404",element:s.jsx(ve,{children:s.jsx(In,{})})},{path:"/500",element:s.jsx(ve,{children:s.jsx(Ln,{})})}]}function Qi(){const e=Fi(),t=Vi(),r=Ui(),a=$i();return s.jsxs(Yr,{children:[e.map(({path:n,element:i})=>s.jsx(be,{path:n,element:i},n)),t.map(({path:n,element:i})=>s.jsx(be,{path:n,element:i},n)),r.map(({path:n,element:i})=>s.jsx(be,{path:n,element:i},n)),a.map(({path:n,element:i})=>s.jsx(be,{path:n,element:i},n)),s.jsx(be,{path:"/",element:s.jsx(Ge,{to:"/dashboard",replace:!0})}),s.jsx(be,{path:"*",element:s.jsx(Ge,{to:"/404",replace:!0})})]})}function Bi(e={}){const{enabled:t=!0,preventDefault:r=!0,onHelpOpen:a}=e,n=et(),{setSidebarOpen:i,sidebarOpen:o}=xe(),c=f.useCallback(l=>{if(!t)return;const p=l.target;if(p&&(p.tagName==="INPUT"||p.tagName==="TEXTAREA"||p.isContentEditable===!0||p.getAttribute("role")==="textbox")){if(l.key==="k"&&(l.ctrlKey||l.metaKey)){r&&l.preventDefault();const u=document.querySelector('input[type="search"], input[placeholder*="search" i], input[placeholder*="rechercher" i]');u?(u.focus(),u.select()):n("/search");return}return}if((l.ctrlKey||l.metaKey)&&l.key==="k"){r&&l.preventDefault();const u=document.querySelector('input[type="search"], input[placeholder*="search" i], input[placeholder*="rechercher" i]');u?(u.focus(),u.select()):n("/search");return}if((l.ctrlKey||l.metaKey)&&l.key==="n"){r&&l.preventDefault(),n("/chat");return}if((l.ctrlKey||l.metaKey)&&l.key==="b"){r&&l.preventDefault(),i(!o);return}if(l.key==="Escape"){document.querySelectorAll('[role="menu"][aria-expanded="true"]').forEach(d=>{const h=d.previousElementSibling;h&&h.click()});return}if(l.key==="?"&&!l.ctrlKey&&!l.metaKey&&!l.shiftKey){r&&l.preventDefault(),a&&a();return}},[t,r,n,i,o,a]);f.useEffect(()=>{if(t)return window.addEventListener("keydown",c),()=>{window.removeEventListener("keydown",c)}},[t,c])}const ce={SEARCH:"Ctrl+K",NEW_MESSAGE:"Ctrl+N",PLAY_PAUSE:"Space",NEXT_TRACK:"Ctrl+Right",PREVIOUS_TRACK:"Ctrl+Left",VOLUME_UP:"Ctrl+Up",VOLUME_DOWN:"Ctrl+Down",MUTE:"Ctrl+M",HELP:"?",ESCAPE:"Escape"};function Ki({open:e,onClose:t}){const{t:r}=Or(),a=[{key:ce.SEARCH,description:r("keyboard.shortcuts.search","Focus search or navigate to search page")},{key:ce.NEW_MESSAGE,description:r("keyboard.shortcuts.newMessage","Open new chat/message")},{key:ce.PLAY_PAUSE,description:r("keyboard.shortcuts.playPause","Play or pause current track")},{key:ce.NEXT_TRACK,description:r("keyboard.shortcuts.nextTrack","Play next track")},{key:ce.PREVIOUS_TRACK,description:r("keyboard.shortcuts.previousTrack","Play previous track")},{key:ce.VOLUME_UP,description:r("keyboard.shortcuts.volumeUp","Increase volume")},{key:ce.VOLUME_DOWN,description:r("keyboard.shortcuts.volumeDown","Decrease volume")},{key:ce.MUTE,description:r("keyboard.shortcuts.mute","Toggle mute")},{key:"Ctrl+B / Cmd+B",description:r("keyboard.shortcuts.toggleSidebar","Toggle sidebar")},{key:ce.ESCAPE,description:r("keyboard.shortcuts.escape","Close modals or go back")},{key:ce.HELP,description:r("keyboard.shortcuts.help","Show this help dialog")}];return s.jsx(At,{open:e,onClose:t,title:r("keyboard.shortcuts.title","Keyboard Shortcuts"),size:"lg",children:s.jsx("div",{className:"space-y-4",children:a.map((n,i)=>s.jsxs("div",{className:"flex items-center justify-between border-b border-kodo-steel dark:border-kodo-steel pb-2 last:border-0",children:[s.jsx("span",{className:"text-sm text-kodo-content-dim dark:text-kodo-content-dim",children:n.description}),s.jsx("kbd",{className:"px-2 py-1 text-xs font-semibold text-kodo-text-main dark:text-kodo-text-main bg-kodo-void dark:bg-kodo-graphite border border-kodo-steel dark:border-kodo-steel rounded",children:n.key})]},i))})})}const Hi=Le()(Zt(qe(e=>({filters:{},setFilters:t=>{e({filters:t})}}),{name:"library-storage",partialize:e=>({filters:e.filters})}),{name:"LibraryStore",enabled:!1}));async function Wi(e={}){const{hydrateAuth:t=!0,hydrateLibrary:r=!1,hydrateChat:a=!1,requireAuth:n=!0}=e,i={success:!0,hydrated:[],errors:[]};try{if(n){const{isAuthenticated:o}=Z.getState();if(!o)return g.debug("[StateHydration] User not authenticated, skipping hydration"),i}if(t)try{const{isAuthenticated:o,isLoading:c}=Z.getState(),l=ee.hasTokens();o&&l&&!c||(await Gi(),i.hydrated.push("auth"),g.debug("[StateHydration] Auth state hydrated"))}catch(o){const c=o instanceof Error?o:new Error(String(o));i.errors.push({store:"auth",error:c}),i.success=!1,g.error("[StateHydration] Failed to hydrate auth state",{error:c.message})}if(r)try{await Yi(),i.hydrated.push("library"),g.debug("[StateHydration] Library state hydrated")}catch(o){const c=o instanceof Error?o:new Error(String(o));i.errors.push({store:"library",error:c}),i.success=!1,g.error("[StateHydration] Failed to hydrate library state",{error:c.message})}if(a)try{await Xi(),i.hydrated.push("chat"),g.debug("[StateHydration] Chat state hydrated")}catch(o){const c=o instanceof Error?o:new Error(String(o));i.errors.push({store:"chat",error:c}),i.success=!1,g.error("[StateHydration] Failed to hydrate chat state",{error:c.message})}}catch(o){const c=o instanceof Error?o:new Error(String(o));g.error("[StateHydration] Fatal error during hydration",{error:c.message}),i.success=!1}return i}async function Gi(){const{refreshUser:e,isAuthenticated:t}=Z.getState();await e()}async function Yi(){const{fetchFavorites:e}=Hi.getState();await e()}async function Xi(){g.debug("[StateHydration] Chat state hydration skipped - using React Query")}function Ji(e={}){const[t,r]=f.useState(!0),[a,n]=f.useState(null);return f.useEffect(()=>{let i=!0;return Wi(e).then(o=>{i&&(n(o),r(!1))}).catch(o=>{i&&(g.error("[StateHydration] Hook error:",o),n({success:!1,hydrated:[],errors:[{store:"unknown",error:o instanceof Error?o:new Error(String(o))}]}),r(!1))}),()=>{i=!1}},[]),{isHydrating:t,hydrationResult:a}}function Zi(){const e=St();f.useEffect(()=>{const t=r=>{const{queryKeys:a,resourceType:n,resourceId:i}=r.detail;if(a&&a.length>0)for(const o of a)e.invalidateQueries({queryKey:o});if(n){const c={tracks:[["tracks"],["track"],["library"]],playlists:[["playlists"],["playlist"]],users:[["users"],["user"],["auth"]],conversations:[["conversations"],["conversation"],["chat"]],roles:[["roles"],["role"]],library:[["library"],["tracks"],["favorites"]],auth:[["auth"],["user"]],ui:[],all:[]}[n]||[];for(const l of c)e.invalidateQueries({queryKey:i?[...l,i]:l})}};return window.addEventListener("veza:invalidate-queries",t),()=>{window.removeEventListener("veza:invalidate-queries",t)}},[e])}function eo(e){if(typeof window>"u"||!window.BroadcastChannel)return g.warn("[ReactQuerySync] BroadcastChannel not supported in this environment"),null;try{return new BroadcastChannel(e)}catch(t){return g.warn("[ReactQuerySync] Failed to create BroadcastChannel",{error:t instanceof Error?t.message:String(t),stack:t instanceof Error?t.stack:void 0,channelName:e}),null}}function to(){if(typeof window>"u")return"server";let e=sessionStorage.getItem("veza-tab-id");return e||(e=`tab-${Date.now()}-${Math.random().toString(36).substring(2,9)}`,sessionStorage.setItem("veza-tab-id",e)),e}function Xt(){return`${Date.now()}-${Math.random().toString(36).substring(2,9)}`}function ro(e,t={}){const r=t.channelName||"veza-react-query-sync",a=t.enabled!==!1,n=t.shouldSync||(()=>!0);if(!a)return()=>{};const i=eo(r);if(!i)return g.warn("[ReactQuerySync] BroadcastChannel not available, sync disabled"),()=>{};const o=to(),c=new Set;let l=!1;function p(v){if(l||!n(v,"query-invalidate"))return;const y={type:"query-invalidate",queryKey:v,timestamp:Date.now(),messageId:Xt(),tabId:o};try{i&&(i.postMessage(y),g.debug("[ReactQuerySync] Broadcasted query invalidation",{queryKey:v,messageId:y.messageId}))}catch(k){g.error("[ReactQuerySync] Failed to broadcast invalidation",{error:k instanceof Error?k.message:String(k),queryKey:v})}}function u(v){const y=v.data;if(!(!y||typeof y!="object"||!y.type||!Array.isArray(y.queryKey)||typeof y.timestamp!="number"||typeof y.messageId!="string")&&!(y.type!=="query-invalidate"&&y.type!=="query-set-data"&&y.type!=="mutation-success")&&y.tabId!==o&&!c.has(y.messageId)&&(c.add(y.messageId),c.size>1e3&&Array.from(c).slice(0,500).forEach(S=>c.delete(S)),!!n(y.queryKey,y.type))){l=!0;try{switch(y.type){case"query-invalidate":e.invalidateQueries({queryKey:y.queryKey}),g.debug("[ReactQuerySync] Invalidated query from other tab",{queryKey:y.queryKey,messageId:y.messageId});break;case"query-set-data":y.data!==void 0&&(e.setQueryData(y.queryKey,y.data),g.debug("[ReactQuerySync] Updated query data from other tab",{queryKey:y.queryKey,messageId:y.messageId}));break;case"mutation-success":e.invalidateQueries({queryKey:y.queryKey}),g.debug("[ReactQuerySync] Invalidated queries after mutation from other tab",{queryKey:y.queryKey,messageId:y.messageId});break;default:g.warn("[ReactQuerySync] Unknown message type",{type:y.type,messageId:y.messageId})}}catch(k){g.error("[ReactQuerySync] Error processing sync message",{error:k instanceof Error?k.message:String(k),messageId:y.messageId,queryKey:y.queryKey})}finally{setTimeout(()=>{l=!1},50)}}}i.addEventListener("message",u);const d=e.getMutationCache().subscribe(v=>{if(!(!v||!i)&&v.type==="updated"&&v.mutation.state.status==="success"){const y=v.mutation.options.mutationKey;if(y){const k={type:"mutation-success",queryKey:y,timestamp:Date.now(),messageId:Xt(),tabId:o};try{i.postMessage(k),g.debug("[ReactQuerySync] Broadcasted mutation success",{queryKey:y,messageId:k.messageId})}catch(S){g.error("[ReactQuerySync] Failed to broadcast mutation",{error:S instanceof Error?S.message:String(S),queryKey:y})}}}}),h=e.getQueryCache().subscribe(v=>{if(v?.type==="removed"||v?.type==="updated"&&v.query?.state.isInvalidated){const y=v.query.queryKey;p(y)}});return g.info("[ReactQuerySync] React Query cache synchronization enabled",{channelName:r,tabId:o}),()=>{i.removeEventListener("message",u),d(),h(),i.close(),g.info("[ReactQuerySync] React Query cache synchronization disabled")}}const He=[{id:"1",title:"Neon Nightrider",artist:"Cyber_Punk_OST",album:"Night City Vol.1",duration:"3:45",durationSec:225,plays:12e3,like_count:3400,coverUrl:"https://picsum.photos/id/55/400/400",isPremium:!0,waveformData:Array.from({length:100},()=>Math.random()),lyrics:[{time:10,text:"Neon lights flickering..."},{time:15,text:"Driving through the cyber city"},{time:20,text:"Bass dropping heavy on the pavement"}]},{id:"2",title:"Glitch in the Matrix",artist:"Null Pointer",album:"System Failure",duration:"4:20",durationSec:260,plays:8500,like_count:2100,coverUrl:"https://picsum.photos/id/58/400/400",waveformData:Array.from({length:100},()=>Math.random())},{id:"3",title:"Tokyo Drift (Lofi)",artist:"Sakura Beats",album:"Chillhop Essentials",duration:"2:55",durationSec:175,plays:45e3,like_count:12e3,coverUrl:"https://picsum.photos/id/60/400/400",isPremium:!0,waveformData:Array.from({length:100},()=>Math.random())},{id:"4",title:"Neural Link",artist:"Mainframe",album:"AI Dreams",duration:"5:10",durationSec:310,plays:2300,like_count:450,coverUrl:"https://picsum.photos/id/70/200/200",waveformData:Array.from({length:100},()=>Math.random())},{id:"5",title:"Synthwave Sunset",artist:"Retro Boy",album:"Analog Memories",duration:"3:30",durationSec:210,plays:1200,like_count:300,coverUrl:"https://picsum.photos/id/80/200/200",waveformData:Array.from({length:100},()=>Math.random())}],so={mode:"waveform",color:"#66FCF1",sensitivity:50};function ao(){const[e,t]=f.useState(null),[r,a]=f.useState([]),[n,i]=f.useState([]),[o,c]=f.useState(!1),[l,p]=f.useState(0),[u,d]=f.useState(0),[h,v]=f.useState(80),[y,k]=f.useState(!1),[S,_]=f.useState(!1),[E,I]=f.useState("off"),[M,m]=f.useState(1),[x,j]=f.useState(!0),[F,$]=f.useState(so),[U,Y]=f.useState(!0),X=f.useRef(null);f.useEffect(()=>{t(He[0]),a(He.slice(1))},[]);const H=()=>{if(r.length>0){const C=S?r[Math.floor(Math.random()*r.length)]:r[0];i(L=>e?[...L,e]:L),a(E!=="all"?L=>L.filter(J=>J.id!==C.id):L=>[...L.filter(J=>J.id!==C.id),C]),t(C),d(0),c(!0)}else if(U){const C=He[Math.floor(Math.random()*He.length)];i(L=>e?[...L,e]:L),t({...C,id:`auto-${Date.now()}`,title:`Autoplay: ${C.title}`}),d(0),c(!0)}else c(!1),d(0)};f.useEffect(()=>(o&&e?X.current=window.setInterval(()=>{d(C=>{if(e?.durationSec&&C>=e.durationSec){if(E==="one")return 0;if(r.length>0||U)H();else return c(!1),C;return 0}return C+1*M})},1e3/M):X.current&&clearInterval(X.current),()=>{X.current&&clearInterval(X.current)}),[o,e,E,M,r.length,U]),f.useEffect(()=>{e?.durationSec&&p(u/e.durationSec*100)},[u,e]);const K=(C,L)=>{if(e&&e.id!==C.id&&i(J=>[...J,e]),t(C),L){const J=L.findIndex(ft=>ft.id===C.id);J!==-1&&a(L.slice(J+1))}c(!0),d(0)},W=()=>c(!o),ie=()=>{if(u>3)d(0);else if(n.length>0){const C=n[n.length-1];a(L=>e?[e,...L]:L),i(L=>L.slice(0,-1)),t(C),d(0),c(!0)}},Ne=C=>{if(e?.durationSec){const L=C/100*e.durationSec;d(L),p(C)}},ct=C=>v(C),ut=()=>k(C=>!C),dt=()=>_(!S),Ue=()=>{const C=["off","all","one"],L=C[(C.indexOf(E)+1)%C.length];I(L)},Te=()=>j(!x),O=()=>Y(!U),oe=C=>a(L=>[...L,C]),mt=C=>a(L=>[C,...L]),$r=C=>a(L=>L.filter(J=>J.id!==C)),Qr=()=>a([]),Br=(C,L)=>{const J=Array.from(r),[ft]=J.splice(C,1);J.splice(L,0,ft),a(J)};return{currentTrack:e,isPlaying:o,queue:r,history:n,progress:l,currentTime:u,duration:e?.durationSec||0,volume:h,isMuted:y,shuffle:S,repeatMode:E,playbackRate:M,pitchCorrection:x,visualizerSettings:F,autoplay:U,playTrack:K,togglePlay:W,nextTrack:H,prevTrack:ie,seek:Ne,setVolume:ct,toggleMute:ut,toggleShuffle:dt,toggleRepeat:Ue,setPlaybackRate:m,togglePitchCorrection:Te,setVisualizerSettings:$,toggleAutoplay:O,addToQueue:oe,removeFromQueue:$r,playNext:mt,reorderQueue:Br,clearQueue:Qr}}const Vr=f.createContext(void 0),xl=()=>{const e=f.useContext(Vr);if(!e)throw new Error("useAudio must be used within AudioProvider");return e},no=({children:e})=>{const t=ao();return s.jsx(Vr.Provider,{value:t,children:e})};function io(){const{refreshUser:e}=Z(),{theme:t,setTheme:r,language:a,setLanguage:n}=xe(),[i,o]=f.useState(!1),[c,l]=f.useState(!1),p=St();return Bi({enabled:!0,onHelpOpen:()=>o(!0)}),Ji({hydrateAuth:!0,hydrateLibrary:!1,hydrateChat:!1,requireAuth:!1}),Zi(),f.useEffect(()=>ro(p,{enabled:!0,channelName:"veza-react-query-sync"}),[p]),f.useEffect(()=>{if((async()=>{await new Promise(h=>setTimeout(h,100));const{isAuthenticated:d}=Z.getState();d&&G.refreshToken().catch(h=>{g.warn("Failed to fetch CSRF token on app init",{error:h instanceof Error?h.message:String(h),stack:h instanceof Error?h.stack:void 0})})})(),!t||t==="system"){const d=document.documentElement;!d.classList.contains("dark")&&!d.classList.contains("light")?r("dark"):r(t)}else r(t);if(typeof window<"u"&&window.i18n){const d=window.i18n.language||a;d!==a?window.i18n.changeLanguage(a):a!==d&&n(d)}},[r,t,a,n]),f.useEffect(()=>{(async()=>{try{await e()}catch(d){g.error("[App] Auth initialization failed",{error:d instanceof Error?d.message:String(d),stack:d instanceof Error?d.stack:void 0})}finally{l(!0)}})()},[e]),f.useEffect(()=>{if(t!=="system")return;const u=window.matchMedia("(prefers-color-scheme: dark)"),d=h=>{const v=document.documentElement;h.matches?v.classList.add("dark"):v.classList.remove("dark")};return u.addEventListener?u.addEventListener("change",d):u.addListener(d),()=>{u.removeEventListener?u.removeEventListener("change",d):u.removeListener(d)}},[t]),c?s.jsx(ve,{children:s.jsx(ln,{children:s.jsxs(no,{children:[s.jsx(Pr,{}),s.jsx(gn,{}),s.jsx(Qi,{}),s.jsx(Ki,{open:i,onClose:()=>o(!1)})]})})}):s.jsx("div",{className:"flex items-center justify-center min-h-screen bg-background",children:s.jsxs("div",{className:"text-center",children:[s.jsx("div",{className:"animate-spin rounded-full h-12 w-12 border-b-2 border-primary mx-auto mb-4"}),s.jsx("p",{className:"text-muted-foreground",children:"Chargement..."})]})})}const oo={loading:"Chargement...",save:"Sauvegarder",cancel:"Annuler",edit:"Modifier",delete:"Supprimer",confirm:"Confirmer",close:"Fermer",back:"Retour",next:"Suivant",previous:"Précédent",search:"Rechercher",filter:"Filtrer",sort:"Trier",view:"Voir",download:"Télécharger",upload:"Téléverser",share:"Partager",copy:"Copier",refresh:"Actualiser",settings:"Paramètres",profile:"Profil",logout:"Déconnexion",login:"Connexion",register:"S'inscrire",email:"Email",password:"Mot de passe",username:"Nom d'utilisateur",firstName:"Prénom",lastName:"Nom",name:"Nom",title:"Titre",description:"Description",date:"Date",time:"Heure",status:"Statut",type:"Type",size:"Taille",actions:"Actions",error:"Erreur",success:"Succès",warning:"Attention",info:"Information",yes:"Oui",no:"Non",never:"Jamais",changeTheme:"Changer le thème",userMenu:"Menu utilisateur",notifications:"Notifications"},lo={login:{title:"Connexion",subtitle:"Connectez-vous à votre compte Veza",email:"Email",password:"Mot de passe",rememberMe:"Se souvenir de moi",forgotPassword:"Mot de passe oublié ?",loginButton:"Se connecter",noAccount:"Pas encore de compte ?",createAccount:"Créer un compte",errors:{invalidCredentials:"Email ou mot de passe incorrect",accountLocked:"Compte verrouillé",emailNotVerified:"Email non vérifié"}},register:{title:"Créer un compte",subtitle:"Rejoignez la communauté Veza",firstName:"Prénom",lastName:"Nom",username:"Nom d'utilisateur",email:"Email",password:"Mot de passe",confirmPassword:"Confirmer le mot de passe",registerButton:"Créer le compte",hasAccount:"Déjà un compte ?",loginLink:"Se connecter",errors:{passwordMismatch:"Les mots de passe ne correspondent pas",emailExists:"Cet email est déjà utilisé",usernameExists:"Ce nom d'utilisateur est déjà pris",weakPassword:"Le mot de passe doit contenir au moins 8 caractères"}},forgotPassword:{title:"Mot de passe oublié",subtitle:"Entrez votre email pour recevoir un lien de réinitialisation",email:"Email",sendButton:"Envoyer le lien",backToLogin:"Retour à la connexion",success:"Email de réinitialisation envoyé"}},co={title:"Tableau de bord",welcome:"Bienvenue, {{name}} !",stats:{totalTracks:"Pistes totales",totalPlaylists:"Playlists",totalFavorites:"Favoris",totalStorage:"Stockage utilisé"},recentActivity:"Activité récente",recentTracks:"Pistes récentes",quickActions:"Actions rapides",uploadTrack:"Téléverser une piste",createPlaylist:"Créer une playlist",startChat:"Démarrer un chat"},uo={title:"Chat",conversations:"Conversations",newConversation:"Nouvelle conversation",searchConversations:"Rechercher des conversations",noConversations:"Aucune conversation",startConversation:"Démarrer une conversation",messages:{placeholder:"Tapez votre message...",send:"Envoyer",typing:"{{user}} est en train d'écrire...",online:"En ligne",offline:"Hors ligne",lastSeen:"Vu pour la dernière fois {{time}}"},errors:{connectionFailed:"Échec de la connexion au chat",messageFailed:"Échec de l'envoi du message",reconnecting:"Reconnexion en cours..."}},mo={title:"Bibliothèque",myFiles:"Mes fichiers",favorites:"Favoris",recent:"Récents",search:"Rechercher dans la bibliothèque",filterBy:"Filtrer par",sortBy:"Trier par",viewMode:{grid:"Vue grille",list:"Vue liste"},upload:{title:"Téléverser un fichier",dragDrop:"Glissez-déposez vos fichiers ici",or:"ou",browseFiles:"Parcourir les fichiers",supportedFormats:"Formats supportés: MP3, WAV, FLAC, PDF, DOC, DOCX",maxSize:"Taille maximale: 100MB"},actions:{play:"Lire",download:"Télécharger",share:"Partager",addToFavorites:"Ajouter aux favoris",removeFromFavorites:"Retirer des favoris",edit:"Modifier",delete:"Supprimer"},empty:{title:"Votre bibliothèque est vide",subtitle:"Commencez par téléverser vos premiers fichiers",uploadButton:"Téléverser un fichier"}},fo={title:"Profil",subtitle:"Gérez vos informations personnelles et préférences",personalInfo:"Informations personnelles",updateProfile:"Mettre à jour votre profil",edit:"Modifier",save:"Sauvegarder",cancel:"Annuler",avatar:{title:"Photo de profil",changePhoto:"Changer la photo",removePhoto:"Supprimer la photo"},accountInfo:"Informations du compte",memberSince:"Membre depuis",emailVerified:"Email vérifié",lastLogin:"Dernière connexion",fields:{firstName:"Prénom",lastName:"Nom",username:"Nom d'utilisateur",email:"Email",bio:"Bio",bioPlaceholder:"Parlez-nous de vous..."}},ho={title:"Paramètres",subtitle:"Gérez vos préférences et paramètres de compte",tabs:{appearance:"Apparence",language:"Langue",notifications:"Notifications",security:"Sécurité"},appearance:{theme:"Thème",themeDescription:"Choisissez le thème qui vous convient le mieux",light:"Clair",dark:"Sombre",system:"Système",systemDescription:"Suivre le système"},language:{title:"Langue et région",description:"Choisissez votre langue préférée",language:"Langue"},notifications:{title:"Notifications",description:"Configurez vos préférences de notification",emailNotifications:"Notifications par email",emailDescription:"Recevez des notifications par email",pushNotifications:"Notifications push",pushDescription:"Recevez des notifications push dans le navigateur",chatNotifications:"Notifications de chat",chatDescription:"Recevez des notifications pour les nouveaux messages"},security:{title:"Sécurité",description:"Gérez vos paramètres de sécurité",changePassword:"Changer le mot de passe",changePasswordDescription:"Mettez à jour votre mot de passe",twoFactor:"Authentification à deux facteurs",twoFactorDescription:"Ajoutez une couche de sécurité supplémentaire",activeSessions:"Sessions actives",activeSessionsDescription:"Gérez vos sessions de connexion",modify:"Modifier",configure:"Configurer",view:"Voir"},save:"Sauvegarder les modifications",saving:"Sauvegarde..."},po={404:{title:"Page non trouvée",message:"La page que vous recherchez n'existe pas.",backHome:"Retour à l'accueil"},500:{title:"Erreur serveur",message:"Une erreur interne s'est produite. Veuillez réessayer plus tard.",retry:"Réessayer"},network:{title:"Erreur de connexion",message:"Impossible de se connecter au serveur. Vérifiez votre connexion internet.",retry:"Réessayer"},unauthorized:{title:"Accès non autorisé",message:"Vous n'avez pas les permissions nécessaires pour accéder à cette ressource.",login:"Se connecter"}},go={dashboard:"Tableau de bord",chat:"Chat",library:"Bibliothèque",profile:"Profil",settings:"Paramètres",menu:"Menu",close:"Fermer"},yo={required:"Ce champ est obligatoire",email:"Veuillez entrer une adresse email valide",minLength:"Ce champ doit contenir au moins {{min}} caractères",maxLength:"Ce champ ne peut pas dépasser {{max}} caractères",passwordMatch:"Les mots de passe ne correspondent pas",fileSize:"Le fichier ne peut pas dépasser {{max}}MB",fileType:"Type de fichier non supporté"},vo={install:{title:"Installer Veza",description:"Accédez rapidement à Veza depuis votre écran d'accueil",button:"Installer",installing:"Installation...",later:"Plus tard",success:"Application installée avec succès !",error:"Erreur lors de l'installation"},update:{title:"Mise à jour disponible",description:"Une nouvelle version de Veza est disponible",button:"Mettre à jour",updating:"Mise à jour...",later:"Plus tard",success:"Application mise à jour !",error:"Erreur lors de la mise à jour"},offline:{title:"Mode hors ligne",description:"Vous êtes actuellement hors ligne. Certaines fonctionnalités peuvent être limitées.",retry:"Réessayer"},notifications:{permission:{title:"Notifications",description:"Autorisez les notifications pour recevoir les mises à jour importantes",allow:"Autoriser",deny:"Refuser"}}},xo={title:"Pistes",upload:"Téléverser une piste",play:"Lire",pause:"Pause",like:"Aimer",unlike:"Ne plus aimer",addToFavorites:"Ajouter aux favoris",removeFromFavorites:"Retirer des favoris",share:"Partager",download:"Télécharger",comments:"Commentaires",addComment:"Ajouter un commentaire",editComment:"Modifier le commentaire",deleteComment:"Supprimer le commentaire",reply:"Répondre",noTracks:"Aucune piste disponible",noResults:"Aucun résultat trouvé",loading:"Chargement des pistes...",duration:"Durée",artist:"Artiste",album:"Album",genre:"Genre",year:"Année",plays:"Lectures",likes:"J'aime"},bo={title:"Playlists",create:"Créer une playlist",edit:"Modifier la playlist",delete:"Supprimer la playlist",follow:"Suivre",unfollow:"Ne plus suivre",following:"Abonné",followers:"Abonnés",share:"Partager",addTrack:"Ajouter une piste",removeTrack:"Retirer la piste",collaborators:"Collaborateurs",addCollaborator:"Ajouter un collaborateur",removeCollaborator:"Retirer un collaborateur",noPlaylists:"Aucune playlist disponible",loading:"Chargement des playlists...",tracks:"Pistes",public:"Publique",private:"Privée"},wo={title:"Notifications",markAsRead:"Marquer comme lu",markAllAsRead:"Tout marquer comme lu",clearAll:"Tout effacer",noNotifications:"Aucune notification",viewAll:"Voir toutes les notifications",newMessage:"Nouveau message",trackUploaded:"Piste téléversée",userMentioned:"Vous avez été mentionné",system:"Notification système",friendRequest:"Demande d'ami",conversationInvite:"Invitation à une conversation"},ko={title:"Recherche",placeholder:"Rechercher des pistes, playlists, utilisateurs...",results:"Résultats",noResults:"Aucun résultat trouvé",tracks:"Pistes",playlists:"Playlists",users:"Utilisateurs",all:"Tout"},Eo={title:"Analytiques",period:"Période",last7Days:"7 derniers jours",last30Days:"30 derniers jours",last90Days:"90 derniers jours",lastYear:"Dernière année",topTracks:"Pistes populaires",topPlaylists:"Playlists populaires",totalPlays:"Total de lectures",totalLikes:"Total de j'aime",totalDownloads:"Total de téléchargements"},_o={title:"Webhooks",create:"Créer un webhook",edit:"Modifier le webhook",delete:"Supprimer le webhook",test:"Tester le webhook",regenerateKey:"Régénérer la clé API",url:"URL",events:"Événements",status:"Statut",active:"Actif",inactive:"Inactif",noWebhooks:"Aucun webhook configuré"},So={title:"Tableau de bord administrateur",users:"Utilisateurs",systemStats:"Statistiques système",auditLogs:"Journaux d'audit",suspiciousActivity:"Activité suspecte"},No={shortcuts:{title:"Raccourcis clavier",search:"Focus sur la recherche ou naviguer vers la page de recherche",newMessage:"Ouvrir un nouveau chat/message",playPause:"Lire ou mettre en pause la piste actuelle",nextTrack:"Lire la piste suivante",previousTrack:"Lire la piste précédente",volumeUp:"Augmenter le volume",volumeDown:"Diminuer le volume",mute:"Activer/désactiver le mode silencieux",toggleSidebar:"Afficher/masquer la barre latérale",escape:"Fermer les modals ou revenir en arrière",help:"Afficher cette boîte de dialogue d'aide"}},To={play:"Lire",pause:"Pause",next:"Piste suivante",previous:"Piste précédente",shuffleOn:"Aléatoire: Activé",shuffleOff:"Aléatoire: Désactivé",repeatOff:"Répétition: Désactivée",repeatTrack:"Répétition: Piste",repeatPlaylist:"Répétition: Playlist",mute:"Muet",unmute:"Activer le son",showQueue:"Afficher la file d'attente",hideQueue:"Masquer la file d'attente"},jo={common:oo,auth:lo,dashboard:co,chat:uo,library:mo,profile:fo,settings:ho,errors:po,navigation:go,validation:yo,pwa:vo,tracks:xo,playlists:bo,notifications:wo,search:ko,analytics:Eo,webhooks:_o,admin:So,keyboard:No,player:To},Co={loading:"Loading...",save:"Save",cancel:"Cancel",edit:"Edit",delete:"Delete",confirm:"Confirm",close:"Close",back:"Back",next:"Next",previous:"Previous",search:"Search",filter:"Filter",sort:"Sort",view:"View",download:"Download",upload:"Upload",share:"Share",copy:"Copy",refresh:"Refresh",settings:"Settings",profile:"Profile",logout:"Logout",login:"Login",register:"Register",email:"Email",password:"Password",username:"Username",firstName:"First Name",lastName:"Last Name",name:"Name",title:"Title",description:"Description",date:"Date",time:"Time",status:"Status",type:"Type",size:"Size",actions:"Actions",error:"Error",success:"Success",warning:"Warning",info:"Information",yes:"Yes",no:"No",never:"Never",changeTheme:"Change theme",userMenu:"User menu",notifications:"Notifications"},Ro={login:{title:"Login",subtitle:"Sign in to your Veza account",email:"Email",password:"Password",rememberMe:"Remember me",forgotPassword:"Forgot password?",loginButton:"Sign in",noAccount:"Don't have an account?",createAccount:"Create account",errors:{invalidCredentials:"Invalid email or password",accountLocked:"Account locked",emailNotVerified:"Email not verified"}},register:{title:"Create Account",subtitle:"Join the Veza community",firstName:"First Name",lastName:"Last Name",username:"Username",email:"Email",password:"Password",confirmPassword:"Confirm Password",registerButton:"Create Account",hasAccount:"Already have an account?",loginLink:"Sign in",errors:{passwordMismatch:"Passwords do not match",emailExists:"This email is already in use",usernameExists:"This username is already taken",weakPassword:"Password must contain at least 8 characters"}},forgotPassword:{title:"Forgot Password",subtitle:"Enter your email to receive a reset link",email:"Email",sendButton:"Send Reset Link",backToLogin:"Back to login",success:"Reset email sent"}},Ao={title:"Dashboard",welcome:"Welcome, {{name}}!",stats:{totalTracks:"Total Tracks",totalPlaylists:"Playlists",totalFavorites:"Favorites",totalStorage:"Storage Used"},recentActivity:"Recent Activity",recentTracks:"Recent Tracks",quickActions:"Quick Actions",uploadTrack:"Upload Track",createPlaylist:"Create Playlist",startChat:"Start Chat"},Po={title:"Chat",conversations:"Conversations",newConversation:"New Conversation",searchConversations:"Search conversations",noConversations:"No conversations",startConversation:"Start a conversation",messages:{placeholder:"Type your message...",send:"Send",typing:"{{user}} is typing...",online:"Online",offline:"Offline",lastSeen:"Last seen {{time}}"},errors:{connectionFailed:"Failed to connect to chat",messageFailed:"Failed to send message",reconnecting:"Reconnecting..."}},Io={title:"Library",myFiles:"My Files",favorites:"Favorites",recent:"Recent",search:"Search library",filterBy:"Filter by",sortBy:"Sort by",viewMode:{grid:"Grid view",list:"List view"},upload:{title:"Upload File",dragDrop:"Drag and drop your files here",or:"or",browseFiles:"Browse files",supportedFormats:"Supported formats: MP3, WAV, FLAC, PDF, DOC, DOCX",maxSize:"Max size: 100MB"},actions:{play:"Play",download:"Download",share:"Share",addToFavorites:"Add to favorites",removeFromFavorites:"Remove from favorites",edit:"Edit",delete:"Delete"},empty:{title:"Your library is empty",subtitle:"Start by uploading your first files",uploadButton:"Upload file"}},Lo={title:"Profile",subtitle:"Manage your personal information and preferences",personalInfo:"Personal Information",updateProfile:"Update your profile",edit:"Edit",save:"Save",cancel:"Cancel",avatar:{title:"Profile Picture",changePhoto:"Change photo",removePhoto:"Remove photo"},accountInfo:"Account Information",memberSince:"Member since",emailVerified:"Email verified",lastLogin:"Last login",fields:{firstName:"First Name",lastName:"Last Name",username:"Username",email:"Email",bio:"Bio",bioPlaceholder:"Tell us about yourself..."}},qo={title:"Settings",subtitle:"Manage your preferences and account settings",tabs:{appearance:"Appearance",language:"Language",notifications:"Notifications",security:"Security"},appearance:{theme:"Theme",themeDescription:"Choose the theme that works best for you",light:"Light",dark:"Dark",system:"System",systemDescription:"Follow system"},language:{title:"Language and Region",description:"Choose your preferred language",language:"Language"},notifications:{title:"Notifications",description:"Configure your notification preferences",emailNotifications:"Email notifications",emailDescription:"Receive notifications by email",pushNotifications:"Push notifications",pushDescription:"Receive push notifications in browser",chatNotifications:"Chat notifications",chatDescription:"Receive notifications for new messages"},security:{title:"Security",description:"Manage your security settings",changePassword:"Change password",changePasswordDescription:"Update your password",twoFactor:"Two-factor authentication",twoFactorDescription:"Add an extra layer of security",activeSessions:"Active sessions",activeSessionsDescription:"Manage your login sessions",modify:"Modify",configure:"Configure",view:"View"},save:"Save changes",saving:"Saving..."},Do={404:{title:"Page Not Found",message:"The page you're looking for doesn't exist.",backHome:"Back to home"},500:{title:"Server Error",message:"An internal error occurred. Please try again later.",retry:"Retry"},network:{title:"Connection Error",message:"Unable to connect to server. Check your internet connection.",retry:"Retry"},unauthorized:{title:"Unauthorized Access",message:"You don't have permission to access this resource.",login:"Login"}},Mo={dashboard:"Dashboard",chat:"Chat",library:"Library",profile:"Profile",settings:"Settings",menu:"Menu",close:"Close"},Oo={required:"This field is required",email:"Please enter a valid email address",minLength:"This field must contain at least {{min}} characters",maxLength:"This field cannot exceed {{max}} characters",passwordMatch:"Passwords do not match",fileSize:"File cannot exceed {{max}}MB",fileType:"File type not supported"},zo={install:{title:"Install Veza",description:"Quickly access Veza from your home screen",button:"Install",installing:"Installing...",later:"Later",success:"App installed successfully!",error:"Installation error"},update:{title:"Update available",description:"A new version of Veza is available",button:"Update",updating:"Updating...",later:"Later",success:"App updated!",error:"Update error"},offline:{title:"Offline mode",description:"You are currently offline. Some features may be limited.",retry:"Retry"},notifications:{permission:{title:"Notifications",description:"Allow notifications to receive important updates",allow:"Allow",deny:"Deny"}}},Fo={title:"Tracks",upload:"Upload Track",play:"Play",pause:"Pause",like:"Like",unlike:"Unlike",addToFavorites:"Add to favorites",removeFromFavorites:"Remove from favorites",share:"Share",download:"Download",comments:"Comments",addComment:"Add a comment",editComment:"Edit comment",deleteComment:"Delete comment",reply:"Reply",noTracks:"No tracks available",noResults:"No results found",loading:"Loading tracks...",duration:"Duration",artist:"Artist",album:"Album",genre:"Genre",year:"Year",plays:"Plays",likes:"Likes"},Vo={title:"Playlists",create:"Create Playlist",edit:"Edit Playlist",delete:"Delete Playlist",follow:"Follow",unfollow:"Unfollow",following:"Following",followers:"Followers",share:"Share",addTrack:"Add Track",removeTrack:"Remove Track",collaborators:"Collaborators",addCollaborator:"Add Collaborator",removeCollaborator:"Remove Collaborator",noPlaylists:"No playlists available",loading:"Loading playlists...",tracks:"Tracks",public:"Public",private:"Private"},Uo={title:"Notifications",markAsRead:"Mark as read",markAllAsRead:"Mark all as read",clearAll:"Clear all",noNotifications:"No notifications",viewAll:"View all notifications",newMessage:"New message",trackUploaded:"Track uploaded",userMentioned:"You were mentioned",system:"System notification",friendRequest:"Friend request",conversationInvite:"Conversation invite"},$o={title:"Search",placeholder:"Search tracks, playlists, users...",results:"Results",noResults:"No results found",tracks:"Tracks",playlists:"Playlists",users:"Users",all:"All"},Qo={title:"Analytics",period:"Period",last7Days:"Last 7 days",last30Days:"Last 30 days",last90Days:"Last 90 days",lastYear:"Last year",topTracks:"Top Tracks",topPlaylists:"Top Playlists",totalPlays:"Total Plays",totalLikes:"Total Likes",totalDownloads:"Total Downloads"},Bo={title:"Webhooks",create:"Create Webhook",edit:"Edit Webhook",delete:"Delete Webhook",test:"Test Webhook",regenerateKey:"Regenerate API Key",url:"URL",events:"Events",status:"Status",active:"Active",inactive:"Inactive",noWebhooks:"No webhooks configured"},Ko={title:"Admin Dashboard",users:"Users",systemStats:"System Statistics",auditLogs:"Audit Logs",suspiciousActivity:"Suspicious Activity"},Ho={shortcuts:{title:"Keyboard Shortcuts",search:"Focus search or navigate to search page",newMessage:"Open new chat/message",playPause:"Play or pause current track",nextTrack:"Play next track",previousTrack:"Play previous track",volumeUp:"Increase volume",volumeDown:"Decrease volume",mute:"Toggle mute",toggleSidebar:"Toggle sidebar",escape:"Close modals or go back",help:"Show this help dialog"}},Wo={play:"Play",pause:"Pause",next:"Next track",previous:"Previous track",shuffleOn:"Shuffle: On",shuffleOff:"Shuffle: Off",repeatOff:"Repeat: Off",repeatTrack:"Repeat: Track",repeatPlaylist:"Repeat: Playlist",mute:"Mute",unmute:"Unmute",showQueue:"Show queue",hideQueue:"Hide queue"},Go={common:Co,auth:Ro,dashboard:Ao,chat:Po,library:Io,profile:Lo,settings:qo,errors:Do,navigation:Mo,validation:Oo,pwa:zo,tracks:Fo,playlists:Vo,notifications:Uo,search:$o,analytics:Qo,webhooks:Bo,admin:Ko,keyboard:Ho,player:Wo},Yo={fr:{translation:jo},en:{translation:Go}};tr.use(ns).use(is).init({resources:Yo,fallbackLng:"en",debug:!1,interpolation:{escapeValue:!1},detection:{order:["localStorage","navigator","htmlTag"],caches:["localStorage"]}});typeof window<"u"&&(window.i18n=tr);function Xo(){const e="production";{g.debug("[Sentry] Error tracking disabled",{reason:"DSN not configured",environment:e});return}}const Jo={theme:"system",setTheme:()=>null},Zo=f.createContext(Jo);function el({children:e,defaultTheme:t="system",storageKey:r="vite-ui-theme"}){const[a,n]=f.useState(()=>localStorage.getItem(r)||t);f.useEffect(()=>{const o=window.document.documentElement;if(o.classList.remove("light","dark"),a==="system"){const c=window.matchMedia("(prefers-color-scheme: dark)").matches?"dark":"light";o.classList.add(c);return}o.classList.add(a)},[a]),f.useEffect(()=>{if(a!=="system")return;const o=window.matchMedia("(prefers-color-scheme: dark)"),c=()=>{const l=window.document.documentElement;o.matches?(l.classList.add("dark"),l.classList.remove("light")):(l.classList.add("light"),l.classList.remove("dark"))};return o.addEventListener("change",c),()=>o.removeEventListener("change",c)},[a]);const i={theme:a,setTheme:o=>{localStorage.setItem(r,o),n(o)}};return s.jsx(Zo.Provider,{value:i,value:i,children:e})}typeof window<"u"&&(window.addEventListener("error",e=>{},!0),window.addEventListener("unhandledrejection",e=>{}));Xo();const Ur=new Jr({defaultOptions:{queries:{retry:!1,refetchOnWindowFocus:!1,staleTime:60*1e3,gcTime:300*1e3,refetchOnMount:!0,refetchOnReconnect:!0}}});Xs(Ur);async function tl(){nt.USE_MSW}const rl=()=>new Promise(e=>{const t=()=>{try{if(document.readyState!=="complete"&&document.readyState!=="interactive")return!1;const r=Array.from(document.styleSheets);if(r.length===0)return!1;let a=0;for(const n of r)try{(n.cssRules!==null||n.href===null)&&a++}catch{n.href!==null&&a++}return a===r.length}catch{return!1}};if(document.readyState==="complete"&&t()){requestAnimationFrame(()=>{requestAnimationFrame(()=>{requestAnimationFrame(()=>{setTimeout(()=>{t()?e():setTimeout(()=>e(),100)},100)})})});return}if(document.readyState==="loading")window.addEventListener("load",()=>{let r=0;const a=20,n=setInterval(()=>{r++,(t()||r>=a)&&(clearInterval(n),requestAnimationFrame(()=>{requestAnimationFrame(()=>{requestAnimationFrame(()=>{setTimeout(()=>{e()},50)})})}))},50)},{once:!0});else{let r=0;const a=20,n=setInterval(()=>{r++,(t()||r>=a)&&(clearInterval(n),requestAnimationFrame(()=>{requestAnimationFrame(()=>{requestAnimationFrame(()=>{setTimeout(()=>{e()},50)})})}))},50)}}),sl=()=>{Hr.createRoot(document.getElementById("root")).render(s.jsx(Wr.StrictMode,{children:s.jsx(Zr,{client:Ur,children:s.jsx(el,{defaultTheme:"dark",storageKey:"vite-ui-theme",children:s.jsxs(Xr,{future:{v7_startTransition:!0,v7_relativeSplatPath:!0},children:[s.jsx(io,{}),s.jsx(ea,{position:"top-right"})]})})})}))},al=N(()=>import("./vendor-fFnFILYR.js").then(e=>e.Y),__vite__mapDeps([0,1,2])).then(e=>e).catch(e=>{});Promise.all([tl(),al]).then(()=>{}).catch(e=>{g.error("[Init] Failed to initialize; continuing",{error:e instanceof Error?e.message:String(e),stack:e instanceof Error?e.stack:void 0})}).then(()=>rl()).finally(()=>{sl()});export{br as A,P as B,Nr as C,At as D,Cr as E,bn as L,Ga as M,Lt as S,bi as T,N as _,D as a,hl as b,pl as c,w as d,Ha as e,gl as f,ii as g,Z as h,nt as i,Dr as j,xl as k,g as l,vl as m,Rt as n,dl as o,B as p,fl as q,kr as r,zr as s,te as t,qr as u,It as v,kt as w,vr as x,yl as y,ml as z};
|