- DESIGN_TOKENS.md: Complete rewrite to document --sumi-* token system - APP_SHELL.md: Update layout shell docs (glass bg, backdrop-blur, z-index) - DESIGN_DIRECTION.md: Update aesthetic direction to SUMI philosophy - .storybook/preview.tsx: Remove deleted CSS imports, update bg colors - eslint.config.js: Update color rule message from Kodo to SUMI tokens - tailwind.config.ts: Fix comment referencing deleted design-tokens.css Co-authored-by: Cursor <cursoragent@cursor.com>
5 lines
221 KiB
JavaScript
5 lines
221 KiB
JavaScript
const __vite__mapDeps=(i,m=__vite__mapDeps,d=(m.f||(m.f=["assets/vendor-CAoAb3tF.js","assets/vendor-react-Dkpvlwai.js","assets/vendor-BD_zwJK7.css","assets/DashboardPage-YCMhF3W0.js","assets/vendor-router-4bycex72.js","assets/vendor-tanstack-BoI3DtL9.js","assets/chatStore-Dpim9vVR.js","assets/AnimatedNumber-Dt_wg-GW.js","assets/vendor-icons-CbmLcMl-.js","assets/vendor-utils-CDFfoeXY.js","assets/ChatPage-B8BAcAdb.js","assets/input-CpxrTzwP.js","assets/Select-Zbef75Fw.js","assets/dropdown-WuZUrg5z.js","assets/useIsRateLimited-V6u_TMsM.js","assets/confirmation-dialog-oRC6nIEK.js","assets/avatar-DSgu46M3.js","assets/LibraryPage-Bs71TQk9.js","assets/ContentFadeIn-Tb-ft8CP.js","assets/tracks-DFRy168u.js","assets/trackService-BilERhFT.js","assets/progress-5klaDPNN.js","assets/alert-DvTTzGyG.js","assets/UserProfilePage-CSNlfZ_c.js","assets/users-_nyTUiUz.js","assets/PlaylistCard-DbxTYpbq.js","assets/features-DIZYat5y.js","assets/socialService-DIjj2A6_.js","assets/Tabs-DcqFJUlH.js","assets/SettingsPage-CSqfJRlB.js","assets/checkbox-zOPO199O.js","assets/LoginPage-BbWKY4E4.js","assets/AuthInput-D8HO890B.js","assets/AuthLayout-Cq0LJiYh.js","assets/RegisterPage-DbPAqniK.js","assets/PasswordStrengthIndicator-DAS5SCbo.js","assets/ForgotPasswordPage-KvMFzvc3.js","assets/usePasswordReset-CSqFXQtE.js","assets/VerifyEmailPage-DuS24L5f.js","assets/ResetPasswordPage-9TFWnCyB.js","assets/SessionsPage-DNibxB7b.js","assets/NotFoundPage-sz5r5MGU.js","assets/ServerErrorPage-jZz_mSIW.js","assets/RolesPage-Do-nT-Bu.js","assets/textarea-DMG-sYZV.js","assets/TrackDetailPage-YaPhIZ5N.js","assets/Spinner-B_7V8TwM.js","assets/useCopyToClipboard-BsHfBITc.js","assets/routes-D8al6ym8.js","assets/Pagination-MmdnmGQ0.js","assets/useDebounce-B-QrukTv.js","assets/routes-B3giLbLK.css","assets/AdminDashboardView-BA3kSUMs.js","assets/AnalyticsView-CXNlCI9N.js","assets/StatCard-5r7CYk9-.js","assets/WebhooksView-zD80nU1x.js","assets/webhookService-BgsiUSts.js","assets/DesignSystemDemo-CSO7r1b-.js","assets/SocialView-D4x7N4R4.js","assets/GearView-TKbTgc2Z.js","assets/LiveView-kUoUJm2D.js","assets/EducationView-CybxtgC5.js","assets/QueueView-CgH4FdTb.js","assets/DeveloperDashboardView-Ixv7KfYn.js","assets/NotificationsView-DUoPDuge.js","assets/MarketplaceHome-CSnDyays.js","assets/marketplaceService-CUzt02g_.js","assets/cartStore-CJpUIjVU.js","assets/SearchPage-BYMUfiz0.js","assets/SellerDashboardView-BmLj6E51.js","assets/commerceService-bs-xd9qB.js","assets/WishlistView-I41eG0yr.js","assets/PurchasesView-DipY77Ae.js"])))=>i.map(i=>d[i]);
|
|
import{a as f,j as s,R as fr,c as hr,d as ds}from"./vendor-react-Dkpvlwai.js";import{N as at,u as ct,L as nt,a as ms,R as fs,b as ke,B as hs}from"./vendor-router-4bycex72.js";import{u as pr,a as Rt,b as $t,Q as ps,c as gs}from"./vendor-tanstack-BoI3DtL9.js";import{k as Oe,l as Ve,n as Ue,q as ze,t as gr,u as ys,v as vs,S as xs,w as yr,x as At,y as je,z as bs,B as ws,C as vr,D as ks,E as Es}from"./vendor-CAoAb3tF.js";import{s as x,o as A,Z as Pt,r as $e,b as re,e as se,a as he,n as $,c as ie,f as Ss,d as js}from"./vendor-utils-CDFfoeXY.js";import{L as Ce,A as Qe,R as xr,H as br,I as ut,a as _e,C as Ns,X as pe,b as qe,T as _s,c as Ts,W as Cs,d as Qt,e as Rs,B as As,f as Ps,g as wr,h as kr,i as Is,j as Ls,M as qs,S as Ds,k as Ms,U as Os,l as Er,m as Sr,n as zs,o as Fs,p as Vs,q as Us,r as $s,s as Qs,t as Bs,u as Hs,v as Ks,w as Ws,x as Gs,y as Ys,z as Xs,D as Js,G as Zs,E as ea,F as It,J as ta,K as Lt,N as ra,O as sa,P as aa,Q as jr,V as Nr,Y as _r,Z as Tr,_ as Cr,$ as Rr,a0 as na,a1 as ia,a2 as oa,a3 as Bt,a4 as la,a5 as ca,a6 as ua,a7 as Ht}from"./vendor-icons-CbmLcMl-.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 da="modulepreload",ma=function(e){return"/"+e},Kt={},T=function(t,r,a){let n=Promise.resolve();if(r&&r.length>0){let l=function(m){return Promise.all(m.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(m=>{if(m=ma(m),m in Kt)return;Kt[m]=!0;const u=m.endsWith(".css"),d=u?'[rel="stylesheet"]':"";if(document.querySelector(`link[href="${m}"]${d}`))return;const h=document.createElement("link");if(h.rel=u?"stylesheet":da,u||(h.as="script"),h.crossOrigin="",h.href=m,c&&h.setAttribute("nonce",c),document.head.appendChild(h),u)return new Promise((y,p)=>{h.addEventListener("load",y),h.addEventListener("error",()=>p(new Error(`Unable to preload CSS for ${m}`)))})}))}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 Ar=null;function fa(e){Ar=e}function ha(){return Ar}const pa=f.lazy(()=>T(()=>import("./vendor-CAoAb3tF.js").then(e=>e.Y),__vite__mapDeps([0,1,2])).then(e=>({default:e.Toaster})));function ga(e){return s.jsx(f.Suspense,{fallback:null,children:s.jsx(pa,{...e})})}const Wt="veza_access_token",Gt="veza_refresh_token";class te{static setTokens(t,r){try{localStorage.removeItem(Wt),localStorage.removeItem(Gt)}catch{}}static getAccessToken(){return null}static getRefreshToken(){return null}static clearTokens(){try{localStorage.removeItem(Wt),localStorage.removeItem(Gt)}catch{}}static hasTokens(){return!1}}const ya="WARN".toUpperCase();let it={};function Yt(e){it={...it,...e}}function va(){return{...it}}function Ye(e,t,r,...a){const n={...it,...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&&xa(l,o).catch(()=>{})}}async function xa(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 Xe(e){const t=["DEBUG","INFO","WARN","ERROR"],r=t.indexOf(ya),a=t.indexOf(e);return r===-1||a===-1?!0:a>=r}const g={debug:(e,t,...r)=>{Xe("DEBUG")&&Ye("DEBUG",e,t,...r)},info:(e,t,...r)=>{Xe("INFO")&&Ye("INFO",e,t,...r)},warn:(e,t,...r)=>{Xe("WARN")&&Ye("WARN",e,t,...r)},error:(e,t,...r)=>{Xe("ERROR")&&Ye("ERROR",e,t,...r)}},me=T(()=>import("./vendor-CAoAb3tF.js").then(e=>e.Y),__vite__mapDeps([0,1,2]));let st=null,St=!1;me.then(e=>{st=e,St=!0}).catch(()=>{St=!0});function Xt(){return!st&&St?(g.error("Toast module failed to load"),{success:()=>{},error:()=>{},loading:()=>{},custom:()=>{},dismiss:()=>{},remove:()=>{},promise:()=>Promise.resolve()}):st?st.default:{success:(...e)=>{me.then(t=>t.default.success(...e))},error:(...e)=>{me.then(t=>t.default.error(...e))},loading:(...e)=>{me.then(t=>t.default.loading(...e))},custom:(...e)=>{me.then(t=>t.default.custom(...e))},dismiss:(...e)=>{me.then(t=>t.default.dismiss(...e))},remove:(...e)=>{me.then(t=>t.default.remove(...e))},promise:(...e)=>me.then(t=>t.default.promise(...e))}}const ee=new Proxy({},{get(e,t){const r=Xt();if(t in r){const a=r[t];return typeof a=="function"?a.bind(r):a}},apply(e,t,r){const a=Xt();return typeof a=="function"?a(...r):me.then(n=>n.default(...r))}});let vt=null;const ba=60*1e3,wa=240*1e3;let De=null,Ne=null;function ka(){return vt||(vt=Oe.create({baseURL:"https://api.veza.com/api/v1",timeout:1e4,headers:{"Content-Type":"application/json"},withCredentials:!0})),vt}async function Fe(){try{const t=await ka().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)}`);te.setTokens("","cookie-based"),Pr(r)}catch(e){throw te.clearTokens(),dt(),e}}function Pr(e=300){dt(),Ea();const t=e*1e3,r=Math.max(0,t-ba);if(r<=0){Fe().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}De=setTimeout(()=>{Fe().catch(a=>{g.warn("Proactive token refresh failed",{error:a instanceof Error?a.message:String(a),stack:a instanceof Error?a.stack:void 0})}),De=null},r)}function Ea(){Ne&&clearInterval(Ne),Ne=setInterval(()=>{Fe().catch(e=>{g.warn("Periodic token refresh failed",{error:e instanceof Error?e.message:String(e),stack:e instanceof Error?e.stack:void 0}),dt()})},wa)}function dt(){De&&(clearTimeout(De),De=null),Ne&&(clearInterval(Ne),Ne=null)}function qt(){Pr(300)}function Ir(){dt()}const Sa=Object.freeze(Object.defineProperty({__proto__:null,cleanupProactiveRefresh:Ir,initializeProactiveRefresh:qt,refreshToken:Fe},Symbol.toStringTag,{value:"Module"})),Je=x().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 /"}),Jt="veza.fr",ja=A({VITE_DOMAIN:x().default("veza.fr"),VITE_API_URL:Je.default("/api/v1"),VITE_WS_URL:Je.default(`ws://${Jt}:8081/ws`),VITE_STREAM_URL:Je.default(`ws://${Jt}:8082/stream`),VITE_UPLOAD_URL:Je.default("/upload"),VITE_APP_NAME:x().default("Veza"),VITE_API_VERSION:x().default("v1"),VITE_DEBUG:x().transform(e=>e==="true"||e==="1").default("false"),VITE_USE_MSW:x().transform(e=>e==="1"||e==="true").default("0"),VITE_FCM_VAPID_KEY:x().optional(),VITE_SENTRY_DSN:x().url().optional()}),Na=()=>{try{return ja.parse({VITE_DOMAIN:"veza.fr",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 Pt?(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}},ae=Na(),mt={DOMAIN:ae.VITE_DOMAIN,API_URL:ae.VITE_API_URL,WS_URL:ae.VITE_WS_URL,STREAM_URL:ae.VITE_STREAM_URL,UPLOAD_URL:ae.VITE_UPLOAD_URL,APP_NAME:ae.VITE_APP_NAME,API_VERSION:ae.VITE_API_VERSION,DEBUG:ae.VITE_DEBUG,USE_MSW:ae.VITE_USE_MSW,FCM_VAPID_KEY:ae.VITE_FCM_VAPID_KEY,SENTRY_DSN:ae.VITE_SENTRY_DSN},ne={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."},_a={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 Ta(e,t){return e in ne?ne[e]:t||ne.UNKNOWN}function Ca(e,t,r){const a=_a[e];return a&&t in a?a[t]:r||ne.UNKNOWN}function Lr(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=Ra(a.message),o=Ca(t,i,void 0);if(o!==ne.UNKNOWN)return o}if(n>0){const i=Ta(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||ne.UNKNOWN}if(e instanceof Error)return e.message||ne.UNKNOWN;if(e&&typeof e=="object"&&"code"in e){const a=e.code;if(a==="ECONNABORTED"||a==="ETIMEDOUT")return ne.TIMEOUT;if(a==="ERR_NETWORK"||!e.response)return ne.NETWORK}return ne.UNKNOWN}function Ra(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 qr={timeout:ne.TIMEOUT};function Aa(e){if(e instanceof Error)return e.message===qr.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 Pa(){return typeof navigator>"u"?!0:navigator.onLine}function Ia(){return!Pa()}function K(e){if(qa(e))return e;if(Da(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 xt(r.error);if(n(r)){const l=r.error;if(l&&("code"in l||"message"in l))return xt(l)}if(i(r))return xt(r)}if(t.request&&!t.response)return Aa(t)?{code:0,message:qr.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"||Ia()?{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||{},m=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,y=l["retry-after"]?parseInt(String(l["retry-after"]),10):m?.error?.retry_after||60,p=h?new Date(h*1e3):void 0,k=p?Math.max(0,Math.ceil((p.getTime()-Date.now())/1e3)):y;return{code:429,message:m?.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:jt(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:jt(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 jt(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 La(e){if(typeof e=="object"&&e!==null&&!Array.isArray(e))return e}function xt(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:jt(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:La(t.context)}}function Ll(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 ft(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 qa(e){return typeof e=="object"&&e!==null&&"code"in e&&"message"in e&&typeof e.code=="number"&&typeof e.message=="string"}function Da(e){return typeof e=="object"&&e!==null&&"isAxiosError"in e&&e.isAxiosError===!0}class Ma{token=null;refreshPromise=null;async refreshToken(){return this.refreshPromise?this.refreshPromise:(this.refreshPromise=(async()=>{try{const r=(await F.get("/csrf-token")).data;return this.token=r.csrf_token,this.token}catch(t){const r=t instanceof Error?t.message:String(t);throw r.includes("HTML page instead of JSON")||g.error("Failed to fetch CSRF token",{message:r}),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 Y=new Ma;class Oa{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 F.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 fe=new Oa;class za{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(m=>(setTimeout(()=>{const u=this.cache.get(o);u&&u.promise===l&&(this.cache.delete(o),g.debug(`[RequestDeduplication] Removed from cache: ${o}`))},i),m)).catch(m=>{const u=this.cache.get(o);throw u&&u.promise===l&&(this.cache.delete(o),g.debug(`[RequestDeduplication] Removed from cache (error): ${o}`)),m});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 Fa=new za;typeof window<"u"&&setInterval(()=>{Fa.cleanup(6e4)},300*1e3);class Va{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"],m=this.generateCacheKey(t);if(this.cache.size>=this.maxSize&&!this.cache.has(m)){const u=this.cache.keys().next().value;u&&this.cache.delete(u)}this.cache.set(m,{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:m,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 xe=new Va({defaultTTL:300*1e3,maxSize:100,respectCacheControl:!0,enableETag:!0});typeof window<"u"&&setInterval(()=>{xe.cleanup()},60*1e3);function Zt(e={}){const{target:t="all",resourceType:r,resourceId:a,invalidateAll:n=!1,queryKeys:i=[],storeNames:o=[]}=e;try{(t==="cache"||t==="all")&&(n?(xe.clear(),g.debug("[StateInvalidation] Cleared all response cache")):r&&Ua(r,a)),(t==="queries"||t==="all")&&$a(i,r,a),(t==="stores"||t==="all")&&Qa(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 Ua(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"){xe.clear();return}const a=r[e]||[];for(const n of a)xe.invalidate(n);if(t)for(const n of a)xe.invalidate(`${n}/${t}`)}function $a(e,t,r){const a=ha();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 Qa(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)Ba(i).catch(o=>{g.warn(`[StateInvalidation] Failed to invalidate store ${i}`,{error:String(o)})})}async function Ba(e,t,r){try{switch(e){case"auth":{const{useAuthStore:a}=await T(async()=>{const{useAuthStore:n}=await Promise.resolve().then(()=>Ee);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 Ha(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}Zt(r?{resourceType:r,resourceId:a,target:"all"}:{target:"cache",invalidateAll:!0})}function Ka(e){if(e!=null)return typeof e=="string"?e:String(e)}function Nt(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]=Ka(n):n&&typeof n=="object"&&!Array.isArray(n)&&!(n instanceof Date)?r[a]=Nt(n,t):Array.isArray(n)&&n.length>0&&typeof n[0]=="object"&&(r[a]=n.map(i=>typeof i=="object"&&i!==null?Nt(i,t):i));return r}const Re="1.2.0";function Be(e,t=Re,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 L=x().uuid("Invalid UUID format"),B=x().datetime({message:"Invalid ISO8601 date format"}),He=Be(A({id:L,username:x().min(1),slug:x().optional(),email:x().email(),first_name:x().optional().nullable(),last_name:x().optional().nullable(),avatar:x().optional().nullable(),bio:x().optional().nullable(),location:x().optional().nullable(),birthdate:B.optional().nullable(),gender:x().optional().nullable(),username_changed_at:B.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:B.optional().nullable(),created_at:B,updated_at:B,is_2fa_enabled:re().optional(),social_links:$e(he()).optional().nullable()}),Re,"User response schema - matches backend User model"),Wa=A({id:L,conversation_id:L,sender_id:L,content:x(),message_type:se(["text","image","audio","file"]),attachment_url:x().url().optional(),created_at:B,updated_at:B,sender:He.optional()});A({id:L,name:x(),type:se(["direct","group"]),creator_id:L,created_at:B,updated_at:B,participants:ie(He).optional(),last_message:Wa.optional(),unread_count:$().int().nonnegative().optional()});const Dr=Be(A({id:L,creator_id:L,file_id:L.optional().nullable(),title:x().min(1),artist:x().min(1),album:x(),duration:$().int().nonnegative(),genre:x(),year:$().int().min(1900).max(2100),file_path:x(),file_size:$().nonnegative(),format:x(),bitrate:$().nonnegative(),sample_rate:$().nonnegative(),waveform_path:x().optional().nullable(),cover_art_path:x().optional().nullable(),is_public:re(),status:se(["uploading","processing","completed","failed"]),status_message:x().optional().nullable(),stream_status:se(["pending","processing","ready","error"]),stream_manifest_url:x().url().optional().nullable(),play_count:$().int().nonnegative(),like_count:$().int().nonnegative(),created_at:B,updated_at:B,user:He.optional(),is_premium:re().optional(),lyrics:ie(A({time:$(),text:x()})).optional(),waveform_data:ie($()).optional(),tags:ie(x()).optional()}),Re,"Track response schema - matches backend Track model");Be(A({id:L,user_id:L,title:x().min(1),description:x().optional().nullable(),visibility:se(["public","private","unlisted"]).optional(),is_public:re(),cover_url:x().url().optional().nullable(),track_count:$().int().nonnegative(),follower_count:$().int().nonnegative(),created_at:B,updated_at:B,tracks:ie(Dr).optional(),user:He.optional(),playlist_tracks:ie(he()).optional(),collaborators:ie(he()).optional()}),Re,"Playlist response schema - matches backend Playlist model");A({id:L,user_id:L,ip_address:x(),user_agent:x(),revoked_at:B.optional().nullable(),expires_at:B,created_at:B});A({id:L,user_id:L.optional().nullable(),action:x(),resource:x(),resource_id:L.optional().nullable(),metadata:$e(he()).optional().nullable(),ip_address:x().optional().nullable(),user_agent:x().optional().nullable(),timestamp:B});Be(A({code:$().int(),message:x(),details:ie(A({field:x(),message:x(),value:x().optional()})).optional(),request_id:x().optional(),timestamp:B,context:$e(he()).optional(),retry_after:$().int().positive().optional()}),Re,"API Error response schema - matches backend error format");Be(A({page:$().int().positive(),limit:$().int().positive(),total:$().int().nonnegative(),total_pages:$().int().nonnegative(),has_next:re(),has_prev:re(),next_cursor:x().optional(),prev_cursor:x().optional()}),Re,"Pagination metadata schema");A({id:L,user_id:L,type:se(["new_message","track_uploaded","user_mentioned","system"]),content:x(),read:re(),created_at:B});A({id:L,playlist_id:L,track_id:L,position:$().int().nonnegative(),added_by:L,added_at:B,track:Dr.optional()});A({id:L,playlist_id:L,user_id:L,role:se(["owner","editor","viewer"]),created_at:B,user:He.optional()});function Ga(e,t,r={}){const{normalizeIds:a=!0}=r;let n=t;return a&&typeof t=="object"&&t!==null&&(n=Nt(t)),e.parse(n)}function er(e,t,r={}){try{return{success:!0,data:Ga(e,t,r)}}catch(a){if(a instanceof Pt)return{success:!1,error:a};throw a}}const Ke=x().email("Invalid email format"),ht=x().min(8,"Password must be at least 8 characters"),pt=x().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");A({email:Ke,password:x().min(1,"Password is required")});A({username:pt,email:Ke,password:ht,first_name:x().max(100).optional(),last_name:x().max(100).optional()});A({code:x().min(6,"TOTP code must be at least 6 characters").max(6,"TOTP code must be exactly 6 characters"),secret:x().min(1,"Secret is required")});A({password:ht});A({username:pt,email:Ke,password:ht});A({username:pt.optional(),email:Ke.optional(),password:ht.optional()});A({first_name:x().max(100).optional(),last_name:x().max(100).optional(),username:pt.optional(),bio:x().max(500).optional(),location:x().max(100).optional(),birthdate:x().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()});A({conversation_id:L,content:x().min(1,"Message content is required"),message_type:se(["text","image","audio","file"]).optional(),attachment_url:x().url().optional()});A({content:x().min(1,"Message content is required").optional()});A({name:x().min(1,"Conversation name is required"),type:se(["direct","group"]),participant_ids:ie(L).min(1,"At least one participant is required")});A({name:x().min(1,"Conversation name is required").optional()});A({track_ids:ie(L).min(1,"At least one track ID is required")});A({filename:x().min(1,"Filename is required"),total_chunks:$().int().min(1,"Total chunks must be at least 1"),total_size:$().int().min(1,"Total size must be at least 1")});A({upload_id:x().min(1,"Upload ID is required")});A({upload_id:x().min(1,"Upload ID is required"),chunk_number:$().int().min(0,"Chunk number must be non-negative"),total_chunks:$().int().min(1,"Total chunks must be at least 1"),total_size:$().int().min(1,"Total size must be at least 1"),filename:x().min(1,"Filename is required")});A({event_name:x().min(1,"Event name is required").max(100,"Event name must be at most 100 characters"),payload:$e(he()).optional()});A({url:x().url("Invalid webhook URL"),events:ie(x()).min(1,"At least one event is required"),secret:x().min(1,"Secret is required").optional()});A({level:x().optional(),message:x().optional(),context:$e(he()).optional(),timestamp:x().optional(),data:he().optional()});A({email:Ke});A({title:x().min(1,"Track title is required"),artist_id:L,album_id:L.optional(),genre:x().min(1,"Genre is required")});A({title:x().min(1,"Track title is required").optional(),artist_id:L.optional(),album_id:L.optional(),genre:x().min(1,"Genre is required").optional()});const We=A({page:$().int().positive().optional(),limit:$().int().positive().max(100).optional(),cursor:x().optional()});We.extend({query:x().optional()});We.extend({conversation_id:L});We.extend({query:x().optional()});We.extend({artist:x().optional(),genre:x().optional()});We.extend({query:x().min(1,"Search query is required")});A({type:se(["image","audio","document"])});function Ya(e,t){return e.parse(t)}function Xa(e,t){try{return{success:!0,data:Ya(e,t)}}catch(r){if(r instanceof Pt)return{success:!1,error:r};throw r}}const tr={limit:null,remaining:null,reset:null,retryAfter:null,isLimited:!1,lastUpdated:null},_t=Ve()(Ue(e=>({...tr,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(tr)}}),{name:"rate-limit-storage",partialize:e=>({limit:e.limit,remaining:e.remaining,reset:e.reset,retryAfter:e.retryAfter,isLimited:e.isLimited,lastUpdated:null})}));class Ja{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 ot=new Ja,rr={failureRateThreshold:5,minValidationsForAlert:10,checkInterval:300*1e3};class Za{config=rr;checkIntervalId=null;lastAlertTime=0;alertCooldown=900*1e3;start(t){this.checkIntervalId&&this.stop(),this.config={...rr,...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=ot.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 Mr=new Za;typeof window<"u"&&Mr.start();const Or={DEFAULT:1e4,UPLOAD:3e5,LONG_POLLING:3e4},Tt=1e3,F=Oe.create({baseURL:mt.API_URL,timeout:Or.DEFAULT,headers:{"Content-Type":"application/json"},withCredentials:!0});let Ze=!1,ge=0;const bt=3;let Se=[];const en=e=>new Promise(t=>setTimeout(t,e)),ye={maxRetries:3,baseDelay:1e3,maxDelay:1e4,retryableStatusCodes:[500,502,503,504],retryableNetworkErrors:["ECONNABORTED","ETIMEDOUT","ENOTFOUND","ECONNREFUSED","ECONNRESET","EAI_AGAIN","Network Error"]},Ct=e=>e?["GET","HEAD","OPTIONS"].includes(e.toUpperCase()):!1;class tn{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 Dt=new tn,zr=e=>!!(e.response?.status===206||e.code==="ECONNABORTED"&&e.message?.toLowerCase().includes("timeout")&&e.request||e.code==="ECONNRESET"&&e.response||Dt.isPartialFailure()),rn=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"||Dt.isCompleteFailure()),sn=(e,t=ye)=>{if(Oe.isCancel(e)||e.code==="ERR_BAD_RESPONSE"||e.message?.includes("HTML page instead of JSON")||e.config?._disableRetry)return!1;if(zr(e))return Ct(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?Ct(e.config?.method):!1},an=(e,t,r=ye.baseDelay,a=ye.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)},ve=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]=ve(r[a]))}return r},Me=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},wt=e=>{Se.forEach(t=>{e?t.reject(e):t.resolve(void 0)}),Se=[]};F.interceptors.request.use(async e=>{const t=Date.now();e._requestStartTime=t,e._isSlowRequest=!1,e.headers&&(e.headers["X-API-Version"]=mt.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=Y.getToken();if(!c)try{c=await Y.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=Xa(o,e.data);if(!c.success){const l=Me(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 m=c.error?.errors.map(u=>`${u.path.join(".")}: ${u.message}`).join(", ")||"Request validation failed";throw new Error(`Request validation failed: ${m}`)}e.data=c.data}if(e._requestStartTime=Date.now(),e?._enableLogging){const c=Me(e),l=ve({...e.headers}),m=ve(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:m,timeout:e.timeout,signal:e.signal?"AbortController":void 0})}return e},e=>Promise.reject(e));function nn(e){const t=e.headers?.["content-type"];if(typeof t=="string"&&t.toLowerCase().includes("text/html"))return!0;const r=e.data;if(typeof r=="string"){const a=r.trim().toLowerCase();return a.startsWith("<!doctype")||a.startsWith("<html")}return!1}F.interceptors.response.use(e=>{if(nn(e)){const h="The API returned an HTML page instead of JSON. Another application may be using port 8080. Stop any other server (e.g. phishing lab) and ensure the Veza backend is running.";if(typeof window<"u"){const y="veza_wrong_server_shown";sessionStorage.getItem(y)||(sessionStorage.setItem(y,"true"),ee(h,{icon:"⚠️",duration:12e3}))}return Promise.reject(new ze(h,"ERR_BAD_RESPONSE",e.config,e.request,e))}Dt.recordRequest(!0);const t=e.config?._requestStartTime;if(t){const h=Date.now()-t;h>Tt&&(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:Tt}))}const a=e.headers["x-request-id"]||e.headers["X-Request-ID"]||e.config?._requestId;a&&Yt({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)&&_t.getState().updateRateLimit({limit:n,remaining:i,reset:o,retryAfter:null}),e.config?._enableLogging){const h=ve(e.data),y=ve(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:y,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 y=e.headers.sunset||e.headers.Sunset,p=y?`This API version is deprecated and will be removed on ${y}. Please update to the latest version.`:"This API version is deprecated. Please update to the latest version.";ee(p,{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:y})}}if(!e.data||typeof e.data!="object")return e;const m=e.config.method?.toUpperCase(),u=["POST","PUT","PATCH","DELETE"].includes(m||"");if(u&&e.config?._showSuccessToast&&typeof window<"u"){const h=e.config?._successMessage||e.data?.message||on(m||"");h&&ee.success(h)}if(m==="GET"&&!e.config?._disableCache&&xe.set(e.config,e),u){const h=e.config.url||"";e.config.method,Ha(h)}if("success"in e.data){if(e.data.success===!0){const h=e.data.data!==void 0?e.data.data:null,y=e.config?._responseSchema;if(y&&h!==null){const p=er(y,h);if(p.success){const k=Me(e.config);g.debug("[API Response Validation Success]",{request_id:k,url:e.config.url}),ot.recordSuccess(e.config.url)}else{const k=Me(e.config),E={request_id:k,url:e.config.url,method:e.config.method?.toUpperCase(),status:e.status,error_type:"api_response_validation_failed",validation_errors:p.error?.errors.map(b=>({path:b.path.join("."),message:b.message,code:b.code,received:b.code==="invalid_type"?b.received:void 0,expected:b.code==="invalid_type"?b.expected:void 0})),response_data_preview:JSON.stringify(h).substring(0,200),schema_provided:!!y,timestamp:new Date().toISOString()};g.error("[API Response Validation Failed]",E,p.error),ot.recordFailure(e.config.url);const j=e.config?._validationRecovery,N=j?.useCache!==!1,D=j?.retry===!0,V=j?.notifyUser!==!1;if(N&&m==="GET"){const b=xe.get(e.config);if(b){let _=b.data;if(_&&typeof _=="object"&&"success"in _&&_.success===!0&&(_=_.data!==void 0?_.data:null),_!==null&&er(y,_).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"}),V&&typeof window<"u"&&ee("Data may be outdated. Please refresh if issues persist.",{icon:"⚠️",duration:5e3}),{...b,data:_}}}if(D&&!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"}),F.request(e.config);V&&typeof window<"u"&&ee("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 y=new ze(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(y)}}if(e.data&&typeof e.data=="object"&&!("success"in e.data)){const h=Me(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(Oe.isCancel(e)){const w=e.config?._requestId;return e.config?._enableLogging&&g.debug(`[API Request Cancelled] ${e.config?.method?.toUpperCase()||"GET"} ${e.config?.url}`,{request_id:w}),Promise.reject(e)}const t=e.config;let r=t?._requestId;if(e.response?.headers){const w=e.response.headers["x-request-id"]||e.response.headers["X-Request-ID"];w&&(r=w,Yt({request_id:r}));const S=e.response.headers["x-ratelimit-limit"]||e.response.headers["X-RateLimit-Limit"],C=e.response.headers["x-ratelimit-remaining"]||e.response.headers["X-RateLimit-Remaining"],R=e.response.headers["x-ratelimit-reset"]||e.response.headers["X-RateLimit-Reset"],M=e.response.headers["retry-after"]||e.response.headers["Retry-After"];(S||C||R||M)&&_t.getState().updateRateLimit({limit:S,remaining:C,reset:R,retryAfter:M})}const a=t?._enableLogging;if(a&&e.response){const S=e.response.headers?.["content-type"]?.toLowerCase?.().includes("text/html")||typeof e.response.data=="string"&&e.response.data.trim().toLowerCase().startsWith("<!doctype")?"[HTML response omitted - wrong server on port 8080?]":ve(e.response.data),C=ve(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:C,data:S,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 w=e.response?.data,S=(typeof w?.error=="string"?w.error:w?.message||"").toLowerCase();if(S.includes("csrf")||S.includes("token")||S.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 R=await Y.ensureToken();return t.headers&&(t.headers["X-CSRF-Token"]=R),g.debug("[API] CSRF token refreshed, retrying request",{request_id:r,url:t?.url}),F.request(t)}catch(R){const M=R instanceof Error?R.message:String(R);M.includes("HTML page instead of JSON")||g.error("[API] CSRF token refresh failed",{request_id:r,url:t?.url,message:M})}}}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}),te.clearTokens(),Y.clearToken(),typeof window<"u"&&(T(async()=>{const{useAuthStore:w}=await Promise.resolve().then(()=>Ee);return{useAuthStore:w}},void 0).then(({useAuthStore:w})=>{w.getState().logoutLocal()}).catch(w=>{g.error("[API] Failed to import auth store for logout",{error:w})}),sessionStorage.setItem("auth_error","Votre session a expiré. Veuillez vous reconnecter."),window.location.href="/login"),Promise.reject(K(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}),te.clearTokens(),Y.clearToken(),typeof window<"u"&&T(async()=>{const{useAuthStore:w}=await Promise.resolve().then(()=>Ee);return{useAuthStore:w}},void 0).then(({useAuthStore:w})=>{w.getState().logoutLocal()}).catch(w=>{g.error("[API] Failed to import auth store for logout",{error:w})}),Promise.reject(K(e));if(e.response?.status===401&&t&&!t._retry&&!o&&!c&&!l){if(Ze)return g.debug("[API] Refresh already in progress, queuing request",{request_id:r,url:t?.url,queue_size:Se.length}),new Promise((w,S)=>{Se.push({resolve:w,reject:S})}).then(()=>(g.debug("[API] Replaying queued request after successful refresh",{request_id:r,url:t?.url}),F(t))).catch(w=>{const S=w,C=S?.response?.status??S?.code,R=t?.url??"";return C!=null&&C>=500&&R.includes("/webhooks")||g.error("[API] Queued request failed after refresh",{request_id:r,url:t?.url,error:w}),Promise.reject(w)});if(t._retry=!0,Ze=!0,g.info("[API] Starting token refresh due to 401",{request_id:r,url:t?.url,method:t?.method}),ge>=bt)return g.error("[API] Max refresh attempts reached, logging out",{request_id:r,attempts:ge,max_attempts:bt}),ge=0,Ze=!1,te.clearTokens(),Y.clearToken(),typeof window<"u"&&(T(async()=>{const{useAuthStore:w}=await Promise.resolve().then(()=>Ee);return{useAuthStore:w}},void 0).then(({useAuthStore:w})=>{w.getState().logoutLocal()}).catch(w=>{g.error("[API] Failed to import auth store for logout",{error:w})}),sessionStorage.setItem("auth_error","Votre session a expiré après plusieurs tentatives. Veuillez vous reconnecter."),window.location.href="/login"),wt(new Error("Max refresh attempts reached")),Promise.reject(K(e));ge++;try{return await Fe(),g.info("[API] Token refresh successful, retrying original request",{request_id:r,url:t?.url,queue_size:Se.length,attempt:ge}),ge=0,wt(null),F(t)}catch(w){return g.error("[API] Token refresh failed",{attempt:ge,max_attempts:bt,request_id:r,error:w,queue_size:Se.length}),wt(w),te.clearTokens(),Y.clearToken(),typeof window<"u"&&(T(async()=>{const{useAuthStore:S}=await Promise.resolve().then(()=>Ee);return{useAuthStore:S}},void 0).then(({useAuthStore:S})=>{S.getState().logoutLocal()}).catch(S=>{g.error("[API] Failed to import auth store for logout",{error:S})}),sessionStorage.setItem("auth_error","Votre session a expiré. Veuillez vous reconnecter."),window.location.href="/login"),Promise.reject(w)}finally{Ze=!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 w=t.method?.toUpperCase();if(["POST","PUT","DELETE","PATCH"].includes(w||"")){t._csrfRetry=!0;try{const C=await Y.refreshToken();return t.headers&&C&&(t.headers["X-CSRF-Token"]=C),F(t)}catch(C){const R=C instanceof Error?C.message:String(C);R.includes("HTML page instead of JSON")||g.error("[API] Failed to refresh CSRF token after CSRF error",{message:R});const M=K(e);return Promise.reject(M)}}}const u=e.response?.status,d=t?._retryCount||0,h=ye.maxRetries;if(u===429){const w=K(e),S=e.response?.headers["retry-after"]||e.response?.headers["Retry-After"],C=S?parseInt(S,10):60;return g.warn("[API] Rate limit exceeded, not retrying",{url:t?.url,retry_after:C,request_id:w.request_id}),w.message&&ee.error(w.message,{duration:C*1e3}),Promise.reject(w)}const p=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:K(e).request_id});const w=K(e);return w.httpStatus=u,Promise.reject(w)}if(sn(e,ye)&&t&&d<p){const w=t.method?.toUpperCase(),S=Ct(w);if(!S&&u&&u!==500&&u!==502&&u!==503&&u!==504){const G=K(e);return Promise.reject(G)}t._retryCount=d+1;const C=an(e,d,ye.baseDelay,ye.maxDelay),R=K(e),M=u?`HTTP ${u}`:e.code||"Network Error";return d===0&&(R.request_id?g.warn(`[API Retry] ${M} error, retrying (1/${p}) - Request ID: ${R.request_id}`,{status:u||"N/A",error_code:e.code||"N/A",retry_count:1,max_retries:p,delay_ms:Math.round(C),request_id:R.request_id,url:t?.url,method:t?.method,is_idempotent:S}):g.warn(`[API Retry] ${M} error, retrying (1/${p})`,{status:u||"N/A",error_code:e.code||"N/A",retry_count:1,max_retries:p,delay_ms:Math.round(C),url:t?.url,method:t?.method,is_idempotent:S})),en(C).then(()=>F(t))}if(d>=p){const w=K(e),S=u?`HTTP ${u}`:e.code||"Network Error";return w.request_id?g.error(`[API Error] ${S} error after ${h} retries - Request ID: ${w.request_id}`,{code:w.code,message:w.message,request_id:w.request_id,timestamp:w.timestamp,url:t?.url,method:t?.method}):g.error(`[API Error] ${S} error after ${h} retries`,{code:w.code,message:w.message,timestamp:w.timestamp,url:t?.url,method:t?.method}),Promise.reject(w)}const j=K(e);u===401&&!o&&!c&&!l&&typeof window<"u"&&ft(j)==="authentication"&&(te.clearTokens(),Y.clearToken(),T(async()=>{const{useAuthStore:S}=await Promise.resolve().then(()=>Ee);return{useAuthStore:S}},void 0).then(({useAuthStore:S})=>{S.getState().logoutLocal()}).catch(S=>{g.error("[API] Failed to import auth store for logout",{error:S})}),sessionStorage.setItem("auth_error","Votre session a expiré. Veuillez vous reconnecter."),window.location.href="/login");const N=j.message?.includes("HTML page instead of JSON")??!1,D=t?.url??"",V=u&&u>=500&&D.includes("/webhooks"),b=!t?._disableToast&&u!==401&&u!==404&&!Oe.isCancel(e)&&!N&&!V,_=!e.response;if(_){const{recordNetworkError:w}=await T(async()=>{const{recordNetworkError:S}=await Promise.resolve().then(()=>xn);return{recordNetworkError:S}},void 0);w(j)}const H=_?"network-error-toast":void 0;if(b&&typeof window<"u"){const w=t?.url||"";let S;w.includes("/auth/")?S="auth":w.includes("/tracks")||w.includes("/track/")?S="track":w.includes("/playlists")||w.includes("/playlist/")?S="playlist":w.includes("/upload")?S="upload":w.includes("/conversations")||w.includes("/chat")?S="conversation":w.includes("/search")&&(S="search");const R=Lr(j,S,u===422);if(!e.response&&t&&fe.shouldQueueRequest(t)&&(typeof navigator<"u"&&!navigator.onLine||!e.response&&e.request)){const be=t.method?.toUpperCase(),Ae=be==="DELETE"?"low":be==="POST"?"high":"normal";try{await fe.queueRequest(t,{priority:Ae}),ee.success("Requête mise en file d'attente. Elle sera envoyée à la reconnexion.",{duration:4e3,id:"offline-queue-toast"})}catch(we){g.error("[API] Failed to queue request for offline replay",{error:we})}}const M=zr(e),G=rn(e);let le=R;_&&(M?le=`${R} ⚠️ Connexion intermittente détectée. Certaines requêtes réussissent, d'autres échouent. La connexion devrait se rétablir automatiquement.`:G?le=`${R} ❌ Aucune connexion réseau. Vérifiez votre connexion internet et réessayez.`:le=`${R} 💡 Vérifiez votre connexion internet. Si le problème persiste, le serveur pourrait être temporairement indisponible.`),(M||G)&&g.warn("[API] Network failure detected",{request_id:r,is_partial_failure:M,is_complete_failure:G,url:t?.url,method:t?.method,error_code:e.code,error_message:e.message}),ee.error(le,{duration:8e3,id:H})}const oe=e.response?.status,Z=t?.url??"";return oe&&oe>=500&&Z.includes("/webhooks")||g.error(`[API Error] ${j.message}`,{request_id:j.request_id||r,code:j.code,message:j.message,timestamp:j.timestamp,details:j.details,context:j.context,url:t?.url,method:t?.method}),Promise.reject(j)});function on(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 ql=Object.freeze(Object.defineProperty({__proto__:null,API_TIMEOUTS:Or,SLOW_REQUEST_THRESHOLD:Tt,apiClient:F,validationAlerting:Mr,validationMetrics:ot},Symbol.toStringTag,{value:"Module"}));async function Fr(e){try{const t=await F.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&&(te.setTokens(r,a||""),qt()),!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 K(t)}}async function Vr(e){try{const t=await F.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)te.setTokens(r,a||""),e.remember_me?localStorage.setItem("remember_me","true"):localStorage.removeItem("remember_me"),qt();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 K(t)}}async function Ur(){try{await F.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{Ir(),te.clearTokens()}}async function Mt(){try{return(await F.get("/auth/me")).data}catch(e){throw K(e)}}const Dl={login:Vr,register:Fr,logout:Ur,getMe:Mt,refresh:async e=>{const{data:t}=await F.post("/auth/refresh",{refresh_token:e});return t},verifyEmail:async e=>{const{data:t}=await F.post("/auth/verify-email",void 0,{params:{token:e.token}});return t},resendVerification:async e=>{const{data:t}=await F.post("/auth/resend-verification",e);return t},checkUsername:async e=>{const{data:t}=await F.get("/auth/check-username",{params:{username:e.username}});return t},requestPasswordReset:async e=>{const{data:t}=await F.post("/auth/password/reset-request",e);return t},resetPassword:async e=>{const{data:t}=await F.post("/auth/password/reset",e);return t},getOAuthProviders:async()=>{const{data:e}=await F.get("/auth/oauth/providers");return e},initiateOAuth:e=>{window.location.href=`${mt.API_URL}/auth/oauth/${e}`},setup2FA:async()=>{const{data:e}=await F.post("/auth/2fa/setup");return e},verify2FA:async e=>{const{data:t}=await F.post("/auth/2fa/verify",{code:e});return t},disable2FA:async e=>{const{data:t}=await F.post("/auth/2fa/disable",{code:e});return t},get2FAStatus:async()=>{const{data:e}=await F.get("/auth/2fa/status");return e}};function ln(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 $r(e,t={}){return(r,a,n)=>{const i=t.channelName||"default-store",o=t.enabled!==!1,c=t.shouldSync||(()=>!0),l=t.onStateSync;let m=null,u=!1,d=null,h=0;const y=new Set,p=[];if(o&&(m=ln(i),m)){const E=()=>{if(p.length===0||u)return;p.sort((N,D)=>D.timestamp-N.timestamp);const j=p.shift();j&&j.timestamp>h&&(u=!0,r(j.state),d=j.state,h=j.timestamp,y.size>100&&Array.from(y).slice(0,50).forEach(D=>y.delete(D)),setTimeout(()=>{u=!1,E()},50))};m.onmessage=j=>{const N=j.data;if(!N||typeof N!="object"||!N.type||!N.storeName||typeof N.timestamp!="number"||N.type!=="state-update"&&N.type!=="state-request"&&N.type!=="state-response"||N.storeName!==i)return;const D=N.messageId||`${N.type}-${N.timestamp}-${Math.random()}`;if(!y.has(D)){if(N.type==="state-update"&&N.state){if(u){p.push({state:N.state,timestamp:N.timestamp,messageId:D}),E();return}if(N.timestamp<=h){y.add(D);return}if(c(N.state,d)){y.add(D),u=!0;const V=d;r(N.state);const b=N.state;if(d=b,h=N.timestamp,l)try{l(b,V)}catch(_){g.warn("[BroadcastSync] Error in onStateSync callback",{error:_ instanceof Error?_.message:String(_),stack:_ instanceof Error?_.stack:void 0,storeName:i})}setTimeout(()=>{u=!1,E()},50)}else y.add(D)}else if(N.type==="state-request"){const V=a(),b=JSON.parse(JSON.stringify(V));m&&m.postMessage({type:"state-response",storeName:i,state:b,timestamp:Date.now()})}else if(N.type==="state-response"&&N.state)if(!d||N.timestamp>h){y.add(D),u=!0;const V=d;r(N.state);const b=N.state;if(d=b,h=N.timestamp,l)try{l(b,V)}catch(_){g.warn("[BroadcastSync] Error in onStateSync callback",{error:_ instanceof Error?_.message:String(_),stack:_ instanceof Error?_.stack:void 0,storeName:i})}setTimeout(()=>{u=!1,E()},50)}else y.add(D)}},m.postMessage({type:"state-request",storeName:i,timestamp:Date.now()})}return e((...E)=>{if(u)r(...E);else if(r(...E),m&&o){const j=a();if(c(j,d)){const N=Date.now(),D=`update-${N}-${Math.random()}`,V=JSON.parse(JSON.stringify(j));if(m.postMessage({type:"state-update",storeName:i,state:V,timestamp:N,messageId:D}),l)try{l(j,d)}catch(b){g.warn("[BroadcastSync] Error in onStateSync callback",{error:b instanceof Error?b.message:String(b),stack:b instanceof Error?b.stack:void 0,storeName:i})}d=j,h=N}}},a,n)}}const J=Ve()(Ue($r(e=>({isAuthenticated:!1,isLoading:!1,error:null,login:async t=>{e({isLoading:!0,error:null});try{const r=await Vr(t);return e({isAuthenticated:!0,isLoading:!1,error:null}),Y.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:K(r),isLoading:!1,isAuthenticated:!1}),r}},register:async t=>{e({isLoading:!0,error:null});try{const a=!!(await Fr(t)).token?.access_token;e({isAuthenticated:a,isLoading:!1,error:null}),a&&Y.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:K(r),isLoading:!1,isAuthenticated:!1}),r}},logout:async()=>{e({isLoading:!0});try{await Ur()}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}),Y.clearToken()}},logoutLocal:()=>{g.info("[Auth] Performing local logout (no API call)",{}),te.clearTokens(),T(async()=>{const{cleanupProactiveRefresh:t}=await Promise.resolve().then(()=>Sa);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)})}),Y.clearToken(),e({isAuthenticated:!1,isLoading:!1,error:null})},refreshUser:async()=>{const r=J.getState().isAuthenticated;e({isLoading:!0});try{await Mt(),e({isAuthenticated:!0,isLoading:!1,error:null}),Y.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=K(a),i=typeof n.code=="number"?n.code:0;i===401||i===1001||i===1002?(te.clearTokens(),e({error:n,isLoading:!1,isAuthenticated:!1})):e({error:n,isLoading:!1,isAuthenticated:!!r})}},checkAuthStatus:async()=>{{J.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})})),Ee=Object.freeze(Object.defineProperty({__proto__:null,useAuthStore:J},Symbol.toStringTag,{value:"Module"}));function Qr(){return!1}const de=Ve()(gr(Ue($r(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:Qr()}));function v(...e){return ys(vs(e))}const cn=yr("inline-flex items-center justify-center whitespace-nowrap rounded-full text-sm font-sans font-medium tracking-tight transition-[color,box-shadow,border-color,background-color] duration-[var(--sumi-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 focus-visible:shadow-[var(--sumi-shadow-glow)] disabled:pointer-events-none disabled:opacity-50 gap-2",{variants:{variant:{default:"bg-primary text-primary-foreground hover:bg-primary/90 border border-transparent font-semibold",primary:"bg-primary text-primary-foreground hover:bg-primary/90 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/30 text-foreground hover:bg-muted/50 border border-border hover:border-border",ghost:"text-muted-foreground hover:text-foreground hover:bg-muted/50",link:"text-primary underline-offset-4 hover:underline"},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"}}),I=f.forwardRef(({className:e,variant:t,size:r,asChild:a=!1,icon:n,loading:i=!1,children:o,disabled:c,...l},m)=>{const u=a?xs:"button",d=c||i;return s.jsx(u,{className:v(cn({variant:t,size:r,className:e}),i&&"opacity-70"),ref:m,disabled:d,...l,children:a?o:s.jsxs(s.Fragment,{children:[i&&s.jsx(Ce,{className:"mr-2 h-4 w-4 animate-spin"}),!i&&n&&s.jsx("span",{className:"flex items-center justify-center pointer-events-none",children:n}),o]})})});I.displayName="Button";let un=class extends fr.Component{constructor(t){super(t),this.state={hasError:!1,error:null}}static getDerivedStateFromError(t){return{hasError:!0,error:t}}handleReset=()=>{this.setState({hasError:!1,error:null}),this.props.onReset?.()};render(){return this.state.hasError?this.props.fallback?this.props.fallback:s.jsxs("div",{className:"flex flex-col items-center justify-center min-h-layout-page p-6 text-center animate-fade-in",children:[s.jsxs("div",{className:"relative mb-6",children:[s.jsx("div",{className:"absolute inset-0 bg-destructive/20 rounded-full blur-2xl animate-pulse"}),s.jsx("div",{className:"relative bg-destructive/10 rounded-full p-6",children:s.jsx(Qe,{className:"h-12 w-12 text-destructive"})})]}),s.jsx("h2",{className:"text-heading-2 mb-2",children:"Something went wrong"}),s.jsx("p",{className:"text-muted-foreground max-w-md mb-6",children:"An unexpected error occurred. This has been logged and we'll look into it."}),this.state.error&&s.jsxs("details",{className:"mb-6 w-full max-w-md text-left",children:[s.jsx("summary",{className:"text-caption cursor-pointer hover:text-foreground transition-colors",children:"Technical details"}),s.jsx("pre",{className:"mt-2 p-3 rounded-lg bg-muted text-xs text-muted-foreground overflow-auto max-h-32",children:this.state.error.message})]}),s.jsxs("div",{className:"flex gap-3",children:[s.jsxs(I,{onClick:this.handleReset,className:"gap-2",children:[s.jsx(xr,{className:"h-4 w-4"})," Try again"]}),s.jsxs(I,{variant:"outline",onClick:()=>window.location.href="/",className:"gap-2",children:[s.jsx(br,{className:"h-4 w-4"})," Go home"]})]})]}):this.props.children}};const dn=yr("flex flex-col rounded-lg text-card-foreground transition-[box-shadow,background-color,border-color] duration-[var(--sumi-duration-normal)] ease-out relative overflow-hidden",{variants:{variant:{default:"bg-card border border-border shadow-card hover:shadow-card-hover",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",interactive:"bg-card border border-transparent shadow-card cursor-pointer hover:shadow-card-hover hover:border-primary/20 focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring focus-visible:ring-offset-2",spotlight:"bg-card/80 border border-border hover:border-border",surface:"bg-card border border-border shadow-none hover:bg-card/90 hover:border-border hover:shadow-card-hover transition-all duration-[var(--sumi-duration-slow)] ease-in-out"},padding:{none:"",sm:"p-4",default:"p-6",lg:"p-8"}},defaultVariants:{variant:"default",padding:"none"}});function Ot({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}),[m,u]=f.useState(0),d=k=>{if(!o.current||t!=="spotlight"&&!a)return;const j=o.current.getBoundingClientRect();l({x:k.clientX-j.left,y:k.clientY-j.top})},h=()=>{u(1)},y=()=>{u(0)},p=t==="spotlight"||a;return s.jsxs("div",{ref:o,onMouseMove:d,onMouseEnter:h,onMouseLeave:y,"data-slot":"card",className:v(dn({variant:t,padding:r}),e),...i,children:[p&&s.jsx("div",{className:"pointer-events-none absolute -inset-px opacity-0 transition duration-[var(--sumi-duration-normal)]",style:{opacity:m,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 Ol({className:e,...t}){return s.jsx("div",{"data-slot":"card-header",className:v("flex flex-col gap-1.5 p-6 pb-0",e),...t})}function zl({className:e,...t}){return s.jsx("h3",{"data-slot":"card-title",className:v("text-lg font-semibold leading-tight tracking-tight text-foreground",e),...t})}function Fl({className:e,...t}){return s.jsx("p",{"data-slot":"card-description",className:v("text-sm text-muted-foreground/90",e),...t})}function Br({className:e,...t}){return s.jsx("div",{"data-slot":"card-content",className:v("p-6 pt-4",e),...t})}function Vl({className:e,...t}){return s.jsx("div",{"data-slot":"card-footer",className:v("flex items-center gap-3 p-6 pt-0",e),...t})}const mn={success:Ns,error:_e,warning:Qe,info:ut},sr={success:"border-success/30 bg-success/10 text-success",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"},ar=5e3;function fn({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 m=e.duration??ar;let u=null;return m>0&&(u=setTimeout(()=>{o()},m)),()=>{u&&clearTimeout(u)}},[e.duration,e.id,o]);const c=e.type?mn[e.type]:ut,l=e.type?sr[e.type]:sr.info;return s.jsxs(Ot,{variant:"glass",className:v("relative flex min-w-80 max-w-sm items-start gap-4 p-4 shadow-modal transition-all duration-[var(--sumi-duration-normal)] 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.jsxs("div",{className:"flex-1 min-w-0",children:[s.jsx("p",{className:"text-sm font-medium leading-relaxed font-sans",children:e.message}),e.action&&s.jsx("button",{onClick:()=>{e.action?.onClick(),o()},className:"mt-1.5 text-xs font-semibold underline underline-offset-2 hover:no-underline transition-colors",children:e.action.label})]}),s.jsx("button",{onClick:o,className:"flex-shrink-0 rounded-md p-1 opacity-60 transition-opacity duration-[var(--duration-fast)] hover:opacity-100 hover:bg-muted/50 focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-primary/50 focus-visible:ring-offset-2 focus-visible:ring-offset-background","aria-label":"Close",children:s.jsx(pe,{className:"h-4 w-4"})}),s.jsx("div",{className:v("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||ar)-300}ms`}})]})}const Hr=f.createContext(void 0);function Kr(){const e=f.useContext(Hr);if(!e)throw new Error("useToastContext must be used within ToastProvider");return e}function Ul(){const e=Kr();return{...e,addToast:(r,a)=>{typeof r=="string"?e.addToast({message:r,type:a||"info"}):e.addToast(r)}}}const hn={"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 pn({children:e,position:t="top-right",className:r}){const[a,n]=f.useState([]),i=f.useCallback(l=>{const m=`toast-${Date.now()}-${Math.random().toString(36).substr(2,9)}`,u={...l,id:m};n(d=>[...d,u])},[]),o=f.useCallback(l=>{n(m=>m.filter(u=>u.id!==l))},[]),c={toasts:a,addToast:i,removeToast:o};return s.jsxs(Hr.Provider,{value:c,children:[e,s.jsx("div",{className:v("fixed z-50 flex flex-col gap-2",hn[t],r),children:a.map(l=>s.jsx(fn,{toast:l,onDismiss:o},l.id))})]})}function Wr(){const e=f.useRef(null),{theme:t}=de();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,m=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 p=0;p<c;p++)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})},y=()=>{a.clearRect(0,0,r.width,r.height),o.forEach((p,k)=>{p.x+=p.speedX,p.y+=p.speedY,p.x<0&&(p.x=r.width),p.x>r.width&&(p.x=0),p.y<0&&(p.y=r.height),p.y>r.height&&(p.y=0),a.beginPath(),a.arc(p.x,p.y,p.size,0,Math.PI*2),a.fillStyle=`rgba(${m}, ${p.opacity})`,a.fill();for(let E=k+1;E<o.length;E++){const j=o[E],N=p.x-j.x,D=p.y-j.y,V=Math.sqrt(N*N+D*D);if(V<l){a.beginPath();const b=n?.05:.1;a.strokeStyle=`rgba(${u}, ${b*(1-V/l)})`,a.lineWidth=.5,a.moveTo(p.x,p.y),a.lineTo(j.x,j.y),a.stroke()}}}),i=requestAnimationFrame(y)};return window.addEventListener("resize",d),d(),h(),y(),()=>{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 gn(){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 zt=null,lt=null;const yn=3e4;function vn(e){const t=ft(e);(t==="network"||t==="timeout")&&(zt=e instanceof Error||e&&typeof e=="object"&&"message"in e?e:new Error(String(e)),lt=Date.now())}function Gr(){zt=null,lt=null}function Yr(){return!zt||!lt?!1:Date.now()-lt>yn?(Gr(),!1):!0}const xn=Object.freeze(Object.defineProperty({__proto__:null,clearNetworkError:Gr,hasRecentNetworkError:Yr,recordNetworkError:vn},Symbol.toStringTag,{value:"Module"}));function Xr({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=m=>{if(m.key==="Escape"){r?.();return}m.key==="Tab"&&(m.shiftKey?document.activeElement===o&&(m.preventDefault(),c?.focus()):document.activeElement===c&&(m.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 bn={sm:"max-w-sm",md:"max-w-md",lg:"max-w-2xl",xl:"max-w-4xl",full:"max-w-full m-4 h-layout-modal-full"};function wn({open:e,onClose:t,children:r,title:a,closeOnOverlayClick:n=!0,closeOnEscape:i=!0,size:o="md",className:c,footer:l}){const m=f.useRef(null),u=f.useId();f.useEffect(()=>{if(e)return document.body.style.overflow="hidden",()=>{document.body.style.overflow=""}},[e]),f.useEffect(()=>{if(!i||!e)return;const h=y=>{y.key==="Escape"&&t()};return document.addEventListener("keydown",h),()=>document.removeEventListener("keydown",h)},[e,i,t]);const d=h=>{n&&h.target===h.currentTarget&&t()};return hr.createPortal(s.jsx(At,{children:e&&s.jsxs(je.div,{className:"fixed inset-0 z-[400] flex items-center justify-center p-4",onClick:d,exit:{opacity:0},transition:{duration:.2},children:[s.jsx(je.div,{className:"absolute inset-0 bg-black/60 backdrop-blur-sm",initial:{opacity:0},animate:{opacity:1},exit:{opacity:0},transition:{duration:.2}}),s.jsx(Xr,{children:s.jsxs(je.div,{ref:m,role:"dialog","aria-modal":"true","aria-labelledby":a?u:void 0,initial:{opacity:0,scale:.95},animate:{opacity:1,scale:1},exit:{opacity:0,scale:.95},transition:{duration:.2,ease:[.33,1,.68,1]},className:v("relative w-full bg-popover border border-border rounded-xl shadow-2xl flex flex-col overflow-hidden",bn[o],c),onClick:h=>h.stopPropagation(),children:[a&&s.jsxs("div",{className:"p-4 border-b border-border bg-card flex justify-between items-center shrink-0",children:[s.jsx("h3",{id:u,className:"font-bold text-foreground text-lg font-heading",children:a}),s.jsx(I,{variant:"ghost",size:"icon",onClick:t,className:"ml-auto","aria-label":"Fermer",children:s.jsx(pe,{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-border bg-card shrink-0 flex justify-end gap-4",children:l})]})})]},"modal")}),document.body)}const kn={alert:_e,confirm:_e,info:ut,default:void 0},En={alert:"text-destructive",confirm:"text-primary",info:"text-muted-foreground",default:""};function Jr({open:e,onClose:t,onOpenChange:r,title:a,children:n,footer:i,variant:o="default",onConfirm:c,onCancel:l,confirmLabel:m="Confirm",cancelLabel:u="Cancel",showCancel:d=!0,size:h="md"}){const y=()=>{r?r(!1):t&&t()},p=async()=>{c&&await c(),y()},k=()=>{l&&l(),y()},E=kn[o],j=En[o];return s.jsxs(wn,{open:e,onClose:y,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(I,{variant:"outline",onClick:k,children:u}),c&&s.jsx(I,{variant:o==="alert"?"destructive":"default",onClick:p,children:m})]}):void 0,children:[a&&E&&s.jsx("div",{className:"flex items-center gap-4 mb-4",children:s.jsx(E,{className:v("h-5 w-5",j)})}),n]})}const Sn=f.forwardRef(({variant:e="rectangular",width:t,height:r,className:a,...n},i)=>{const o="relative overflow-hidden bg-muted/50",c={text:"rounded h-4 w-full",circular:"rounded-full",rectangular:"rounded-lg"},l={width:t,height:r};return s.jsx("div",{ref:i,className:v(o,c[e],a),style:l,"aria-hidden":"true",...n,children:s.jsx("div",{className:"absolute inset-0 skeleton-shimmer"})})});Sn.displayName="Skeleton";function jn(e){return new Date(e).toLocaleString()}function Nn(e){const t=e.config.method?.toUpperCase()||"UNKNOWN",r=e.config.url||"Unknown URL";return`${t} ${r}`}function _n(e){switch(e){case"high":return"bg-destructive/20 text-destructive border-destructive/30";case"normal":return"bg-muted/20 text-muted-foreground border-border/30";case"low":return"bg-muted/30 text-muted-foreground border-border/50";default:return"bg-muted/30 text-muted-foreground border-border/50"}}function nr({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(fe.getQueue())};u();const d=setInterval(u,1e3);return()=>clearInterval(d)},[e]);const l=async u=>{i(u);try{await fe.removeRequest(u),a(fe.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)}},m=async()=>{c(!0);try{await fe.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(Jr,{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-card/50 rounded-lg border border-border",children:[s.jsxs("div",{className:"flex items-center gap-2",children:[s.jsx(qe,{className:"w-5 h-5 text-muted-foreground"}),s.jsx("span",{className:"text-sm text-muted-foreground",children:r.length===0?"No queued requests":`${r.length} ${r.length===1?"request":"requests"} queued`})]}),r.length>0&&s.jsxs(I,{variant:"destructive",size:"sm",onClick:m,disabled:o,children:[s.jsx(_s,{className:"w-4 h-4 mr-2"}),"Clear All"]})]}),r.length===0?s.jsxs("div",{className:"text-center py-8 text-muted-foreground",children:[s.jsx(Ts,{className:"w-12 h-12 mx-auto mb-4 text-primary/50"}),s.jsx("p",{className:"text-sm",children:"All requests have been processed"})]}):s.jsx("div",{className:"space-y-2 max-h-layout-list overflow-y-auto custom-scrollbar",children:r.map(u=>s.jsx("div",{className:"p-4 bg-card/30 rounded-lg border border-border hover:border-border/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-foreground truncate",children:Nn(u)})}),s.jsxs("div",{className:"flex items-center gap-4 flex-wrap text-xs text-muted-foreground",children:[s.jsx("span",{className:v("px-2 py-0.5 rounded border",_n(u.priority)),children:u.priority}),s.jsxs("span",{className:"flex items-center gap-1",children:[s.jsx(qe,{className:"w-3 h-3"}),jn(u.timestamp)]}),u.retryCount>0&&s.jsxs("span",{className:"flex items-center gap-1 text-destructive",children:[s.jsx(_e,{className:"w-3 h-3"}),u.retryCount," retry",u.retryCount>1?"ies":""]})]})]}),s.jsx(I,{variant:"ghost",size:"icon",onClick:()=>l(u.id),disabled:n===u.id,className:"shrink-0",children:n===u.id?s.jsx(qe,{className:"w-4 h-4 animate-spin"}):s.jsx(pe,{className:"w-4 h-4"})})]})},u.id))}),r.length>0&&s.jsx("div",{className:"p-4 bg-muted/10 border border-border/20 rounded-lg text-xs text-muted-foreground",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 Tn(){const e=gn(),[t,r]=f.useState(0),[a,n]=f.useState(!1),[i,o]=f.useState(!1),[c,l]=f.useState(!1),[m,u]=f.useState(!1);return f.useEffect(()=>{const d=()=>{const y=fe.getQueueSize();r(y)};d();const h=setInterval(d,1e3);return()=>clearInterval(h)},[]),f.useEffect(()=>{if(e&&t>0){n(!0);const d=setInterval(()=>{fe.getQueueSize()===0&&(n(!1),clearInterval(d))},500);return()=>clearInterval(d)}else{n(!1);return}},[e,t]),f.useEffect(()=>{const d=()=>{o(Yr())};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-destructive/90 backdrop-blur-sm text-foreground px-4 py-2.5 text-sm z-50 flex items-center justify-center gap-2 shadow-lg border-b border-destructive",children:[s.jsx(Cs,{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(Qt,{className:"w-3.5 h-3.5"}),"View Queue"]})]}),s.jsx(nr,{open:c,onClose:()=>l(!1)})]}):a&&t>0&&m?s.jsxs(s.Fragment,{children:[s.jsxs("div",{className:"fixed top-0 left-0 right-0 bg-primary/90 backdrop-blur-sm text-foreground px-4 py-2.5 text-sm z-50 flex items-center justify-center gap-2 shadow-lg border-b border-border",children:[s.jsx(Ce,{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 fe.clearQueue(),r(0)},className:"ml-2 px-2 py-1 bg-destructive/20 hover:bg-destructive/30 rounded border border-destructive/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-background/20 hover:bg-background/30 rounded border border-border/30 transition-colors flex items-center gap-1.5 text-xs font-medium",title:"View queued requests",children:[s.jsx(Qt,{className:"w-3.5 h-3.5"}),"View Queue"]})]})]}),s.jsx(nr,{open:c,onClose:()=>l(!1)})]}):null}function Cn(e,t){const r=K(e),a=ft(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:** ${Pn(n)}`),l.push(`**Platform:** ${In(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 m=l.join(`
|
|
`);return{title:c,body:m,metadata:{requestId:r.request_id,errorCode:r.code,statusCode:r.status,category:a,timestamp:o,userAgent:n,url:i}}}async function Zr(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 Rn(e,t){const r=An();if(!r){Zr(e);return}const a=new URLSearchParams({title:e.title,body:e.body}),n=`${r}/issues/new?${a.toString()}`;window.open(n,"_blank")}function An(){return null}function Pn(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 In(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 Ln(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=K(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 es=f.forwardRef(({error:e,onRetry:t,onDismiss:r,showDetails:a,context:n,variant:i="inline",severity:o="error",size:c="md",className:l,dismissible:m,title:u,icon:d,actions:h=[],...y},p)=>{const[k,E]=f.useState(!1),[j,N]=f.useState(!1),[D,V]=f.useState(!0),b=f.useMemo(()=>Ln(e),[e]),_=f.useMemo(()=>K(e),[e]),H=f.useMemo(()=>ft(_),[_]),oe=f.useMemo(()=>H==="server_error"||b.status!==void 0&&b.status>=500,[H,e]),W=a??!1,w=f.useMemo(()=>{if(b.message)try{return Lr(b,n?.resource,!1)}catch{return b.message}return"An unexpected error occurred"},[b,n]),S=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]),C=f.useMemo(()=>{if(d)return d;const U=c==="sm"?"w-4 h-4":c==="lg"?"w-6 h-6":"w-5 h-5";switch(o){case"error":return s.jsx(_e,{className:v(U,"text-destructive")});case"warning":return s.jsx(Qe,{className:v(U,"text-warning")});case"info":return s.jsx(ut,{className:v(U,"text-info")});default:return s.jsx(_e,{className:v(U,"text-destructive")})}},[d,o,c]),R=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]),M=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]),G=f.useCallback(async()=>{if(!(!t||j)){N(!0);try{await t()}finally{N(!1)}}},[t,j]),le=f.useCallback(()=>{r&&r(),i==="modal"&&V(!1)},[r,i]),Ge=f.useCallback(async()=>{try{const U=Cn(e,{component:n?.resource,action:n?.action,userId:n?.userId,additionalInfo:n});try{Rn(U),ee.success("Opening GitHub issue...")}catch{await Zr(U),ee.success("Issue report copied to clipboard")}}catch{ee.error("Failed to generate issue report")}},[e,n]),be=f.useCallback(async()=>{if(_.request_id)try{await navigator.clipboard.writeText(_.request_id),ee.success("Request ID copied to clipboard")}catch{ee.error("Failed to copy request ID")}},[_.request_id]),Ae=m??(r!==void 0||i==="modal"),we=()=>{if(!W||!k)return null;const U=[];return _.request_id&&U.push({label:"Request ID",value:_.request_id}),b.code&&U.push({label:"Error Code",value:String(b.code)}),b.status&&U.push({label:"HTTP Status",value:String(b.status)}),b.details&&U.push({label:"Details",value:JSON.stringify(b.details,null,2)}),b.stack&&U.push({label:"Stack Trace",value:b.stack}),n&&U.push({label:"Context",value:JSON.stringify(n,null,2)}),U.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:U.map((ce,gt)=>s.jsxs("div",{className:"text-xs",children:[s.jsxs("span",{className:"font-semibold opacity-70",children:[ce.label,":"]}),s.jsx("pre",{className:"mt-1 p-2 bg-black/20 rounded text-xs overflow-x-auto",children:typeof ce.value=="string"?ce.value:JSON.stringify(ce.value,null,2)})]},gt))})})},Pe=s.jsxs("div",{ref:p,role:"alert","aria-live":"polite",className:v("rounded-lg border flex shadow-card",R.bg,R.border,R.text,M.padding,M.gap,l),...y,children:[s.jsx("div",{className:"flex-shrink-0 pt-0.5",children:C}),s.jsxs("div",{className:"flex-1 min-w-0",children:[s.jsx("div",{className:v("font-semibold mb-1",M.title),children:S}),s.jsx("div",{className:v("opacity-90",M.text),children:w}),we(),(t||h.length>0||oe||W&&(b.code||b.details||b.stack||n))&&s.jsxs("div",{className:"mt-4 flex flex-wrap gap-2 items-center",children:[t&&s.jsx(I,{variant:"outline",size:c==="sm"?"sm":"default",onClick:G,disabled:j,className:"border-current text-current hover:bg-current/10 bg-transparent",children:j?"Retrying...":"Retry"}),oe&&_.request_id&&s.jsxs(s.Fragment,{children:[s.jsxs(I,{variant:"outline",size:c==="sm"?"sm":"default",onClick:be,className:"border-current text-current hover:bg-current/10 bg-transparent",title:"Copy Request ID",children:[s.jsx(Rs,{className:"w-4 h-4 mr-1.5"}),"Copy ID"]}),s.jsxs(I,{variant:"outline",size:c==="sm"?"sm":"default",onClick:Ge,className:"border-current text-current hover:bg-current/10 bg-transparent",children:[s.jsx(As,{className:"w-4 h-4 mr-1.5"}),"Report"]})]}),h.map((U,ce)=>s.jsx(I,{variant:U.variant||"outline",size:c==="sm"?"sm":"default",onClick:U.onClick,className:"border-current text-current hover:bg-current/10 bg-transparent",children:U.label},ce)),W&&(b.code||b.details||b.stack||n)&&s.jsx(I,{variant:"ghost",size:c==="sm"?"sm":"default",onClick:()=>E(!k),className:"text-current hover:bg-current/10 hover:text-current",children:k?s.jsxs(s.Fragment,{children:[s.jsx(Ps,{className:"w-4 h-4 mr-1"}),"Hide Details"]}):s.jsxs(s.Fragment,{children:[s.jsx(wr,{className:"w-4 h-4 mr-1"}),"Show Details"]})})]})]}),Ae&&s.jsx("button",{onClick:le,className:"opacity-70 hover:opacity-100 transition-opacity flex-shrink-0 self-start","aria-label":"Dismiss error",children:s.jsx(pe,{className:v(c==="sm"?"w-4 h-4":"w-5 h-5")})})]});switch(i){case"banner":return s.jsx("div",{className:"w-full",children:Pe});case"card":return s.jsx(Ot,{className:v(R.border,l,"glass"),children:s.jsx(Br,{className:v(M.padding,"pt-6"),children:Pe})});case"modal":return s.jsx(Jr,{open:D,onClose:le,title:S,variant:o==="error"?"alert":"default",footer:s.jsxs("div",{className:"flex gap-2 justify-end",children:[t&&s.jsx(I,{variant:"outline",onClick:G,disabled:j,children:j?"Retrying...":"Retry"}),h.map((U,ce)=>s.jsx(I,{variant:U.variant||"outline",onClick:U.onClick,children:U.label},ce)),s.jsx(I,{variant:"default",onClick:le,children:t?"Close":"Dismiss"})]}),children:s.jsxs("div",{className:v(R.text),children:[s.jsx("div",{className:v("opacity-90 mb-4",M.text),children:w}),we()]})});default:return Pe}});es.displayName="ErrorDisplay";class Te 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=va(),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"&&bs(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(es,{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}}function ts(){const{isAuthenticated:e}=J();return pr({queryKey:["user","me"],queryFn:Mt,enabled:e,retry:!1,staleTime:300*1e3,gcTime:600*1e3})}const rs=()=>{const{isAuthenticated:e,logout:t}=J(),{data:r}=ts();return{user:r??null,accessToken:null,refreshToken:null,isAuthenticated:e,logout:async()=>{await t()}}};function qn({children:e}){const{isAuthenticated:t}=rs(),[r,a]=f.useState(!0),n=!1,{isLoading:i}=J();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(at,{to:"/login",replace:!0})}function Dn(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 ss({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-[var(--sumi-duration-normal)]",children:s.jsxs("div",{className:"bg-card/50 border border-border/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-destructive/10 rounded-full flex items-center justify-center mx-auto mb-6",children:s.jsx(Qe,{className:"h-8 w-8 text-destructive"})}),s.jsxs("h2",{className:"text-xl font-bold mb-2",children:["Failed to load ",e]}),s.jsx("p",{className:"text-muted-foreground mb-6 text-sm",children:Dn(t)}),s.jsxs("div",{className:"flex flex-col gap-3",children:[r&&s.jsxs(I,{onClick:r,variant:"outline",className:"w-full flex items-center justify-center gap-2",children:[s.jsx(xr,{className:"h-4 w-4"}),"Try Again"]}),s.jsx(I,{onClick:()=>window.location.reload(),variant:"default",className:"w-full flex items-center justify-center gap-2",children:"Refresh Page"})]})]})})}class Mn 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(ss,{pageName:this.props.pageName,error:this.state.error,onRetry:this.handleRetry}):this.props.children}}function On({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:v("flex flex-col items-center justify-center min-h-48",t),children:[s.jsx("div",{className:v("animate-spin rounded-full border-2 border-muted border-t-primary",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-muted-foreground dark:text-muted-foreground",children:r})]})}function zn(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(ss,{pageName:t,error:r instanceof Error?r:new Error(a)})})})}function q(e,t,r){const a=r?()=>zn(e,r):e,n=f.lazy(a);return function(o){const{fallback:c,...l}=o,m=s.jsx(f.Suspense,{fallback:s.jsx(On,{}),children:s.jsx(n,{...l})});return r?s.jsx(Mn,{pageName:r,children:m}):m}}const Fn=q(()=>T(()=>import("./DashboardPage-YCMhF3W0.js"),__vite__mapDeps([3,1,0,2,4,5,6,7,8,9])),void 0,"Dashboard"),Vn=q(()=>T(()=>import("./ChatPage-B8BAcAdb.js"),__vite__mapDeps([10,1,0,2,5,11,8,12,13,6,14,15,16,4,9])).then(e=>({default:e.ChatPage})),void 0,"Chat"),Un=q(()=>T(()=>import("./LibraryPage-Bs71TQk9.js"),__vite__mapDeps([17,1,0,2,18,5,19,20,14,13,8,21,22,11,9,4])).then(e=>({default:e.LibraryPage})),void 0,"Library"),$n=q(()=>T(()=>import("./UserProfilePage-CSNlfZ_c.js"),__vite__mapDeps([23,1,0,2,5,24,19,20,25,26,4,8,27,9,16,7,28])).then(e=>({default:e.UserProfilePage})),void 0,"Profile"),Qn=q(()=>T(()=>import("./SettingsPage-CSqfJRlB.js"),__vite__mapDeps([29,1,0,2,24,28,11,8,12,13,30,22,26,9,4,5])).then(e=>({default:e.SettingsPage})),void 0,"Settings"),Bn=q(()=>T(()=>import("./LoginPage-BbWKY4E4.js"),__vite__mapDeps([31,1,0,2,4,32,8,33,5,30,9])),void 0,"Login"),Hn=q(()=>T(()=>import("./RegisterPage-DbPAqniK.js"),__vite__mapDeps([34,1,0,2,33,4,5,30,8,32,35,9])),void 0,"Register"),Kn=q(()=>T(()=>import("./ForgotPasswordPage-KvMFzvc3.js"),__vite__mapDeps([36,1,0,2,4,33,32,8,37,5,9])),void 0,"Forgot Password"),Wn=q(()=>T(()=>import("./VerifyEmailPage-DuS24L5f.js"),__vite__mapDeps([38,1,0,2,4,33,5,9,8])),void 0,"Verify Email"),Gn=q(()=>T(()=>import("./ResetPasswordPage-9TFWnCyB.js"),__vite__mapDeps([39,1,0,2,4,33,32,8,35,37,5,9])),void 0,"Reset Password"),Yn=q(()=>T(()=>import("./SessionsPage-DNibxB7b.js"),__vite__mapDeps([40,1,0,2,15,8,4,5,9])),void 0,"Sessions"),Xn=q(()=>T(()=>import("./NotFoundPage-sz5r5MGU.js"),__vite__mapDeps([41,1,0,2,4,8,5,9])),void 0,"Not Found"),Jn=q(()=>T(()=>import("./ServerErrorPage-jZz_mSIW.js"),__vite__mapDeps([42,1,0,2,4,8,5,9])),void 0,"Server Error"),Zn=q(()=>T(()=>import("./UserProfilePage-CSNlfZ_c.js"),__vite__mapDeps([23,1,0,2,5,24,19,20,25,26,4,8,27,9,16,7,28])).then(e=>({default:e.UserProfilePage})),void 0,"User Profile"),ei=q(()=>T(()=>import("./RolesPage-Do-nT-Bu.js"),__vite__mapDeps([43,1,0,2,26,11,8,44,12,13,4,5,9])).then(e=>({default:e.RolesPage})),void 0,"Roles"),ti=q(()=>T(()=>import("./TrackDetailPage-YaPhIZ5N.js"),__vite__mapDeps([45,1,0,2,5,20,14,13,8,28,16,11,46,15,9,19,47,22,4])).then(e=>({default:e.TrackDetailPage})),void 0,"Track Detail"),ri=q(()=>T(()=>import("./routes-D8al6ym8.js"),__vite__mapDeps([48,1,0,2,18,5,25,26,4,8,46,49,9,11,44,30,12,13,16,15,28,50,51])).then(e=>({default:e.PlaylistRoutes})),void 0,"Playlists"),si=q(()=>T(()=>import("./AdminDashboardView-BA3kSUMs.js"),__vite__mapDeps([52,1,0,2,8,7,28,4,5,9])).then(e=>({default:e.AdminDashboardView})),void 0,"Admin Dashboard"),ai=q(()=>T(()=>import("./AnalyticsView-CXNlCI9N.js"),__vite__mapDeps([53,1,0,2,8,54,7,4,5,9])).then(e=>({default:e.AnalyticsView})),void 0,"Analytics"),ni=q(()=>T(()=>import("./WebhooksView-zD80nU1x.js"),__vite__mapDeps([55,1,0,2,11,8,56,4,5,9])).then(e=>({default:e.WebhooksView})),void 0,"Webhooks"),ii=q(()=>T(()=>import("./DesignSystemDemo-CSO7r1b-.js"),__vite__mapDeps([57,1,0,2])).then(e=>({default:e.DesignSystemDemo})),void 0,"Design System Demo"),oi=q(()=>T(()=>import("./SocialView-D4x7N4R4.js"),__vite__mapDeps([58,1,0,2,20,8,16,4,5,9])).then(e=>({default:e.SocialView})),void 0,"Social");q(()=>T(()=>import("./GearView-TKbTgc2Z.js"),__vite__mapDeps([59,1,0,2,8,11,4,5,9])).then(e=>({default:e.GearView})),void 0,"Gear");q(()=>T(()=>import("./LiveView-kUoUJm2D.js"),__vite__mapDeps([60,1,0,2,8,4,5,9])).then(e=>({default:e.LiveView})),void 0,"Live");q(()=>T(()=>import("./EducationView-CybxtgC5.js"),__vite__mapDeps([61,1,0,2,21,8,11,4,5,9])).then(e=>({default:e.EducationView})),void 0,"Education");q(()=>T(()=>import("./QueueView-CgH4FdTb.js"),__vite__mapDeps([62,1,0,2,11,8,4,5,9])).then(e=>({default:e.QueueView})),void 0,"Queue");q(()=>T(()=>import("./DeveloperDashboardView-Ixv7KfYn.js"),__vite__mapDeps([63,1,0,2,54,7,8,11,47,56,28,4,5,9])).then(e=>({default:e.DeveloperDashboardView})),void 0,"Developer");const li=q(()=>T(()=>import("./NotificationsView-DUoPDuge.js"),__vite__mapDeps([64,1,0,2,8,27,4,5,9])).then(e=>({default:e.NotificationsView})),void 0,"Notifications"),ci=q(()=>T(()=>import("./MarketplaceHome-CSnDyays.js"),__vite__mapDeps([65,1,0,2,66,8,11,67,49,4,5,9])).then(e=>({default:e.MarketplaceHome})),void 0,"Marketplace"),ui=q(()=>T(()=>import("./SearchPage-BYMUfiz0.js"),__vite__mapDeps([68,1,0,2,4,50,8,28,16,9,5])).then(e=>({default:e.SearchPage})),void 0,"Search"),di=q(()=>T(()=>import("./SellerDashboardView-BmLj6E51.js"),__vite__mapDeps([69,1,0,2,8,66,70,4,5,9])).then(e=>({default:e.SellerDashboardView})),void 0,"Seller Dashboard"),mi=q(()=>T(()=>import("./WishlistView-I41eG0yr.js"),__vite__mapDeps([71,1,0,2,67,8,4,5,9])).then(e=>({default:e.WishlistView})),void 0,"Wishlist"),fi=q(()=>T(()=>import("./PurchasesView-DipY77Ae.js"),__vite__mapDeps([72,1,0,2,8,70,11,4,5,9])).then(e=>({default:e.PurchasesView})),void 0,"Purchases");function Ie({feature:e}){return s.jsxs("div",{className:"flex min-h-[60vh] flex-col items-center justify-center gap-4 text-center",children:[s.jsx("h1",{className:"text-3xl font-bold tracking-tight",children:e}),s.jsx("p",{className:"max-w-md text-lg text-muted-foreground",children:"This feature is currently under development and will be available soon."})]})}function hi({children:e}){const{isAuthenticated:t}=rs(),r=!1,{isLoading:a}=J();return a?null:t||r?s.jsx(at,{to:"/dashboard",replace:!0}):s.jsx(s.Fragment,{children:e})}function pi(){const{i18n:e,t}=ws(),{language:r,setLanguage:a}=de(),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 gi({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 yi(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 F.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 ze?new Error(t.response?.data?.error||t.message||"Failed to fetch notifications"):t}}async function vi(e){try{await F.post(`/notifications/${e}/read`)}catch(t){throw t instanceof ze?new Error(t.response?.data?.error||t.message||"Failed to mark notification as read"):t}}async function xi(){try{await F.post("/notifications/read-all")}catch(e){throw e instanceof ze?new Error(e.response?.data?.error||e.message||"Failed to mark all notifications as read"):e}}function bi(){const{addToast:e}=Kr();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 wi=3e4,ki=50;function Ei(e){const[t,r]=f.useState(!1),a=f.useRef(null),n=ct(),i=Rt(),{success:o,error:c}=bi(),l=pr({queryKey:["notifications","menu"],queryFn:()=>yi({limit:ki}),refetchInterval:wi,staleTime:1e4,enabled:e?.notificationsOverride===void 0&&e?.isLoadingOverride===void 0&&e?.errorOverride===void 0}),m=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=m.filter(b=>!b.read).length,y=l.refetch,p=["notifications","menu"],k=$t({mutationFn:vi,onMutate:async b=>{await i.cancelQueries({queryKey:p});const _=i.getQueryData(p);return _&&i.setQueryData(p,{..._,notifications:_.notifications.map(H=>H.id===b?{...H,read:!0}:H),unreadCount:Math.max((_.unreadCount??1)-1,0)}),{previous:_}},onError:(b,_,H)=>{H?.previous&&i.setQueryData(p,H.previous),c("Erreur lors du marquage")},onSuccess:()=>{i.invalidateQueries({queryKey:p})}}),E=$t({mutationFn:xi,onMutate:async()=>{await i.cancelQueries({queryKey:p});const b=i.getQueryData(p);return b&&i.setQueryData(p,{...b,notifications:b.notifications.map(_=>({..._,read:!0})),unreadCount:0}),{previous:b}},onError:(b,_,H)=>{H?.previous&&i.setQueryData(p,H.previous),c("Erreur lors du marquage")},onSuccess:()=>{i.invalidateQueries({queryKey:p}),o("Toutes les notifications ont été marquées comme lues")}});f.useEffect(()=>{function b(_){a.current&&!a.current.contains(_.target)&&r(!1)}return t&&document.addEventListener("mousedown",b),()=>document.removeEventListener("mousedown",b)},[t]),f.useEffect(()=>{t&&y()},[t,y]);const j=f.useCallback(b=>k.mutate(b),[k]),N=f.useCallback(()=>E.mutate(),[E]),D=f.useCallback(b=>{b.read||j(b.id),b.link&&(n(b.link),r(!1))},[j,n]),V=f.useCallback(()=>{n("/notifications"),r(!1)},[n]);return{menuRef:a,isOpen:t,setIsOpen:r,notifications:m,isLoading:u,error:d,unreadCount:h,handleMarkAsRead:j,handleMarkAllAsRead:N,handleNotificationClick:D,handleViewAll:V,markAsReadMutation:k,markAllAsReadMutation:E}}function Si({isOpen:e,unreadCount:t,onClick:r}){return s.jsxs(I,{variant:"ghost",size:"icon",className:"relative",onClick:r,"aria-label":"Notifications","aria-expanded":e,"aria-haspopup":"true",children:[s.jsx(kr,{className:"h-5 w-5"}),t>0&&s.jsx(s.Fragment,{children:s.jsxs("span",{className:"absolute -top-1 -right-1 flex h-5 w-5",children:[s.jsx("span",{className:"animate-ping absolute inline-flex h-full w-full rounded-full bg-destructive opacity-75"}),s.jsx("span",{className:"relative inline-flex h-5 w-5 bg-destructive rounded-full text-xs text-destructive-foreground items-center justify-center font-semibold","aria-label":`${t} notifications non lues`,children:t>9?"9+":t})]})})]})}function ji({notification:e,onMarkAsRead:t,onClick:r,isMarking:a}){return s.jsx("div",{role:"button",tabIndex:0,className:v("p-4 hover:bg-accent transition-colors cursor-pointer","focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring focus-visible:ring-offset-2 focus-visible:ring-offset-background",!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:v("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:Ss(new Date(e.created_at),{addSuffix:!0,locale:js})})]}),s.jsx("div",{className:"flex items-center space-x-1 ml-2 shrink-0",children:!e.read&&s.jsx(I,{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(Ce,{className:"h-3 w-3 animate-spin"}):s.jsx(Is,{className:"h-3 w-3"})})})]})})}function Ni({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(Ce,{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(kr,{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,c)=>s.jsx("div",{className:"animate-stagger-in",style:{animationDelay:`${Math.min(c*50,500)}ms`},children:s.jsx(ji,{notification:o,onMarkAsRead:a,onClick:n,isMarking:i})},o.id))})}function _i({unreadCount:e,notifications:t,isLoading:r,onMarkAllAsRead:a,onMarkAsRead:n,onNotificationClick:i,onViewAll:o,markAllPending:c,markPending:l,error:m}){return s.jsxs(je.div,{initial:{opacity:0,y:-8,scale:.96},animate:{opacity:1,y:0,scale:1},exit:{opacity:0,y:-8,scale:.96},transition:{duration:.15,ease:"easeOut"},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(I,{variant:"ghost",size:"sm",onClick:a,className:"h-7 text-xs",disabled:c,children:[c?s.jsx(Ce,{className:"h-3 w-3 mr-1 animate-spin"}):s.jsx(Ls,{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(Ni,{isLoading:r,error:m??null,notifications:t,onMarkAsRead:n,onNotificationClick:i,isMarkingAsRead:l})}),t.length>0&&s.jsx("div",{className:"p-4 border-t shrink-0",children:s.jsx(I,{variant:"ghost",size:"sm",className:"w-full",onClick:o,children:"Voir toutes les notifications"})})]})}function Ti({isLoadingOverride:e,errorOverride:t,notificationsOverride:r}={}){const{menuRef:a,isOpen:n,setIsOpen:i,notifications:o,isLoading:c,error:l,unreadCount:m,handleMarkAsRead:u,handleMarkAllAsRead:d,handleNotificationClick:h,handleViewAll:y,markAsReadMutation:p,markAllAsReadMutation:k}=Ei({isLoadingOverride:e,errorOverride:t,notificationsOverride:r??void 0});return s.jsxs("div",{className:"relative",ref:a,children:[s.jsx(Si,{isOpen:n,unreadCount:m,onClick:()=>i(!n)}),s.jsx(At,{children:n&&s.jsx(_i,{unreadCount:m,notifications:o,isLoading:c,error:l,onMarkAllAsRead:d,onMarkAsRead:u,onNotificationClick:h,onViewAll:y,markAllPending:k.isPending,markPending:p.isPending})})]})}function Ci(){const{limit:e,remaining:t,reset:r,isLimited:a}=_t(),[n,i]=f.useState(null);f.useEffect(()=>{if(!r){i(null);return}const u=()=>{const h=Math.floor(Date.now()/1e3),y=r-h;i(y>0?y: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 y=Math.floor(d/60),p=d%60;return p>0?`${y}h ${p}m`:`${y}h`},m=a||t!==null&&t<=0;return s.jsxs("div",{className:v("flex items-center gap-2 px-4 py-1.5 rounded-lg text-xs font-medium transition-all",m?"bg-destructive/10 text-destructive border border-destructive/30":"bg-warning/10 text-warning border border-warning/30"),role:"alert","aria-live":"polite",children:[s.jsx(Qe,{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(qe,{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(qe,{className:"w-3 h-3"}),"resets in ",l(n)]})]})})]})}function Ri(e,t,r,a){const[n,i]=f.useState(!1),[o,c]=f.useState(!1),[l,m]=f.useState(e),[u,d]=f.useState({}),h=f.useRef(null),y=f.useRef(null),p=f.useRef(null),k=f.useRef(null),E=f.useCallback(()=>{if(!p.current||!k.current||!n)return;const b=p.current.getBoundingClientRect(),_=k.current.getBoundingClientRect(),H=window.innerWidth,oe=window.innerHeight,Z=8;let W=e,w=0,S=0;switch(e){case"top":b.top-_.height-Z<0&&(W="bottom");break;case"bottom":b.bottom+_.height+Z>oe&&(W="top");break;case"left":b.left-_.width-Z<0&&(W="right");break;case"right":b.right+_.width+Z>H&&(W="left");break}if(W==="top"||W==="bottom"){const C=b.left+b.width/2,R=_.width/2,M=Z,G=H-Z;C-R<M?w=M-(C-R):C+R>G&&(w=G-(C+R))}else{const C=b.top+b.height/2,R=_.height/2,M=Z,G=oe-Z;C-R<M?S=M-(C-R):C+R>G&&(S=G-(C+R))}m(W),d({...w!==0&&{transform:`translate(calc(-50% + ${w}px), 0)`},...S!==0&&{transform:`translate(0, calc(-50% + ${S}px))`}})},[e,n]);f.useEffect(()=>{n&&E()},[n,E]),f.useEffect(()=>{o&&n&&E()},[o,n,E]);const j=f.useCallback(()=>{h.current&&clearTimeout(h.current),h.current=setTimeout(()=>{i(!0),c(!0)},r)},[r]),N=f.useCallback(()=>{h.current&&clearTimeout(h.current),y.current&&clearTimeout(y.current),y.current=setTimeout(()=>{i(!1)},100)},[]),D=f.useCallback(()=>{t==="click"&&i(b=>{const _=!b;return _&&c(!0),_})},[t]),V=t==="hover"?{onMouseEnter:j,onMouseLeave:N}:t==="click"?{onClick:D}:{onFocus:j,onBlur:N};return f.useEffect(()=>()=>{h.current&&clearTimeout(h.current),y.current&&clearTimeout(y.current)},[]),{visible:n,isMounted:o,calculatedPosition:l,tooltipStyle:u,wrapperRef:p,tooltipRef:k,triggerProps:a?{}:V}}const Ai={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"},Pi={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 Ii({content:e,visible:t,calculatedPosition:r,tooltipStyle:a,tooltipRef:n,showArrow:i,maxWidth:o,className:c}){return s.jsxs("div",{ref:n,className:v("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(--sumi-duration-normal)]",Ai[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:v("absolute w-0 h-0 border-4",Pi[r])})]})}function ue({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:m,isMounted:u,calculatedPosition:d,tooltipStyle:h,wrapperRef:y,tooltipRef:p,triggerProps:k}=Ri(r,a,n,c);if(c)return s.jsx(s.Fragment,{children:t});const E=a==="hover",j=E?k:{},N=!E&&f.isValidElement(t)&&f.Children.only(t)?f.cloneElement(t,k):t;return s.jsxs("div",{ref:y,className:"relative inline-block",...j,children:[N,u&&s.jsx(Ii,{content:e,visible:m,calculatedPosition:d,tooltipStyle:h,tooltipRef:p,showArrow:i,maxWidth:o,className:l})]})}function Li(e){const[t,r]=f.useState(!1),{logout:a}=J(),{data:n}=ts(),{theme:i,setTheme:o,sidebarOpen:c,setSidebarOpen:l}=de(),{t:m}=pi(),u=ct(),d=async()=>{await a(),u("/login")},h=()=>{o(i==="light"?"dark":i==="dark"?"system":"light")},y=()=>{switch(i){case"light":return s.jsx(Vs,{className:"h-4 w-4"});case"dark":return s.jsx(Fs,{className:"h-4 w-4"});default:return s.jsx(zs,{className:"h-4 w-4"})}};return s.jsx("header",{className:"fixed top-0 left-0 right-0 h-header z-[200] pointer-events-none",children:s.jsxs("div",{className:v("absolute top-0 right-0 h-header bg-[var(--sumi-glass-bg)] backdrop-blur-[12px] border-b border-[var(--sumi-border-faint)] flex items-center justify-between px-4 md:px-6 pointer-events-auto transition-all duration-[var(--sumi-duration-fast)]",c?"left-header-expanded":"left-header-collapsed","max-lg:left-0"),children:[s.jsx("button",{onClick:()=>l(!c),className:"lg:hidden p-2 rounded-lg hover:bg-muted/50 text-muted-foreground hover:text-foreground mr-2 transition-colors duration-[var(--duration-fast)]",children:s.jsx(qs,{className:"w-5 h-5"})}),s.jsx("div",{className:"flex-1 max-w-md relative hidden md:block group",children:s.jsxs("div",{role:"search",className:"relative flex items-center group/search rounded-full focus-within:ring-2 focus-within:ring-primary/50 transition-all duration-[var(--duration-fast)]",children:[s.jsx(Ds,{className:"absolute left-3 w-4 h-4 text-muted-foreground pointer-events-none"}),s.jsx("input",{type:"search",placeholder:"What do you want to play?","aria-label":"Rechercher des pistes, artistes, playlists",className:"w-full h-10 pl-10 pr-4 bg-muted/30 border-0 rounded-full text-sm text-foreground placeholder:text-muted-foreground focus:outline-none focus:ring-0 focus-visible:ring-2 focus-visible:ring-primary/50 focus-visible:ring-inset transition-all duration-[var(--duration-fast)]",onKeyDown:p=>{if(p.key==="Enter"){p.preventDefault();const k=(p.currentTarget.value||"").trim();u(k?`/search?q=${encodeURIComponent(k)}`:"/search")}}}),s.jsxs("kbd",{className:"absolute right-3 hidden sm:inline-flex items-center gap-0.5 px-2 py-0.5 rounded bg-muted/50 text-xs font-medium text-muted-foreground",children:[s.jsx(Ms,{className:"w-3 h-3"}),"K"]})]})}),s.jsxs("div",{className:"flex items-center gap-1 ml-2",children:[s.jsxs("div",{className:"hidden xl:flex items-center gap-2 mr-2 px-2.5 py-1 rounded-full bg-muted/30 text-muted-foreground",children:[s.jsx("span",{className:"w-1.5 h-1.5 rounded-full bg-primary shrink-0"}),s.jsx("span",{className:"text-xs",children:"Online"})]}),s.jsx(Ti,{}),s.jsx(Ci,{}),s.jsx("div",{className:"h-6 w-px bg-border mx-1","aria-hidden":!0}),s.jsx(ue,{content:m("common.changeTheme"),children:s.jsx(I,{variant:"ghost",size:"icon",onClick:h,className:"min-h-10 min-w-10 rounded-full hover:bg-muted/50 text-muted-foreground hover:text-foreground transition-colors duration-[var(--duration-fast)]",children:y()})}),s.jsxs("div",{className:"relative",children:[s.jsxs("button",{onClick:()=>r(!t),className:"flex items-center gap-2 pl-0.5 pr-2 py-0.5 rounded-full hover:bg-muted/50 transition-colors duration-[var(--duration-fast)] focus:outline-none focus:ring-2 focus:ring-ring group",children:[s.jsx("div",{className:"w-8 h-8 rounded-full bg-primary/20 flex items-center justify-center shrink-0 group-hover:ring-2 group-hover:ring-primary/50 group-hover:scale-105 transition-all",children:s.jsx("span",{className:"text-xs font-semibold text-primary",children:n?.username?.substring(0,2).toUpperCase()||"VZ"})}),s.jsx("span",{className:"hidden lg:block text-sm font-medium text-foreground truncate max-w-24",children:n?.username})]}),t&&s.jsx(Xr,{active:t,onEscape:()=>r(!1),children:s.jsxs("div",{className:"absolute right-0 top-full mt-2 w-56 bg-card backdrop-blur-xl border border-border rounded-xl shadow-xl p-2 z-50 animate-scaleIn origin-top-right",children:[s.jsxs("div",{className:"px-3 py-2.5 border-b border-border mb-1",children:[s.jsx("p",{className:"text-sm font-semibold text-foreground truncate",children:n?.username}),s.jsx("p",{className:"text-xs text-muted-foreground truncate",children:n?.email}),!n?.is_verified&&s.jsx("div",{className:"mt-2 flex justify-center",children:s.jsx(gi,{verified:!1})})]}),s.jsxs("div",{className:"p-1 space-y-0.5",children:[s.jsxs(nt,{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 duration-[var(--duration-fast)]",children:[s.jsx(Os,{className:"w-4 h-4"})," Profil"]}),s.jsxs(nt,{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 duration-[var(--duration-fast)]",children:[s.jsx(Er,{className:"w-4 h-4"})," Paramètres"]})]}),s.jsx("div",{className:"h-px bg-border my-1","aria-hidden":!0}),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 duration-[var(--duration-fast)]",children:[s.jsx(Sr,{className:"w-4 h-4"})," Déconnexion"]})})]})})]})]})]})})}const qi=1024;function Di(){const e=ct(),{logout:t}=J(),{setSidebarOpen:r}=de(),a=f.useCallback(()=>{typeof window<"u"&&window.innerWidth<qi&&r(!1)},[r]),n=f.useCallback(()=>{t(),e("/login")},[t,e]);return{handleMobileNav:a,handleLogout:n}}const Mi=[{section:"My Studio",items:[{id:"dashboard",label:"Command Center",icon:s.jsx(br,{className:"w-4 h-4"})},{id:"studio",label:"Cloud Files",icon:s.jsx(Bs,{className:"w-4 h-4"})},{id:"tracks",label:"Projects",icon:s.jsx(Hs,{className:"w-4 h-4"})},{id:"gear",label:"Gear Locker",icon:s.jsx(Ks,{className:"w-4 h-4"})},{id:"analytics",label:"Performance",icon:s.jsx(Ws,{className:"w-4 h-4"})}]},{section:"Veza Network",items:[{id:"social",label:"Community Feed",icon:s.jsx(Gs,{className:"w-4 h-4"})},{id:"marketplace",label:"Marketplace",icon:s.jsx(Ys,{className:"w-4 h-4"})},{id:"live",label:"Live Sessions",icon:s.jsx(Xs,{className:"w-4 h-4"}),badge:3},{id:"chat",label:"Channels",icon:s.jsx(Js,{className:"w-4 h-4"}),badge:12},{id:"education",label:"Academy",icon:s.jsx(Zs,{className:"w-4 h-4"})}]},{section:"Commerce",items:[{id:"sell",label:"Seller Dashboard",icon:s.jsx(ea,{className:"w-4 h-4"})},{id:"wishlist",label:"Wishlist",icon:s.jsx(It,{className:"w-4 h-4"})},{id:"purchases",label:"Purchases",icon:s.jsx(ta,{className:"w-4 h-4"})}]},{section:"Library",items:[{id:"playlists",label:"Playlists",icon:s.jsx(Lt,{className:"w-4 h-4"})},{id:"queue",label:"Play Queue",icon:s.jsx(ra,{className:"w-4 h-4"})}]},{section:"System",items:[{id:"developer",label:"Developer API",icon:s.jsx(sa,{className:"w-4 h-4"})},{id:"admin",label:"Admin Panel",icon:s.jsx(aa,{className:"w-4 h-4"})}]}],kt={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"},ir=v("w-full flex items-center px-3 py-2 rounded-lg text-sm font-medium transition-all duration-[var(--duration-fast)] group relative","focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-primary/50 focus-visible:ring-offset-2 focus-visible:ring-offset-background"),or="text-muted-foreground hover:text-foreground hover:bg-sidebar-accent active:bg-sidebar-accent/80",lr="bg-primary/10 text-primary sidebar-active-indicator",Oi=({currentView:e})=>{const t=ms(),{sidebarOpen:r,setSidebarOpen:a}=de(),{handleMobileNav:n,handleLogout:i}=Di(),o=e||Object.keys(kt).find(c=>kt[c]===t.pathname)||"dashboard";return s.jsxs(s.Fragment,{children:[r&&s.jsx("div",{className:"fixed inset-0 bg-background/80 backdrop-blur-sm lg:hidden z-sidebar-overlay",onClick:()=>a(!1),"aria-hidden":"true",role:"presentation"}),s.jsxs("aside",{"data-testid":"app-sidebar",className:v("fixed left-sidebar bottom-sidebar top-sidebar rounded-xl flex flex-col transition-shell z-sidebar overflow-hidden","bg-[var(--sumi-bg-raised)] backdrop-blur-md border-r border-[var(--sumi-border-faint)]",r?"w-sidebar-expanded translate-x-0 opacity-100":"-translate-x-full lg:translate-x-0 lg:opacity-100 lg:w-sidebar-collapsed"),"aria-label":"Main sidebar",children:[s.jsxs("div",{className:"px-4 py-4 flex items-center gap-3 relative",children:[s.jsx("div",{className:"w-8 h-8 rounded-lg bg-sidebar-accent flex items-center justify-center flex-shrink-0",children:s.jsx(Us,{className:"w-4 h-4 text-muted-foreground"})}),s.jsxs("div",{className:v("transition-shell overflow-hidden min-w-0",r?"opacity-100":"w-0 opacity-0"),children:[s.jsx("h2",{className:"text-sm font-semibold text-foreground truncate",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 shrink-0 animate-pulse","aria-hidden":"true"}),s.jsx("span",{className:"text-xs text-muted-foreground truncate",children:"Online"})]})]}),s.jsx(I,{variant:"ghost",size:"icon",onClick:()=>a(!r),className:v("ml-auto text-muted-foreground hover:text-foreground hidden lg:flex hover:bg-sidebar-accent",!r&&"absolute left-1/2 -translate-x-1/2 top-1/2 -translate-y-1/2"),"aria-label":r?"Collapse sidebar":"Expand sidebar",children:r?s.jsx($s,{className:"w-4 h-4"}):s.jsx(Qs,{className:"w-4 h-4"})})]}),s.jsx("nav",{className:"flex-1 overflow-y-auto custom-scrollbar px-3 py-2",role:"navigation","aria-label":"Main navigation",children:Mi.map((c,l)=>s.jsxs("div",{children:[l>0&&s.jsx("div",{className:v("h-px bg-border/50 mx-3 my-1.5 transition-opacity duration-[var(--sumi-duration-normal)]",!r&&"mx-1"),"aria-hidden":"true"}),s.jsx("h3",{className:v("text-xs font-medium text-muted-foreground mb-2 px-3 transition-all duration-[var(--sumi-duration-normal)] uppercase tracking-wider",!r&&"opacity-0 h-0 overflow-hidden mb-0 px-0"),id:`sidebar-section-${c.section.replace(/\s+/g,"-").toLowerCase()}`,children:c.section}),s.jsx("ul",{className:"space-y-0.5 list-none m-0 p-0","aria-labelledby":`sidebar-section-${c.section.replace(/\s+/g,"-").toLowerCase()}`,children:c.items.map(m=>{const u=kt[m.id]||"/dashboard",d=o===m.id;return s.jsx("li",{className:"list-none m-0 p-0",children:s.jsx(ue,{content:m.label,position:"right",disabled:r,children:s.jsxs(nt,{to:u,onClick:n,"aria-current":d?"page":void 0,className:v(ir,d?lr:or,!r&&"justify-center px-0"),children:[s.jsxs("div",{className:v("flex items-center gap-3 relative z-10 min-w-0",!r&&"justify-center"),children:[s.jsx("span",{className:v("shrink-0 transition-all duration-[var(--duration-fast)]","group-hover:scale-110",d?"text-primary":"text-muted-foreground group-hover:text-foreground"),children:m.icon}),s.jsx("span",{className:v("transition-all duration-[var(--sumi-duration-normal)] whitespace-nowrap truncate",r?"opacity-100":"w-0 opacity-0 overflow-hidden"),children:m.label})]}),m.badge!=null&&r&&s.jsx("span",{className:"ml-auto flex h-5 min-w-5 items-center justify-center rounded-full bg-primary/15 text-primary text-xs font-semibold tabular-nums shrink-0",children:m.badge}),m.badge!=null&&!r&&s.jsxs("span",{className:"absolute top-1.5 right-1.5 flex h-2 w-2","aria-hidden":"true",children:[s.jsx("span",{className:"animate-ping absolute inline-flex h-full w-full rounded-full bg-primary opacity-75"}),s.jsx("span",{className:"relative inline-flex rounded-full h-2 w-2 bg-primary"})]})]})})},m.id)})})]},c.section))}),s.jsxs("div",{className:"p-2 border-t border-[var(--sumi-border-faint)] space-y-0.5",children:[s.jsx(ue,{content:"Settings",position:"right",disabled:r,children:s.jsxs(nt,{to:"/settings",onClick:n,"aria-current":o==="settings"?"page":void 0,className:v(ir,o==="settings"?lr:or,!r&&"justify-center px-0"),children:[s.jsx(Er,{className:v("w-4 h-4 shrink-0 transition-all duration-[var(--duration-fast)]","group-hover:scale-110",o==="settings"?"text-primary":"text-muted-foreground group-hover:text-foreground")}),s.jsx("span",{className:v("truncate transition-all duration-[var(--sumi-duration-normal)]",r?"opacity-100":"w-0 opacity-0 overflow-hidden"),children:"Settings"})]})}),s.jsx(ue,{content:"Sign Out",position:"right",disabled:r,children:s.jsxs(I,{variant:"ghost",onClick:i,className:v("w-full text-muted-foreground hover:text-destructive hover:bg-destructive/10 gap-3 justify-start rounded-lg group","focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-primary/50 focus-visible:ring-offset-2 focus-visible:ring-offset-background",!r&&"justify-center px-0"),"aria-label":"Sign out",children:[s.jsx(Sr,{className:"w-4 h-4 shrink-0 transition-transform duration-[var(--duration-fast)] group-hover:scale-110"}),s.jsx("span",{className:v("whitespace-nowrap transition-all duration-[var(--sumi-duration-normal)]",r?"opacity-100":"w-0 opacity-0 overflow-hidden"),children:"Sign Out"})]})})]})]})]})},Ft=Ve()(Ue((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 cr(e){if(isNaN(e)||!isFinite(e)||e<0)return"0:00";const t=Math.floor(e/60),r=Math.floor(e%60);return`${t}:${r.toString().padStart(2,"0")}`}function zi(e){return e?!!(e.id&&e.title&&e.url):!1}class Vt{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)}static isValidMediaUrl(t){if(!t||typeof t!="string"||t.trim()===""||t==="undefined"||t==="null")return!1;try{const r=new URL(t,window.location.origin);return r.protocol==="http:"||r.protocol==="https:"||r.protocol==="blob:"}catch{return!1}}async loadTrack(t){if(!this.audioElement)throw new Error("Audio element not initialized");if(!t){this.audioElement.src="";return}if(!zi(t))throw new Error("Invalid track");if(!Vt.isValidMediaUrl(t.url)){this.audioElement.src="";return}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 z=new Vt;function Fi(e){const t=Ft(),r=f.useRef(null),a=e?.current||r.current;f.useEffect(()=>{if(a)return z.initialize(a),()=>{z.cleanup()}},[a]),f.useEffect(()=>{if(!a)return;const d=t.muted?0:t.volume/100;z.setVolume(d),z.setMuted(t.muted)},[a,t.volume,t.muted]),f.useEffect(()=>{if(!a)return;(async()=>{try{await z.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 z.play():z.pause()}catch(h){g.error("Failed to sync playback:",{error:h}),t.pause()}})()},[a,t.isPlaying,t]),f.useEffect(()=>{if(a)return z.onTimeUpdate(d=>{t.setCurrentTime(d)}),z.onDurationChange(d=>{t.setDuration(d)}),z.onEnded(()=>{t.repeat==="track"?(z.seek(0),z.play().catch(d=>g.error("Failed to reply track:",{error:d}))):t.next()}),z.onError(d=>{const h=d instanceof Error?d.message:String(d);h.includes("fetch")||h.includes("Invalid")||h.includes("MEDIA_ERR")?g.debug("Audio playback error (invalid URL or network):",{error:h}):g.error("Audio playback error:",{error:d}),t.pause()}),z.onPlay(()=>{t.isPlaying||t.resume()}),z.onPause(()=>{t.isPlaying&&t.pause()}),()=>{z.onTimeUpdate(null),z.onDurationChange(null),z.onEnded(null),z.onError(null),z.onPlay(null),z.onPause(null)}},[a,t]);const n=f.useCallback(async d=>{if(t.play(d),d&&a)try{await z.loadTrack(d),await z.play()}catch(h){g.error("Failed to play track:",{error:h}),t.pause()}},[t,a]),i=f.useCallback(()=>{t.pause(),a&&z.pause()},[t,a]),o=f.useCallback(async()=>{if(t.resume(),a)try{await z.play()}catch(d){g.error("Failed to resume playback:",{error:d}),t.pause()}},[t,a]),c=f.useCallback(()=>{t.stop(),a&&z.stop()},[t,a]),l=f.useCallback(d=>{t.seek(d),a&&z.seek(d)},[t,a]),m=f.useCallback(d=>{if(t.setVolume(d),a){const h=t.muted?0:d/100;z.setVolume(h)}},[t,a]),u=f.useCallback(()=>{t.toggleMute(),a&&z.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:m,toggleMute:u,toggleShuffle:t.toggleShuffle,setRepeat:t.setRepeat,addToQueue:t.addToQueue,clearQueue:t.clearQueue}}const Vi=5,Ui=5;function $i(e,t={}){const{enabled:r=!0,seekStep:a=Vi,volumeStep:n=Ui,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 m=Math.max(0,e.currentTime-a);e.seek(m);break}case"ArrowRight":{i&&c.preventDefault();const m=Math.min(e.duration||0,e.currentTime+a);e.seek(m);break}case"ArrowUp":{i&&c.preventDefault();const m=Math.min(100,e.volume+n);e.setVolume(m);break}case"ArrowDown":{i&&c.preventDefault();const m=Math.max(0,e.volume-n);e.setVolume(m);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 et=24,Qi=.7;function Bi(e,t){const[r,a]=f.useState(()=>Array(et).fill(0)),n=f.useRef(null),i=f.useRef(null),o=f.useRef(null),c=f.useRef(null);return f.useEffect(()=>e?((()=>{try{const m=new AudioContext,u=m.createMediaElementSource(e),d=m.createAnalyser();d.fftSize=256,d.smoothingTimeConstant=Qi,d.minDecibels=-60,d.maxDecibels=-10,u.connect(d),d.connect(m.destination),n.current=m,i.current=d,o.current=u}catch{}})(),()=>{c.current&&cancelAnimationFrame(c.current),o.current?.disconnect(),i.current?.disconnect(),n.current?.close(),n.current=null,i.current=null,o.current=null}):void 0,[e]),f.useEffect(()=>{const l=i.current,m=n.current;if(!l||!m||!t){t||a(Array(et).fill(0));return}m.state==="suspended"&&m.resume();const u=new Uint8Array(l.frequencyBinCount),d=()=>{if(!i.current)return;i.current.getByteFrequencyData(u);const h=Math.floor(u.length/et),y=Array.from({length:et},(p,k)=>u[Math.min(k*h,u.length-1)]/255);a(y),c.current=requestAnimationFrame(d)};return c.current=requestAnimationFrame(d),()=>{c.current&&cancelAnimationFrame(c.current)}},[t]),r}const tt="flex items-center justify-center rounded-full flex-shrink-0 transition-all duration-[var(--sumi-duration-normal)] active:scale-95";function Hi({isPlaying:e,onPlayPause:t,onNext:r,onPrevious:a,onShuffle:n,onRepeat:i,shuffle:o,repeat:c,isExpanded:l=!1,compact:m=!1}){const u=m?"w-8 h-8":"w-10 h-10",d=l?"w-16 h-16":m?"w-10 h-10":"w-12 h-12",h=l?"w-6 h-6":m?"w-4 h-4":"w-5 h-5",y=l?"w-8 h-8":m?"w-5 h-5":"w-6 h-6",p=m?"gap-1.5":l?"gap-6":"gap-2 sm:gap-3 md:gap-4";return s.jsxs("div",{className:v("flex items-center justify-center",p),children:[s.jsx(ue,{content:"Shuffle",children:s.jsx("button",{onClick:n,className:v(tt,u,o?"text-primary bg-primary/10 shadow-queue-item-current":"text-muted-foreground hover:text-foreground hover:bg-white/5"),children:s.jsx(jr,{className:v("w-4 h-4",l&&"w-5 h-5")})})}),s.jsx("button",{onClick:a,className:v(tt,u,"text-foreground hover:text-primary hover:bg-white/5"),children:s.jsx(Nr,{className:v(h,"fill-current")})}),s.jsx("button",{onClick:t,className:v("flex items-center justify-center rounded-full bg-primary text-black flex-shrink-0 active:scale-95 transition-all shadow-sm",d),children:e?s.jsx(_r,{className:v(y,"fill-current")}):s.jsx(Tr,{className:v(y,"fill-current ml-0.5")})}),s.jsx("button",{onClick:r,className:v(tt,u,"text-foreground hover:text-primary hover:bg-white/5"),children:s.jsx(Cr,{className:v(h,"fill-current")})}),s.jsx(ue,{content:"Repeat",children:s.jsxs("button",{onClick:i,className:v(tt,u,"relative",c!=="off"?"text-primary bg-primary/10 shadow-queue-item-current":"text-muted-foreground hover:text-foreground hover:bg-white/5"),children:[s.jsx(Rr,{className:v("w-4 h-4",l&&"w-5 h-5")}),c==="track"&&s.jsx("span",{className:"absolute -top-0.5 -right-0.5 text-[8px] font-bold bg-primary text-black px-1 rounded-full",children:"1"})]})})]})}const as=f.forwardRef(({label:e,variant:t="cyan",icon:r,size:a="md",dot:n,count:i,children:o,className:c,onDismiss:l,pulse:m,...u},d)=>{const y={default:"cyan",primary:"cyan",success:"lime",warning:"gold",error:"magenta",secondary:"magenta",terminal:"lime"}[t]||t,p={cyan:"bg-muted/10 text-muted-foreground border-border/30",magenta:"bg-destructive/10 text-destructive border-destructive/30",lime:"bg-success/10 text-success border-success/30",gold:"bg-warning/10 text-warning border-warning/30"},k={sm:"px-2 py-0.5 text-xs",md:"px-2.5 py-0.5 text-xs",lg:"px-4 py-1 text-xs"},E={cyan:"bg-muted-foreground",magenta:"bg-destructive",lime:"bg-success",gold:"bg-warning"},j=e||o,N=y;return n&&!j&&!r&&i===void 0?s.jsx("span",{ref:d,className:v("inline-block h-2 w-2 rounded-full",E[N]||E.cyan,m&&"animate-pulse",c),...u}):s.jsxs("span",{ref:d,className:v("inline-flex items-center gap-1.5 rounded-full font-bold uppercase tracking-widest border",p[N]||p.cyan,k[a],m&&"animate-pulse",c),...u,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}),j,i!==void 0&&i>0&&s.jsx("span",{className:"ml-1 px-1.5 py-0.5 rounded-full bg-current/20 text-xs",children:i}),l&&s.jsx("button",{type:"button",onClick:D=>{D.stopPropagation(),l()},className:"ml-1 -mr-0.5 inline-flex items-center justify-center rounded-full p-0.5 hover:bg-black/10 transition-colors","aria-label":"Remove",children:s.jsx(pe,{className:"h-3 w-3"})})]})});as.displayName="Badge";const ns=f.forwardRef(({className:e,children:t,...r},a)=>s.jsx("div",{ref:a,className:v("relative overflow-auto custom-scrollbar",e),...r,children:t}));ns.displayName="ScrollArea";const Ki=f.forwardRef(({className:e,...t},r)=>s.jsx("div",{ref:r,className:v("flex touch-none select-none transition-colors",e),...t}));Ki.displayName="ScrollBar";function Wi({icon:e,title:t,description:r,action:a,className:n,size:i="md",variant:o="default"}){const c={sm:"py-6",md:"py-12",lg:"py-16"},l={sm:"h-8 w-8",md:"h-12 w-12",lg:"h-16 w-16"},m={sm:"p-3",md:"p-4",lg:"p-5"},u=s.jsxs("div",{className:"flex flex-col items-center animate-empty-state-in",children:[e&&s.jsx("div",{className:"flex justify-center mb-4",children:s.jsx("div",{className:v("bg-muted rounded-full flex items-center justify-center",m[i]),children:s.jsx("div",{className:v("text-muted-foreground",l[i]),children:e})})}),s.jsx("h3",{className:"text-lg font-semibold mb-2 text-foreground font-heading",children:t}),r&&s.jsx("p",{className:"text-sm text-muted-foreground mb-4 max-w-md mx-auto text-center",children:r}),a&&s.jsx(I,{onClick:a.onClick,variant:a.variant||"default",size:i==="sm"?"sm":"default",children:a.label})]});return o==="centered"?s.jsx("div",{className:v("flex flex-1 items-center justify-center text-center",c[i],n),children:u}):o==="card"?s.jsx("div",{className:v("border-2 border-dashed border-border rounded-xl text-center",c[i],n),children:u}):s.jsx(Ot,{className:v(n),children:s.jsx(Br,{className:v("text-center",c[i]),children:u})})}function Gi({isOpen:e,onClose:t,currentTrackId:r,onPlay:a}){const{queue:n,currentIndex:i,removeFromQueue:o,clearQueue:c}=Ft(),{sidebarOpen:l}=de();return e?s.jsxs("div",{className:v("fixed bottom-24 left-4 right-4 z-40 transition-all duration-[var(--sumi-duration-normal)] ease-[var(--sumi-ease-out)] transform",l?"lg:left-main-expanded":"lg:left-main-collapsed","lg:right-4",e?"translate-y-0 opacity-100":"translate-y-10 opacity-0 pointer-events-none"),children:[s.jsxs("div",{className:"max-w-4xl mx-auto bg-black/80 backdrop-blur-2xl border border-white/10 rounded-2xl shadow-2xl overflow-hidden max-h-layout-drawer 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-foreground font-bold font-heading tracking-wide",children:"Play Queue"}),s.jsxs(as,{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-foreground hover:bg-white/10 rounded-md transition-colors duration-[var(--duration-fast)] focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-primary/50 focus-visible:ring-offset-2 focus-visible:ring-offset-background",children:"Clear"}),s.jsx("button",{onClick:t,className:"p-1.5 text-muted-foreground hover:text-foreground hover:bg-white/10 rounded-full transition-colors duration-[var(--duration-fast)] focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-primary/50 focus-visible:ring-offset-2 focus-visible:ring-offset-background",children:s.jsx(pe,{className:"w-5 h-5"})})]})]}),s.jsx("div",{className:"flex-1 overflow-hidden relative",children:n.length===0?s.jsx(Wi,{icon:s.jsx(Lt,{className:"w-full h-full"}),title:"Your queue is empty",description:"Add tracks to keep the vibe going.",size:"sm",className:"border-0 shadow-none bg-transparent"}):s.jsx(ns,{className:"h-full max-h-layout-list",children:s.jsx("div",{className:"p-2 space-y-1",children:n.map((m,u)=>{const d=u===i,h=u<i;return s.jsxs("div",{className:v("group flex items-center gap-3 p-2 rounded-lg transition-all duration-[var(--duration-fast)] border border-transparent",d?"bg-primary/10 border-primary/20 shadow-queue-item-current":"hover:bg-white/5 hover:border-white/5",h&&"opacity-50"),children:[s.jsx("div",{className:"text-white/20 group-hover:text-white/40 cursor-grab px-1",children:s.jsx(na,{className:"w-4 h-4"})}),s.jsx("div",{className:"w-6 text-center text-xs font-mono text-muted-foreground",children:d?s.jsx("div",{className:"w-2 h-2 rounded-full bg-primary mx-auto animate-pulse shadow-queue-item-current"}):u+1}),s.jsxs("div",{className:"flex-1 min-w-0 cursor-pointer",onClick:()=>!d&&a(m),children:[s.jsx("h4",{className:v("text-sm font-medium truncate transition-colors",d?"text-primary":"text-foreground group-hover:text-foreground"),children:m.title}),s.jsx("p",{className:"text-xs text-muted-foreground truncate opacity-70 group-hover:opacity-100",children:m.artist})]}),s.jsx("button",{onClick:y=>{y.stopPropagation(),o(u)},className:"opacity-0 group-hover:opacity-100 p-2 text-muted-foreground hover:text-destructive hover:bg-destructive/10 rounded-full transition-all duration-[var(--duration-fast)] focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-primary/50 focus-visible:ring-offset-2 focus-visible:ring-offset-background",children:s.jsx(pe,{className:"w-3 h-3"})})]},`${m.id}-${u}`)})})})})]}),s.jsx("div",{className:"fixed inset-0 bg-black/20 -z-10 backdrop-blur-sm md:hidden",onClick:t})]}):null}const Ut=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,...m},u)=>{const d=y=>{const p=[Number(y.target.value)];r&&r(p)},h=(t[0]-a)/(n-a)*100;return s.jsxs("div",{className:v("group relative flex w-full touch-none select-none items-center",e),children:[s.jsx("div",{className:"relative h-1 group-hover:h-1.5 w-full grow overflow-hidden rounded-full bg-muted transition-all duration-150",children:s.jsx("div",{className:"absolute h-full bg-primary transition-all duration-[var(--duration-fast)] shadow-slider-thumb group-hover:shadow-[0_0_8px_var(--primary)]",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,...m}),s.jsx("div",{className:v("absolute h-5 w-5 rounded-full border-2 border-primary bg-background ring-offset-background pointer-events-none shadow-slider-thumb","scale-0 opacity-0 group-hover:scale-100 group-hover:opacity-100 transition-all duration-150",o&&"opacity-50"),style:{left:`calc(${h}% - 10px)`}})]})});Ut.displayName="Slider";function Yi({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"},m={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:v("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(Ce,{className:v(m[r],"animate-spin"),"aria-hidden":"true"}),s.jsx("span",{className:"sr-only",children:"Chargement..."})]}):e?s.jsxs(s.Fragment,{children:[s.jsx(_r,{className:m[r],"aria-hidden":"true"}),s.jsx("span",{className:"sr-only",children:"Mettre en pause"})]}):s.jsxs(s.Fragment,{children:[s.jsx(Tr,{className:v(m[r],"ml-0.5"),"aria-hidden":"true"}),s.jsx("span",{className:"sr-only",children:"Lire"})]})})}function ur({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"},m={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:v("flex items-center gap-2",o),children:[s.jsxs("button",{type:"button",onClick:t,disabled:d,className:v("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(Nr,{className:m[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:v("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(Cr,{className:m[n],"aria-hidden":"true"}),s.jsx("span",{className:"sr-only",children:"Piste suivante"})]})]})}function Xi({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"},m={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é"}},y=()=>{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:v("flex items-center gap-2",n),children:[s.jsx(ue,{content:h(),disabled:i,children:s.jsxs("button",{type:"button",onClick:d,disabled:i,className:v("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":y(),"aria-pressed":e!=="off","aria-disabled":i,children:[s.jsx(Rr,{className:v(m[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.jsx(ue,{content:t?"Mélanger activé":"Mélanger désactivé",disabled:i,children:s.jsxs("button",{type:"button",onClick:a,disabled:i,className:v("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,children:[s.jsx(jr,{className:v(m[o],t&&"fill-current"),"aria-hidden":"true"}),s.jsx("span",{className:"sr-only",children:t?"Mélanger activé":"Mélanger désactivé"})]})})]})}function Ji({isOpen:e,onClose:t,currentTime:r,duration:a,onSeek:n,player:i}){const{currentTrack:o}=Ft(),[c,l]=f.useState(!1),[m,u]=f.useState(!0),d=f.useRef(null);if(!e||!o)return null;const h=o.lyrics,y=p=>{if(!p&&p!==0)return"0:00";const k=Math.floor(p/60),E=Math.floor(p%60);return`${k}:${E.toString().padStart(2,"0")}`};return f.useEffect(()=>{if(!m||!h?.length||!d.current)return;const p=h.findIndex((k,E)=>r>=k.time&&(E===h.length-1||r<h[E+1].time));p>=0&&d.current.children[p]?.scrollIntoView({behavior:"smooth",block:"center"})},[r,h,m]),s.jsxs("div",{className:v("fixed inset-0 z-[500] bg-black/95 backdrop-blur-3xl overflow-hidden flex flex-col transition-all duration-[var(--sumi-duration-slow)]",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(I,{variant:"ghost",className:"text-foreground hover:bg-white/10 rounded-full",onClick:t,children:s.jsx(wr,{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(I,{variant:"ghost",className:"text-foreground hover:bg-white/10 rounded-full",children:s.jsx(ia,{className:"w-6 h-6"})})]}),s.jsxs("div",{className:v("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 transition-all duration-[var(--sumi-duration-slow)]",c&&"md:gap-8"),children:[s.jsxs("div",{className:v("relative group transition-all duration-[var(--sumi-duration-slow)]",c?"w-full max-w-md md:max-w-sm aspect-square":"w-full max-w-md md:max-w-xl aspect-square"),children:[s.jsx("div",{className:"absolute inset-0 bg-gradient-to-br from-primary/20 to-secondary/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-cover-depth 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-heading font-bold text-foreground leading-tight",children:o.title}),s.jsx("p",{className:"text-xl md:text-2xl text-muted-foreground font-medium",children:o.artist})]}),s.jsx(I,{size:"icon",variant:"ghost",className:"text-muted-foreground hover:text-destructive hover:bg-destructive/10 rounded-full h-12 w-12 transition-all",children:s.jsx(It,{className:"w-6 h-6"})})]}),s.jsxs("div",{className:"space-y-4 group/progress",children:[s.jsx(Ut,{value:[r],onValueChange:p=>n(p[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:y(r)}),s.jsx("span",{children:y(a)})]})]}),s.jsxs("div",{className:"flex items-center justify-between",children:[s.jsx("div",{className:"flex items-center gap-4",children:s.jsx(Xi,{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(ur,{onNext:i.next,onPrevious:i.previous,canGoNext:!0,canGoPrevious:!0,size:"lg"}),s.jsx(Yi,{isPlaying:i.isPlaying,onClick:()=>i.isPlaying?i.pause():i.resume(),size:"xl",className:"scale-125"}),s.jsx(ur,{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(I,{size:"icon",variant:"ghost",className:"text-muted-foreground hover:text-foreground",children:s.jsx(oa,{className:"w-5 h-5"})}),s.jsx(ue,{content:c?"Hide lyrics":"Show lyrics",children:s.jsx(I,{size:"icon",variant:"ghost",className:v("transition-colors",c?"text-primary":"text-muted-foreground hover:text-foreground"),onClick:()=>l(!c),children:s.jsx(Bt,{className:"w-5 h-5"})})})]})]})]}),c&&s.jsxs("div",{className:v("group/lyrics w-full md:flex-1 h-layout-lyrics-sm md:h-layout-lyrics flex flex-col relative rounded-xl overflow-hidden border border-white/10 bg-black/30 backdrop-blur-md","animate-in slide-in-from-right-4 duration-300"),onMouseEnter:()=>u(!1),onMouseLeave:()=>u(!0),children:[s.jsx("div",{className:"absolute top-2 right-2 z-10 opacity-0 group-hover/lyrics:opacity-100 transition-opacity",children:s.jsx(ue,{content:"Auto-scroll",children:s.jsx(I,{variant:"ghost",size:"icon",className:m?"bg-primary/20 text-primary":"text-muted-foreground",onClick:()=>u(!m),children:s.jsx(la,{className:"w-4 h-4"})})})}),h?.length?s.jsx("div",{ref:d,className:"flex-1 overflow-y-auto custom-scrollbar px-6 py-8 space-y-6 text-center",children:h.map((p,k)=>{const E=r>=p.time&&(k===h.length-1||r<h[k+1].time);return s.jsx("p",{className:v("text-xl md:text-2xl font-bold transition-all duration-[var(--sumi-duration-slow)] cursor-pointer hover:text-foreground",E?"text-foreground scale-105":"text-white/20"),onClick:()=>n(p.time),children:p.text},k)})}):s.jsxs("div",{className:"flex-1 flex flex-col items-center justify-center text-muted-foreground",children:[s.jsx(Bt,{className:"w-12 h-12 mb-3 opacity-50"}),s.jsx("p",{children:"No lyrics available for this track."})]})]})]})]})}const dr=24;function Zi({levels:e,playing:t,className:r}){const a=e.length===dr?e:Array(dr).fill(0);return s.jsx("div",{className:v("flex items-center gap-0.5 h-8","opacity-80",r),role:"img","aria-label":t?"Audio waveform":"Paused",children:a.map((n,i)=>s.jsx("div",{className:v("w-0.5 rounded-full min-h-[4px] flex-shrink-0","bg-gradient-to-t from-[var(--chart-2)] to-[var(--chart-1)]","transition-all duration-75 ease-out"),style:{height:t?`${Math.max(4,4+n*28)}px`:"4px"}},i))})}function eo({children:e,isHovered:t,className:r}){return s.jsxs("div",{className:v("relative w-full rounded-xl overflow-hidden","backdrop-blur-[16px]","bg-[var(--sumi-glass-bg)]","border border-[var(--sumi-glass-border)]","transition-all duration-[var(--sumi-duration-normal)] ease-[var(--sumi-ease-out)]","shadow-[var(--sumi-shadow-xl)] player-bar-entrance",t&&"shadow-[var(--sumi-shadow-xl)] border-[var(--sumi-border-accent)]",!t&&"shadow-[var(--sumi-shadow-lg)]",r),children:[e,s.jsx("div",{className:v("absolute inset-0 pointer-events-none -z-10","bg-[var(--sumi-accent-subtle)]","opacity-0 transition-opacity duration-[var(--sumi-duration-slow)] ease-[var(--sumi-ease-out)]",t&&"opacity-100")})]})}function to({currentTime:e,duration:t,onSeek:r,className:a}){const n=f.useRef(null),i=t>0?Math.max(0,Math.min(1,e/t)):0,o=c=>{if(!n.current)return;const l=n.current.getBoundingClientRect(),m=c.clientX-l.left;r(Math.max(0,Math.min(1,m/l.width)))};return s.jsx("div",{ref:n,role:"slider","aria-label":"Progression","aria-valuemin":0,"aria-valuemax":t,"aria-valuenow":e,tabIndex:0,className:v("absolute bottom-0 left-0 right-0 h-1.5 z-20 cursor-pointer","bg-[var(--sumi-border-default)] hover:bg-[var(--sumi-border-strong)] transition-colors duration-[var(--sumi-duration-fast)]",a),onClick:o,children:s.jsx("div",{className:"h-full rounded-r bg-[var(--sumi-accent)] transition-[transform] duration-75 ease-out will-change-transform",style:{transform:`scaleX(${i})`,transformOrigin:"left"}})})}const Et="h-8 w-8 sm:h-9 sm:w-9 rounded-full transition-transform duration-150 active:scale-95";function ro({volume:e,muted:t,onVolumeChange:r,onToggleMute:a,showQueue:n,onToggleQueue:i,waveformLevels:o,isPlaying:c}){return s.jsxs("section",{className:"flex items-center justify-end gap-1 sm:gap-2 flex-shrink-0 min-w-32 shrink-0","aria-label":"Volume and queue",children:[s.jsx("div",{className:"hidden xl:block shrink-0",children:s.jsx(Zi,{levels:o,playing:c})}),s.jsxs("div",{className:"flex items-center gap-0.5 group/volume flex-shrink-0",children:[s.jsx(I,{variant:"ghost",size:"icon",className:v(Et,"text-muted-foreground hover:text-foreground"),onClick:a,children:t||e===0?s.jsx(ca,{className:"w-4 h-4"}):s.jsx(ua,{className:"w-4 h-4"})}),s.jsx("div",{className:"w-0 group-hover/volume:w-14 overflow-hidden transition-all duration-150 ease-out",children:s.jsx(Ut,{value:[t?0:e],onValueChange:l=>r(l[0]),max:100,className:"w-14 min-w-0"})})]}),s.jsx("div",{className:"w-px h-5 bg-[var(--sumi-border-faint)] flex-shrink-0"}),s.jsx(I,{variant:"ghost",size:"icon",className:v(Et,n?"text-primary bg-primary/10":"text-muted-foreground hover:text-foreground"),onClick:i,children:s.jsx(Lt,{className:"w-4 h-4"})}),s.jsx(I,{variant:"ghost",size:"icon",className:v(Et,"text-muted-foreground hover:text-[var(--chart-2)] hover:bg-[var(--chart-2)]/10"),children:s.jsx(It,{className:"w-4 h-4"})})]})}function so({title:e,artist:t,cover:r,isIdle:a,isPlaying:n,onExpand:i}){return s.jsxs("section",{className:"flex items-center gap-2 min-w-24 flex-1 overflow-hidden","aria-label":"Track info",children:[s.jsxs("div",{className:v("relative w-10 h-10 sm:w-11 sm:h-11 rounded-lg overflow-hidden flex-shrink-0","transition-transform duration-300 ease-out","hover:scale-105 active:scale-95",!a&&"cursor-pointer group/art"),onClick:a?void 0:i,children:[r?s.jsx("img",{src:r,alt:"",className:v("w-full h-full object-cover transition-transform duration-700",n&&"scale-110")}):s.jsx("div",{className:"w-full h-full bg-[var(--sumi-border-faint)] flex items-center justify-center",children:s.jsx(Ht,{className:v("w-5 h-5 text-muted-foreground",a&&"opacity-20")})}),!a&&s.jsx("div",{className:"absolute inset-0 bg-black/50 flex items-center justify-center opacity-0 group-hover/art:opacity-100 transition-opacity duration-150",children:s.jsx(Ht,{className:"w-5 h-5 text-foreground"})})]}),s.jsxs("div",{className:"flex flex-col justify-center min-w-0 overflow-hidden cursor-pointer",onClick:a?void 0:i,children:[s.jsx("h3",{className:v("font-heading font-bold text-xs sm:text-sm text-foreground truncate","transition-colors duration-150",!a&&"hover:text-primary"),children:e}),s.jsx("p",{className:v("text-xs text-muted-foreground truncate","transition-colors duration-150",!a&&"hover:text-foreground"),children:t})]})]})}const ao={title:"System Online",artist:"Select a track to play",cover:""};function no(){const e=f.useRef(null),[t,r]=f.useState(null),a=f.useCallback(E=>{e.current=E,r(E)},[]),{sidebarOpen:n}=de(),i=Fi(e);$i(i);const[o,c]=f.useState(!1),[l,m]=f.useState(!1),[u,d]=f.useState(!1),h=Bi(t,i.isPlaying),y=i.currentTrack,p=y||ao,k=!y;return s.jsxs(s.Fragment,{children:[s.jsx("audio",{ref:a}),s.jsx(Ji,{isOpen:l,onClose:()=>m(!1),currentTime:i.currentTime,duration:i.duration,onSeek:i.seek,player:i}),s.jsx(Gi,{isOpen:u,onClose:()=>d(!1),currentTrackId:y?.id,onPlay:E=>i.play(E)}),hr.createPortal(s.jsx("div",{"data-testid":"global-player",role:"region","aria-label":"Global player",className:v("fixed bottom-6 left-4 right-4 z-player transition-all duration-[var(--sumi-duration-slow)] ease-[var(--sumi-ease-out)]","lg:right-4 w-player-bar",n?"lg:left-main-expanded lg:w-player-bar-expanded":"lg:left-main-collapsed lg:w-player-bar-collapsed",l&&"translate-y-full opacity-0 pointer-events-none"),onMouseEnter:()=>c(!0),onMouseLeave:()=>c(!1),children:s.jsxs(eo,{isHovered:o,children:[s.jsxs("div",{className:"flex items-center justify-between gap-2 sm:gap-3 h-14 sm:h-16 px-3 sm:px-4 relative z-10 min-w-0 flex-nowrap",children:[s.jsx(so,{title:p.title,artist:p.artist||"Unknown Artist",cover:p.cover,isIdle:k,isPlaying:i.isPlaying,onExpand:()=>!k&&m(!0)}),s.jsxs("section",{className:"flex flex-col items-center justify-center gap-0.5 flex-shrink-0","aria-label":"Playback controls",children:[s.jsx(Hi,{compact:!0,isPlaying:i.isPlaying,onPlayPause:()=>{i.isPlaying?i.pause():k||i.resume()},onNext:i.next,onPrevious:i.previous,onShuffle:i.toggleShuffle,onRepeat:()=>{const E=["off","track","playlist"],j=E[(E.indexOf(i.repeat)+1)%E.length];i.setRepeat(j)},shuffle:i.shuffle,repeat:i.repeat}),s.jsxs("div",{className:v("flex items-center gap-1.5 text-xs font-mono text-muted-foreground whitespace-nowrap",k?"opacity-50":"opacity-90"),children:[s.jsx("span",{children:cr(i.currentTime)}),s.jsx("span",{className:"opacity-30",children:"/"}),s.jsx("span",{children:cr(i.duration)})]})]}),s.jsx(ro,{volume:i.volume,muted:i.muted,onVolumeChange:i.setVolume,onToggleMute:i.toggleMute,showQueue:u,onToggleQueue:()=>d(!u),waveformLevels:h,isPlaying:i.isPlaying})]}),!k&&s.jsx(to,{currentTime:i.currentTime,duration:i.duration,onSeek:E=>i.seek(E*i.duration)})]})}),document.body)]})}function io({children:e}){const{sidebarOpen:t}=de();return s.jsxs("div",{className:"flex h-screen w-full overflow-hidden relative bg-background",children:[s.jsx(Wr,{}),s.jsx(Oi,{}),s.jsxs("div",{className:v("flex-1 flex flex-col h-full min-w-0 relative z-[var(--sumi-z-raised)] transition-all duration-[var(--sumi-duration-slow)] ease-[var(--sumi-ease-in-out)]",t?"lg:ml-main-expanded":"lg:ml-main-collapsed","max-lg:ml-0"),children:[s.jsx(Li,{}),s.jsx("main",{className:"flex-1 overflow-y-auto overflow-x-hidden pt-main pb-main 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 w-full min-w-0","aria-label":"Player bar container",children:s.jsx(no,{})})]})]})}function oo({children:e}){return s.jsx(io,{children:e})}function Le(e){return s.jsx(hi,{children:s.jsx(Te,{children:e})})}function Q(e){return s.jsx(qn,{children:s.jsx(oo,{children:s.jsx(Te,{children:e})})})}function lo(){return[{path:"/login",element:Le(s.jsx(Bn,{}))},{path:"/register",element:Le(s.jsx(Hn,{}))},{path:"/forgot-password",element:Le(s.jsx(Kn,{}))},{path:"/verify-email",element:Le(s.jsx(Wn,{}))},{path:"/reset-password",element:Le(s.jsx(Gn,{}))}]}function co(){return[{path:"/design-system",element:s.jsx(Te,{children:s.jsx(ii,{})})},{path:"/u/:username",element:s.jsx(Te,{children:s.jsx(Zn,{})})}]}function uo(){return[{path:"/dashboard",element:Q(s.jsx(Fn,{}))},{path:"/marketplace",element:Q(s.jsx(ci,{}))},{path:"/sell",element:Q(s.jsx(di,{onCreateProduct:()=>{}}))},{path:"/wishlist",element:Q(s.jsx(mi,{}))},{path:"/purchases",element:Q(s.jsx(fi,{}))},{path:"/chat",element:Q(s.jsx(Vn,{}))},{path:"/library",element:Q(s.jsx(Un,{}))},{path:"/profile",element:Q(s.jsx($n,{}))},{path:"/settings",element:Q(s.jsx(Qn,{}))},{path:"/settings/sessions",element:Q(s.jsx(Yn,{}))},{path:"/admin/roles",element:Q(s.jsx(ei,{}))},{path:"/tracks/:id",element:Q(s.jsx(ti,{}))},{path:"/playlists/*",element:Q(s.jsx(ri,{}))},{path:"/search",element:Q(s.jsx(ui,{}))},{path:"/notifications",element:Q(s.jsx(li,{}))},{path:"/analytics",element:Q(s.jsx(ai,{onNavigateTrack:()=>{}}))},{path:"/webhooks",element:Q(s.jsx(ni,{}))},{path:"/admin",element:Q(s.jsx(si,{}))},{path:"/social",element:Q(s.jsx(oi,{onViewProfile:()=>{}}))},{path:"/gear",element:Q(s.jsx(Ie,{feature:"Gear"}))},{path:"/live",element:Q(s.jsx(Ie,{feature:"Live"}))},{path:"/education",element:Q(s.jsx(Ie,{feature:"Education"}))},{path:"/queue",element:Q(s.jsx(Ie,{feature:"Queue"}))},{path:"/developer",element:Q(s.jsx(Ie,{feature:"Developer"}))}]}function mo(){return[{path:"/404",element:s.jsx(Te,{children:s.jsx(Xn,{})})},{path:"/500",element:s.jsx(Te,{children:s.jsx(Jn,{})})}]}function fo(){const e=lo(),t=co(),r=uo(),a=mo();return s.jsxs(fs,{children:[e.map(({path:n,element:i})=>s.jsx(ke,{path:n,element:i},n)),t.map(({path:n,element:i})=>s.jsx(ke,{path:n,element:i},n)),r.map(({path:n,element:i})=>s.jsx(ke,{path:n,element:i},n)),a.map(({path:n,element:i})=>s.jsx(ke,{path:n,element:i},n)),s.jsx(ke,{path:"/",element:s.jsx(at,{to:"/dashboard",replace:!0})}),s.jsx(ke,{path:"*",element:s.jsx(at,{to:"/404",replace:!0})})]})}function ho(e={}){const{enabled:t=!0,preventDefault:r=!0,onHelpOpen:a}=e,n=ct(),{setSidebarOpen:i,sidebarOpen:o}=de(),c=f.useCallback(l=>{if(!t)return;const m=l.target;if(m&&(m.tagName==="INPUT"||m.tagName==="TEXTAREA"||m.isContentEditable===!0||m.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){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 po=[{title:"General",shortcuts:[{keys:["Ctrl","K"],description:"Open search"},{keys:["?"],description:"Show keyboard shortcuts"},{keys:["Esc"],description:"Close dialog / panel"}]},{title:"Playback",shortcuts:[{keys:["Space"],description:"Play / Pause"},{keys:["N"],description:"Next track"},{keys:["P"],description:"Previous track"},{keys:["M"],description:"Toggle mute"},{keys:["↑"],description:"Volume up"},{keys:["↓"],description:"Volume down"}]},{title:"Navigation",shortcuts:[{keys:["G","H"],description:"Go to Home"},{keys:["G","L"],description:"Go to Library"},{keys:["G","S"],description:"Go to Settings"}]}];function go({isOpen:e,onClose:t}){return f.useEffect(()=>{if(!e)return;const r=a=>{(a.key==="Escape"||a.key==="?")&&(a.preventDefault(),t())};return window.addEventListener("keydown",r),()=>window.removeEventListener("keydown",r)},[e,t]),s.jsx(At,{children:e&&s.jsxs(s.Fragment,{children:[s.jsx(je.div,{initial:{opacity:0},animate:{opacity:1},exit:{opacity:0},transition:{duration:.15},onClick:t,className:"fixed inset-0 z-50 bg-black/60 backdrop-blur-sm"}),s.jsxs(je.div,{initial:{opacity:0,scale:.95,y:20},animate:{opacity:1,scale:1,y:0},exit:{opacity:0,scale:.95,y:20},transition:{duration:.2,ease:[.16,1,.3,1]},className:"fixed inset-x-4 top-[10%] bottom-[10%] z-50 mx-auto max-w-2xl overflow-y-auto rounded-2xl border border-border bg-background/95 backdrop-blur-md p-6 shadow-2xl sm:inset-x-auto",role:"dialog","aria-modal":"true","aria-label":"Keyboard Shortcuts",children:[s.jsxs("div",{className:"flex items-center justify-between mb-6",children:[s.jsx("h2",{className:"text-xl font-semibold text-foreground",children:"Keyboard Shortcuts"}),s.jsx("button",{onClick:t,className:"p-2 rounded-lg hover:bg-muted transition-colors","aria-label":"Close",children:s.jsx(pe,{className:"h-5 w-5"})})]}),s.jsx("div",{className:"space-y-6",children:po.map(r=>s.jsxs("div",{children:[s.jsx("h3",{className:"text-xs font-semibold uppercase tracking-wider text-muted-foreground mb-3",children:r.title}),s.jsx("div",{className:"space-y-1",children:r.shortcuts.map(a=>s.jsxs("div",{className:"flex items-center justify-between py-2 px-3 rounded-lg hover:bg-muted/50 transition-colors",children:[s.jsx("span",{className:"text-sm text-foreground",children:a.description}),s.jsx("div",{className:"flex items-center gap-1",children:a.keys.map((n,i)=>s.jsxs("span",{children:[s.jsx("kbd",{className:"inline-flex h-6 min-w-6 items-center justify-center rounded-md border border-border bg-muted px-1.5 text-[11px] font-medium text-muted-foreground",children:n}),i<a.keys.length-1&&s.jsx("span",{className:"mx-0.5 text-xs text-muted-foreground",children:"+"})]},i))})]},a.description))})]},r.title))}),s.jsx("div",{className:"mt-6 pt-4 border-t border-border",children:s.jsxs("p",{className:"text-xs text-muted-foreground text-center",children:["Press"," ",s.jsx("kbd",{className:"inline-flex h-5 min-w-5 items-center justify-center rounded border border-border bg-muted px-1 text-[10px] font-medium",children:"?"})," ","to toggle this panel"]})})]})]})})}const yo=Ve()(gr(Ue(e=>({filters:{},setFilters:t=>{e({filters:t})}}),{name:"library-storage",partialize:e=>({filters:e.filters})}),{name:"LibraryStore",enabled:Qr()}));async function vo(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}=J.getState();if(!o)return g.debug("[StateHydration] User not authenticated, skipping hydration"),i}if(t)try{const{isAuthenticated:o,isLoading:c}=J.getState(),l=te.hasTokens();o&&l&&!c||(await xo(),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 bo(),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 wo(),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 xo(){const{refreshUser:e,isAuthenticated:t}=J.getState();await e()}async function bo(){const{fetchFavorites:e}=yo.getState();await e()}async function wo(){g.debug("[StateHydration] Chat state hydration skipped - using React Query")}function ko(e={}){const[t,r]=f.useState(!0),[a,n]=f.useState(null);return f.useEffect(()=>{let i=!0;return vo(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 Eo(){const e=Rt();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 So(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 jo(){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 mr(){return`${Date.now()}-${Math.random().toString(36).substring(2,9)}`}function No(e,t={}){const r=t.channelName||"veza-react-query-sync",a=t.enabled!==!1,n=t.shouldSync||(()=>!0);if(!a)return()=>{};const i=So(r);if(!i)return g.warn("[ReactQuerySync] BroadcastChannel not available, sync disabled"),()=>{};const o=jo(),c=new Set;let l=!1;function m(y){if(l||!n(y,"query-invalidate"))return;const p={type:"query-invalidate",queryKey:y,timestamp:Date.now(),messageId:mr(),tabId:o};try{i&&(i.postMessage(p),g.debug("[ReactQuerySync] Broadcasted query invalidation",{queryKey:y,messageId:p.messageId}))}catch(k){g.error("[ReactQuerySync] Failed to broadcast invalidation",{error:k instanceof Error?k.message:String(k),queryKey:y})}}function u(y){const p=y.data;if(!(!p||typeof p!="object"||!p.type||!Array.isArray(p.queryKey)||typeof p.timestamp!="number"||typeof p.messageId!="string")&&!(p.type!=="query-invalidate"&&p.type!=="query-set-data"&&p.type!=="mutation-success")&&p.tabId!==o&&!c.has(p.messageId)&&(c.add(p.messageId),c.size>1e3&&Array.from(c).slice(0,500).forEach(E=>c.delete(E)),!!n(p.queryKey,p.type))){l=!0;try{switch(p.type){case"query-invalidate":e.invalidateQueries({queryKey:p.queryKey}),g.debug("[ReactQuerySync] Invalidated query from other tab",{queryKey:p.queryKey,messageId:p.messageId});break;case"query-set-data":p.data!==void 0&&(e.setQueryData(p.queryKey,p.data),g.debug("[ReactQuerySync] Updated query data from other tab",{queryKey:p.queryKey,messageId:p.messageId}));break;case"mutation-success":e.invalidateQueries({queryKey:p.queryKey}),g.debug("[ReactQuerySync] Invalidated queries after mutation from other tab",{queryKey:p.queryKey,messageId:p.messageId});break;default:g.warn("[ReactQuerySync] Unknown message type",{type:p.type,messageId:p.messageId})}}catch(k){g.error("[ReactQuerySync] Error processing sync message",{error:k instanceof Error?k.message:String(k),messageId:p.messageId,queryKey:p.queryKey})}finally{setTimeout(()=>{l=!1},50)}}}i.addEventListener("message",u);const d=e.getMutationCache().subscribe(y=>{if(!(!y||!i)&&y.type==="updated"&&y.mutation.state.status==="success"){const p=y.mutation.options.mutationKey;if(p){const k={type:"mutation-success",queryKey:p,timestamp:Date.now(),messageId:mr(),tabId:o};try{i.postMessage(k),g.debug("[ReactQuerySync] Broadcasted mutation success",{queryKey:p,messageId:k.messageId})}catch(E){g.error("[ReactQuerySync] Failed to broadcast mutation",{error:E instanceof Error?E.message:String(E),queryKey:p})}}}}),h=e.getQueryCache().subscribe(y=>{if(y?.type==="removed"||y?.type==="updated"&&y.query?.state.isInvalidated){const p=y.query.queryKey;m(p)}});return g.debug("[ReactQuerySync] React Query cache synchronization enabled",{channelName:r,tabId:o}),()=>{i.removeEventListener("message",u),d(),h(),i.close(),g.debug("[ReactQuerySync] React Query cache synchronization disabled")}}const rt=[{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())}],_o={mode:"waveform",color:"#7c9dd6",sensitivity:50};function To(){const[e,t]=f.useState(null),[r,a]=f.useState([]),[n,i]=f.useState([]),[o,c]=f.useState(!1),[l,m]=f.useState(0),[u,d]=f.useState(0),[h,y]=f.useState(80),[p,k]=f.useState(!1),[E,j]=f.useState(!1),[N,D]=f.useState("off"),[V,b]=f.useState(1),[_,H]=f.useState(!0),[oe,Z]=f.useState(_o),[W,w]=f.useState(!0),S=f.useRef(null);f.useEffect(()=>{t(rt[0]),a(rt.slice(1))},[]);const C=()=>{if(r.length>0){const P=E?r[Math.floor(Math.random()*r.length)]:r[0];i(O=>e?[...O,e]:O),a(N!=="all"?O=>O.filter(X=>X.id!==P.id):O=>[...O.filter(X=>X.id!==P.id),P]),t(P),d(0),c(!0)}else if(W){const P=rt[Math.floor(Math.random()*rt.length)];i(O=>e?[...O,e]:O),t({...P,id:`auto-${Date.now()}`,title:`Autoplay: ${P.title}`}),d(0),c(!0)}else c(!1),d(0)};f.useEffect(()=>(o&&e?S.current=window.setInterval(()=>{d(P=>{if(e?.durationSec&&P>=e.durationSec){if(N==="one")return 0;if(r.length>0||W)C();else return c(!1),P;return 0}return P+1*V})},1e3/V):S.current&&clearInterval(S.current),()=>{S.current&&clearInterval(S.current)}),[o,e,N,V,r.length,W]),f.useEffect(()=>{e?.durationSec&&m(u/e.durationSec*100)},[u,e]);const R=(P,O)=>{if(e&&e.id!==P.id&&i(X=>[...X,e]),t(P),O){const X=O.findIndex(yt=>yt.id===P.id);X!==-1&&a(O.slice(X+1))}c(!0),d(0)},M=()=>c(!o),G=()=>{if(u>3)d(0);else if(n.length>0){const P=n[n.length-1];a(O=>e?[e,...O]:O),i(O=>O.slice(0,-1)),t(P),d(0),c(!0)}},le=P=>{if(e?.durationSec){const O=P/100*e.durationSec;d(O),m(P)}},Ge=P=>y(P),be=()=>k(P=>!P),Ae=()=>j(!E),we=()=>{const P=["off","all","one"],O=P[(P.indexOf(N)+1)%P.length];D(O)},Pe=()=>H(!_),U=()=>w(!W),ce=P=>a(O=>[...O,P]),gt=P=>a(O=>[P,...O]),ls=P=>a(O=>O.filter(X=>X.id!==P)),cs=()=>a([]),us=(P,O)=>{const X=Array.from(r),[yt]=X.splice(P,1);X.splice(O,0,yt),a(X)};return{currentTrack:e,isPlaying:o,queue:r,history:n,progress:l,currentTime:u,duration:e?.durationSec||0,volume:h,isMuted:p,shuffle:E,repeatMode:N,playbackRate:V,pitchCorrection:_,visualizerSettings:oe,autoplay:W,playTrack:R,togglePlay:M,nextTrack:C,prevTrack:G,seek:le,setVolume:Ge,toggleMute:be,toggleShuffle:Ae,toggleRepeat:we,setPlaybackRate:b,togglePitchCorrection:Pe,setVisualizerSettings:Z,toggleAutoplay:U,addToQueue:ce,removeFromQueue:ls,playNext:gt,reorderQueue:us,clearQueue:cs}}const is=f.createContext(void 0),$l=()=>{const e=f.useContext(is);if(!e)throw new Error("useAudio must be used within AudioProvider");return e},Co=({children:e})=>{const t=To();return s.jsx(is.Provider,{value:t,children:e})};function Ro(){const{refreshUser:e}=J(),{theme:t,setTheme:r,language:a,setLanguage:n}=de(),[i,o]=f.useState(!1),[c,l]=f.useState(!1),m=Rt();return ho({enabled:!0,onHelpOpen:()=>o(!0)}),ko({hydrateAuth:!0,hydrateLibrary:!1,hydrateChat:!1,requireAuth:!1}),Eo(),f.useEffect(()=>No(m,{enabled:!0,channelName:"veza-react-query-sync"}),[m]),f.useEffect(()=>{if((async()=>{await new Promise(h=>setTimeout(h,100));const{isAuthenticated:d}=J.getState();d&&Y.refreshToken().catch(h=>{const y=h instanceof Error?h.message:String(h);y.includes("HTML page instead of JSON")||g.warn("Failed to fetch CSRF token on app init",{message:y})})})(),!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 y=document.documentElement;h.matches?y.classList.add("dark"):y.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(un,{children:s.jsx(pn,{children:s.jsxs(Co,{children:[s.jsx(Wr,{}),s.jsx(Tn,{}),s.jsx(fo,{}),s.jsx(go,{isOpen: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 Ao={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"},Po={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é"}},Io={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"},Lo={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..."}},qo={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"}},Do={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..."}},Mo={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..."},Oo={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"}},zo={dashboard:"Tableau de bord",chat:"Chat",library:"Bibliothèque",profile:"Profil",settings:"Paramètres",menu:"Menu",close:"Fermer"},Fo={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"}}},Uo={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"},$o={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"},Qo={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"},Bo={title:"Recherche",placeholder:"Rechercher des pistes, playlists, utilisateurs...",results:"Résultats",noResults:"Aucun résultat trouvé",tracks:"Pistes",playlists:"Playlists",users:"Utilisateurs",all:"Tout"},Ho={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"},Ko={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é"},Wo={title:"Tableau de bord administrateur",users:"Utilisateurs",systemStats:"Statistiques système",auditLogs:"Journaux d'audit",suspiciousActivity:"Activité suspecte"},Go={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"}},Yo={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"},Xo={common:Ao,auth:Po,dashboard:Io,chat:Lo,library:qo,profile:Do,settings:Mo,errors:Oo,navigation:zo,validation:Fo,pwa:Vo,tracks:Uo,playlists:$o,notifications:Qo,search:Bo,analytics:Ho,webhooks:Ko,admin:Wo,keyboard:Go,player:Yo},Jo={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"},Zo={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"}},el={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"},tl={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..."}},rl={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"}},sl={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..."}},al={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..."},nl={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"}},il={dashboard:"Dashboard",chat:"Chat",library:"Library",profile:"Profile",settings:"Settings",menu:"Menu",close:"Close"},ol={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"},ll={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"}}},cl={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"},ul={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"},dl={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"},ml={title:"Search",placeholder:"Search tracks, playlists, users...",results:"Results",noResults:"No results found",tracks:"Tracks",playlists:"Playlists",users:"Users",all:"All"},fl={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"},hl={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"},pl={title:"Admin Dashboard",users:"Users",systemStats:"System Statistics",auditLogs:"Audit Logs",suspiciousActivity:"Suspicious Activity"},gl={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"}},yl={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"},vl={common:Jo,auth:Zo,dashboard:el,chat:tl,library:rl,profile:sl,settings:al,errors:nl,navigation:il,validation:ol,pwa:ll,tracks:cl,playlists:ul,notifications:dl,search:ml,analytics:fl,webhooks:hl,admin:pl,keyboard:gl,player:yl},xl={fr:{translation:Xo},en:{translation:vl}};vr.use(ks).use(Es).init({resources:xl,fallbackLng:"en",debug:!1,interpolation:{escapeValue:!1},detection:{order:["localStorage","navigator","htmlTag"],caches:["localStorage"]}});typeof window<"u"&&(window.i18n=vr);function bl(){const e="production";{g.debug("[Sentry] Error tracking disabled",{reason:"DSN not configured",environment:e});return}}const wl={theme:"system",setTheme:()=>null},kl=f.createContext(wl);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(a==="system"){const c=window.matchMedia("(prefers-color-scheme: dark)").matches?"dark":"light";o.setAttribute("data-theme",c);return}o.setAttribute("data-theme",a)},[a]),f.useEffect(()=>{if(a!=="system")return;const o=window.matchMedia("(prefers-color-scheme: dark)"),c=()=>{window.document.documentElement.setAttribute("data-theme",o.matches?"dark":"light")};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(kl.Provider,{value:i,value:i,children:e})}typeof window<"u"&&(window.addEventListener("error",e=>{},!0),window.addEventListener("unhandledrejection",e=>{}));bl();const os=new ps({defaultOptions:{queries:{retry:!1,refetchOnWindowFocus:!1,staleTime:60*1e3,gcTime:300*1e3,refetchOnMount:!0,refetchOnReconnect:!0}}});fa(os);async function Sl(){mt.USE_MSW}const jl=()=>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)}}),Nl=()=>{ds.createRoot(document.getElementById("root")).render(s.jsx(fr.StrictMode,{children:s.jsx(gs,{client:os,children:s.jsx(El,{defaultTheme:"dark",storageKey:"vite-ui-theme",children:s.jsxs(hs,{future:{v7_startTransition:!0,v7_relativeSplatPath:!0},children:[s.jsx(Ro,{}),s.jsx(ga,{position:"top-right"})]})})})}))},_l=T(()=>import("./vendor-CAoAb3tF.js").then(e=>e.Y),__vite__mapDeps([0,1,2])).then(e=>e).catch(e=>{});Promise.all([Sl(),_l]).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(()=>jl()).finally(()=>{Nl()});export{Or as A,I as B,Ot as C,Jr as D,es as E,Vl as F,ql as G,On as L,wn as M,Sn as S,ue as T,T as _,F as a,Ol as b,zl as c,v as d,Br as e,Fl as f,bi as g,J as h,mt as i,rs as j,Wi as k,g as l,$l as m,Ul as n,Ut as o,K as p,Mt as q,Qr as r,Ll as s,ee as t,ts as u,Fr as v,Dl as w,as as x,Ft as y,_t as z};
|