veza/apps/web/dist_verification/assets/index-BWcMVITa.js

5 lines
192 KiB
JavaScript

const __vite__mapDeps=(i,m=__vite__mapDeps,d=(m.f||(m.f=["assets/vendor-IYr-MHu4.js","assets/vendor-react-BHG7lGYR.js","assets/vendor-BD_zwJK7.css","assets/DashboardPage-DBeOkkV3.js","assets/vendor-tanstack-BzWBL1hV.js","assets/vendor-icons-DaGlTw4_.js","assets/vendor-utils-CgOSfOkx.js","assets/vendor-router-D-s5vIeO.js","assets/ChatPage-BfTFcCbO.js","assets/input-BGBI2Wze.js","assets/label-N1Bsuay_.js","assets/select-laDQECdR.js","assets/dropdown-BYn_8IId.js","assets/useIsRateLimited-HpmSVPdB.js","assets/confirmation-dialog-D8kbmfRa.js","assets/LibraryPage-55ubQtbB.js","assets/tracks-Bqg0pqgn.js","assets/progress-BQIngDvS.js","assets/alert-tey2YzVZ.js","assets/ProfilePage-BgZBWx-u.js","assets/textarea-If6sHLPh.js","assets/users-BcpK1D4V.js","assets/SettingsPage-C3AsvyKj.js","assets/LoginPage-BebUqHKQ.js","assets/useFormValidation-B1Tm3VtD.js","assets/checkbox-DUBsARHw.js","assets/RegisterPage-CcmefX82.js","assets/ForgotPasswordPage-YxRqJouX.js","assets/AuthButton-ByJY1yM3.js","assets/usePasswordReset-CY5zVo2R.js","assets/VerifyEmailPage-38fQWUYS.js","assets/ResetPasswordPage-CmeLbHE0.js","assets/SessionsPage-C5XUNUhD.js","assets/badge-CPAgRIoX.js","assets/NotFoundPage-BNqND_Xf.js","assets/ServerErrorPage-BBBqZ02f.js","assets/UserProfilePage-CGqKROeh.js","assets/playlists-C-Ora5VP.js","assets/PlaylistCard-z0bLl0kY.js","assets/features-6vY6zDlz.js","assets/avatar-B2y8ugWJ.js","assets/tabs-DP-eavm_.js","assets/socialService-is9ldyAe.js","assets/RolesPage-BazMBP1o.js","assets/TrackDetailPage-BJpZT2dq.js","assets/Spinner-BIGPirtm.js","assets/routes-BW8tCpD8.js","assets/Pagination-i598iEQZ.js","assets/useDebounce-Cc7fGPgq.js","assets/routes-B3giLbLK.css","assets/SearchPage-CmFSjE4p.js","assets/NotificationsPage-CJq_f7tr.js","assets/MarketplaceHome-C8IsZMEQ.js","assets/AnalyticsPage-CsUpS4-F.js","assets/WebhooksPage-BUKVljfN.js","assets/AdminDashboardPage-DO0rPMOR.js","assets/DesignSystemDemoPage-Comnif18.js","assets/SocialPage-DguJum4V.js","assets/GearPage-DM6CApaQ.js","assets/LivePage-BPSq4nAF.js","assets/EducationPage-B-YHj2Wa.js","assets/QueuePage-B8oRZVDA.js","assets/DeveloperPage-Cm1O9pRO.js"])))=>i.map(i=>d[i]);
import{a as f,j as s,c as zs,R as fe,d as Us}from"./vendor-react-BHG7lGYR.js";import{N as Xe,u as et,L as Ce,a as Fs,R as Vs,b as P,B as $s}from"./vendor-router-D-s5vIeO.js";import{u as Xt,a as jt,b as At,Q as Qs,c as Bs}from"./vendor-tanstack-BzWBL1hV.js";import{k as Me,l as tt,n as st,q as rt,t as Jt,u as Zt,v as es,S as Ws,w as ts,x as Ks,y as ss,z as rs,B as Hs,C as Gs}from"./vendor-IYr-MHu4.js";import{s as v,o as R,Z as Et,r as Ue,b as ae,e as ie,a as ke,n as M,c as de,f as Ys,d as Xs}from"./vendor-utils-CgOSfOkx.js";import{X as at,I as ot,A as Re,a as it,C as It,B as Pt,b as Js,c as Zs,S as er,M as tr,P as sr,E as rr,d as ar,e as or,D as ir,f as nr,g as qe,T as lr,h as cr,W as dr,L as Lt,i as Ge,j as qt,k as ur,l as mr,m as hr,n as fr,U as pr,o as as,p as os,q as gr,r as yr,s as xr,t as vr,u as br,v as wr,H as kr,w as Sr,x as _r,y as jr,z as Er,F as Nr,G as Tr,R as Cr,J as Rr,K as Ar,N as Ir,O as is,Q as Pr,V as xt,Y as Lr,Z as qr,_ as Dr,$ as Or,a0 as Mr,a1 as zr,a2 as Ur,a3 as Fr,a4 as Vr,a5 as $r,a6 as Qr,a7 as Br,a8 as Wr,a9 as Kr}from"./vendor-icons-DaGlTw4_.js";(function(){const t=document.createElement("link").relList;if(t&&t.supports&&t.supports("modulepreload"))return;for(const o of document.querySelectorAll('link[rel="modulepreload"]'))a(o);new MutationObserver(o=>{for(const l of o)if(l.type==="childList")for(const n of l.addedNodes)n.tagName==="LINK"&&n.rel==="modulepreload"&&a(n)}).observe(document,{childList:!0,subtree:!0});function r(o){const l={};return o.integrity&&(l.integrity=o.integrity),o.referrerPolicy&&(l.referrerPolicy=o.referrerPolicy),o.crossOrigin==="use-credentials"?l.credentials="include":o.crossOrigin==="anonymous"?l.credentials="omit":l.credentials="same-origin",l}function a(o){if(o.ep)return;o.ep=!0;const l=r(o);fetch(o.href,l)}})();const Hr="modulepreload",Gr=function(e){return`/${e}`},Dt={},T=function(t,r,a){let o=Promise.resolve();if(r&&r.length>0){const i=function(h){return Promise.all(h.map(u=>Promise.resolve(u).then(p=>({status:"fulfilled",value:p}),p=>({status:"rejected",reason:p}))))};document.getElementsByTagName("link");const n=document.querySelector("meta[property=csp-nonce]"),c=n?.nonce||n?.getAttribute("nonce");o=i(r.map(h=>{if(h=Gr(h),h in Dt)return;Dt[h]=!0;const u=h.endsWith(".css"),p=u?'[rel="stylesheet"]':"";if(document.querySelector(`link[href="${h}"]${p}`))return;const g=document.createElement("link");if(g.rel=u?"stylesheet":Hr,u||(g.as="script"),g.crossOrigin="",g.href=h,c&&g.setAttribute("nonce",c),document.head.appendChild(g),u)return new Promise((x,y)=>{g.addEventListener("load",x),g.addEventListener("error",()=>y(new Error(`Unable to preload CSS for ${h}`)))})}))}function l(n){const c=new Event("vite:preloadError",{cancelable:!0});if(c.payload=n,window.dispatchEvent(c),!c.defaultPrevented)throw n}return o.then(n=>{for(const c of n||[])c.status==="rejected"&&l(c.reason);return t().catch(l)})};let ns=null;function Yr(e){ns=e}function Xr(){return ns}const Jr=f.lazy(()=>T(()=>import("./vendor-IYr-MHu4.js").then(e=>e.W),__vite__mapDeps([0,1,2])).then(e=>({default:e.Toaster})));function Zr(e){return s.jsx(f.Suspense,{fallback:null,children:s.jsx(Jr,{...e})})}const Ot="veza_access_token",Mt="veza_refresh_token";class ce{static setTokens(t,r){try{localStorage.removeItem(Ot),localStorage.removeItem(Mt)}catch{}}static getAccessToken(){return null}static getRefreshToken(){return null}static clearTokens(){try{localStorage.removeItem(Ot),localStorage.removeItem(Mt)}catch{}}static hasTokens(){return!1}}const ea="WARN".toUpperCase();let Je={};function zt(e){Je={...Je,...e}}function ta(){return{...Je}}function Be(e,t,r,...a){const o={...Je,...r},l=new Date().toISOString();{const n={timestamp:l,level:e,message:t,...o,...a.length>0&&{data:a}},c=JSON.stringify(n);console.log(c);const i="http://localhost:8080/api/v1/api/v1/logs/frontend";i&&sa(i,n).catch(()=>{})}}async function sa(e,t){try{if(navigator.sendBeacon){const r=new Blob([JSON.stringify(t)],{type:"application/json"});navigator.sendBeacon(e,r)}else await fetch(e,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(t),keepalive:!0})}catch{}}function We(e){const t=["DEBUG","INFO","WARN","ERROR"],r=t.indexOf(ea),a=t.indexOf(e);return r===-1||a===-1?!0:a>=r}const m={debug:(e,t,...r)=>{We("DEBUG")&&Be("DEBUG",e,t,...r)},info:(e,t,...r)=>{We("INFO")&&Be("INFO",e,t,...r)},warn:(e,t,...r)=>{We("WARN")&&Be("WARN",e,t,...r)},error:(e,t,...r)=>{We("ERROR")&&Be("ERROR",e,t,...r)}},ye=T(()=>import("./vendor-IYr-MHu4.js").then(e=>e.W),__vite__mapDeps([0,1,2]));let Ye=null,vt=!1;ye.then(e=>{Ye=e,vt=!0}).catch(e=>{vt=!0});function Ut(){return!Ye&&vt?(m.error("Toast module failed to load"),{success:()=>{},error:()=>{},loading:()=>{},custom:()=>{},dismiss:()=>{},remove:()=>{},promise:()=>Promise.resolve()}):Ye?Ye.default:{success:(...e)=>{ye.then(t=>t.default.success(...e))},error:(...e)=>{ye.then(t=>t.default.error(...e))},loading:(...e)=>{ye.then(t=>t.default.loading(...e))},custom:(...e)=>{ye.then(t=>t.default.custom(...e))},dismiss:(...e)=>{ye.then(t=>t.default.dismiss(...e))},remove:(...e)=>{ye.then(t=>t.default.remove(...e))},promise:(...e)=>ye.then(t=>t.default.promise(...e))}}const ee=new Proxy({},{get(e,t){const r=Ut();if(t in r){const a=r[t];return typeof a=="function"?a.bind(r):a}},apply(e,t,r){const a=Ut();return typeof a=="function"?a(...r):ye.then(o=>o.default(...r))}});let ft=null;const ra=60*1e3,aa=240*1e3;let De=null,Te=null;function oa(){return ft||(ft=Me.create({baseURL:"http://localhost:8080/api/v1",timeout:1e4,headers:{"Content-Type":"application/json"},withCredentials:!0})),ft}async function ze(){try{const t=await oa().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)}`);ce.setTokens("","cookie-based"),ls(r)}catch(e){throw ce.clearTokens(),nt(),e}}function ls(e=300){nt(),ia();const t=e*1e3,r=Math.max(0,t-ra);if(r<=0){ze().catch(a=>{m.warn("Proactive token refresh failed",{error:a instanceof Error?a.message:String(a),stack:a instanceof Error?a.stack:void 0})});return}De=setTimeout(()=>{ze().catch(a=>{m.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 ia(){Te&&clearInterval(Te),Te=setInterval(()=>{ze().catch(e=>{m.warn("Periodic token refresh failed",{error:e instanceof Error?e.message:String(e),stack:e instanceof Error?e.stack:void 0}),nt()})},aa)}function nt(){De&&(clearTimeout(De),De=null),Te&&(clearInterval(Te),Te=null)}function Nt(){ls(300)}function cs(){nt()}const na=Object.freeze(Object.defineProperty({__proto__:null,cleanupProactiveRefresh:cs,initializeProactiveRefresh:Nt,refreshToken:ze},Symbol.toStringTag,{value:"Module"})),Ke=v().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 /"}),la=R({VITE_API_URL:Ke.default("/api/v1"),VITE_WS_URL:Ke.default("/ws"),VITE_STREAM_URL:Ke.default("/stream"),VITE_UPLOAD_URL:Ke.default("/upload"),VITE_APP_NAME:v().default("Veza"),VITE_API_VERSION:v().default("v1"),VITE_DEBUG:v().transform(e=>e==="true"||e==="1").default("false"),VITE_USE_MSW:v().transform(e=>e==="1"||e==="true").default("0"),VITE_FCM_VAPID_KEY:v().optional(),VITE_SENTRY_DSN:v().url().optional()}),ca=()=>{try{return la.parse({VITE_API_URL:"http://localhost:8080/api/v1",VITE_WS_URL:"ws://localhost:8081/ws",VITE_STREAM_URL:"ws://localhost:8082/stream",VITE_UPLOAD_URL:void 0,VITE_APP_NAME:void 0,VITE_API_VERSION:void 0,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 Et?(m.error("❌ Invalid environment variables",{errors:e.errors}),new Error(`Environment variables validation failed: ${e.errors.map(t=>`${t.path.join(".")}: ${t.message}`).join(", ")}`)):e}},me=ca(),lt={API_URL:me.VITE_API_URL,WS_URL:me.VITE_WS_URL,STREAM_URL:me.VITE_STREAM_URL,UPLOAD_URL:me.VITE_UPLOAD_URL,APP_NAME:me.VITE_APP_NAME,API_VERSION:me.VITE_API_VERSION,DEBUG:me.VITE_DEBUG,USE_MSW:me.VITE_USE_MSW,FCM_VAPID_KEY:me.VITE_FCM_VAPID_KEY,SENTRY_DSN:me.VITE_SENTRY_DSN},le={400:"La requête est invalide. Veuillez vérifier les informations fournies.",401:"Vous devez être connecté pour effectuer cette action.",403:"Vous n'avez pas les permissions nécessaires pour effectuer cette action.",404:"La ressource demandée est introuvable.",409:"Un conflit est survenu. Cette ressource existe déjà ou a été modifiée.",422:"Les données fournies ne sont pas valides.",429:"Trop de requêtes. Veuillez patienter quelques instants avant de réessayer.",500:"Une erreur serveur s'est produite. Veuillez réessayer plus tard.",502:"Erreur de communication avec le serveur. Veuillez réessayer plus tard.",503:"Service temporairement indisponible. Veuillez réessayer dans quelques instants.",504:"Le serveur met trop de temps à répondre. Veuillez réessayer plus tard.",NETWORK:"Erreur de connexion. Vérifiez votre connexion internet et réessayez. Si le problème persiste, le serveur pourrait être temporairement indisponible.",TIMEOUT:"La requête a expiré. Vérifiez votre connexion internet et réessayez.",UNKNOWN:"Une erreur inattendue s'est produite. Veuillez réessayer."},da={auth:{login:"Échec de la connexion. Vérifiez vos identifiants.",logout:"Erreur lors de la déconnexion.",register:"Erreur lors de l'inscription. Veuillez réessayer.",tokenExpired:"Votre session a expiré. Veuillez vous reconnecter."},upload:{fileTooLarge:"Le fichier est trop volumineux.",invalidFormat:"Le format de fichier n'est pas supporté.",uploadFailed:"L'upload a échoué. Veuillez réessayer.",networkError:"Erreur réseau lors de l'upload. Vérifiez votre connexion."},playlist:{notFound:"La playlist est introuvable.",accessDenied:"Vous n'avez pas accès à cette playlist.",createFailed:"Erreur lors de la création de la playlist.",updateFailed:"Erreur lors de la mise à jour de la playlist.",deleteFailed:"Erreur lors de la suppression de la playlist."},track:{notFound:"Le morceau est introuvable.",playFailed:"Impossible de lire le morceau. Vérifiez votre connexion.",uploadFailed:"Erreur lors de l'upload du morceau.",deleteFailed:"Erreur lors de la suppression du morceau."},conversation:{notFound:"La conversation est introuvable.",accessDenied:"Vous n'avez pas accès à cette conversation.",createFailed:"Erreur lors de la création de la conversation.",sendMessageFailed:"Erreur lors de l'envoi du message."},search:{failed:"La recherche a échoué. Veuillez réessayer.",timeout:"La recherche a pris trop de temps. Veuillez réessayer.",invalidQuery:"La requête de recherche est invalide."}};function ua(e,t){return e in le?le[e]:t||le.UNKNOWN}function ma(e,t,r){const a=da[e];return a&&t in a?a[t]:r||le.UNKNOWN}function ds(e,t,r=!1){if(e&&typeof e=="object"&&"code"in e&&"message"in e){const a=e,o=typeof a.code=="number"?a.code:0;if(t&&o>=400&&o<500){const l=ha(a.message),n=ma(t,l,void 0);if(n!==le.UNKNOWN)return n}if(o>0){const l=ua(o,a.message);if(r&&a.details&&Array.isArray(a.details)){const n=a.details.map(c=>c.message||c.field).filter(Boolean).join(", ");if(n)return`${l} (${n})`}return l}return a.message||le.UNKNOWN}if(e instanceof Error)return e.message||le.UNKNOWN;if(e&&typeof e=="object"&&"code"in e){const a=e.code;if(a==="ECONNABORTED"||a==="ETIMEDOUT")return le.TIMEOUT;if(a==="ERR_NETWORK"||!e.response)return le.NETWORK}return le.UNKNOWN}function ha(e){const t=e.toLowerCase();return t.includes("login")||t.includes("connexion")?"login":t.includes("logout")||t.includes("déconnexion")?"logout":t.includes("register")||t.includes("inscription")?"register":t.includes("upload")||t.includes("téléchargement")?t.includes("large")||t.includes("volumineux")?"fileTooLarge":t.includes("format")||t.includes("type")?"invalidFormat":"uploadFailed":t.includes("not found")||t.includes("introuvable")?"notFound":t.includes("access denied")||t.includes("permission")?"accessDenied":t.includes("create")||t.includes("créer")?"createFailed":t.includes("update")||t.includes("mise à jour")?"updateFailed":t.includes("delete")||t.includes("suppression")?"deleteFailed":""}const us={timeout:le.TIMEOUT};function fa(e){if(e instanceof Error)return e.message===us.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 ga(){return!pa()}function $(e){if(xa(e))return e;if(va(e)){const t=e,r=t.response?.data,a=i=>typeof i=="object"&&i!==null&&"success"in i&&i.success===!1&&"error"in i,o=i=>typeof i=="object"&&i!==null&&"error"in i&&typeof i.error=="object",l=i=>typeof i=="object"&&i!==null&&"code"in i&&"message"in i;if(r){if(a(r))return pt(r.error);if(o(r)){const i=r.error;if(i&&("code"in i||"message"in i))return pt(i)}if(l(r))return pt(r)}if(t.request&&!t.response)return fa(t)?{code:0,message:us.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"||ga()?{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 n=t.response?.status;if(n===429){const i=t.response?.headers||{},h=r,u=i["x-ratelimit-limit"]?parseInt(String(i["x-ratelimit-limit"]),10):void 0,p=i["x-ratelimit-remaining"]?parseInt(String(i["x-ratelimit-remaining"]),10):void 0,g=i["x-ratelimit-reset"]?parseInt(String(i["x-ratelimit-reset"]),10):void 0,x=i["retry-after"]?parseInt(String(i["retry-after"]),10):h?.error?.retry_after||60,y=g?new Date(g*1e3):void 0,k=y?Math.max(0,Math.ceil((y.getTime()-Date.now())/1e3)):x;return{code:429,message:h?.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":""}.`},...p!==void 0?[{field:"remaining",message:`${p} requête${p>1?"s":""} restante${p>1?"s":""}`}]:[]],retry_after:k}}if(n===503){const i=r;return{code:503,message:i?.message||"Service temporairement indisponible. Veuillez réessayer dans quelques instants.",timestamp:new Date().toISOString(),details:bt(i?.details)}}if(n===502){const i=r;return{code:502,message:i?.message||"Erreur de communication avec le serveur. Veuillez réessayer plus tard.",timestamp:new Date().toISOString(),details:bt(i?.details)}}return{code:n||0,message:r?.message||t.message||"An unexpected error occurred",timestamp:new Date().toISOString()}}return e instanceof Error?{code:0,message:e.message||"An unexpected error occurred",timestamp:new Date().toISOString()}:{code:0,message:"An unexpected error occurred",timestamp:new Date().toISOString()}}function bt(e){if(!Array.isArray(e))return;const t=e.filter(r=>typeof r=="object"&&r!==null&&"field"in r&&"message"in r&&typeof r.field=="string"&&typeof r.message=="string");return t.length>0?t:void 0}function ya(e){if(typeof e=="object"&&e!==null&&!Array.isArray(e))return e}function pt(e){const t=e;return{code:typeof t.code=="number"?t.code:parseInt(String(t.code||0),10),message:typeof t.message=="string"?t.message:"An error occurred",details:bt(t.details),request_id:typeof t.request_id=="string"?t.request_id:void 0,timestamp:typeof t.timestamp=="string"?t.timestamp:new Date().toISOString(),context:ya(t.context)}}function Hn(e,t=!1){let r=e.message;if(e.details&&Array.isArray(e.details)&&e.details.length>0){const a=e.details.map(o=>`${o.field}: ${o.message}`).join(", ");r=`${e.message} (${a})`}return t&&e.request_id&&(r=`${r} [Request ID: ${e.request_id}]`),r}function ct(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 Gn(e){if(!e.details||!Array.isArray(e.details))return{};const t={};for(const r of e.details)r.field&&r.message&&(t[r.field]=r.message);return t}function xa(e){return typeof e=="object"&&e!==null&&"code"in e&&"message"in e&&typeof e.code=="number"&&typeof e.message=="string"}function va(e){return typeof e=="object"&&e!==null&&"isAxiosError"in e&&e.isAxiosError===!0}class ba{token=null;refreshPromise=null;async refreshToken(){return this.refreshPromise?this.refreshPromise:(this.refreshPromise=(async()=>{try{const r=(await O.get("/csrf-token")).data;return this.token=r.csrf_token,this.token}catch(t){throw m.error("Failed to fetch CSRF token:",{error:t}),t}finally{this.refreshPromise=null}})(),this.refreshPromise)}getToken(){return this.token}async ensureToken(){return this.token?this.token:this.refreshToken()}clearToken(){this.token=null,this.refreshPromise=null}clearCsrfToken(){this.clearToken()}async refreshCsrfToken(){return this.refreshToken()}getCsrfHeaders(){const t=this.getToken();return t?{"X-CSRF-Token":t}:{}}}const oe=new ba;class wa{queue=[];isProcessing=!1;maxQueueSize=100;defaultMaxRetries=3;defaultRetryDelay=1e3;constructor(){this.loadQueue(),typeof window<"u"&&(window.addEventListener("online",()=>{m.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(i=>i.priority==="low");c!==-1?this.queue.splice(c,1):this.queue.shift()}const o={id:this.generateRequestId(),config:t,timestamp:Date.now(),retryCount:0,priority:a},l={high:0,normal:1,low:2},n=this.queue.findIndex(c=>l[c.priority]>l[a]);return n===-1?this.queue.push(o):this.queue.splice(n,0,o),await this.saveQueue(),m.info(`[OfflineQueue] Request queued: ${t.method?.toUpperCase()} ${t.url}`,{requestId:o.id,priority:a,queueSize:this.queue.length}),o.id}async processQueue(){if(!(this.isProcessing||this.isOffline()||this.queue.length===0)){for(this.isProcessing=!0,m.info(`[OfflineQueue] Processing ${this.queue.length} queued requests`);this.queue.length>0&&!this.isOffline();){const t=this.queue[0];try{await O.request(t.config),this.queue.shift(),await this.saveQueue(),m.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?(m.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(o=>setTimeout(o,this.defaultRetryDelay*t.retryCount))),this.isOffline()){m.warn("[OfflineQueue] Connection lost, stopping queue processing");break}}}this.isProcessing=!1,this.queue.length>0?m.info(`[OfflineQueue] Queue processing complete, ${this.queue.length} requests remaining`):m.info("[OfflineQueue] All queued requests processed successfully")}}getQueueSize(){return this.queue.length}getQueue(){return[...this.queue]}async clearQueue(){this.queue=[],await this.saveQueue(),m.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(),m.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){m.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(o=>o.timestamp>a),this.queue.length!==r.length&&await this.saveQueue(),m.info(`[OfflineQueue] Loaded ${this.queue.length} requests from storage`)}}}catch(t){m.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 xe=new wa;class ka{cache=new Map;defaultCacheTime=1e3;generateRequestKey(t){const r=(t.method||"GET").toUpperCase(),a=t.url||"",o=t.baseURL||"",l=a.startsWith("http")?a:`${o}${a}`,n=t.params?Object.keys(t.params).sort().map(i=>`${i}=${JSON.stringify(t.params[i])}`).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}:${l}${n?`?${n}`:""}${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:o=!0,cacheTime:l=this.defaultCacheTime}=a;if(!o||!this.shouldDeduplicate(t))return r();const n=this.generateRequestKey(t),c=this.cache.get(n);if(c)return c.resolveCount++,m.debug(`[RequestDeduplication] Reusing request: ${t.method?.toUpperCase()} ${t.url}`,{key:n,resolveCount:c.resolveCount}),c.promise;const i=r().then(h=>(setTimeout(()=>{const u=this.cache.get(n);u&&u.promise===i&&(this.cache.delete(n),m.debug(`[RequestDeduplication] Removed from cache: ${n}`))},l),h)).catch(h=>{const u=this.cache.get(n);throw u&&u.promise===i&&(this.cache.delete(n),m.debug(`[RequestDeduplication] Removed from cache (error): ${n}`)),h});return this.cache.set(n,{promise:i,timestamp:Date.now(),resolveCount:1}),m.debug(`[RequestDeduplication] New request: ${t.method?.toUpperCase()} ${t.url}`,{key:n,cacheSize:this.cache.size}),i}clearCache(){const t=this.cache.size;this.cache.clear(),m.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[o,l]of this.cache.entries())r-l.timestamp>t&&(this.cache.delete(o),a++);a>0&&m.debug(`[RequestDeduplication] Cleaned up ${a} old cache entries`)}}const Sa=new ka;typeof window<"u"&&setInterval(()=>{Sa.cleanup(6e4)},300*1e3);class _a{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||"",o=t.baseURL||"",l=a.startsWith("http")?a:`${o}${a}`,n=t.params?Object.keys(t.params).sort().map(i=>`${i}=${JSON.stringify(t.params[i])}`).join("&"):"",c=t.headers?.Authorization||"";return`${r}:${l}${n?`?${n}`:""}:${c}`}parseCacheControl(t){if(!t)return{};const r={},a=t.split(",").map(o=>o.trim());for(const o of a)if(o.includes("=")){const[l,n]=o.split("=").map(c=>c.trim());r[l.toLowerCase()]=n}else r[o.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 o=Date.now()-t.timestamp;if(t.maxAge){const l=t.maxAge*1e3;if(o>l)return!1}else if(o>this.defaultTTL)return!1;if(this.enableETag&&t.etag){const l=r.headers?.["If-None-Match"];if(l&&l!==t.etag)return!1}if(t.lastModified){const l=r.headers?.["If-Modified-Since"];if(l){const n=new Date(t.lastModified).getTime(),c=new Date(l).getTime();if(n<c)return!1}}return!0}get(t){if((t.method||"GET").toUpperCase()!=="GET"||t?._disableCache===!0)return null;const a=this.generateCacheKey(t),o=this.cache.get(a);if(!o)return null;if(!this.isCacheValid(o,t))return this.cache.delete(a),m.debug(`[ResponseCache] Cache expired: ${t.url}`),null;const l={data:o.data,status:o.status,statusText:o.statusText,headers:o.headers,config:t,request:{}};return m.debug(`[ResponseCache] Cache hit: ${t.url}`,{key:a,age:Date.now()-o.timestamp}),l}set(t,r){if((t.method||"GET").toUpperCase()!=="GET"||t?._disableCache===!0)return;const o=r.headers["cache-control"]||r.headers["Cache-Control"],l=this.parseCacheControl(o);if(l.noStore||l.noCache){m.debug(`[ResponseCache] Not caching (no-store/no-cache): ${t.url}`);return}let n;this.respectCacheControl&&l.maxAge?n=l.maxAge:n=Math.floor(this.defaultTTL/1e3);const c=r.headers.etag||r.headers.ETag,i=r.headers["last-modified"]||r.headers["Last-Modified"],h=this.generateCacheKey(t);if(this.cache.size>=this.maxSize&&!this.cache.has(h)){const u=this.cache.keys().next().value;u&&this.cache.delete(u)}this.cache.set(h,{data:r.data,headers:r.headers,status:r.status,statusText:r.statusText,timestamp:Date.now(),etag:c,lastModified:i,maxAge:n}),m.debug(`[ResponseCache] Cached: ${t.url}`,{key:h,maxAge:n,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&&m.info(`[ResponseCache] Invalidated ${r} cache entries for pattern: ${t}`),r}clear(){const t=this.cache.size;this.cache.clear(),m.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,o]of this.cache.entries()){const l=t-o.timestamp,n=(o.maxAge||Math.floor(this.defaultTTL/1e3))*1e3;l>n&&(this.cache.delete(a),r++)}return r>0&&m.debug(`[ResponseCache] Cleaned up ${r} expired cache entries`),r}}const je=new _a({defaultTTL:300*1e3,maxSize:100,respectCacheControl:!0,enableETag:!0});typeof window<"u"&&setInterval(()=>{je.cleanup()},60*1e3);function Ft(e={}){const{target:t="all",resourceType:r,resourceId:a,invalidateAll:o=!1,queryKeys:l=[],storeNames:n=[]}=e;try{(t==="cache"||t==="all")&&(o?(je.clear(),m.debug("[StateInvalidation] Cleared all response cache")):r&&ja(r,a)),(t==="queries"||t==="all")&&Ea(l,r,a),(t==="stores"||t==="all")&&Na(n,r,a),m.debug("[StateInvalidation] State invalidated",{target:t,resourceType:r,resourceId:a,invalidateAll:o})}catch(c){m.error("[StateInvalidation] Error invalidating state",{error:String(c)})}}function ja(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"){je.clear();return}const a=r[e]||[];for(const o of a)je.invalidate(o);if(t)for(const o of a)je.invalidate(`${o}/${t}`)}function Ea(e,t,r){const a=Xr();if(!a){if(m.warn("[StateInvalidation] QueryClient not available, falling back to event system"),typeof window<"u"){const o=new CustomEvent("veza:invalidate-queries",{detail:{queryKeys:e,resourceType:t,resourceId:r}});window.dispatchEvent(o)}return}if(e&&e.length>0)for(const o of e)a.invalidateQueries({queryKey:o});if(t){const l={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 n of l)a.invalidateQueries({queryKey:r?[...n,r]:n})}m.debug("[StateInvalidation] Invalidated React Query cache",{queryKeys:e,resourceType:t,resourceId:r})}function Na(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"]},o=e.length>0?e:t?a[t]||[]:[];for(const l of o)Ta(l).catch(n=>{m.warn(`[StateInvalidation] Failed to invalidate store ${l}`,{error:String(n)})})}async function Ta(e,t,r){try{switch(e){case"auth":{const{useAuthStore:a}=await T(async()=>{const{useAuthStore:o}=await Promise.resolve().then(()=>Le);return{useAuthStore:o}},void 0);a.getState().refreshUser?.();break}case"library":break;case"chat":break;case"ui":break;default:m.warn(`[StateInvalidation] Unknown store: ${e}`)}}catch(a){m.error(`[StateInvalidation] Error invalidating store ${e}`,{error:String(a)})}}function Ca(e,t){if(!e)return;let r,a;if(e.includes("/tracks/")){r="tracks";const o=e.match(/\/tracks\/([^/]+)/);a=o?o[1]:void 0}else if(e.includes("/playlists/")){r="playlists";const o=e.match(/\/playlists\/([^/]+)/);a=o?o[1]:void 0}else if(e.includes("/users/")||e.includes("/auth/")){r="users";const o=e.match(/\/(users|auth)\/([^/]+)/);a=o?o[2]:void 0}else if(e.includes("/conversations/")){r="conversations";const o=e.match(/\/conversations\/([^/]+)/);a=o?o[1]:void 0}else if(e.includes("/roles/")){r="roles";const o=e.match(/\/roles\/([^/]+)/);a=o?o[1]:void 0}Ft(r?{resourceType:r,resourceId:a,target:"all"}:{target:"cache",invalidateAll:!0})}function Ra(e){if(e!=null)return typeof e=="string"?e:String(e)}function wt(e,t=["id","user_id","track_id","playlist_id","conversation_id","message_id","sender_id","creator_id","created_by","parent_id","parent_message_id"]){if(!e||typeof e!="object")return e;const r={...e};for(const[a,o]of Object.entries(r))t.includes(a)?r[a]=Ra(o):o&&typeof o=="object"&&!Array.isArray(o)&&!(o instanceof Date)?r[a]=wt(o,t):Array.isArray(o)&&o.length>0&&typeof o[0]=="object"&&(r[a]=o.map(l=>typeof l=="object"&&l!==null?wt(l,t):l));return r}const Ae="1.2.0";function Fe(e,t=Ae,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 I=v().uuid("Invalid UUID format"),V=v().datetime({message:"Invalid ISO8601 date format"}),Ve=Fe(R({id:I,username:v().min(1),slug:v().optional(),email:v().email(),first_name:v().optional().nullable(),last_name:v().optional().nullable(),avatar:v().optional().nullable(),bio:v().optional().nullable(),location:v().optional().nullable(),birthdate:V.optional().nullable(),gender:v().optional().nullable(),username_changed_at:V.optional().nullable(),role:ie(["user","admin","super_admin"]),is_active:ae(),is_verified:ae(),is_banned:ae().optional(),is_admin:ae(),is_public:ae(),last_login_at:V.optional().nullable(),created_at:V,updated_at:V,is_2fa_enabled:ae().optional(),social_links:Ue(ke()).optional().nullable()}),Ae,"User response schema - matches backend User model"),Aa=R({id:I,conversation_id:I,sender_id:I,content:v(),message_type:ie(["text","image","audio","file"]),attachment_url:v().url().optional(),created_at:V,updated_at:V,sender:Ve.optional()});R({id:I,name:v(),type:ie(["direct","group"]),creator_id:I,created_at:V,updated_at:V,participants:de(Ve).optional(),last_message:Aa.optional(),unread_count:M().int().nonnegative().optional()});const ms=Fe(R({id:I,creator_id:I,file_id:I.optional().nullable(),title:v().min(1),artist:v().min(1),album:v(),duration:M().int().nonnegative(),genre:v(),year:M().int().min(1900).max(2100),file_path:v(),file_size:M().nonnegative(),format:v(),bitrate:M().nonnegative(),sample_rate:M().nonnegative(),waveform_path:v().optional().nullable(),cover_art_path:v().optional().nullable(),is_public:ae(),status:ie(["uploading","processing","completed","failed"]),status_message:v().optional().nullable(),stream_status:ie(["pending","processing","ready","error"]),stream_manifest_url:v().url().optional().nullable(),play_count:M().int().nonnegative(),like_count:M().int().nonnegative(),created_at:V,updated_at:V,user:Ve.optional(),is_premium:ae().optional(),lyrics:de(R({time:M(),text:v()})).optional(),waveform_data:de(M()).optional(),tags:de(v()).optional()}),Ae,"Track response schema - matches backend Track model");Fe(R({id:I,user_id:I,title:v().min(1),description:v().optional().nullable(),visibility:ie(["public","private","unlisted"]).optional(),is_public:ae(),cover_url:v().url().optional().nullable(),track_count:M().int().nonnegative(),follower_count:M().int().nonnegative(),created_at:V,updated_at:V,tracks:de(ms).optional(),user:Ve.optional(),playlist_tracks:de(ke()).optional(),collaborators:de(ke()).optional()}),Ae,"Playlist response schema - matches backend Playlist model");R({id:I,user_id:I,ip_address:v(),user_agent:v(),revoked_at:V.optional().nullable(),expires_at:V,created_at:V});R({id:I,user_id:I.optional().nullable(),action:v(),resource:v(),resource_id:I.optional().nullable(),metadata:Ue(ke()).optional().nullable(),ip_address:v().optional().nullable(),user_agent:v().optional().nullable(),timestamp:V});Fe(R({code:M().int(),message:v(),details:de(R({field:v(),message:v(),value:v().optional()})).optional(),request_id:v().optional(),timestamp:V,context:Ue(ke()).optional(),retry_after:M().int().positive().optional()}),Ae,"API Error response schema - matches backend error format");Fe(R({page:M().int().positive(),limit:M().int().positive(),total:M().int().nonnegative(),total_pages:M().int().nonnegative(),has_next:ae(),has_prev:ae(),next_cursor:v().optional(),prev_cursor:v().optional()}),Ae,"Pagination metadata schema");R({id:I,user_id:I,type:ie(["new_message","track_uploaded","user_mentioned","system"]),content:v(),read:ae(),created_at:V});R({id:I,playlist_id:I,track_id:I,position:M().int().nonnegative(),added_by:I,added_at:V,track:ms.optional()});R({id:I,playlist_id:I,user_id:I,role:ie(["owner","editor","viewer"]),created_at:V,user:Ve.optional()});function Ia(e,t,r={}){const{normalizeIds:a=!0}=r;let o=t;return a&&typeof t=="object"&&t!==null&&(o=wt(t)),e.parse(o)}function Vt(e,t,r={}){try{return{success:!0,data:Ia(e,t,r)}}catch(a){if(a instanceof Et)return{success:!1,error:a};throw a}}const $e=v().email("Invalid email format"),dt=v().min(8,"Password must be at least 8 characters"),ut=v().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");R({email:$e,password:v().min(1,"Password is required")});R({username:ut,email:$e,password:dt,first_name:v().max(100).optional(),last_name:v().max(100).optional()});R({code:v().min(6,"TOTP code must be at least 6 characters").max(6,"TOTP code must be exactly 6 characters"),secret:v().min(1,"Secret is required")});R({password:dt});R({username:ut,email:$e,password:dt});R({username:ut.optional(),email:$e.optional(),password:dt.optional()});R({first_name:v().max(100).optional(),last_name:v().max(100).optional(),username:ut.optional(),bio:v().max(500).optional(),location:v().max(100).optional(),birthdate:v().regex(/^\d{4}-\d{2}-\d{2}$/,"Invalid date format. Use YYYY-MM-DD").optional(),gender:ie(["Male","Female","Other","Prefer not to say"]).optional()});R({conversation_id:I,content:v().min(1,"Message content is required"),message_type:ie(["text","image","audio","file"]).optional(),attachment_url:v().url().optional()});R({content:v().min(1,"Message content is required").optional()});R({name:v().min(1,"Conversation name is required"),type:ie(["direct","group"]),participant_ids:de(I).min(1,"At least one participant is required")});R({name:v().min(1,"Conversation name is required").optional()});R({track_ids:de(I).min(1,"At least one track ID is required")});R({filename:v().min(1,"Filename is required"),total_chunks:M().int().min(1,"Total chunks must be at least 1"),total_size:M().int().min(1,"Total size must be at least 1")});R({upload_id:v().min(1,"Upload ID is required")});R({upload_id:v().min(1,"Upload ID is required"),chunk_number:M().int().min(0,"Chunk number must be non-negative"),total_chunks:M().int().min(1,"Total chunks must be at least 1"),total_size:M().int().min(1,"Total size must be at least 1"),filename:v().min(1,"Filename is required")});R({event_name:v().min(1,"Event name is required").max(100,"Event name must be at most 100 characters"),payload:Ue(ke()).optional()});R({url:v().url("Invalid webhook URL"),events:de(v()).min(1,"At least one event is required"),secret:v().min(1,"Secret is required").optional()});R({level:v().optional(),message:v().optional(),context:Ue(ke()).optional(),timestamp:v().optional(),data:ke().optional()});R({email:$e});R({title:v().min(1,"Track title is required"),artist_id:I,album_id:I.optional(),genre:v().min(1,"Genre is required")});R({title:v().min(1,"Track title is required").optional(),artist_id:I.optional(),album_id:I.optional(),genre:v().min(1,"Genre is required").optional()});const Qe=R({page:M().int().positive().optional(),limit:M().int().positive().max(100).optional(),cursor:v().optional()});Qe.extend({query:v().optional()});Qe.extend({conversation_id:I});Qe.extend({query:v().optional()});Qe.extend({artist:v().optional(),genre:v().optional()});Qe.extend({query:v().min(1,"Search query is required")});R({type:ie(["image","audio","document"])});function Pa(e,t){return e.parse(t)}function La(e,t){try{return{success:!0,data:Pa(e,t)}}catch(r){if(r instanceof Et)return{success:!1,error:r};throw r}}const $t={limit:null,remaining:null,reset:null,retryAfter:null,isLimited:!1,lastUpdated:null},kt=tt()(st(e=>({...$t,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,o=t.reset!==null&&t.reset!==void 0?typeof t.reset=="string"?parseInt(t.reset,10):t.reset:null,l=t.retryAfter!==null&&t.retryAfter!==void 0?typeof t.retryAfter=="string"?parseInt(t.retryAfter,10):t.retryAfter:null,n=a!==null&&a<=0||l!==null;e({limit:r,remaining:a,reset:o,retryAfter:l,isLimited:n,lastUpdated:Date.now()})},clearRateLimit:()=>{e($t)}}),{name:"rate-limit-storage",partialize:e=>({limit:e.limit,remaining:e.remaining,reset:e.reset,retryAfter:e.retryAfter,isLimited:e.isLimited,lastUpdated:null})}));class qa{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 St=new qa,Qt={failureRateThreshold:5,minValidationsForAlert:10,checkInterval:300*1e3};class Da{config=Qt;checkIntervalId=null;lastAlertTime=0;alertCooldown=900*1e3;start(t){this.checkIntervalId&&this.stop(),this.config={...Qt,...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=St.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,m.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 Oa=new Da;typeof window<"u"&&Oa.start();const Ma={DEFAULT:1e4,UPLOAD:3e5,LONG_POLLING:3e4},Bt=1e3,O=Me.create({baseURL:lt.API_URL,timeout:Ma.DEFAULT,headers:{"Content-Type":"application/json"},withCredentials:!0});let gt=!1,Ne=[];const za=e=>new Promise(t=>setTimeout(t,e)),Se={maxRetries:3,baseDelay:1e3,maxDelay:1e4,retryableStatusCodes:[500,502,503,504],retryableNetworkErrors:["ECONNABORTED","ETIMEDOUT","ENOTFOUND","ECONNREFUSED","ECONNRESET","EAI_AGAIN","Network Error"]},_t=e=>e?["GET","HEAD","OPTIONS"].includes(e.toUpperCase()):!1;class Ua{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 Tt=new Ua,hs=e=>!!(e.response?.status===206||e.code==="ECONNABORTED"&&e.message?.toLowerCase().includes("timeout")&&e.request||e.code==="ECONNRESET"&&e.response||Tt.isPartialFailure()),Fa=e=>!!(!e.response&&!e.request||e.code==="ECONNREFUSED"||e.code==="ERR_CONNECTION_REFUSED"||e.code==="ENETUNREACH"||e.code==="ERR_NETWORK"||e.code==="ERR_INTERNET_DISCONNECTED"||Tt.isCompleteFailure()),Va=(e,t=Se)=>{if(Me.isCancel(e)||e.config?._disableRetry)return!1;if(hs(e))return _t(e.config?.method);if(e.response?.status)return t.retryableStatusCodes.includes(e.response.status);if(e.code)return t.retryableNetworkErrors.includes(e.code);if(e.message){const r=e.message.toLowerCase();return["network","timeout","connection","econn","etimedout","enotfound"].some(o=>r.includes(o))}return!e.response&&e.request?_t(e.config?.method):!1},$a=(e,t,r=Se.baseDelay,a=Se.maxDelay)=>{const o=e.response?.headers["retry-after"]||e.response?.headers["Retry-After"];if(o){const c=parseInt(String(o),10);if(!isNaN(c)&&c>0)return Math.min(c*1e3,a)}const l=r*Math.pow(2,t),n=Math.random()*r;return Math.min(l+n,a)},_e=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 o=a.toLowerCase();t.some(l=>o.includes(l))?r[a]="[REDACTED]":typeof r[a]=="object"&&r[a]!==null&&(r[a]=_e(r[a]))}return r},Oe=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=>{Ne.forEach(t=>{e?t.reject(e):t.resolve(void 0)}),Ne=[]};O.interceptors.request.use(async e=>{const t=Date.now();e._requestStartTime=t,e._isSlowRequest=!1,e.headers&&(e.headers["X-API-Version"]=lt.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||""),o=e.url?.includes("/auth/login")||e.url?.includes("/auth/register"),l=e.url?.includes("/csrf-token");if(a&&!l&&!o&&e.headers){let c=oe.getToken();if(!c)try{c=await oe.ensureToken()}catch{m.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 n=e?._requestSchema;if(n&&e.data!==void 0&&e.data!==null&&!(e.data instanceof FormData)){const c=La(n,e.data);if(!c.success){const i=Oe(e);m.warn("[API Request Validation Error]",{request_id:i,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 h=c.error?.errors.map(u=>`${u.path.join(".")}: ${u.message}`).join(", ")||"Request validation failed";throw new Error(`Request validation failed: ${h}`)}e.data=c.data}if(e._requestStartTime=Date.now(),e?._enableLogging){const c=Oe(e),i=_e({...e.headers}),h=_e(e.data);m.debug(`[API Request] ${r||"GET"} ${e.url}`,{request_id:c,method:r||"GET",url:e.url,baseURL:e.baseURL,headers:i,params:e.params,data:h,timeout:e.timeout,signal:e.signal?"AbortController":void 0})}return e},e=>Promise.reject(e));O.interceptors.response.use(e=>{Tt.recordRequest(!0);const t=e.config?._requestStartTime;if(t){const g=Date.now()-t;g>Bt&&(e.config._isSlowRequest=!0,e.config._requestDuration=g,e.config?._enableLogging&&m.debug(`[API Slow Request] ${e.config?.method?.toUpperCase()} ${e.config?.url} took ${g}ms`,{duration:g,threshold:Bt}))}const a=e.headers["x-request-id"]||e.headers["X-Request-ID"]||e.config?._requestId;a&&zt({request_id:a});const o=e.headers["x-ratelimit-limit"]||e.headers["X-RateLimit-Limit"],l=e.headers["x-ratelimit-remaining"]||e.headers["X-RateLimit-Remaining"],n=e.headers["x-ratelimit-reset"]||e.headers["X-RateLimit-Reset"];if((o||l||n)&&kt.getState().updateRateLimit({limit:o,remaining:l,reset:n,retryAfter:null}),e.config?._enableLogging){const g=_e(e.data),x=_e(e.headers);m.debug(`[API Response] ${e.config.method?.toUpperCase()||"GET"} ${e.config.url} ${e.status}`,{request_id:a,status:e.status,statusText:e.statusText,headers:x,data:g,duration:e.config?._requestStartTime?Date.now()-e.config._requestStartTime:void 0})}if((e.headers["x-api-deprecated"]||e.headers["X-API-Deprecated"])==="true"){const g="api_deprecation_warning_shown";if(typeof window<"u"&&!sessionStorage.getItem(g)){const x=e.headers.sunset||e.headers.Sunset,y=x?`This API version is deprecated and will be removed on ${x}. Please update to the latest version.`:"This API version is deprecated. Please update to the latest version.";ee(y,{icon:"⚠️",duration:1e4}),sessionStorage.setItem(g,"true"),m.warn("[API] Deprecated API version detected",{url:e.config.url,version:e.headers["x-api-version"]||e.headers["X-API-Version"],sunset_date:x})}}if(!e.data||typeof e.data!="object")return e;const h=e.config.method?.toUpperCase(),u=["POST","PUT","PATCH","DELETE"].includes(h||"");if(u&&e.config?._showSuccessToast&&typeof window<"u"){const g=e.config?._successMessage||e.data?.message||Qa(h||"");g&&ee.success(g)}if(h==="GET"&&!e.config?._disableCache&&je.set(e.config,e),u){const g=e.config.url||"";e.config.method,Ca(g)}if("success"in e.data){if(e.data.success===!0){const g=e.data.data!==void 0?e.data.data:null,x=e.config?._responseSchema;if(x&&g!==null){const y=Vt(x,g);if(y.success){const k=Oe(e.config);m.debug("[API Response Validation Success]",{request_id:k,url:e.config.url}),St.recordSuccess(e.config.url)}else{const k=Oe(e.config),C={request_id:k,url:e.config.url,method:e.config.method?.toUpperCase(),status:e.status,error_type:"api_response_validation_failed",validation_errors:y.error?.errors.map(w=>({path:w.path.join("."),message:w.message,code:w.code,received:w.code==="invalid_type"?w.received:void 0,expected:w.code==="invalid_type"?w.expected:void 0})),response_data_preview:JSON.stringify(g).substring(0,200),schema_provided:!!x,timestamp:new Date().toISOString()};m.error("[API Response Validation Failed]",C,y.error),St.recordFailure(e.config.url);const E=e.config?._validationRecovery,d=E?.useCache!==!1,b=E?.retry===!0,j=E?.notifyUser!==!1;if(d&&h==="GET"){const w=je.get(e.config);if(w){let _=w.data;if(_&&typeof _=="object"&&"success"in _&&_.success===!0&&(_=_.data!==void 0?_.data:null),_!==null&&Vt(x,_).success)return m.warn("[API Validation Recovery] Using cached response due to validation failure",{request_id:k,url:e.config.url,recovery_type:"cache_fallback"}),j&&typeof window<"u"&&ee("Data may be outdated. Please refresh if issues persist.",{icon:"⚠️",duration:5e3}),{...w,data:_}}}if(b&&!e.config?._validationRetryAttempted)return e.config._validationRetryAttempted=!0,m.warn("[API Validation Recovery] Retrying request due to validation failure",{request_id:k,url:e.config.url,recovery_type:"retry"}),O.request(e.config);j&&typeof window<"u"&&ee("Some data may be incomplete. Please refresh if issues persist.",{icon:"⚠️",duration:5e3})}}return{...e,data:g}}if(e.data.success===!1){const g=e.data.error||e.data;m.error("[API] Response with success=false:",{url:e.config.url,error:g});const x=new rt(g?.message||"Request failed","API_ERROR",e.config,e.request,{...e,status:e.status||400,statusText:e.statusText||"Bad Request",data:{success:!1,error:g}});return Promise.reject(x)}}if(e.data&&typeof e.data=="object"&&!("success"in e.data)){const g=Oe(e.config);m.warn("[API] Received non-wrapped response format (unexpected)",{request_id:g,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(Me.isCancel(e)){const d=e.config?._requestId;return e.config?._enableLogging&&m.debug(`[API Request Cancelled] ${e.config?.method?.toUpperCase()||"GET"} ${e.config?.url}`,{request_id:d}),Promise.reject(e)}const t=e.config;let r=t?._requestId;if(e.response?.headers){const d=e.response.headers["x-request-id"]||e.response.headers["X-Request-ID"];d&&(r=d,zt({request_id:r}));const b=e.response.headers["x-ratelimit-limit"]||e.response.headers["X-RateLimit-Limit"],j=e.response.headers["x-ratelimit-remaining"]||e.response.headers["X-RateLimit-Remaining"],w=e.response.headers["x-ratelimit-reset"]||e.response.headers["X-RateLimit-Reset"],_=e.response.headers["retry-after"]||e.response.headers["Retry-After"];(b||j||w||_)&&kt.getState().updateRateLimit({limit:b,remaining:j,reset:w,retryAfter:_})}const a=t?._enableLogging;if(a&&e.response){const d=_e(e.response.data),b=_e(e.response.headers);m.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:b,data:d,duration:t?._requestStartTime?Date.now()-t._requestStartTime:void 0})}else a&&e.request&&!e.response&&m.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 o=t?.url?.includes("/auth/refresh"),l=t?.url?.includes("/auth/logout");if((e.response?.status===401||e.response?.status===400)&&o)return m.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}),ce.clearTokens(),oe.clearToken(),typeof window<"u"&&(T(async()=>{const{useAuthStore:d}=await Promise.resolve().then(()=>Le);return{useAuthStore:d}},void 0).then(({useAuthStore:d})=>{d.getState().logoutLocal()}).catch(d=>{m.error("[API] Failed to import auth store for logout",{error:d})}),sessionStorage.setItem("auth_error","Votre session a expiré. Veuillez vous reconnecter."),window.location.href="/login"),Promise.reject($(e));if(e.response?.status===401&&l)return m.warn("[API] 401 on /auth/logout - token expired/invalid, clearing tokens locally",{request_id:r,url:t?.url}),ce.clearTokens(),oe.clearToken(),typeof window<"u"&&T(async()=>{const{useAuthStore:d}=await Promise.resolve().then(()=>Le);return{useAuthStore:d}},void 0).then(({useAuthStore:d})=>{d.getState().logoutLocal()}).catch(d=>{m.error("[API] Failed to import auth store for logout",{error:d})}),Promise.reject($(e));if(e.response?.status===401&&t&&!t._retry&&!o&&!l){if(gt)return m.debug("[API] Refresh already in progress, queuing request",{request_id:r,url:t?.url,queue_size:Ne.length}),new Promise((d,b)=>{Ne.push({resolve:d,reject:b})}).then(()=>(m.debug("[API] Replaying queued request after successful refresh",{request_id:r,url:t?.url}),O(t))).catch(d=>(m.error("[API] Queued request failed after refresh",{request_id:r,url:t?.url,error:d}),Promise.reject(d)));t._retry=!0,gt=!0,m.info("[API] Starting token refresh due to 401",{request_id:r,url:t?.url,method:t?.method});try{return await ze(),m.info("[API] Token refresh successful, retrying original request",{request_id:r,url:t?.url,queue_size:Ne.length}),Wt(null),O(t)}catch(d){return m.error("[API] Token refresh failed, logging out",{request_id:r,error:d,queue_size:Ne.length}),Wt(d),ce.clearTokens(),oe.clearToken(),typeof window<"u"&&(T(async()=>{const{useAuthStore:b}=await Promise.resolve().then(()=>Le);return{useAuthStore:b}},void 0).then(({useAuthStore:b})=>{b.getState().logoutLocal()}).catch(b=>{m.error("[API] Failed to import auth store for logout",{error:b})}),sessionStorage.setItem("auth_error","Votre session a expiré. Veuillez vous reconnecter."),window.location.href="/login"),Promise.reject(d)}finally{gt=!1,m.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 d=t.method?.toUpperCase();if(["POST","PUT","DELETE","PATCH"].includes(d||"")){t._csrfRetry=!0;try{const j=await oe.refreshToken();return t.headers&&j&&(t.headers["X-CSRF-Token"]=j),O(t)}catch(j){m.error("[API] Failed to refresh CSRF token after CSRF error",{error:j});const w=$(e);return Promise.reject(w)}}}const c=e.response?.status,i=t?._retryCount||0,h=Se.maxRetries;if(c===429){const d=$(e),b=e.response?.headers["retry-after"]||e.response?.headers["Retry-After"],j=b?parseInt(b,10):60;return m.warn("[API] Rate limit exceeded, not retrying",{url:t?.url,retry_after:j,request_id:d.request_id}),d.message&&ee.error(d.message,{duration:j*1e3}),Promise.reject(d)}const p=h,g=t?.url?.includes("/marketplace/products");if(c===500&&g){m.warn("[API] 500 error on marketplace/products, not retrying (likely empty state)",{url:t?.url,retry_count:i,request_id:$(e).request_id});const d=$(e);return d.httpStatus=c,Promise.reject(d)}if(Va(e,Se)&&t&&i<p){const d=t.method?.toUpperCase(),b=_t(d);if(!b&&c&&c!==500&&c!==502&&c!==503&&c!==504){const W=$(e);return Promise.reject(W)}t._retryCount=i+1;const j=$a(e,i,Se.baseDelay,Se.maxDelay),w=$(e),_=c?`HTTP ${c}`:e.code||"Network Error";return w.request_id?m.warn(`[API Retry] ${_} error, retrying (${i+1}/${p}) - Request ID: ${w.request_id}`,{status:c||"N/A",error_code:e.code||"N/A",retry_count:i+1,max_retries:p,delay_ms:Math.round(j),request_id:w.request_id,url:t?.url,method:t?.method,is_idempotent:b}):m.warn(`[API Retry] ${_} error, retrying (${i+1}/${p})`,{status:c||"N/A",error_code:e.code||"N/A",retry_count:i+1,max_retries:p,delay_ms:Math.round(j),url:t?.url,method:t?.method,is_idempotent:b}),za(j).then(()=>O(t))}if(i>=p){const d=$(e),b=c?`HTTP ${c}`:e.code||"Network Error";return d.request_id?m.error(`[API Error] ${b} error after ${h} retries - Request ID: ${d.request_id}`,{code:d.code,message:d.message,request_id:d.request_id,timestamp:d.timestamp,url:t?.url,method:t?.method}):m.error(`[API Error] ${b} error after ${h} retries`,{code:d.code,message:d.message,timestamp:d.timestamp,url:t?.url,method:t?.method}),Promise.reject(d)}const y=$(e);c===401&&!o&&!l&&typeof window<"u"&&ct(y)==="authentication"&&(ce.clearTokens(),oe.clearToken(),T(async()=>{const{useAuthStore:b}=await Promise.resolve().then(()=>Le);return{useAuthStore:b}},void 0).then(({useAuthStore:b})=>{b.getState().logoutLocal()}).catch(b=>{m.error("[API] Failed to import auth store for logout",{error:b})}),sessionStorage.setItem("auth_error","Votre session a expiré. Veuillez vous reconnecter."),window.location.href="/login");const k=!t?._disableToast&&c!==401&&c!==404&&!Me.isCancel(e),C=!e.response;if(C){const{recordNetworkError:d}=await T(async()=>{const{recordNetworkError:b}=await Promise.resolve().then(()=>To);return{recordNetworkError:b}},void 0);d(y)}const E=C?"network-error-toast":void 0;if(k&&typeof window<"u"){const d=t?.url||"";let b;d.includes("/auth/")?b="auth":d.includes("/tracks")||d.includes("/track/")?b="track":d.includes("/playlists")||d.includes("/playlist/")?b="playlist":d.includes("/upload")?b="upload":d.includes("/conversations")||d.includes("/chat")?b="conversation":d.includes("/search")&&(b="search");const w=ds(y,b,c===422);if(!e.response&&t&&xe.shouldQueueRequest(t)&&(typeof navigator<"u"&&!navigator.onLine||!e.response&&e.request)){const ue=t.method?.toUpperCase(),se=ue==="DELETE"?"low":ue==="POST"?"high":"normal";try{await xe.queueRequest(t,{priority:se}),ee.success("Requête mise en file d'attente. Elle sera envoyée à la reconnexion.",{duration:4e3,id:"offline-queue-toast"})}catch(ve){m.error("[API] Failed to queue request for offline replay",{error:ve})}}const _=hs(e),W=Fa(e);let te=w;C&&(_?te=`${w} ⚠️ Connexion intermittente détectée. Certaines requêtes réussissent, d'autres échouent. La connexion devrait se rétablir automatiquement.`:W?te=`${w} ❌ Aucune connexion réseau. Vérifiez votre connexion internet et réessayez.`:te=`${w} 💡 Vérifiez votre connexion internet. Si le problème persiste, le serveur pourrait être temporairement indisponible.`),(_||W)&&m.warn("[API] Network failure detected",{request_id:r,is_partial_failure:_,is_complete_failure:W,url:t?.url,method:t?.method,error_code:e.code,error_message:e.message}),ee.error(te,{duration:8e3,id:E})}return m.error(`[API Error] ${y.message}`,{request_id:y.request_id||r,code:y.code,message:y.message,timestamp:y.timestamp,details:y.details,context:y.context,url:t?.url,method:t?.method}),Promise.reject(y)});function Qa(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""}}async function fs(e){try{const t=await O.post("/auth/register",{email:e.email,password:e.password,password_confirmation:e.password_confirm,username:e.username});let r,a,o,l;if(t.data?.token?.access_token?(r=t.data.token.access_token,a=t.data.token.refresh_token||"",o=t.data.token.expires_in,l=t.data.user):t.data?.access_token?(r=t.data.access_token,a=t.data.refresh_token||"",o=t.data.expires_in,l=t.data.user):t.data?.Token?.AccessToken?(r=t.data.Token.AccessToken,a=t.data.Token.RefreshToken||"",o=t.data.Token.ExpiresIn,l=t.data.User||t.data.user):(t.data?.User||t.data?.user)&&(l=t.data.User||t.data.user),r&&(ce.setTokens(r,a||""),Nt()),!l)throw new Error("Registration response missing user data");if(!r||o===void 0)throw new Error("Registration response missing tokens. Email verification may be required.");return{user:l,token:{access_token:r,refresh_token:a||"",expires_in:o}}}catch(t){throw $(t)}}async function ps(e){try{const t=await O.post("/auth/login",{email:e.email,password:e.password,remember_me:e.remember_me||!1});let r,a,o,l;if(t.data?.token?.access_token?(r=t.data.token.access_token,a=t.data.token.refresh_token||"",o=t.data.token.expires_in,l=t.data.user):t.data?.access_token?(r=t.data.access_token,a=t.data.refresh_token||"",o=t.data.expires_in,l=t.data.user):t.data?.Token?.AccessToken&&(r=t.data.Token.AccessToken,a=t.data.Token.RefreshToken||"",o=t.data.Token.ExpiresIn,l=t.data.User||t.data.user),t.data?.requires_2fa){if(l||(l=t.data.user||t.data.User),!l)throw new Error("Login response missing user data");return{user:l,token:{access_token:"",refresh_token:"",expires_in:0},requires_2fa:!0}}if(r)ce.setTokens(r,a||""),e.remember_me?localStorage.setItem("remember_me","true"):localStorage.removeItem("remember_me"),Nt();else throw m.error("[AUTH] Tokens not found in login response",{responseData:t.data}),new Error("Login response missing tokens");return{user:l,token:{access_token:r,refresh_token:a||"",expires_in:o||3600},requires_2fa:t.data?.requires_2fa}}catch(t){throw $(t)}}async function gs(){try{await O.post("/auth/logout")}catch(e){m.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{cs(),ce.clearTokens()}}async function ys(){try{return(await O.get("/auth/me")).data}catch(e){throw $(e)}}const Yn={login:ps,register:fs,logout:gs,getMe:ys,refresh:async e=>{const{data:t}=await O.post("/auth/refresh",{refresh_token:e});return t},verifyEmail:async e=>{const{data:t}=await O.post("/auth/verify-email",void 0,{params:{token:e.token}});return t},resendVerification:async e=>{const{data:t}=await O.post("/auth/resend-verification",e);return t},checkUsername:async e=>{const{data:t}=await O.get("/auth/check-username",{params:{username:e.username}});return t},requestPasswordReset:async e=>{const{data:t}=await O.post("/auth/password/reset-request",e);return t},resetPassword:async e=>{const{data:t}=await O.post("/auth/password/reset",e);return t},getOAuthProviders:async()=>{const{data:e}=await O.get("/auth/oauth/providers");return e},initiateOAuth:e=>{window.location.href=`${lt.API_URL}/auth/oauth/${e}`},setup2FA:async()=>{const{data:e}=await O.post("/auth/2fa/setup");return e},verify2FA:async e=>{const{data:t}=await O.post("/auth/2fa/verify",{code:e});return t},disable2FA:async e=>{const{data:t}=await O.post("/auth/2fa/disable",{code:e});return t},get2FAStatus:async()=>{const{data:e}=await O.get("/auth/2fa/status");return e}};function Ba(e){if(typeof window>"u"||!window.BroadcastChannel)return m.warn("[BroadcastSync] BroadcastChannel not supported in this environment"),null;try{return new BroadcastChannel(`veza-store-${e}`)}catch(t){return m.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 xs(e,t={}){return(r,a,o)=>{const l=t.channelName||"default-store",n=t.enabled!==!1,c=t.shouldSync||(()=>!0),i=t.onStateSync;let h=null,u=!1,p=null,g=0;const x=new Set,y=[];if(n&&(h=Ba(l),h)){const C=()=>{if(y.length===0||u)return;y.sort((d,b)=>b.timestamp-d.timestamp);const E=y.shift();E&&E.timestamp>g&&(u=!0,r(E.state),p=E.state,g=E.timestamp,x.size>100&&Array.from(x).slice(0,50).forEach(b=>x.delete(b)),setTimeout(()=>{u=!1,C()},50))};h.onmessage=E=>{const d=E.data;if(!d||typeof d!="object"||!d.type||!d.storeName||typeof d.timestamp!="number"||d.type!=="state-update"&&d.type!=="state-request"&&d.type!=="state-response"||d.storeName!==l)return;const b=d.messageId||`${d.type}-${d.timestamp}-${Math.random()}`;if(!x.has(b)){if(d.type==="state-update"&&d.state){if(u){y.push({state:d.state,timestamp:d.timestamp,messageId:b}),C();return}if(d.timestamp<=g){x.add(b);return}if(c(d.state,p)){x.add(b),u=!0;const j=p;r(d.state);const w=d.state;if(p=w,g=d.timestamp,i)try{i(w,j)}catch(_){m.warn("[BroadcastSync] Error in onStateSync callback",{error:_ instanceof Error?_.message:String(_),stack:_ instanceof Error?_.stack:void 0,storeName:l})}setTimeout(()=>{u=!1,C()},50)}else x.add(b)}else if(d.type==="state-request"){const j=a(),w=JSON.parse(JSON.stringify(j));h&&h.postMessage({type:"state-response",storeName:l,state:w,timestamp:Date.now()})}else if(d.type==="state-response"&&d.state)if(!p||d.timestamp>g){x.add(b),u=!0;const j=p;r(d.state);const w=d.state;if(p=w,g=d.timestamp,i)try{i(w,j)}catch(_){m.warn("[BroadcastSync] Error in onStateSync callback",{error:_ instanceof Error?_.message:String(_),stack:_ instanceof Error?_.stack:void 0,storeName:l})}setTimeout(()=>{u=!1,C()},50)}else x.add(b)}},h.postMessage({type:"state-request",storeName:l,timestamp:Date.now()})}return e((...C)=>{if(u)r(...C);else if(r(...C),h&&n){const E=a();if(c(E,p)){const d=Date.now(),b=`update-${d}-${Math.random()}`,j=JSON.parse(JSON.stringify(E));if(h.postMessage({type:"state-update",storeName:l,state:j,timestamp:d,messageId:b}),i)try{i(E,p)}catch(w){m.warn("[BroadcastSync] Error in onStateSync callback",{error:w instanceof Error?w.message:String(w),stack:w instanceof Error?w.stack:void 0,storeName:l})}p=E,g=d}}},a,o)}}const Z=tt()(st(xs(e=>({isAuthenticated:!1,isLoading:!1,error:null,login:async t=>{e({isLoading:!0,error:null});try{await ps(t),e({isAuthenticated:!0,isLoading:!1,error:null}),oe.refreshToken().catch(r=>{m.warn("Failed to fetch CSRF token after login",{error:r instanceof Error?r.message:String(r),stack:r instanceof Error?r.stack:void 0})})}catch(r){throw e({error:$(r),isLoading:!1,isAuthenticated:!1}),r}},register:async t=>{e({isLoading:!0,error:null});try{const a=!!(await fs(t)).token?.access_token;e({isAuthenticated:a,isLoading:!1,error:null}),a&&oe.refreshToken().catch(o=>{m.warn("Failed to fetch CSRF token after register",{error:o instanceof Error?o.message:String(o),stack:o instanceof Error?o.stack:void 0})})}catch(r){throw e({error:$(r),isLoading:!1,isAuthenticated:!1}),r}},logout:async()=>{e({isLoading:!0});try{await gs()}catch(t){m.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}),oe.clearToken()}},logoutLocal:()=>{m.info("[Auth] Performing local logout (no API call)",{}),ce.clearTokens(),T(async()=>{const{cleanupProactiveRefresh:t}=await Promise.resolve().then(()=>na);return{cleanupProactiveRefresh:t}},void 0).then(({cleanupProactiveRefresh:t})=>{t()}).catch(t=>{m.warn("Failed to cleanup proactive refresh",{error:t instanceof Error?t.message:String(t)})}),oe.clearToken(),e({isAuthenticated:!1,isLoading:!1,error:null})},refreshUser:async()=>{const t=Z.getState();{t.isAuthenticated||e({isAuthenticated:!1,isLoading:!1});return}},checkAuthStatus:async()=>{{Z.getState().isAuthenticated||e({isAuthenticated:!1,isLoading:!1});return}},clearError:()=>e({error:null}),setLoading:t=>e({isLoading:t})}),{channelName:"auth-store",enabled:!0,shouldSync:(e,t)=>{const r=e,a=t;return r.isAuthenticated!==a?.isAuthenticated}}),{name:"auth-storage",partialize:e=>({isAuthenticated:e.isAuthenticated})})),Le=Object.freeze(Object.defineProperty({__proto__:null,useAuthStore:Z},Symbol.toStringTag,{value:"Module"})),Ee=tt()(Jt(st(xs(e=>({theme:"dark",language:"en",sidebarOpen:!0,notifications:[],setTheme:t=>{e({theme:t});const r=document.documentElement;if(t==="system"){const a=window.matchMedia("(prefers-color-scheme: dark)").matches;r.classList.remove("light","dark"),r.classList.add(a?"dark":"light"),r.setAttribute("data-theme",a?"dark":"light")}else r.classList.remove("light","dark"),r.classList.add(t),r.setAttribute("data-theme",t)},setLanguage:t=>{e({language:t}),typeof window<"u"&&window.i18n&&window.i18n.changeLanguage(t)},setSidebarOpen:t=>e({sidebarOpen:t}),addNotification:t=>{const r={...t,id:crypto.randomUUID(),timestamp:new Date().toISOString()};e(a=>({notifications:[...a.notifications,r]}))},removeNotification:t=>{e(r=>({notifications:r.notifications.filter(a=>a.id!==t)}))},markNotificationAsRead:t=>{e(r=>({notifications:r.notifications.map(a=>a.id===t?{...a,read:!0}:a)}))},clearNotifications:()=>e({notifications:[]})}),{channelName:"ui-store",enabled:!0,shouldSync:(e,t)=>e.theme!==t?.theme||e.language!==t?.language||e.sidebarOpen!==t?.sidebarOpen}),{name:"ui-storage",partialize:e=>({theme:e.theme,language:e.language,sidebarOpen:e.sidebarOpen})}),{name:"UIStore",enabled:!1}));function S(...e){return Zt(es(e))}const Wa=ts("inline-flex items-center justify-center whitespace-nowrap rounded-xl text-sm font-medium transition-colors duration-200 focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-kodo-cyan focus-visible:ring-offset-2 focus-visible:ring-offset-kodo-void disabled:pointer-events-none disabled:opacity-50 gap-2",{variants:{variant:{default:"bg-kodo-cyan text-kodo-void hover:bg-kodo-cyan-dim hover:shadow-[0_0_15px_rgba(102,252,241,0.3)] border border-transparent font-semibold tracking-tight",primary:"bg-kodo-cyan text-kodo-void hover:bg-kodo-cyan-dim hover:shadow-[0_0_15px_rgba(102,252,241,0.3)] border border-transparent font-semibold tracking-tight",destructive:"bg-kodo-red/10 text-kodo-red hover:bg-kodo-red/20 border border-kodo-red/30 hover:border-kodo-red/50",outline:"border border-kodo-steel bg-transparent text-white hover:bg-white/5 hover:border-kodo-steel/50",secondary:"bg-kodo-steel/30 text-white hover:bg-kodo-steel/50 border border-white/5 hover:border-white/10",ghost:"hover:bg-white/5 text-white",gaming:"bg-kodo-slate border border-kodo-gold/40 text-kodo-gold hover:bg-kodo-gold/10 hover:border-kodo-gold font-bold tracking-wider uppercase",terminal:"bg-kodo-ink border border-kodo-steel text-gray-300 font-mono text-xs hover:border-kodo-cyan hover:text-kodo-cyan",nature:"bg-kodo-slate border border-kodo-lime/30 text-kodo-lime hover:bg-kodo-lime/10"},size:{default:"h-10 px-4 py-2",sm:"h-8 rounded-lg px-4 text-xs",lg:"h-12 rounded-xl px-8 text-base",icon:"h-10 w-10"}},defaultVariants:{variant:"default",size:"default"}}),z=f.forwardRef(({className:e,variant:t,size:r,asChild:a=!1,icon:o,children:l,...n},c)=>{const i=a?Ws:"button";return s.jsxs(i,{className:S(Wa({variant:t,size:r,className:e})),ref:c,...n,children:[o&&s.jsx("span",{className:"flex items-center justify-center pointer-events-none",children:o}),l]})});z.displayName="Button";const Ka=ts("rounded-2xl shadow-lg backdrop-blur-md relative overflow-hidden transition-colors duration-200 z-10",{variants:{variant:{default:"bg-[rgba(var(--glass-card-bg-base),var(--glass-card-bg-opacity))] backdrop-blur-xl border border-[rgba(var(--glass-card-border),var(--glass-card-border-opacity))] hover:border-[rgba(var(--glass-card-border),0.4)] text-[rgb(var(--kodo-text-main))] shadow-lg transition-all duration-300",manga:"bg-gradient-to-br from-[rgba(var(--kodo-graphite),0.8)] to-[rgba(var(--kodo-slate),0.8)] border border-[rgba(var(--kodo-magenta),0.3)] hover:border-[rgb(var(--kodo-magenta))] hover:shadow-[0_0_20px_rgba(var(--kodo-magenta),0.2)] text-[rgb(var(--kodo-text-main))] backdrop-blur-md transition-all duration-300",gaming:"bg-[rgba(var(--kodo-ink),0.9)] border border-[rgba(var(--kodo-cyan),0.3)] hover:border-[rgb(var(--kodo-cyan))] hover:shadow-[0_0_20px_rgba(var(--kodo-cyan),0.25)] text-[rgb(var(--kodo-text-main))] backdrop-blur-md transition-all duration-300",glass:"bg-[rgba(255,255,255,0.05)] backdrop-blur-[24px] border border-[rgba(255,255,255,0.2)] hover:bg-[rgba(255,255,255,0.1)] text-[rgb(var(--kodo-text-main))] transition-all duration-300"}},defaultVariants:{variant:"default"}}),vs=f.forwardRef(({className:e,variant:t,...r},a)=>s.jsx("div",{ref:a,className:S(Ka({variant:t,className:e})),...r,children:r.children}));vs.displayName="Card";const Ha=f.forwardRef(({className:e,...t},r)=>s.jsx("div",{ref:r,className:S("flex flex-col space-y-1.5 p-8",e),...t}));Ha.displayName="CardHeader";const Ga=f.forwardRef(({className:e,...t},r)=>s.jsx("h3",{ref:r,className:S("font-semibold leading-none tracking-tight text-white",e),...t}));Ga.displayName="CardTitle";const Ya=f.forwardRef(({className:e,...t},r)=>s.jsx("p",{ref:r,className:S("text-sm text-kodo-secondary",e),...t}));Ya.displayName="CardDescription";const bs=f.forwardRef(({className:e,...t},r)=>s.jsx("div",{ref:r,className:S("p-8 pt-0",e),...t}));bs.displayName="CardContent";const Xa=f.forwardRef(({className:e,...t},r)=>s.jsx("div",{ref:r,className:S("flex items-center p-8 pt-0",e),...t}));Xa.displayName="CardFooter";function ws({children:e,active:t=!0,onEscape:r}){const a=f.useRef(null),o=f.useRef(null);return f.useEffect(()=>{if(!t||!a.current)return;o.current=document.activeElement;const l=a.current.querySelectorAll('button, [href], input, select, textarea, [tabindex]:not([tabindex="-1"])'),n=l[0],c=l[l.length-1];n&&n.focus();const i=h=>{if(h.key==="Escape"){r?.();return}h.key==="Tab"&&(h.shiftKey?document.activeElement===n&&(h.preventDefault(),c?.focus()):document.activeElement===c&&(h.preventDefault(),n?.focus()))};return document.addEventListener("keydown",i),()=>{document.removeEventListener("keydown",i),o.current instanceof HTMLElement&&o.current.focus()}},[t,r]),s.jsx("div",{ref:a,tabIndex:-1,children:e})}const Ja={sm:"max-w-sm",md:"max-w-md",lg:"max-w-2xl",xl:"max-w-4xl",full:"max-w-full m-4 h-[calc(100vh-2rem)]"};function Za({open:e,onClose:t,children:r,title:a,closeOnOverlayClick:o=!0,closeOnEscape:l=!0,size:n="md",className:c,footer:i}){const h=f.useRef(null);if(f.useEffect(()=>{if(e)return document.body.style.overflow="hidden",()=>{document.body.style.overflow=""}},[e]),f.useEffect(()=>{if(!l||!e)return;const p=g=>{g.key==="Escape"&&t()};return document.addEventListener("keydown",p),()=>document.removeEventListener("keydown",p)},[e,l,t]),!e)return null;const u=p=>{o&&p.target===p.currentTarget&&t()};return zs.createPortal(s.jsxs("div",{className:"fixed inset-0 z-[100] flex items-center justify-center p-4",onClick:u,children:[s.jsx("div",{className:"absolute inset-0 bg-kodo-void/90 backdrop-blur-sm animate-fadeIn"}),s.jsx(ws,{children:s.jsxs("div",{ref:h,className:S("relative w-full bg-kodo-graphite border border-kodo-steel rounded-xl shadow-2xl flex flex-col overflow-hidden animate-scaleIn",Ja[n],c),onClick:p=>p.stopPropagation(),children:[a&&s.jsxs("div",{className:"p-4 border-b border-kodo-steel bg-kodo-ink flex justify-between items-center shrink-0",children:[s.jsx("h3",{className:"font-bold text-white text-lg font-display",children:a}),s.jsx(z,{variant:"ghost",size:"icon",onClick:t,className:"ml-auto",children:s.jsx(at,{className:"w-5 h-5"})})]}),s.jsx("div",{className:"p-8 overflow-y-auto custom-scrollbar flex-1",children:r}),i&&s.jsx("div",{className:"p-4 border-t border-kodo-steel bg-kodo-ink shrink-0 flex justify-end gap-4",children:i})]})})]}),document.body)}const eo={alert:Re,confirm:Re,info:ot,default:void 0},to={alert:"text-kodo-red",confirm:"text-kodo-cyan",info:"text-kodo-steel",default:""};function Ct({open:e,onClose:t,onOpenChange:r,title:a,children:o,footer:l,variant:n="default",onConfirm:c,onCancel:i,confirmLabel:h="Confirm",cancelLabel:u="Cancel",showCancel:p=!0,size:g="md"}){const x=()=>{r?r(!1):t&&t()},y=async()=>{c&&await c(),x()},k=()=>{i&&i(),x()},C=eo[n],E=to[n];return s.jsxs(Za,{open:e,onClose:x,size:g,closeOnOverlayClick:n==="default",title:a,footer:l||c||i?l||s.jsxs("div",{className:"flex justify-end gap-2",children:[p&&s.jsx(z,{variant:"outline",onClick:k,children:u}),c&&s.jsx(z,{variant:n==="alert"?"destructive":"default",onClick:y,children:h})]}):void 0,children:[a&&C&&s.jsx("div",{className:"flex items-center gap-4 mb-4",children:s.jsx(C,{className:S("h-5 w-5",E)})}),o]})}function Xn({children:e,variant:t="default",className:r}){return s.jsx("div",{className:S("p-8",t==="alert"&&"text-kodo-red",r),children:e})}function Jn({children:e,className:t}){return s.jsx("div",{className:S("flex items-center justify-end gap-2 p-8 border-t border-kodo-steel",t),children:e})}function so(e,t){const r=$(e),a=ct(r),o=typeof navigator<"u"?navigator.userAgent:"Unknown",l=typeof window<"u"?window.location.href:"Unknown",n=new Date().toISOString(),c=`[${a.toUpperCase()}] ${r.message||"Unknown error"}`,i=[];i.push("## 🐞 Error Details"),i.push(""),i.push(`**Message:** ${r.message||"No message provided"}`),r.code!==void 0&&i.push(`**Error Code:** ${r.code}`),r.status!==void 0&&i.push(`**HTTP Status:** ${r.status}`),r.request_id&&i.push(`**Request ID:** \`${r.request_id}\``),i.push(`**Category:** ${a}`),i.push(`**Timestamp:** ${n}`),i.push(""),t&&(i.push("## 📍 Context"),i.push(""),t.component&&i.push(`**Component:** ${t.component}`),t.action&&i.push(`**Action:** ${t.action}`),t.userId&&i.push(`**User ID:** ${t.userId}`),t.additionalInfo&&Object.keys(t.additionalInfo).length>0&&(i.push("**Additional Info:**"),i.push("```json"),i.push(JSON.stringify(t.additionalInfo,null,2)),i.push("```")),i.push("")),r.details&&(i.push("## 🔍 Error Details"),i.push(""),i.push("```json"),i.push(JSON.stringify(r.details,null,2)),i.push("```"),i.push("")),r.errors&&Object.keys(r.errors).length>0&&(i.push("## ⚠️ Validation Errors"),i.push(""),Object.entries(r.errors).forEach(([u,p])=>{i.push(`- **${u}:** ${Array.isArray(p)?p.join(", "):p}`)}),i.push("")),i.push("## 💻 Environment"),i.push(""),i.push(`**URL:** ${l}`),i.push(`**User Agent:** ${o}`),i.push(`**Browser:** ${oo(o)}`),i.push(`**Platform:** ${io(o)}`),typeof window<"u"&&(i.push(`**Screen:** ${window.screen.width}x${window.screen.height}`),i.push(`**Viewport:** ${window.innerWidth}x${window.innerHeight}`)),i.push(""),i.push("## 🔁 Steps to Reproduce"),i.push(""),i.push("1. [Describe step 1]"),i.push("2. [Describe step 2]"),i.push("3. [Describe step 3]"),i.push(""),i.push("## ✅ Expected Behavior"),i.push(""),i.push("[Describe what should have happened]"),i.push("");const h=i.join(`
`);return{title:c,body:h,metadata:{requestId:r.request_id,errorCode:r.code,statusCode:r.status,category:a,timestamp:n,userAgent:o,url:l}}}async function ks(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 ro(e,t){const r=ao();if(!r){ks(e);return}const a=new URLSearchParams({title:e.title,body:e.body}),o=`${r}/issues/new?${a.toString()}`;window.open(o,"_blank")}function ao(){return null}function oo(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 io(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 Kt(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=$(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 Ss=f.forwardRef(({error:e,onRetry:t,onDismiss:r,showDetails:a,context:o,variant:l="inline",severity:n="error",size:c="md",className:i,dismissible:h,title:u,icon:p,actions:g=[],...x},y)=>{const[k,C]=f.useState(!1),[E,d]=f.useState(!1),[b,j]=f.useState(!0),w=f.useMemo(()=>Kt(e),[e]),_=f.useMemo(()=>$(e),[e]),W=f.useMemo(()=>ct(_),[_]),te=f.useMemo(()=>{const N=Kt(e);return W==="server_error"||N.status!==void 0&&N.status>=500},[W,e]),ue=a??!1,se=f.useMemo(()=>{if(w.message)try{return ds(w,o?.resource,!1)}catch{return w.message}return"An unexpected error occurred"},[w,o]),ve=f.useMemo(()=>{if(u)return u;if(o?.action)return`Error ${o.action}`;switch(n){case"error":return"Error";case"warning":return"Warning";case"info":return"Information";default:return"Error"}},[u,o,n]),Q=f.useMemo(()=>{if(p)return p;const N=c==="sm"?"w-4 h-4":c==="lg"?"w-6 h-6":"w-5 h-5";switch(n){case"error":return s.jsx(Re,{className:S(N,"text-kodo-red")});case"warning":return s.jsx(it,{className:S(N,"text-kodo-gold")});case"info":return s.jsx(ot,{className:S(N,"text-kodo-steel")});default:return s.jsx(Re,{className:S(N,"text-kodo-red")})}},[p,n,c]),H=f.useMemo(()=>{switch(n){case"error":return{bg:"bg-kodo-red/10",border:"border-kodo-red/30",text:"text-kodo-red",icon:"text-kodo-red"};case"warning":return{bg:"bg-kodo-gold/10",border:"border-kodo-gold/30",text:"text-kodo-gold",icon:"text-kodo-gold"};case"info":return{bg:"bg-kodo-steel/10",border:"border-kodo-steel/30",text:"text-kodo-steel",icon:"text-kodo-steel"};default:return{bg:"bg-kodo-red/10",border:"border-kodo-red/30",text:"text-kodo-red",icon:"text-kodo-red"}}},[n]),ne=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]),be=f.useCallback(async()=>{if(!(!t||E)){d(!0);try{await t()}finally{d(!1)}}},[t,E]),G=f.useCallback(()=>{r&&r(),l==="modal"&&j(!1)},[r,l]),re=f.useCallback(async()=>{try{const N=so(e,{component:o?.resource,action:o?.action,userId:o?.userId,additionalInfo:o});try{ro(N),ee.success("Opening GitHub issue...")}catch{await ks(N),ee.success("Issue report copied to clipboard")}}catch{ee.error("Failed to generate issue report")}},[e,o]),pe=f.useCallback(async()=>{if(_.request_id)try{if(typeof navigator<"u"&&navigator.clipboard&&navigator.clipboard.writeText)await navigator.clipboard.writeText(_.request_id),ee.success("Request ID copied to clipboard");else{const N=document.createElement("textarea");N.value=_.request_id,N.style.position="fixed",N.style.opacity="0",document.body.appendChild(N),N.select();try{document.execCommand("copy"),ee.success("Request ID copied to clipboard")}finally{document.body.removeChild(N)}}}catch{ee.error("Failed to copy request ID")}},[_.request_id]),we=h??(r!==void 0||l==="modal"),Y=()=>{if(!ue||!k)return null;const N=[];return _.request_id&&N.push({label:"Request ID",value:_.request_id}),w.code&&N.push({label:"Error Code",value:String(w.code)}),w.status&&N.push({label:"HTTP Status",value:String(w.status)}),w.details&&N.push({label:"Details",value:JSON.stringify(w.details,null,2)}),w.stack&&N.push({label:"Stack Trace",value:w.stack}),o&&N.push({label:"Context",value:JSON.stringify(o,null,2)}),N.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:N.map((B,mt)=>s.jsxs("div",{className:"text-xs",children:[s.jsxs("span",{className:"font-semibold opacity-70",children:[B.label,":"]}),s.jsx("pre",{className:"mt-1 p-2 bg-black/20 rounded text-xs overflow-x-auto",children:typeof B.value=="string"?B.value:JSON.stringify(B.value,null,2)})]},mt))})})},K=s.jsxs("div",{ref:y,role:"alert","aria-live":"polite",className:S("rounded-lg border flex",H.bg,H.border,H.text,ne.padding,ne.gap,i),...x,children:[s.jsx("div",{className:"flex-shrink-0",children:Q}),s.jsxs("div",{className:"flex-1 min-w-0",children:[s.jsx("div",{className:S("font-semibold mb-1",ne.title),children:ve}),s.jsx("div",{className:S("opacity-90",ne.text),children:se}),Y(),(t||g.length>0||te||ue&&(w.code||w.details||w.stack||o))&&s.jsxs("div",{className:"mt-4 flex flex-wrap gap-2 items-center",children:[t&&s.jsx(z,{variant:"outline",size:c==="sm"?"sm":"default",onClick:be,disabled:E,className:"border-current text-current hover:bg-current/10",children:E?"Retrying...":"Retry"}),te&&_.request_id&&s.jsxs(s.Fragment,{children:[s.jsxs(z,{variant:"outline",size:c==="sm"?"sm":"default",onClick:pe,className:"border-current text-current hover:bg-current/10",title:"Copy Request ID to clipboard",children:[s.jsx(It,{className:"w-4 h-4 mr-1.5"}),"Copy Request ID"]}),s.jsxs(z,{variant:"outline",size:c==="sm"?"sm":"default",onClick:re,className:"border-current text-current hover:bg-current/10",children:[s.jsx(Pt,{className:"w-4 h-4 mr-1.5"}),"Report Issue"]})]}),g.map((N,B)=>s.jsx(z,{variant:N.variant||"outline",size:c==="sm"?"sm":"default",onClick:N.onClick,className:"border-current text-current hover:bg-current/10",children:N.label},B)),ue&&(w.code||w.details||w.stack||o)&&s.jsx(z,{variant:"ghost",size:c==="sm"?"sm":"default",onClick:()=>C(!k),className:"text-current hover:bg-current/10",children:k?s.jsxs(s.Fragment,{children:[s.jsx(Js,{className:"w-4 h-4 mr-1"}),"Hide Details"]}):s.jsxs(s.Fragment,{children:[s.jsx(Zs,{className:"w-4 h-4 mr-1"}),"Show Details"]})})]})]}),we&&s.jsx("button",{onClick:G,className:"opacity-70 hover:opacity-100 transition-opacity flex-shrink-0","aria-label":"Dismiss error",children:s.jsx(at,{className:S(c==="sm"?"w-4 h-4":"w-5 h-5")})})]});switch(l){case"banner":return s.jsx("div",{className:"w-full",children:K});case"card":return s.jsx(vs,{className:S(H.border,i),children:s.jsx(bs,{className:S(ne.padding,"pt-6"),children:K})});case"modal":return s.jsx(Ct,{open:b,onClose:G,title:ve,variant:n==="error"||n==="warning"?"alert":"info",footer:s.jsxs("div",{className:"flex gap-2 justify-end",children:[t&&s.jsx(z,{variant:"outline",onClick:be,disabled:E,children:E?"Retrying...":"Retry"}),te&&_.request_id&&s.jsxs(s.Fragment,{children:[s.jsxs(z,{variant:"outline",onClick:pe,title:"Copy Request ID to clipboard",children:[s.jsx(It,{className:"w-4 h-4 mr-1.5"}),"Copy Request ID"]}),s.jsxs(z,{variant:"outline",onClick:re,children:[s.jsx(Pt,{className:"w-4 h-4 mr-1.5"}),"Report Issue"]})]}),g.map((N,B)=>s.jsx(z,{variant:N.variant||"outline",onClick:N.onClick,children:N.label},B)),s.jsx(z,{variant:"default",onClick:G,children:t?"Close":"Dismiss"})]}),children:s.jsxs("div",{className:S(H.text),children:[s.jsxs("div",{className:S("opacity-90 mb-4",ne.text),children:[se,te&&_.request_id&&s.jsxs("div",{className:"mt-2 text-xs opacity-75",children:["Request ID:"," ",s.jsx("code",{className:"bg-black/20 px-1.5 py-0.5 rounded",children:_.request_id})]})]}),Y()]})});default:return K}});Ss.displayName="ErrorDisplay";class L 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=ta(),o={...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()};m.error("[ErrorBoundary] React error caught",o),typeof window<"u"&&Ks(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.jsx("div",{className:"min-h-screen flex items-center justify-center bg-kodo-void dark:bg-kodo-ink p-4",children:s.jsx("div",{className:"w-full max-w-md",children:s.jsx(Ss,{error:this.state.error||new Error("Une erreur inattendue s'est produite"),variant:"card",severity:"error",size:"lg",showDetails:!1,context:{component:"ErrorBoundary",action:"rendering component",componentStack:this.state.errorInfo?.componentStack},onRetry:this.handleReset,actions:[{label:"Retour à l'accueil",onClick:()=>{window.location.href="/"},variant:"outline"}]})})}):this.props.children}}function J(...e){return Zt(es(e))}const _s=fe.forwardRef(({variant:e="primary",size:t="md",icon:r,children:a,className:o,...l},n)=>{const c="relative inline-flex items-center justify-center font-body font-medium transition-all duration-200 disabled:opacity-50 disabled:cursor-not-allowed focus:outline-none focus:ring-2 focus:ring-offset-2 focus:ring-offset-kodo-void rounded-lg",i={sm:"text-xs px-3 py-1.5 gap-2",md:"text-sm px-5 py-2.5 gap-2",lg:"text-base px-8 py-3.5 gap-3",icon:"p-2.5"},h={primary:"bg-gradient-to-r from-kodo-cyan-dim to-kodo-cyan text-kodo-void hover:shadow-lg hover:shadow-kodo-cyan/20 border border-transparent font-bold tracking-wide",secondary:"bg-transparent border border-kodo-magenta/50 text-kodo-magenta hover:bg-kodo-magenta/5 hover:border-kodo-magenta hover:text-white",ghost:"bg-transparent text-gray-400 hover:text-white hover:bg-white/5",gaming:"bg-kodo-slate border border-kodo-gold/40 text-kodo-gold hover:bg-kodo-gold/10 hover:border-kodo-gold font-bold tracking-wider uppercase",terminal:"bg-kodo-ink border border-kodo-steel text-gray-300 font-mono text-xs hover:border-kodo-cyan hover:text-kodo-cyan",nature:"bg-kodo-slate border border-kodo-lime/30 text-kodo-lime hover:bg-kodo-lime/10",icon:"bg-transparent hover:bg-white/10 text-gray-400 hover:text-white rounded-full p-2"},u=e==="icon"?J(c,h.icon,o):J(c,i[t],h[e],o);return s.jsxs("button",{ref:n,className:u,...l,children:[r&&s.jsx("span",{className:a?"":"flex items-center justify-center",children:r}),a&&s.jsx("span",{children:a})]})});_s.displayName="Button";const no=fe.forwardRef(({variant:e="default",children:t,className:r,onClick:a},o)=>{const l="relative transition-all duration-300 rounded-xl",n={default:"bg-kodo-graphite border border-kodo-steel/60 p-6 shadow-sm hover:border-kodo-steel",manga:"bg-gradient-to-br from-kodo-graphite to-kodo-slate border border-kodo-magenta/20 p-6 hover:border-kodo-magenta/40 hover:shadow-neon-magenta/10",gaming:"bg-kodo-ink border border-kodo-cyan/20 p-6 hover:border-kodo-cyan/40 hover:shadow-neon-cyan/10",glass:"bg-kodo-slate/40 backdrop-blur-xl border border-white/5 p-6 hover:bg-kodo-slate/50"};return s.jsx("div",{ref:o,className:J(l,n[e],a&&"cursor-pointer",r),onClick:a,children:t})});no.displayName="Card";const lo=fe.forwardRef(({label:e,icon:t,className:r,type:a,autoComplete:o,required:l,id:n,...c},i)=>{const h=fe.useId(),u=n||h,p=o!==void 0?o:a==="email"?"email":a==="password"?"current-password":void 0,g=c["aria-describedby"],x=c["aria-invalid"];return s.jsxs("div",{className:"w-full",children:[e&&s.jsx("label",{htmlFor:u,className:"block text-sm font-medium text-gray-400 mb-2 font-body",children:e}),s.jsxs("div",{className:"relative",children:[t&&s.jsx("div",{className:"absolute left-4 top-1/2 -translate-y-1/2 text-gray-500 pointer-events-none",children:t}),s.jsx("input",{ref:i,id:u,type:a,autoComplete:p,required:l,"aria-describedby":g,"aria-invalid":x,className:J("w-full py-3 bg-kodo-graphite border border-kodo-steel text-white placeholder-gray-500 font-body text-base rounded-lg focus-visible:outline-none focus-visible:border-kodo-cyan/60 transition-colors duration-200",t?"pl-11 pr-4":"px-4",r),...c})]})]})});lo.displayName="Input";const co=fe.forwardRef((e,t)=>s.jsxs("div",{className:"relative w-full group",children:[s.jsx("input",{ref:t,type:"search",className:"w-full pl-12 pr-4 py-3 bg-kodo-graphite border border-kodo-steel text-white placeholder-gray-500 rounded-full focus-visible:outline-none focus-visible:border-kodo-cyan/60 transition-colors duration-300",placeholder:"Search platform...",...e}),s.jsx(er,{className:"absolute left-4 top-1/2 -translate-y-1/2 w-5 h-5 text-gray-500 group-focus-within:text-kodo-cyan transition-colors"})]}));co.displayName="SearchInput";const Zn=({value:e,max:t=100,variant:r="default",color:a="cyan",labelLeft:o,labelRight:l,className:n})=>{const c=Math.min(100,Math.max(0,e/t*100)),i={cyan:"bg-kodo-cyan",magenta:"bg-kodo-magenta",lime:"bg-kodo-lime",gold:"bg-kodo-gold"},h={gold:"from-kodo-gold to-orange-500"};return r==="gaming"?s.jsxs("div",{className:J("relative",n),children:[s.jsx("div",{className:"h-4 bg-kodo-void rounded-full overflow-hidden border border-kodo-gold/30",children:s.jsx("div",{className:J("h-full bg-gradient-to-r shadow-[0_0_10px_rgba(255,215,0,0.5)] transition-all duration-500",h.gold),style:{width:`${c}%`}})}),(o||l)&&s.jsxs("div",{className:"flex justify-between text-[10px] font-mono font-bold text-kodo-gold mt-1 uppercase tracking-wider",children:[s.jsx("span",{children:o}),s.jsx("span",{children:l})]})]}):s.jsxs("div",{className:J("w-full",n),children:[s.jsx("div",{className:"h-2 bg-kodo-steel rounded-full overflow-hidden",children:s.jsx("div",{className:J("h-full transition-all duration-300 shadow-[0_0_10px_currentColor]",i[a]),style:{width:`${c}%`}})}),(o||l)&&s.jsxs("div",{className:"flex justify-between text-xs text-gray-500 mt-1 font-mono",children:[s.jsx("span",{children:o}),s.jsx("span",{children:l})]})]})},uo=fe.forwardRef(({title:e,value:t,change:r,icon:a,color:o="cyan",className:l},n)=>{const c={cyan:"text-kodo-cyan",lime:"text-kodo-lime",magenta:"text-kodo-magenta",gold:"text-kodo-gold",orange:"text-kodo-orange"};return s.jsxs("div",{ref:n,className:J("bg-kodo-graphite border border-kodo-steel/60 p-6 rounded-xl hover:border-kodo-cyan/40 transition-all duration-300",l),children:[s.jsxs("div",{className:"flex flex-row items-center justify-between space-y-0 pb-2",children:[s.jsx("h3",{className:"text-sm font-medium text-kodo-secondary",children:e}),a&&s.jsx("div",{className:J("h-4 w-4",c[o]),children:a})]}),s.jsxs("div",{className:"mt-4",children:[s.jsx("div",{className:"text-2xl font-bold text-white",children:t}),r&&s.jsxs("p",{className:"text-xs text-kodo-secondary mt-1",children:[s.jsx("span",{className:"text-kodo-lime",children:r})," par rapport au mois dernier"]})]})]})});uo.displayName="StatCard";const mo=fe.forwardRef(({tracks:e,onTrackClick:t,onPlayClick:r,onMoreClick:a,className:o},l)=>e.length===0?s.jsx("div",{ref:l,className:J("text-center py-8",o),children:s.jsx("p",{className:"text-kodo-secondary text-sm",children:"Aucune piste disponible"})}):s.jsx("div",{ref:l,className:J("space-y-2",o),children:e.map(n=>s.jsxs("div",{className:"flex items-center gap-3 p-3 rounded-lg bg-kodo-graphite/50 hover:bg-kodo-slate/50 transition-all group cursor-pointer",onClick:()=>t?.(n),children:[s.jsxs("div",{className:"relative w-12 h-12 rounded bg-kodo-slate flex items-center justify-center flex-shrink-0",children:[n.coverUrl?s.jsx("img",{src:n.coverUrl,alt:n.title,className:"w-full h-full object-cover rounded"}):s.jsx(tr,{className:"w-5 h-5 text-kodo-cyan"}),s.jsx("button",{onClick:c=>{c.stopPropagation(),r?.(n)},className:"absolute inset-0 flex items-center justify-center bg-black/60 opacity-0 group-hover:opacity-100 transition-opacity rounded",children:s.jsx(sr,{className:"w-5 h-5 text-white fill-current"})})]}),s.jsxs("div",{className:"flex-1 min-w-0",children:[s.jsx("p",{className:"text-sm font-medium text-white truncate",children:n.title}),n.artist&&s.jsx("p",{className:"text-xs text-kodo-secondary truncate",children:n.artist})]}),n.duration&&s.jsx("span",{className:"text-xs text-kodo-secondary font-mono",children:n.duration}),a&&s.jsx("button",{onClick:c=>{c.stopPropagation(),a(n)},className:"p-2 rounded-lg hover:bg-kodo-steel/30 opacity-0 group-hover:opacity-100 transition-opacity",children:s.jsx(rr,{className:"w-4 h-4 text-kodo-secondary"})})]},n.id))}));mo.displayName="TrackList";const ho=fe.forwardRef(({count:e=0,className:t},r)=>s.jsxs("div",{ref:r,className:J("relative inline-block",t),children:[s.jsx(ar,{className:"w-5 h-5 text-kodo-secondary hover:text-kodo-primary transition-colors"}),e>0&&s.jsx("span",{className:"absolute -top-1 -right-1 w-4 h-4 bg-kodo-red rounded-full flex items-center justify-center text-[10px] font-bold text-white border border-kodo-void",children:e>9?"9+":e})]}));ho.displayName="NotificationBadge";const fo=fe.forwardRef(({src:e,alt:t="Avatar",fallback:r,size:a="md",className:o},l)=>{const n={sm:"w-8 h-8 text-xs",md:"w-10 h-10 text-sm",lg:"w-12 h-12 text-base"};return s.jsx("div",{ref:l,className:J("rounded-full overflow-hidden bg-kodo-slate flex items-center justify-center",n[a],o),children:e?s.jsx("img",{src:e,alt:t,className:"w-full h-full object-cover"}):s.jsx("span",{className:"font-medium text-kodo-primary",children:r||t.charAt(0).toUpperCase()})})});fo.displayName="Avatar";class po{installPrompt=null;registration=null;statusCallbacks=new Set;constructor(){this.initialize()}async initialize(){await this.registerServiceWorker(),this.setupInstallPrompt(),this.setupOnlineDetection(),this.checkForUpdates()}async registerServiceWorker(){m.info("[PWA] Service Worker disabled to prevent cache conflicts with JS chunks")}setupInstallPrompt(){window.addEventListener("beforeinstallprompt",t=>{t.preventDefault(),this.installPrompt=t,m.info("[PWA] Install prompt available"),this.notifyStatusChange()}),window.addEventListener("appinstalled",()=>{m.info("[PWA] App installed successfully"),this.installPrompt=null,this.notifyStatusChange()})}setupOnlineDetection(){window.addEventListener("online",()=>{m.info("[PWA] Back online"),this.notifyStatusChange()}),window.addEventListener("offline",()=>{m.info("[PWA] Gone offline"),this.notifyStatusChange()})}async checkForUpdates(){if(this.registration)try{await this.registration.update()}catch(t){m.error("[PWA] Failed to check for updates:",{error:t})}}async promptInstall(){if(!this.installPrompt)return m.warn("[PWA] Install prompt not available"),!1;try{return await this.installPrompt.prompt(),(await this.installPrompt.userChoice).outcome==="accepted"?(m.info("[PWA] User accepted install prompt"),this.installPrompt=null,!0):(m.info("[PWA] User dismissed install prompt"),!1)}catch(t){return m.error("[PWA] Install prompt failed:",{error:t}),!1}}async updateServiceWorker(){this.registration&&this.registration.waiting&&(this.registration.waiting.postMessage({type:"SKIP_WAITING"}),window.location.reload())}getStatus(){return{isInstallable:!!this.installPrompt,isInstalled:this.isAppInstalled(),isOnline:navigator.onLine,serviceWorkerReady:!!this.registration,updateAvailable:!!this.registration?.waiting}}isAppInstalled(){return window.matchMedia("(display-mode: standalone)").matches||window.navigator.standalone||document.referrer.includes("android-app://")}onStatusChange(t){return this.statusCallbacks.add(t),()=>{this.statusCallbacks.delete(t)}}notifyStatusChange(){const t=this.getStatus();this.statusCallbacks.forEach(r=>{try{r(t)}catch(a){m.error("[PWA] Status callback error:",{error:a})}})}async clearCaches(){if(this.registration){const t=new MessageChannel;return new Promise(r=>{t.port1.onmessage=a=>{a.data.type==="CACHE_CLEARED"&&r()},this.registration.active?.postMessage({type:"CLEAR_CACHE"},[t.port2])})}}async getVersion(){if(this.registration&&this.registration.active){const t=new MessageChannel;return new Promise(r=>{t.port1.onmessage=a=>{a.data.type==="VERSION"&&r(a.data.payload.version)},this.registration.active.postMessage({type:"GET_VERSION"},[t.port2])})}return"unknown"}async showNotification(t,r){"Notification"in window&&Notification.permission==="granted"&&this.registration&&await this.registration.showNotification(t,{icon:"/icons/icon-192x192.png",badge:"/icons/badge-72x72.png",...r})}async requestNotificationPermission(){return"Notification"in window?await Notification.requestPermission():"denied"}}const ge=new po;function go(){const[e,t]=f.useState(ge.getStatus()),[r,a]=f.useState(!1),[o,l]=f.useState(!1);f.useEffect(()=>{const g=ge.onStatusChange(t);return t(ge.getStatus()),g},[]);const n=async()=>{if(!e.isInstallable||r)return!1;a(!0);try{return await ge.promptInstall()}catch(g){return m.error("[PWA Hook] Install failed",{error:g instanceof Error?g.message:String(g),stack:g instanceof Error?g.stack:void 0}),!1}finally{a(!1)}},c=async()=>{if(!(!e.updateAvailable||o)){l(!0);try{await ge.updateServiceWorker()}catch(g){m.error("[PWA Hook] Update failed",{error:g instanceof Error?g.message:String(g),stack:g instanceof Error?g.stack:void 0})}finally{l(!1)}}},i=async()=>await ge.requestNotificationPermission(),h=async(g,x)=>await ge.showNotification(g,x),u=async()=>await ge.clearCaches(),p=async()=>await ge.getVersion();return{...e,hasServiceWorker:e.serviceWorkerReady,isInstalling:r,isUpdating:o,install:n,update:c,requestNotifications:i,showNotification:h,clearCaches:u,getVersion:p,canInstall:e.isInstallable&&!r,canUpdate:e.updateAvailable&&!o,isOffline:!e.isOnline}}function yo(){const{isInstallable:e,isInstalled:t,install:r,isInstalling:a}=go(),[o,l]=f.useState(!1),[n,c]=f.useState(!1);f.useEffect(()=>{l(e&&!t&&!n)},[e,t,n]);const i=async()=>{await r()&&l(!1)},h=()=>{c(!0),l(!1),sessionStorage.setItem("pwa-install-dismissed","true")};return f.useEffect(()=>{const u=sessionStorage.getItem("pwa-install-dismissed")==="true";c(u)},[]),{showBanner:o,isInstalling:a,handleInstall:i,handleDismiss:h}}function xo(){const{showBanner:e,isInstalling:t,handleInstall:r,handleDismiss:a}=yo(),{t:o}=ss();return e?s.jsx("div",{className:S("fixed bottom-8 right-8 z-50 w-80 glass-hud rounded-2xl border-white/10 p-6 shadow-2xl animate-slideInRight hud-corner group overflow-hidden","before:absolute before:inset-0 before:bg-gradient-to-br before:from-kodo-cyan/5 before:to-transparent before:opacity-0 group-hover:before:opacity-100 before:transition-opacity"),children:s.jsxs("div",{className:"flex flex-col gap-4 relative z-10",children:[s.jsxs("div",{className:"flex items-center justify-between",children:[s.jsxs("div",{className:"flex items-center gap-2.5",children:[s.jsx("div",{className:"w-8 h-8 rounded-lg bg-kodo-steel/10 flex items-center justify-center border border-kodo-steel/30 animate-pulse-glow",children:s.jsx(or,{className:"h-4 w-4 text-kodo-steel"})}),s.jsxs("div",{children:[s.jsx("div",{className:"text-hud",children:"System.Uplink"}),s.jsx("h3",{className:"font-display font-black text-xs text-white uppercase tracking-wider",children:o("pwa.install.title","Native_Access")})]})]}),s.jsx("button",{onClick:a,className:"p-1 px-2 rounded-md bg-white/5 text-kodo-secondary hover:text-white transition-all text-[10px] font-mono border border-transparent hover:border-white/10",children:"DISMISS"})]}),s.jsx("p",{className:"text-[11px] font-mono text-white/50 leading-relaxed uppercase tracking-tighter",children:o("pwa.install.description","ESTABLISH_LOCAL_UPLINK_FOR_LOW_LATENCY_OPERATIONS")}),s.jsx("div",{className:"flex gap-2",children:s.jsxs(_s,{variant:"gaming",className:"flex-1 h-9 text-[10px] font-black font-mono tracking-widest bg-kodo-cyan group hover:opacity-90 transition-opacity",onClick:r,disabled:t,children:[s.jsx(ir,{className:"h-3.5 w-3.5 mr-2 transition-opacity group-hover:opacity-80"}),t?"RUNNING...":"INITIATE_INSTALL"]})}),s.jsx("div",{className:"absolute -bottom-8 -right-8 w-16 h-16 bg-kodo-steel/10 blur-2xl rounded-full"})]})}):null}const vo={success:nr,error:Re,warning:it,info:ot},Ht={success:"bg-kodo-lime/10 border-kodo-lime/30 text-kodo-text-main dark:bg-kodo-lime/20 dark:border-kodo-lime/40 dark:text-kodo-lime",error:"bg-kodo-red/10 border-kodo-red/30 text-kodo-text-main dark:bg-kodo-red/20 dark:border-kodo-red/40 dark:text-kodo-red",warning:"bg-kodo-gold/10 border-kodo-gold/30 text-kodo-text-main dark:bg-kodo-gold/20 dark:border-kodo-gold/40 dark:text-kodo-gold",info:"bg-kodo-steel/10 border-kodo-steel/30 text-kodo-text-main dark:bg-kodo-steel/20 dark:border-kodo-steel/40 dark:text-kodo-steel"},bo=5e3;function wo({toast:e,onDismiss:t}){const[r,a]=f.useState(!1),[o,l]=f.useState(!1),n=f.useCallback(()=>{l(!0),setTimeout(()=>{t(e.id)},300)},[e.id,t]);f.useEffect(()=>{a(!0);const h=e.duration??bo;let u=null;return h>0&&(u=setTimeout(()=>{n()},h)),()=>{u&&clearTimeout(u)}},[e.duration,e.id,n]);const c=e.type?vo[e.type]:ot,i=e.type?Ht[e.type]:Ht.info;return s.jsxs("div",{className:S("relative flex min-w-[300px] max-w-md items-start gap-4 rounded-lg border p-4 shadow-lg transition-all duration-300",i,r&&!o?"opacity-100 translate-x-0":"opacity-0 translate-x-full"),role:"alert","aria-live":"polite",children:[s.jsx(c,{className:"h-5 w-5 flex-shrink-0"}),s.jsx("div",{className:"flex-1",children:s.jsx("p",{className:"text-sm font-medium",children:e.message})}),s.jsx("button",{onClick:n,className:"flex-shrink-0 rounded-md p-1 text-current opacity-70 transition-opacity hover:opacity-100 focus:outline-none focus:ring-2 focus:ring-offset-2","aria-label":"Fermer",children:s.jsx(at,{className:"h-4 w-4"})})]})}const js=f.createContext(void 0);function ko(){const e=f.useContext(js);if(!e)throw new Error("useToastContext must be used within ToastProvider");return e}const So={"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 _o({children:e,position:t="top-right",className:r}){const[a,o]=f.useState([]),l=f.useCallback(i=>{const h=`toast-${Date.now()}-${Math.random().toString(36).substr(2,9)}`,u={...i,id:h};o(p=>[...p,u])},[]),n=f.useCallback(i=>{o(h=>h.filter(u=>u.id!==i))},[]),c={toasts:a,addToast:l,removeToast:n};return s.jsxs(js.Provider,{value:c,children:[e,s.jsx("div",{className:S("fixed z-50 flex flex-col gap-2",So[t],r),children:a.map(i=>s.jsx(wo,{toast:i,onDismiss:n},i.id))})]})}function jo(){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 Rt=null,Ze=null;const Eo=3e4;function No(e){const t=ct(e);(t==="network"||t==="timeout")&&(Rt=e instanceof Error||e&&typeof e=="object"&&"message"in e?e:new Error(String(e)),Ze=Date.now())}function Es(){Rt=null,Ze=null}function Ns(){return!Rt||!Ze?!1:Date.now()-Ze>Eo?(Es(),!1):!0}const To=Object.freeze(Object.defineProperty({__proto__:null,clearNetworkError:Es,hasRecentNetworkError:Ns,recordNetworkError:No},Symbol.toStringTag,{value:"Module"}));function Co(e){return new Date(e).toLocaleString()}function Ro(e){const t=e.config.method?.toUpperCase()||"UNKNOWN",r=e.config.url||"Unknown URL";return`${t} ${r}`}function Ao(e){switch(e){case"high":return"bg-kodo-red/20 text-kodo-red border-kodo-red/30";case"normal":return"bg-kodo-steel/20 text-kodo-steel border-kodo-steel/30";case"low":return"bg-kodo-steel/30 text-kodo-secondary border-kodo-steel/50";default:return"bg-kodo-steel/30 text-kodo-secondary border-kodo-steel/50"}}function Gt({open:e,onClose:t}){const[r,a]=f.useState([]),[o,l]=f.useState(null),[n,c]=f.useState(!1);f.useEffect(()=>{if(!e)return;const u=()=>{a(xe.getQueue())};u();const p=setInterval(u,1e3);return()=>clearInterval(p)},[e]);const i=async u=>{l(u);try{await xe.removeRequest(u),a(xe.getQueue())}catch(p){m.error("Failed to remove request",{error:p instanceof Error?p.message:String(p),stack:p instanceof Error?p.stack:void 0,requestId:u})}finally{l(null)}},h=async()=>{c(!0);try{await xe.clearQueue(),a([]),t()}catch(u){m.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(Ct,{open:e,onClose:t,title:"Offline Queue Manager",size:"lg",variant:"info",children:s.jsxs("div",{className:"space-y-4",children:[s.jsxs("div",{className:"flex items-center justify-between p-4 bg-kodo-ink/50 rounded-lg border border-kodo-steel",children:[s.jsxs("div",{className:"flex items-center gap-2",children:[s.jsx(qe,{className:"w-5 h-5 text-kodo-steel"}),s.jsx("span",{className:"text-sm text-kodo-secondary",children:r.length===0?"No queued requests":`${r.length} ${r.length===1?"request":"requests"} queued`})]}),r.length>0&&s.jsxs(z,{variant:"destructive",size:"sm",onClick:h,disabled:n,children:[s.jsx(lr,{className:"w-4 h-4 mr-2"}),"Clear All"]})]}),r.length===0?s.jsxs("div",{className:"text-center py-8 text-kodo-secondary",children:[s.jsx(cr,{className:"w-12 h-12 mx-auto mb-4 text-kodo-cyan/50"}),s.jsx("p",{className:"text-sm",children:"All requests have been processed"})]}):s.jsx("div",{className:"space-y-2 max-h-[400px] overflow-y-auto custom-scrollbar",children:r.map(u=>s.jsx("div",{className:"p-4 bg-kodo-ink/30 rounded-lg border border-kodo-steel hover:border-kodo-steel/50 transition-colors",children:s.jsxs("div",{className:"flex items-start justify-between gap-4",children:[s.jsxs("div",{className:"flex-1 min-w-0",children:[s.jsx("div",{className:"flex items-center gap-2 mb-2",children:s.jsx("span",{className:"font-mono text-sm font-semibold text-white truncate",children:Ro(u)})}),s.jsxs("div",{className:"flex items-center gap-4 flex-wrap text-xs text-kodo-secondary",children:[s.jsx("span",{className:S("px-2 py-0.5 rounded border",Ao(u.priority)),children:u.priority}),s.jsxs("span",{className:"flex items-center gap-1",children:[s.jsx(qe,{className:"w-3 h-3"}),Co(u.timestamp)]}),u.retryCount>0&&s.jsxs("span",{className:"flex items-center gap-1 text-kodo-red",children:[s.jsx(Re,{className:"w-3 h-3"}),u.retryCount," retry",u.retryCount>1?"ies":""]})]})]}),s.jsx(z,{variant:"ghost",size:"icon",onClick:()=>i(u.id),disabled:o===u.id,className:"shrink-0",children:o===u.id?s.jsx(qe,{className:"w-4 h-4 animate-spin"}):s.jsx(at,{className:"w-4 h-4"})})]})},u.id))}),r.length>0&&s.jsx("div",{className:"p-4 bg-kodo-steel/10 border border-kodo-steel/20 rounded-lg text-xs text-kodo-secondary",children:s.jsx("p",{children:"Queued requests will be automatically processed when you're back online. You can remove individual requests or clear the entire queue."})})]})})}function Io(){const e=jo(),[t,r]=f.useState(0),[a,o]=f.useState(!1),[l,n]=f.useState(!1),[c,i]=f.useState(!1),[h,u]=f.useState(!1);return f.useEffect(()=>{const p=()=>{const x=xe.getQueueSize();r(x)};p();const g=setInterval(p,1e3);return()=>clearInterval(g)},[]),f.useEffect(()=>{if(e&&t>0){o(!0);const p=setInterval(()=>{xe.getQueueSize()===0&&(o(!1),clearInterval(p))},500);return()=>clearInterval(p)}else{o(!1);return}},[e,t]),f.useEffect(()=>{const p=()=>{n(Ns())};p();const g=setInterval(p,2e3);return()=>clearInterval(g)},[]),f.useEffect(()=>{if(a&&t>0&&e){const p=setTimeout(()=>{u(!0)},500);return()=>{clearTimeout(p),u(!1)}}else{u(!1);return}},[a,t,e]),e&&t===0&&!a&&!l?null:!e||l?s.jsxs(s.Fragment,{children:[s.jsxs("div",{className:"fixed top-0 left-0 right-0 bg-kodo-red/90 backdrop-blur-sm text-white px-4 py-2.5 text-sm z-50 flex items-center justify-center gap-2 shadow-lg border-b border-kodo-red",children:[s.jsx(dr,{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:()=>i(!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(Lt,{className:"w-3.5 h-3.5"}),"View Queue"]})]}),s.jsx(Gt,{open:c,onClose:()=>i(!1)})]}):a&&t>0&&h?s.jsxs(s.Fragment,{children:[s.jsxs("div",{className:"fixed top-0 left-0 right-0 bg-kodo-cyan/90 backdrop-blur-sm text-kodo-void px-4 py-2.5 text-sm z-50 flex items-center justify-center gap-2 shadow-lg border-b border-kodo-steel",children:[s.jsx(Ge,{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 xe.clearQueue(),r(0)},className:"ml-2 px-2 py-1 bg-kodo-red/20 hover:bg-kodo-red/30 rounded border border-kodo-red/30 transition-colors flex items-center gap-1.5 text-xs font-medium",title:"Clear queued requests",children:"Clear Queue"}),s.jsxs("button",{onClick:()=>i(!0),className:"ml-2 px-2 py-1 bg-kodo-void/20 hover:bg-kodo-void/30 rounded border border-kodo-void/30 transition-colors flex items-center gap-1.5 text-xs font-medium",title:"View queued requests",children:[s.jsx(Lt,{className:"w-3.5 h-3.5"}),"View Queue"]})]})]}),s.jsx(Gt,{open:c,onClose:()=>i(!1)})]}):null}function Ts(){const{isAuthenticated:e}=Z();return Xt({queryKey:["user","me"],queryFn:ys,enabled:e,retry:!1,staleTime:300*1e3,gcTime:600*1e3})}const Cs=()=>{const{isAuthenticated:e,logout:t}=Z(),{data:r}=Ts();return{user:r??null,accessToken:null,refreshToken:null,isAuthenticated:e,logout:async()=>{await t()}}};function U({children:e}){const{isAuthenticated:t}=Cs(),[r,a]=f.useState(!0),o=!1,{isLoading:l}=Z();return f.useEffect(()=>{const c=setTimeout(()=>{a(!1)},200);return()=>clearTimeout(c)},[]),r||l?null:t||o?s.jsx(s.Fragment,{children:e}):s.jsx(Xe,{to:"/login",replace:!0})}function Rs(){const{i18n:e,t}=ss(),{language:r,setLanguage:a}=Ee(),o=l=>{e.changeLanguage(l),a(l)};return{t,i18n:{...e,changeLanguage:async l=>{await e.changeLanguage(l)},isInitialized:e.isInitialized},language:r,changeLanguage:o,isReady:e.isInitialized}}function Po({verified:e}){return e?s.jsx("span",{className:"inline-flex items-center px-2 py-1 rounded-full text-xs font-medium bg-kodo-lime/20 text-kodo-lime dark:bg-kodo-lime/20 dark:text-kodo-lime",children:"✓ Email Verified"}):s.jsx("span",{className:"inline-flex items-center px-2 py-1 rounded-full text-xs font-medium bg-kodo-gold/20 text-kodo-gold dark:bg-kodo-gold/20 dark:text-kodo-gold",children:"⚠ Email Not Verified"})}async function Lo(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 O.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 rt?new Error(t.response?.data?.error||t.message||"Failed to fetch notifications"):t}}async function qo(e){try{await O.post(`/notifications/${e}/read`)}catch(t){throw t instanceof rt?new Error(t.response?.data?.error||t.message||"Failed to mark notification as read"):t}}async function Do(){try{await O.post("/notifications/read-all")}catch(e){throw e instanceof rt?new Error(e.response?.data?.error||e.message||"Failed to mark all notifications as read"):e}}function Oo(){const{addToast:e}=ko();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 Mo=3e4,zo=50;function Uo({className:e}={}){const[t,r]=f.useState(!1),a=f.useRef(null),o=et(),l=jt(),{success:n,error:c}=Oo(),{data:i,isLoading:h,refetch:u}=Xt({queryKey:["notifications","menu"],queryFn:()=>Lo({limit:zo}),refetchInterval:Mo,staleTime:1e4}),p=i?.notifications||[],g=p.filter(d=>!d.read).length,x=At({mutationFn:qo,onMutate:async d=>{await l.cancelQueries({queryKey:["notifications"]});const b=l.getQueryData(["notifications"]);return b&&l.setQueryData(["notifications"],{...b,notifications:b.notifications.map(j=>j.id===d?{...j,read:!0}:j),unreadCount:Math.max((b.unreadCount||1)-1,0)}),{previousNotifications:b}},onError:(d,b,j)=>{j?.previousNotifications&&l.setQueryData(["notifications"],j.previousNotifications),c("Erreur lors du marquage")},onSuccess:()=>{l.invalidateQueries({queryKey:["notifications"]})}}),y=At({mutationFn:Do,onMutate:async()=>{await l.cancelQueries({queryKey:["notifications"]});const d=l.getQueryData(["notifications"]);return d&&l.setQueryData(["notifications"],{...d,notifications:d.notifications.map(b=>({...b,read:!0})),unreadCount:0}),{previousNotifications:d}},onError:(d,b,j)=>{j?.previousNotifications&&l.setQueryData(["notifications"],j.previousNotifications),c("Erreur lors du marquage")},onSuccess:()=>{l.invalidateQueries({queryKey:["notifications"]}),n("Toutes les notifications ont été marquées comme lues")}});f.useEffect(()=>{function d(b){a.current&&!a.current.contains(b.target)&&r(!1)}return t&&document.addEventListener("mousedown",d),()=>{document.removeEventListener("mousedown",d)}},[t]);const k=d=>{x.mutate(d)},C=()=>{y.mutate()},E=d=>{d.read||k(d.id),d.link&&(o(d.link),r(!1))};return f.useEffect(()=>{t&&u()},[t,u]),s.jsxs("div",{className:"relative",ref:a,children:[s.jsxs(z,{variant:"ghost",size:"icon",className:"relative",onClick:()=>r(!t),"aria-label":"Notifications","aria-expanded":t,"aria-haspopup":"true",children:[s.jsx(qt,{className:"h-5 w-5"}),g>0&&s.jsx("span",{className:"absolute -top-1 -right-1 h-5 w-5 bg-destructive rounded-full text-xs text-destructive-foreground flex items-center justify-center font-semibold","aria-label":`${g} notifications non lues`,children:g>9?"9+":g})]}),t&&s.jsxs("div",{className:"absolute right-0 mt-2 w-80 bg-background border rounded-lg shadow-lg z-50 max-h-[500px] flex flex-col",children:[s.jsxs("div",{className:"p-4 border-b flex items-center justify-between",children:[s.jsx("h3",{className:"font-semibold text-sm",children:"Notifications"}),s.jsx("div",{className:"flex items-center space-x-2",children:g>0&&s.jsxs(z,{variant:"ghost",size:"sm",onClick:C,className:"h-7 text-xs",disabled:y.isPending,children:[y.isPending?s.jsx(Ge,{className:"h-3 w-3 mr-1 animate-spin"}):s.jsx(ur,{className:"h-3 w-3 mr-1"}),"Tout marquer comme lu"]})})]}),s.jsx("div",{className:"overflow-y-auto flex-1",children:h?s.jsx("div",{className:"flex items-center justify-center py-8",children:s.jsx(Ge,{className:"h-6 w-6 animate-spin text-muted-foreground"})}):p.length===0?s.jsxs("div",{className:"p-8 text-center text-muted-foreground",children:[s.jsx(qt,{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:p.map(d=>s.jsx("div",{className:S("p-4 hover:bg-accent transition-colors cursor-pointer",!d.read&&"bg-accent/50"),onClick:()=>E(d),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:[!d.read&&s.jsx("span",{className:"h-2 w-2 bg-primary rounded-full flex-shrink-0 mt-1.5"}),s.jsx("p",{className:S("text-sm font-medium",!d.read&&"font-semibold"),children:d.title})]}),d.content&&s.jsx("p",{className:"text-sm text-muted-foreground mb-2 line-clamp-2",children:d.content}),s.jsx("p",{className:"text-xs text-muted-foreground",children:Ys(new Date(d.created_at),{addSuffix:!0,locale:Xs})})]}),s.jsx("div",{className:"flex items-center space-x-1 ml-2 shrink-0",children:!d.read&&s.jsx(z,{variant:"ghost",size:"icon",className:"h-6 w-6",onClick:b=>{b.stopPropagation(),k(d.id)},"aria-label":"Marquer comme lu",disabled:x.isPending,children:x.isPending?s.jsx(Ge,{className:"h-3 w-3 animate-spin"}):s.jsx(mr,{className:"h-3 w-3"})})})]})},d.id))})}),p.length>0&&s.jsx("div",{className:"p-4 border-t",children:s.jsx(z,{variant:"ghost",size:"sm",className:"w-full",onClick:()=>{o("/notifications"),r(!1)},children:"Voir toutes les notifications"})})]})]})}function Fo(){const{limit:e,remaining:t,reset:r,isLimited:a}=kt(),[o,l]=f.useState(null);f.useEffect(()=>{if(!r){l(null);return}const u=()=>{const g=Math.floor(Date.now()/1e3),x=r-g;l(x>0?x:0)};u();const p=setInterval(u,1e3);return()=>clearInterval(p)},[r]);const n=e!==null&&t!==null&&e>0?t/e*100:null;if(!(a||e!==null&&t!==null&&n!==null&&n<20)||e===null)return null;const i=u=>{if(u<=0)return"0s";if(u<60)return`${u}s`;const p=Math.floor(u/60),g=u%60;if(p<60)return g>0?`${p}m ${g}s`:`${p}m`;const x=Math.floor(p/60),y=p%60;return y>0?`${x}h ${y}m`:`${x}h`},h=a||t!==null&&t<=0;return s.jsxs("div",{className:S("flex items-center gap-2 px-4 py-1.5 rounded-lg text-xs font-medium transition-all",h?"bg-kodo-red/10 text-kodo-red border border-kodo-red/30":"bg-kodo-gold/10 text-kodo-gold border border-kodo-gold/30"),role:"alert","aria-live":"polite",children:[s.jsx(it,{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"}),o!==null&&s.jsxs("span",{className:"flex items-center gap-1",children:[s.jsx(qe,{className:"w-3 h-3"}),i(o)]})]}):s.jsxs(s.Fragment,{children:[s.jsx("span",{children:t!==null?`${t}/${e} requests`:`${e} requests`}),o!==null&&s.jsxs("span",{className:"flex items-center gap-1 opacity-75",children:[s.jsx(qe,{className:"w-3 h-3"}),"resets in ",i(o)]})]})})]})}function Vo({content:e,children:t,position:r="top",trigger:a="hover",delay:o=200,showArrow:l=!0,maxWidth:n=300,disabled:c=!1,className:i}){const[h,u]=f.useState(!1),[p,g]=f.useState(!1),[x,y]=f.useState(r),[k,C]=f.useState({}),E=f.useRef(null),d=f.useRef(null),b=f.useRef(null),j=f.useRef(null),w=f.useCallback(()=>{if(!b.current||!j.current||!h)return;const Q=b.current.getBoundingClientRect(),H=j.current.getBoundingClientRect(),ne=window.innerWidth,be=window.innerHeight,G=8;let re=r,pe=0,we=0;switch(r){case"top":Q.top-H.height-G<0&&(re="bottom");break;case"bottom":Q.bottom+H.height+G>be&&(re="top");break;case"left":Q.left-H.width-G<0&&(re="right");break;case"right":Q.right+H.width+G>ne&&(re="left");break}if(re==="top"||re==="bottom"){const Y=Q.left+Q.width/2,K=H.width/2,N=G,B=ne-G;Y-K<N?pe=N-(Y-K):Y+K>B&&(pe=B-(Y+K))}else{const Y=Q.top+Q.height/2,K=H.height/2,N=G,B=be-G;Y-K<N?we=N-(Y-K):Y+K>B&&(we=B-(Y+K))}y(re),C({...pe!==0&&{transform:`translate(calc(-50% + ${pe}px), 0)`},...we!==0&&{transform:`translate(0, calc(-50% + ${we}px))`}})},[r,h]);f.useEffect(()=>{h&&(g(!0),w())},[h,w]),f.useEffect(()=>{p&&h&&w()},[p,h,w]);const _=()=>{E.current&&clearTimeout(E.current),E.current=setTimeout(()=>{u(!0)},o)},W=()=>{E.current&&clearTimeout(E.current),d.current&&clearTimeout(d.current),d.current=setTimeout(()=>{u(!1)},100)},Ie={hover:{onMouseEnter:_,onMouseLeave:W},click:{onClick:()=>{a==="click"&&u(!h)}},focus:{onFocus:_,onBlur:W}}[a],ue={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"},se={top:"top-full left-1/2 -translate-x-1/2 border-t-kodo-ink border-l-transparent border-r-transparent border-b-transparent",bottom:"bottom-full left-1/2 -translate-x-1/2 border-b-kodo-ink border-l-transparent border-r-transparent border-t-transparent",left:"left-full top-1/2 -translate-y-1/2 border-l-kodo-ink border-t-transparent border-b-transparent border-r-transparent",right:"right-full top-1/2 -translate-y-1/2 border-r-kodo-ink border-t-transparent border-b-transparent border-l-transparent"};if(f.useEffect(()=>()=>{E.current&&clearTimeout(E.current),d.current&&clearTimeout(d.current)},[]),c)return s.jsx(s.Fragment,{children:t});const ve=s.jsx(s.Fragment,{children:p&&s.jsxs("div",{ref:j,className:S("absolute z-50 px-4 py-1.5 text-sm text-white bg-kodo-ink rounded-md shadow-lg","border border-kodo-steel pointer-events-none","transition-all duration-200",ue[x],h?"opacity-100 scale-100":"opacity-0 scale-95",i),role:"tooltip",style:{maxWidth:`${n}px`,...k},children:[e,l&&s.jsx("div",{className:S("absolute w-0 h-0 border-4",se[x])})]})});return s.jsxs("div",{ref:b,className:"relative inline-block",...Ie,children:[t,ve]})}function $o(e){const[t,r]=f.useState(!1),{logout:a}=Z(),{data:o}=Ts(),{theme:l,setTheme:n,sidebarOpen:c,setSidebarOpen:i}=Ee(),{t:h}=Rs(),u=et(),p=async()=>{await a(),u("/login")},g=()=>{n(l==="light"?"dark":l==="dark"?"system":"light")},x=()=>{switch(l){case"light":return s.jsx(xr,{className:"h-4 w-4"});case"dark":return s.jsx(yr,{className:"h-4 w-4"});default:return s.jsx(gr,{className:"h-4 w-4"})}};return s.jsx("header",{className:"fixed top-0 left-0 right-0 h-20 z-50 pointer-events-none",children:s.jsxs("div",{className:S("absolute top-0 right-0 h-20 bg-gradient-to-b from-kodo-void/90 via-kodo-void/80 to-transparent backdrop-blur-[8px] flex items-center justify-between px-6 pointer-events-auto transition-all duration-500",c?"left-72":"left-20","max-lg:left-0"),children:[s.jsx("button",{onClick:()=>i(!c),className:"lg:hidden p-2 rounded-lg hover:bg-white/5 text-kodo-text-dim hover:text-white mr-4",children:s.jsx(hr,{className:"w-5 h-5"})}),s.jsx("div",{className:"flex-1 max-w-xl relative hidden md:block group",children:s.jsxs("div",{className:"relative flex items-center group/search",children:[s.jsx(fr,{className:"absolute left-4 w-4 h-4 text-kodo-text-dim group-hover/search:text-kodo-cyan transition-colors duration-300"}),s.jsx("input",{type:"text",placeholder:"Search Network...",className:"w-full h-11 pl-12 pr-16 bg-white/5 border border-white/10 rounded-2xl text-sm text-white placeholder:text-white/30 focus:outline-none focus:bg-kodo-ink/60 focus:border-kodo-cyan/30 focus:ring-4 focus:ring-kodo-cyan/10 transition-all duration-300 shadow-inner"}),s.jsx("div",{className:"absolute right-3 px-2 py-1 rounded-md bg-white/5 border border-white/5 text-[10px] font-mono font-bold text-kodo-text-dim group-hover/search:text-white group-hover/search:bg-white/10 transition-colors",children:"CMD+K"})]})}),s.jsxs("div",{className:"flex items-center gap-3 ml-4",children:[s.jsxs("div",{className:"hidden xl:flex items-center gap-2 mr-4 px-3 py-1.5 rounded-full bg-kodo-cyan/5 border border-kodo-cyan/10",children:[s.jsx("div",{className:"w-1.5 h-1.5 rounded-full bg-kodo-lime animate-pulse shadow-[0_0_8px_rgba(var(--kodo-lime),0.5)]"}),s.jsx("span",{className:"text-[10px] font-mono text-kodo-cyan uppercase font-bold tracking-tight",children:"Network Stable"})]}),s.jsx(Uo,{}),s.jsx(Fo,{}),s.jsx("div",{className:"h-8 w-px bg-gradient-to-b from-transparent via-white/10 to-transparent mx-2"}),s.jsx(Vo,{content:h("common.changeTheme"),children:s.jsx(z,{variant:"ghost",size:"icon",onClick:g,className:"w-9 h-9 rounded-xl hover:bg-white/5 hover:text-white text-kodo-text-dim",children:x()})}),s.jsxs("div",{className:"relative ml-2",children:[s.jsxs("button",{onClick:()=>r(!t),className:"flex items-center gap-3 p-1.5 pr-4 rounded-full hover:bg-white/5 transition-all border border-transparent focus:outline-none focus:ring-2 focus:ring-kodo-cyan/50 group",children:[s.jsx("div",{className:"w-9 h-9 rounded-full bg-gradient-to-br from-kodo-cyan to-kodo-magenta p-[1.5px] shadow-lg shadow-kodo-cyan/10 group-hover:shadow-kodo-cyan/30 transition-shadow duration-300",children:s.jsx("div",{className:"w-full h-full rounded-full bg-kodo-ink flex items-center justify-center overflow-hidden",children:s.jsx("span",{className:"text-xs font-bold text-white group-hover:scale-110 transition-transform duration-300",children:o?.username?.substring(0,2).toUpperCase()||"VZ"})})}),s.jsxs("div",{className:"hidden lg:block text-left",children:[s.jsx("div",{className:"text-xs font-bold text-white leading-none mb-1 group-hover:text-kodo-cyan transition-colors",children:o?.username}),s.jsx("div",{className:"text-[9px] text-kodo-text-dim uppercase tracking-wider font-mono",children:"LVL. 01"})]})]}),t&&s.jsx(ws,{active:t,onEscape:()=>r(!1),children:s.jsxs("div",{className:"absolute right-0 top-full mt-2 w-64 bg-kodo-ink/90 backdrop-blur-xl border border-white/10 rounded-2xl shadow-2xl p-2 z-50 animate-scaleIn origin-top-right",children:[s.jsxs("div",{className:"px-3 py-3 border-b border-white/5 mb-1",children:[s.jsx("p",{className:"text-sm font-bold text-white truncate text-center mb-1",children:o?.username}),s.jsx("p",{className:"text-xs text-kodo-text-dim truncate text-center font-mono",children:o?.email}),!o?.is_verified&&s.jsx("div",{className:"mt-2 flex justify-center",children:s.jsx(Po,{verified:!1})})]}),s.jsxs("div",{className:"p-1 space-y-0.5",children:[s.jsxs(Ce,{to:"/profile",className:"flex items-center gap-3 px-3 py-2.5 text-sm text-kodo-text-dim hover:text-white hover:bg-white/5 rounded-xl transition-colors",children:[s.jsx(pr,{className:"w-4 h-4"})," Profil"]}),s.jsxs(Ce,{to:"/settings",className:"flex items-center gap-3 px-3 py-2.5 text-sm text-kodo-text-dim hover:text-white hover:bg-white/5 rounded-xl transition-colors",children:[s.jsx(as,{className:"w-4 h-4"})," Paramètres"]})]}),s.jsx("div",{className:"h-px bg-white/5 my-1"}),s.jsx("div",{className:"p-1",children:s.jsxs("button",{onClick:p,className:"w-full flex items-center gap-3 px-3 py-2.5 text-sm text-kodo-red hover:bg-kodo-red/10 rounded-xl transition-colors",children:[s.jsx(os,{className:"w-4 h-4"})," Déconnexion"]})})]})})]})]})]})})}const Qo=[{section:"My Studio",items:[{id:"dashboard",label:"Command Center",icon:s.jsx(kr,{className:"w-4 h-4"})},{id:"studio",label:"Cloud Files",icon:s.jsx(Sr,{className:"w-4 h-4"})},{id:"tracks",label:"Projects",icon:s.jsx(_r,{className:"w-4 h-4"})},{id:"gear",label:"Gear Locker",icon:s.jsx(jr,{className:"w-4 h-4"})},{id:"analytics",label:"Performance",icon:s.jsx(Er,{className:"w-4 h-4"})}]},{section:"Veza Network",items:[{id:"social",label:"Community Feed",icon:s.jsx(Nr,{className:"w-4 h-4"})},{id:"marketplace",label:"Marketplace",icon:s.jsx(Tr,{className:"w-4 h-4"})},{id:"live",label:"Live Sessions",icon:s.jsx(Cr,{className:"w-4 h-4 text-kodo-red"}),badge:3},{id:"chat",label:"Channels",icon:s.jsx(Rr,{className:"w-4 h-4"}),badge:12},{id:"education",label:"Academy",icon:s.jsx(Ar,{className:"w-4 h-4"})}]},{section:"Commerce",items:[{id:"sell",label:"Seller Dashboard",icon:s.jsx(Ir,{className:"w-4 h-4"})},{id:"wishlist",label:"Wishlist",icon:s.jsx(is,{className:"w-4 h-4"})},{id:"purchases",label:"Purchases",icon:s.jsx(Pr,{className:"w-4 h-4"})}]},{section:"Library",items:[{id:"playlists",label:"Playlists",icon:s.jsx(xt,{className:"w-4 h-4"})},{id:"queue",label:"Play Queue",icon:s.jsx(Lr,{className:"w-4 h-4"})}]},{section:"System",items:[{id:"developer",label:"Developer API",icon:s.jsx(qr,{className:"w-4 h-4"})},{id:"admin",label:"Admin Panel",icon:s.jsx(Dr,{className:"w-4 h-4"})}]}],yt={dashboard:"/dashboard",studio:"/library",tracks:"/library",gear:"/gear",analytics:"/analytics",social:"/social",marketplace:"/marketplace",live:"/live",chat:"/chat",education:"/education",sell:"/marketplace",wishlist:"/marketplace",purchases:"/marketplace",playlists:"/library",queue:"/queue",developer:"/developer",admin:"/admin",settings:"/settings"},Bo=({currentView:e,onNavigate:t,onLogout:r})=>{const a=et(),o=Fs(),{logout:l}=Z(),{sidebarOpen:n,setSidebarOpen:c}=Ee(),i=()=>{window.innerWidth<1024&&c(!1)},h=e||Object.keys(yt).find(p=>yt[p]===o.pathname)||"dashboard",u=()=>{l(),a("/login"),r&&r()};return s.jsxs(s.Fragment,{children:[n&&s.jsx("div",{className:"fixed inset-0 bg-black/60 backdrop-blur-sm lg:hidden",style:{zIndex:"var(--z-modal-backdrop)"},onClick:()=>c(!1),"aria-hidden":"true"}),s.jsxs("aside",{role:"navigation","aria-label":"Sidebar",className:S("fixed left-6 bottom-6 glass-hud rounded-2xl border-white/10 flex flex-col transition-all duration-500 ease-in-out hud-corner","top-24",n?"w-64 translate-x-0 opacity-100":"-translate-x-full lg:translate-x-0 lg:opacity-100 lg:w-20"),style:{zIndex:90},children:[s.jsxs("div",{className:"p-6 border-b border-white/5 flex items-center gap-4",children:[s.jsx("div",{className:"w-8 h-8 rounded bg-kodo-steel/20 flex items-center justify-center border border-kodo-steel/30 animate-pulse-glow flex-shrink-0",children:s.jsx(vr,{className:"w-5 h-5 text-kodo-steel"})}),s.jsxs("div",{className:S("transition-all duration-300 overflow-hidden",n?"w-auto opacity-100":"w-0 opacity-0"),children:[s.jsx("h2",{className:"text-xs font-mono font-bold text-white tracking-widest uppercase whitespace-nowrap",children:"System Hub"}),s.jsxs("div",{className:"flex items-center gap-1.5 mt-0.5",children:[s.jsx("span",{className:"w-1 h-1 rounded-full bg-kodo-lime animate-pulse"}),s.jsx("span",{className:"text-[10px] font-mono text-kodo-lime opacity-80 uppercase whitespace-nowrap",children:"Active"})]})]}),s.jsx(z,{variant:"ghost",size:"icon",onClick:()=>c(!n),className:S("ml-auto text-kodo-secondary hover:text-white hidden lg:flex",!n&&"absolute left-1/2 -translate-x-1/2 top-20"),"aria-label":n?"Collapse sidebar":"Expand sidebar",children:n?s.jsx(br,{className:"w-4 h-4"}):s.jsx(wr,{className:"w-4 h-4"})})]}),s.jsx("div",{className:"flex-1 overflow-y-auto custom-scrollbar p-4 space-y-6",children:Qo.map((p,g)=>s.jsxs("div",{className:"mb-4",children:[s.jsx("h3",{className:S("text-[9px] font-mono font-bold text-kodo-steel/60 uppercase tracking-[0.2em] mb-3 px-4 flex items-center gap-2 transition-all duration-300",!n&&"justify-center opacity-0 h-0 overflow-hidden mb-0"),children:p.section}),s.jsx("div",{className:"space-y-1",children:p.items.map(x=>{const y=yt[x.id]||"/dashboard",k=h===x.id;return s.jsxs(Ce,{to:y,title:n?void 0:x.label,onClick:()=>{i(),t&&t(x.id)},className:S("w-full flex items-center px-4 py-2.5 rounded-xl text-sm font-medium transition-all duration-300 group relative overflow-hidden","focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-kodo-cyan focus-visible:ring-offset-2 focus-visible:ring-offset-kodo-void",k?"bg-gradient-to-r from-kodo-cyan/20 to-transparent text-white shadow-[0_0_20px_rgba(var(--kodo-cyan),0.15)] border-l-2 border-kodo-cyan":"text-kodo-secondary hover:text-white hover:bg-white/5 border-l-2 border-transparent",!n&&"justify-center px-2"),children:[k&&s.jsx("div",{className:"absolute inset-0 bg-kodo-cyan/5 animate-pulse-slow pointer-events-none"}),s.jsxs("div",{className:S("flex items-center gap-4 relative z-10",!n&&"justify-center"),children:[s.jsx("span",{className:S("transition-colors duration-200 flex-shrink-0",k?"text-kodo-cyan drop-shadow-[0_0_8px_rgba(var(--kodo-cyan),0.6)]":"text-kodo-secondary group-hover:text-white"),children:x.icon}),s.jsx("span",{className:S("transition-all duration-300 whitespace-nowrap origin-left",n?"w-auto opacity-100 scale-100":"w-0 opacity-0 scale-95 hidden"),children:x.label})]}),x.badge&&n&&s.jsx("span",{className:"ml-auto bg-kodo-magenta/20 text-kodo-magenta text-[9px] px-1.5 py-0.5 rounded-full font-mono font-bold border border-kodo-magenta/30 shadow-[0_0_10px_rgba(var(--kodo-magenta),0.2)]",children:x.badge}),x.badge&&!n&&s.jsx("span",{className:"absolute top-2 right-2 w-2 h-2 rounded-full bg-kodo-magenta border border-kodo-void shadow-[0_0_8px_rgba(var(--kodo-magenta),0.5)]"})]},x.id)})})]},g))}),s.jsxs("div",{className:"p-4 border-t border-white/5 bg-white/2",children:[s.jsxs(Ce,{to:"/settings",onClick:()=>{i(),t&&t("settings")},className:S("w-full flex items-center gap-4 px-4 py-2.5 text-sm rounded-xl transition-all","focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-kodo-cyan focus-visible:ring-offset-2 focus-visible:ring-offset-kodo-void",h==="settings"?"bg-kodo-cyan/10 text-kodo-cyan border-l-2 border-kodo-cyan":"text-kodo-secondary hover:text-white hover:bg-white/5 border-l-2 border-transparent",!n&&"justify-center"),title:n?void 0:"Settings",children:[s.jsx(as,{className:"w-4 h-4 flex-shrink-0"}),s.jsx("span",{className:S("transition-all duration-300 whitespace-nowrap",n?"opacity-100":"w-0 opacity-0 hidden"),children:"Settings"})]}),s.jsxs(z,{variant:"ghost",onClick:u,className:S("w-full text-kodo-red/80 hover:text-kodo-red hover:bg-kodo-red/10 mt-1 gap-4",n?"justify-start":"justify-center px-0"),title:n?void 0:"Sign Out",children:[s.jsx(os,{className:"w-4 h-4 flex-shrink-0"}),s.jsx("span",{className:S("transition-all duration-300 whitespace-nowrap",n?"opacity-100":"w-0 opacity-0 hidden"),children:"Initialize Signout"})]})]})]})]})},As=f.createContext(void 0),Wo=()=>{const e=f.useContext(As);if(!e)throw new Error("useAudio must be used within AudioProvider");return e},He=[{id:"1",title:"Neon Nightrider",artist:"Cyber_Punk_OST",album:"Night City Vol.1",duration:"3:45",durationSec:225,plays:12e3,like_count:3400,coverUrl:"https://picsum.photos/id/55/400/400",isPremium:!0,waveformData:Array.from({length:100},()=>Math.random()),lyrics:[{time:10,text:"Neon lights flickering..."},{time:15,text:"Driving through the cyber city"},{time:20,text:"Bass dropping heavy on the pavement"}]},{id:"2",title:"Glitch in the Matrix",artist:"Null Pointer",album:"System Failure",duration:"4:20",durationSec:260,plays:8500,like_count:2100,coverUrl:"https://picsum.photos/id/58/400/400",waveformData:Array.from({length:100},()=>Math.random())},{id:"3",title:"Tokyo Drift (Lofi)",artist:"Sakura Beats",album:"Chillhop Essentials",duration:"2:55",durationSec:175,plays:45e3,like_count:12e3,coverUrl:"https://picsum.photos/id/60/400/400",isPremium:!0,waveformData:Array.from({length:100},()=>Math.random())},{id:"4",title:"Neural Link",artist:"Mainframe",album:"AI Dreams",duration:"5:10",durationSec:310,plays:2300,like_count:450,coverUrl:"https://picsum.photos/id/70/200/200",waveformData:Array.from({length:100},()=>Math.random())},{id:"5",title:"Synthwave Sunset",artist:"Retro Boy",album:"Analog Memories",duration:"3:30",durationSec:210,plays:1200,like_count:300,coverUrl:"https://picsum.photos/id/80/200/200",waveformData:Array.from({length:100},()=>Math.random())}],Ko=({children:e})=>{const[t,r]=f.useState(He[0]),[a,o]=f.useState(He.slice(1)),[l,n]=f.useState([]),[c,i]=f.useState(!1),[h,u]=f.useState(0),[p,g]=f.useState(0),[x,y]=f.useState(80),[k,C]=f.useState(!1),[E,d]=f.useState(!1),[b,j]=f.useState("off"),[w,_]=f.useState(1),[W,te]=f.useState(!0),[Ie,ue]=f.useState({mode:"waveform",color:"#66FCF1",sensitivity:50}),[se,ve]=f.useState(!0),Q=f.useRef(null);f.useEffect(()=>(c&&t?Q.current=window.setInterval(()=>{g(A=>{if(A>=t.durationSec){if(b==="one")return 0;if(a.length>0||se)be();else return i(!1),A;return 0}return A+1*w})},1e3/w):Q.current&&clearInterval(Q.current),()=>{Q.current&&clearInterval(Q.current)}),[c,t,b,w,a,se]),f.useEffect(()=>{t&&u(p/t.durationSec*100)},[p,t]);const H=(A,q)=>{if(t&&t.id!==A.id&&n(X=>[...X,t]),r(A),q){const X=q.findIndex(ht=>ht.id===A.id);X!==-1&&o(q.slice(X+1))}i(!0),g(0)},ne=()=>i(!c),be=()=>{if(a.length>0){const A=E?a[Math.floor(Math.random()*a.length)]:a[0];n(q=>t?[...q,t]:q),o(b!=="all"?q=>q.filter(X=>X.id!==A.id):q=>[...q.filter(X=>X.id!==A.id),A]),r(A),g(0),i(!0)}else if(se){const A=He[Math.floor(Math.random()*He.length)];n(q=>t?[...q,t]:q),r({...A,id:`auto-${Date.now()}`,title:`Autoplay: ${A.title}`}),g(0),i(!0)}else i(!1),g(0)},G=()=>{if(p>3)g(0);else if(l.length>0){const A=l[l.length-1];o(q=>t?[t,...q]:q),n(q=>q.slice(0,-1)),r(A),g(0),i(!0)}},re=A=>{if(t){const q=A/100*t.durationSec;g(q),u(A)}},pe=A=>y(A),we=()=>i(A=>!A),Y=()=>d(!E),K=()=>{const A=["off","all","one"],q=A[(A.indexOf(b)+1)%A.length];j(q)},N=()=>te(!W),B=()=>ve(!se),mt=A=>o(q=>[...q,A]),qs=A=>o(q=>[A,...q]),Ds=A=>o(q=>q.filter(X=>X.id!==A)),Os=()=>o([]),Ms=(A,q)=>{const X=Array.from(a),[ht]=X.splice(A,1);X.splice(q,0,ht),o(X)};return s.jsx(As.Provider,{value:{currentTrack:t,isPlaying:c,queue:a,history:l,progress:h,currentTime:p,duration:t?.durationSec||0,volume:x,isMuted:k,shuffle:E,repeatMode:b,playbackRate:w,pitchCorrection:W,visualizerSettings:Ie,autoplay:se,playTrack:H,togglePlay:ne,nextTrack:be,prevTrack:G,seek:re,setVolume:pe,toggleMute:we,toggleShuffle:Y,toggleRepeat:K,setPlaybackRate:_,togglePitchCorrection:N,setVisualizerSettings:ue,toggleAutoplay:B,addToQueue:mt,removeFromQueue:Ds,playNext:qs,reorderQueue:Ms,clearQueue:Os},children:e})},Is=f.forwardRef(({className:e,value:t=[0],onValueChange:r,min:a=0,max:o=100,step:l=1,disabled:n,"aria-label":c,"aria-labelledby":i,...h},u)=>{const p=x=>{const y=[Number(x.target.value)];r&&r(y)},g=(t[0]-a)/(o-a)*100;return s.jsxs("div",{className:S("relative flex w-full touch-none select-none items-center",e),children:[s.jsx("div",{className:"relative h-2 w-full grow overflow-hidden rounded-full bg-kodo-steel",children:s.jsx("div",{className:"absolute h-full bg-kodo-cyan transition-all",style:{width:`${g}%`}})}),s.jsx("input",{ref:u,type:"range",min:a,max:o,step:l,value:t[0],onChange:p,disabled:n,className:"absolute inset-0 w-full h-full opacity-0 cursor-pointer disabled:cursor-not-allowed","aria-label":c,"aria-labelledby":i,"aria-valuenow":t[0],"aria-valuemin":a,"aria-valuemax":o,...h}),s.jsx("div",{className:S("absolute h-5 w-5 rounded-full border-2 border-kodo-steel bg-white ring-offset-kodo-void transition-transform pointer-events-none",n&&"opacity-50"),style:{left:`calc(${g}% - 10px)`}})]})});Is.displayName="Slider";function Ho(){const{currentTrack:e,isPlaying:t,togglePlay:r,nextTrack:a,prevTrack:o,volume:l,setVolume:n,progress:c,duration:i,seek:h}=Wo(),[u,p]=f.useState(!1),[g,x]=f.useState(!1),y=k=>{if(!k)return"0:00";const C=Math.floor(k/60),E=Math.floor(k%60);return`${C}:${E.toString().padStart(2,"0")}`};return e?s.jsxs("div",{className:"fixed bottom-0 left-0 right-0 z-[100] h-24 bg-kodo-void/95 backdrop-blur-xl border-t border-white/10",onMouseEnter:()=>p(!0),onMouseLeave:()=>p(!1),children:[s.jsxs("div",{className:"absolute top-[-2px] left-0 right-0 h-[4px] cursor-pointer group z-20",onClick:k=>{const C=k.currentTarget.getBoundingClientRect();h((k.clientX-C.left)/C.width*100)},children:[s.jsx("div",{className:"absolute inset-0 bg-kodo-slate/30"}),s.jsx("div",{className:"absolute top-0 left-0 bottom-0 bg-kodo-cyan shadow-[0_0_15px_rgba(0,240,255,0.5)] transition-all duration-75 ease-linear",style:{width:`${c}%`}}),s.jsx("div",{className:"absolute top-0 left-0 bottom-0 w-full opacity-0 group-hover:opacity-100 bg-white/10 transition-opacity"})]}),s.jsxs("div",{className:"grid grid-cols-3 items-center h-full px-4 md:px-8 max-w-[1920px] mx-auto",children:[s.jsxs("div",{className:"flex items-center gap-4 min-w-0 justify-start",children:[s.jsx("div",{className:"relative group/art flex-shrink-0",children:s.jsxs("div",{className:S("w-14 h-14 rounded-md overflow-hidden border border-white/10 shadow-lg relative z-10 bg-kodo-graphite",t?"shadow-glow-cyan":""),children:[e.coverUrl?s.jsx("img",{src:e.coverUrl,alt:e.title,className:"w-full h-full object-cover"}):s.jsx("div",{className:"w-full h-full flex items-center justify-center bg-gradient-to-br from-kodo-graphite to-kodo-ink",children:s.jsx(xt,{className:"w-6 h-6 text-kodo-text-dim"})}),s.jsx("div",{className:"absolute inset-0 bg-black/50 flex items-center justify-center opacity-0 group-hover/art:opacity-100 transition-opacity cursor-pointer",children:s.jsx(Or,{className:"w-5 h-5 text-white"})})]})}),s.jsxs("div",{className:"min-w-0 hidden sm:block",children:[s.jsx(Ce,{to:`/tracks/${e.id}`,className:"block truncate hover:text-kodo-cyan transition-colors",children:s.jsx("h3",{className:"font-bold text-sm text-white truncate",children:e.title})}),s.jsx(Ce,{to:"#",className:"block truncate",children:s.jsx("p",{className:"text-xs text-kodo-text-dim hover:text-white transition-colors truncate",children:typeof e.artist=="string"?e.artist:"Artiste inconnu"})})]}),s.jsx("button",{className:"p-2 text-kodo-text-dim hover:text-kodo-magenta transition-colors hover:bg-white/5 rounded-full ml-2",children:s.jsx(is,{className:"w-5 h-5"})})]}),s.jsxs("div",{className:"flex flex-col items-center justify-center gap-1",children:[s.jsxs("div",{className:"flex items-center gap-4 md:gap-6",children:[s.jsx("button",{className:"text-kodo-text-dim hover:text-white transition-colors p-2 hidden md:block",children:s.jsx(Mr,{className:"w-4 h-4"})}),s.jsx("button",{onClick:o,className:"text-white hover:text-kodo-cyan transition-colors p-2 active:scale-95",children:s.jsx(zr,{className:"w-5 h-5 md:w-6 md:h-6 fill-current"})}),s.jsx("button",{onClick:r,className:"w-10 h-10 md:w-12 md:h-12 rounded-full bg-white text-black flex items-center justify-center hover:scale-105 active:scale-95 transition-all shadow-[0_0_20px_rgba(255,255,255,0.2)] hover:shadow-glow-cyan hover:bg-kodo-cyan",children:t?s.jsx(Ur,{className:"w-5 h-5 fill-current"}):s.jsx(Fr,{className:"w-5 h-5 fill-current ml-1"})}),s.jsx("button",{onClick:a,className:"text-white hover:text-kodo-cyan transition-colors p-2 active:scale-95",children:s.jsx(Vr,{className:"w-5 h-5 md:w-6 md:h-6 fill-current"})}),s.jsx("button",{className:"text-kodo-text-dim hover:text-white transition-colors p-2 hidden md:block",children:s.jsx($r,{className:"w-4 h-4"})})]}),s.jsxs("div",{className:"text-xs font-mono text-kodo-text-dim flex gap-2",children:[s.jsx("span",{children:y(c/100*(typeof i=="number"?i:0))}),s.jsx("span",{className:"text-white/20",children:"/"}),s.jsx("span",{children:y(typeof i=="number"?i:0)})]})]}),s.jsxs("div",{className:"flex items-center justify-end gap-2 md:gap-4",children:[s.jsx("button",{className:"hidden lg:block p-2 text-kodo-text-dim hover:text-white hover:bg-white/5 rounded-lg transition-colors",children:s.jsx(Qr,{className:"w-4 h-4"})}),s.jsx("button",{className:"hidden lg:block p-2 text-kodo-text-dim hover:text-white hover:bg-white/5 rounded-lg transition-colors",children:s.jsx(xt,{className:"w-4 h-4"})}),s.jsxs("div",{className:"flex items-center gap-2 group/volume w-32",onMouseEnter:()=>x(!0),onMouseLeave:()=>x(!1),children:[s.jsx("button",{onClick:()=>n(l===0?50:0),className:"p-2 text-kodo-text-dim hover:text-white transition-colors",children:l===0?s.jsx(Br,{className:"w-5 h-5"}):s.jsx(Wr,{className:"w-5 h-5"})}),s.jsx(Is,{value:[l],max:100,step:1,onValueChange:k=>n(k[0]),className:"w-20 md:w-24 cursor-pointer"})]})]})]})]}):null}function Go(){const e=f.useRef(null),{theme:t}=Ee();return f.useEffect(()=>{const r=e.current;if(!r)return;const a=r.getContext("2d");if(!a)return;const o=document.documentElement.classList.contains("light");let l,n=[];const c=window.innerWidth<768?20:50,i=150,h=o?"14, 165, 233":"102, 252, 241",u=o?"148, 163, 184":"102, 252, 241",p=()=>{r.width=window.innerWidth,r.height=window.innerHeight},g=()=>{n=[];for(let y=0;y<c;y++)n.push({x:Math.random()*r.width,y:Math.random()*r.height,size:Math.random()*(o?3:2),speedX:(Math.random()-.5)*.2,speedY:(Math.random()-.5)*.2,opacity:Math.random()*.5+.1})},x=()=>{a.clearRect(0,0,r.width,r.height),n.forEach((y,k)=>{y.x+=y.speedX,y.y+=y.speedY,y.x<0&&(y.x=r.width),y.x>r.width&&(y.x=0),y.y<0&&(y.y=r.height),y.y>r.height&&(y.y=0),a.beginPath(),a.arc(y.x,y.y,y.size,0,Math.PI*2),a.fillStyle=`rgba(${h}, ${y.opacity})`,a.fill();for(let C=k+1;C<n.length;C++){const E=n[C],d=y.x-E.x,b=y.y-E.y,j=Math.sqrt(d*d+b*b);if(j<i){a.beginPath();const w=o?.05:.1;a.strokeStyle=`rgba(${u}, ${w*(1-j/i)})`,a.lineWidth=.5,a.moveTo(y.x,y.y),a.lineTo(E.x,E.y),a.stroke()}}}),l=requestAnimationFrame(x)};return window.addEventListener("resize",p),p(),g(),x(),()=>{window.removeEventListener("resize",p),cancelAnimationFrame(l)}},[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-kodo-void 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-kodo-cyan/5 dark:bg-kodo-cyan/5 blur-[120px] animate-pulse"}),s.jsx("div",{className:"absolute bottom-[-20%] right-[-10%] w-[60%] h-[60%] rounded-full bg-kodo-magenta/5 dark:bg-kodo-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(--kodo-steel)) 1px, transparent 1px)",backgroundSize:"100px 100px"}})]})}function Yo({children:e}){const{sidebarOpen:t}=Ee();return s.jsxs("div",{className:"flex h-screen w-full overflow-hidden relative bg-kodo-void",children:[s.jsx(Go,{}),s.jsx(Bo,{}),s.jsxs("div",{className:S("flex-1 flex flex-col h-full relative z-10 transition-all duration-500 ease-in-out",t?"lg:ml-72":"lg:ml-28","ml-0"),children:[s.jsx($o,{}),s.jsx("main",{className:"flex-1 overflow-y-auto overflow-x-hidden pt-24 pb-32 px-4 md:px-8 custom-scrollbar",id:"main-scroll-container",children:s.jsx("div",{className:"max-w-[1600px] mx-auto w-full",children:e})}),s.jsx("div",{className:"absolute bottom-0 left-0 right-0 z-50",children:s.jsx(Ho,{})})]})]})}function Xo({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:S("flex flex-col items-center justify-center min-h-[200px]",t),children:[s.jsx("div",{className:S("animate-spin rounded-full border-2 border-kodo-steel border-t-blue-600",a[e]),role:"status","aria-label":"Chargement en cours",children:s.jsx("span",{className:"sr-only",children:"Chargement..."})}),r&&s.jsx("p",{className:"mt-2 text-sm text-kodo-content-dim dark:text-kodo-content-dim",children:r})]})}function Ps({pageName:e,error:t,onRetry:r}){return s.jsx("div",{className:"container mx-auto px-4 py-8",children:s.jsxs("div",{className:"max-w-2xl mx-auto",children:[s.jsxs("div",{className:"flex items-center gap-4 mb-4",children:[s.jsx(it,{className:"h-6 w-6 text-kodo-gold"}),s.jsx("h1",{className:"text-3xl font-bold",children:e})]}),s.jsxs("div",{className:"bg-kodo-gold/10 dark:bg-kodo-gold/20 border border-kodo-gold/30 dark:border-kodo-gold/40 text-kodo-gold dark:text-kodo-gold px-4 py-4 rounded-lg mb-4",children:[s.jsxs("p",{className:"font-medium mb-2",children:["Failed to load ",e]}),t&&s.jsx("p",{className:"text-sm opacity-75",children:t.message||"An error occurred while loading this page"})]}),s.jsxs("div",{className:"flex gap-4",children:[r&&s.jsxs(z,{onClick:r,variant:"outline",className:"flex items-center gap-2",children:[s.jsx(Kr,{className:"h-4 w-4"}),"Retry"]}),s.jsx(z,{onClick:()=>window.location.reload(),variant:"default",className:"flex items-center gap-2",children:"Refresh Page"})]})]})})}class Jo extends f.Component{constructor(t){super(t),this.state={hasError:!1}}static getDerivedStateFromError(t){return{hasError:!0,error:t}}componentDidCatch(t,r){m.error("[LazyComponent] Failed to load lazy component",{pageName:this.props.pageName,error:t.message,stack:t.stack,componentStack:r.componentStack}),this.props.onError&&this.props.onError(t,r)}handleRetry=()=>{this.setState({hasError:!1,error:void 0})};render(){return this.state.hasError?s.jsx(Ps,{pageName:this.props.pageName,error:this.state.error,onRetry:this.handleRetry}):this.props.children}}function Zo(e,t){return e().catch(r=>(m.error("[LazyComponent] Failed to import lazy component",{pageName:t,error:r instanceof Error?r.message:String(r),stack:r instanceof Error?r.stack:void 0}),Promise.resolve({default:()=>s.jsx(Ps,{pageName:t,error:r instanceof Error?r:new Error(String(r))})})))}function D(e,t,r){const a=r?()=>Zo(e,r):e,o=f.lazy(a);return function(n){const{fallback:c,...i}=n,h=s.jsx(f.Suspense,{fallback:s.jsx(Xo,{}),children:s.jsx(o,{...i})});return r?s.jsx(Jo,{pageName:r,children:h}):h}}const ei=D(()=>T(()=>import("./DashboardPage-DBeOkkV3.js"),__vite__mapDeps([3,1,0,2,4,5,6,7])).then(e=>({default:e.DashboardPage})),void 0,"Dashboard"),ti=D(()=>T(()=>import("./ChatPage-BfTFcCbO.js"),__vite__mapDeps([8,1,0,2,4,9,10,11,12,5,13,14,7,6])).then(e=>({default:e.ChatPage})),void 0,"Chat"),si=D(()=>T(()=>import("./LibraryPage-55ubQtbB.js"),__vite__mapDeps([15,1,0,2,4,16,9,13,12,5,17,10,18,7,6])).then(e=>({default:e.LibraryPage})),void 0,"Library"),ri=D(()=>T(()=>import("./ProfilePage-BgZBWx-u.js"),__vite__mapDeps([19,1,0,2,6,4,9,20,17,21,18,5,7])).then(e=>({default:e.ProfilePage})),void 0,"Profile"),ai=D(()=>T(()=>import("./SettingsPage-C3AsvyKj.js"),__vite__mapDeps([22,1,0,2,9,5,7,4,6])).then(e=>({default:e.SettingsPage})),void 0,"Settings"),oi=D(()=>T(()=>import("./LoginPage-BebUqHKQ.js"),__vite__mapDeps([23,1,0,2,7,6,24,25,5,4])).then(e=>({default:e.LoginPage})),void 0,"Login"),ii=D(()=>T(()=>import("./RegisterPage-CcmefX82.js"),__vite__mapDeps([26,1,0,2,7,6,24,5,4])).then(e=>({default:e.RegisterPage})),void 0,"Register"),ni=D(()=>T(()=>import("./ForgotPasswordPage-YxRqJouX.js"),__vite__mapDeps([27,1,0,2,7,28,29,4,6,5])),void 0,"Forgot Password"),li=D(()=>T(()=>import("./VerifyEmailPage-38fQWUYS.js"),__vite__mapDeps([30,1,0,2,7,28,4,6,5])),void 0,"Verify Email"),ci=D(()=>T(()=>import("./ResetPasswordPage-CmeLbHE0.js"),__vite__mapDeps([31,1,0,2,7,28,29,4,6,5])),void 0,"Reset Password"),di=D(()=>T(()=>import("./SessionsPage-C5XUNUhD.js"),__vite__mapDeps([32,1,0,2,33,14,5,7,4,6])),void 0,"Sessions"),ui=D(()=>T(()=>import("./NotFoundPage-BNqND_Xf.js"),__vite__mapDeps([34,1,0,2,7,5,4,6])),void 0,"Not Found"),mi=D(()=>T(()=>import("./ServerErrorPage-BBBqZ02f.js"),__vite__mapDeps([35,1,0,2,7,5,4,6])),void 0,"Server Error"),hi=D(()=>T(()=>import("./UserProfilePage-CGqKROeh.js"),__vite__mapDeps([36,1,0,2,7,4,21,16,37,38,39,5,40,41,42,6])).then(e=>({default:e.UserProfilePage})),void 0,"User Profile"),fi=D(()=>T(()=>import("./RolesPage-BazMBP1o.js"),__vite__mapDeps([43,1,0,2,39,33,9,10,20,5,11,12,7,4,6])).then(e=>({default:e.RolesPage})),void 0,"Roles"),pi=D(()=>T(()=>import("./TrackDetailPage-BJpZT2dq.js"),__vite__mapDeps([44,1,0,2,16,41,4,13,12,5,9,45,40,14,6,10,18,7])).then(e=>({default:e.TrackDetailPage})),void 0,"Track Detail"),gi=D(()=>T(()=>import("./routes-BW8tCpD8.js"),__vite__mapDeps([46,1,0,2,4,38,39,7,5,37,45,47,6,10,20,25,9,11,12,14,48,40,41,49])).then(e=>({default:e.PlaylistRoutes})),void 0,"Playlists"),yi=D(()=>T(()=>import("./SearchPage-CmFSjE4p.js"),__vite__mapDeps([50,1,0,2,7,4,9,41,38,39,5,40,48,47,6])).then(e=>({default:e.SearchPage})),void 0,"Search"),xi=D(()=>T(()=>import("./NotificationsPage-CJq_f7tr.js"),__vite__mapDeps([51,1,0,2,4,33,11,12,9,5,7,6])).then(e=>({default:e.NotificationsPage})),void 0,"Notifications"),vi=D(()=>T(()=>import("./MarketplaceHome-C8IsZMEQ.js"),__vite__mapDeps([52,1,0,2,33,5,9,11,12,10,47,7,4,6])).then(e=>({default:e.MarketplaceHome})),void 0,"Marketplace"),bi=D(()=>T(()=>import("./AnalyticsPage-CsUpS4-F.js"),__vite__mapDeps([53,1,0,2,11,12,9,5,7,4,6])).then(e=>({default:e.AnalyticsPage})),void 0,"Analytics"),wi=D(()=>T(()=>import("./WebhooksPage-BUKVljfN.js"),__vite__mapDeps([54,1,0,2,9,10,14,5,33,7,4,6])).then(e=>({default:e.WebhooksPage})),void 0,"Webhooks"),ki=D(()=>T(()=>import("./AdminDashboardPage-DO0rPMOR.js"),__vite__mapDeps([55,1,0,2,9,33,41,47,5,7,6,4])).then(e=>({default:e.AdminDashboardPage})),void 0,"Admin Dashboard"),Si=D(()=>T(()=>import("./DesignSystemDemoPage-Comnif18.js"),__vite__mapDeps([56,1,0,2,9,7,4,6,5])).then(e=>({default:e.default})),void 0,"Design System Demo"),_i=D(()=>T(()=>import("./SocialPage-DguJum4V.js"),__vite__mapDeps([57,1,0,2,5,42,7,4,6])).then(e=>({default:e.SocialPage})),void 0,"Social Feed"),ji=D(()=>T(()=>import("./GearPage-DM6CApaQ.js"),__vite__mapDeps([58,1,0,2,5,7,4,6])).then(e=>({default:e.GearPage})),void 0,"Gear Locker"),Ei=D(()=>T(()=>import("./LivePage-BPSq4nAF.js"),__vite__mapDeps([59,1,0,2,5,7,4,6])).then(e=>({default:e.LivePage})),void 0,"Live Sessions"),Ni=D(()=>T(()=>import("./EducationPage-B-YHj2Wa.js"),__vite__mapDeps([60,1,0,2,5,7,4,6])).then(e=>({default:e.EducationPage})),void 0,"Education"),Ti=D(()=>T(()=>import("./QueuePage-B8oRZVDA.js"),__vite__mapDeps([61,1,0,2,7,5,4,6])).then(e=>({default:e.QueuePage})),void 0,"Queue"),Ci=D(()=>T(()=>import("./DeveloperPage-Cm1O9pRO.js"),__vite__mapDeps([62,1,0,2,5,9,7,4,6])).then(e=>({default:e.DeveloperPage})),void 0,"Developer API");function F({children:e}){return s.jsx(Yo,{children:e})}function Pe({children:e}){const{isAuthenticated:t}=Cs(),r=!1,{isLoading:a}=Z();return a?null:t||r?s.jsx(Xe,{to:"/dashboard",replace:!0}):s.jsx(s.Fragment,{children:e})}const Ri=()=>s.jsxs(Vs,{children:[s.jsx(P,{path:"/login",element:s.jsx(Pe,{children:s.jsx(L,{children:s.jsx(oi,{})})})}),s.jsx(P,{path:"/register",element:s.jsx(Pe,{children:s.jsx(L,{children:s.jsx(ii,{})})})}),s.jsx(P,{path:"/forgot-password",element:s.jsx(Pe,{children:s.jsx(L,{children:s.jsx(ni,{})})})}),s.jsx(P,{path:"/verify-email",element:s.jsx(Pe,{children:s.jsx(L,{children:s.jsx(li,{})})})}),s.jsx(P,{path:"/reset-password",element:s.jsx(Pe,{children:s.jsx(L,{children:s.jsx(ci,{})})})}),s.jsx(P,{path:"/design-system",element:s.jsx(L,{children:s.jsx(Si,{})})}),s.jsx(P,{path:"/u/:username",element:s.jsx(L,{children:s.jsx(hi,{})})}),s.jsx(P,{path:"/dashboard",element:s.jsx(U,{children:s.jsx(F,{children:s.jsx(L,{children:s.jsx(ei,{})})})})}),s.jsx(P,{path:"/marketplace",element:s.jsx(U,{children:s.jsx(F,{children:s.jsx(L,{children:s.jsx(vi,{})})})})}),s.jsx(P,{path:"/chat",element:s.jsx(U,{children:s.jsx(F,{children:s.jsx(L,{children:s.jsx(ti,{})})})})}),s.jsx(P,{path:"/library",element:s.jsx(U,{children:s.jsx(F,{children:s.jsx(L,{children:s.jsx(si,{})})})})}),s.jsx(P,{path:"/profile",element:s.jsx(U,{children:s.jsx(F,{children:s.jsx(L,{children:s.jsx(ri,{})})})})}),s.jsx(P,{path:"/settings",element:s.jsx(U,{children:s.jsx(F,{children:s.jsx(L,{children:s.jsx(ai,{})})})})}),s.jsx(P,{path:"/settings/sessions",element:s.jsx(U,{children:s.jsx(F,{children:s.jsx(L,{children:s.jsx(di,{})})})})}),s.jsx(P,{path:"/admin/roles",element:s.jsx(U,{children:s.jsx(F,{children:s.jsx(L,{children:s.jsx(fi,{})})})})}),s.jsx(P,{path:"/tracks/:id",element:s.jsx(U,{children:s.jsx(F,{children:s.jsx(L,{children:s.jsx(pi,{})})})})}),s.jsx(P,{path:"/playlists/*",element:s.jsx(U,{children:s.jsx(F,{children:s.jsx(L,{children:s.jsx(gi,{})})})})}),s.jsx(P,{path:"/search",element:s.jsx(U,{children:s.jsx(F,{children:s.jsx(L,{children:s.jsx(yi,{})})})})}),s.jsx(P,{path:"/notifications",element:s.jsx(U,{children:s.jsx(F,{children:s.jsx(L,{children:s.jsx(xi,{})})})})}),s.jsx(P,{path:"/analytics",element:s.jsx(U,{children:s.jsx(F,{children:s.jsx(L,{children:s.jsx(bi,{})})})})}),s.jsx(P,{path:"/webhooks",element:s.jsx(U,{children:s.jsx(F,{children:s.jsx(L,{children:s.jsx(wi,{})})})})}),s.jsx(P,{path:"/admin",element:s.jsx(U,{children:s.jsx(F,{children:s.jsx(L,{children:s.jsx(ki,{})})})})}),s.jsx(P,{path:"/social",element:s.jsx(U,{children:s.jsx(F,{children:s.jsx(L,{children:s.jsx(_i,{})})})})}),s.jsx(P,{path:"/gear",element:s.jsx(U,{children:s.jsx(F,{children:s.jsx(L,{children:s.jsx(ji,{})})})})}),s.jsx(P,{path:"/live",element:s.jsx(U,{children:s.jsx(F,{children:s.jsx(L,{children:s.jsx(Ei,{})})})})}),s.jsx(P,{path:"/education",element:s.jsx(U,{children:s.jsx(F,{children:s.jsx(L,{children:s.jsx(Ni,{})})})})}),s.jsx(P,{path:"/queue",element:s.jsx(U,{children:s.jsx(F,{children:s.jsx(L,{children:s.jsx(Ti,{})})})})}),s.jsx(P,{path:"/developer",element:s.jsx(U,{children:s.jsx(F,{children:s.jsx(L,{children:s.jsx(Ci,{})})})})}),s.jsx(P,{path:"/404",element:s.jsx(L,{children:s.jsx(ui,{})})}),s.jsx(P,{path:"/500",element:s.jsx(L,{children:s.jsx(mi,{})})}),s.jsx(P,{path:"/",element:s.jsx(Xe,{to:"/dashboard",replace:!0})}),s.jsx(P,{path:"*",element:s.jsx(Xe,{to:"/404",replace:!0})})]});function Ai(e={}){const{enabled:t=!0,preventDefault:r=!0,onHelpOpen:a}=e,o=et(),{setSidebarOpen:l,sidebarOpen:n}=Ee(),c=f.useCallback(i=>{if(!t)return;const h=i.target;if(h&&(h.tagName==="INPUT"||h.tagName==="TEXTAREA"||h.isContentEditable===!0||h.getAttribute("role")==="textbox")){if(i.key==="k"&&(i.ctrlKey||i.metaKey)){r&&i.preventDefault();const u=document.querySelector('input[type="search"], input[placeholder*="search" i], input[placeholder*="rechercher" i]');u?(u.focus(),u.select()):o("/search");return}return}if((i.ctrlKey||i.metaKey)&&i.key==="k"){r&&i.preventDefault();const u=document.querySelector('input[type="search"], input[placeholder*="search" i], input[placeholder*="rechercher" i]');u?(u.focus(),u.select()):o("/search");return}if((i.ctrlKey||i.metaKey)&&i.key==="n"){r&&i.preventDefault(),o("/chat");return}if((i.ctrlKey||i.metaKey)&&i.key==="b"){r&&i.preventDefault(),l(!n);return}if(i.key==="Escape"){document.querySelectorAll('[role="menu"][aria-expanded="true"]').forEach(p=>{const g=p.previousElementSibling;g&&g.click()});return}if(i.key==="?"&&!i.ctrlKey&&!i.metaKey&&!i.shiftKey){r&&i.preventDefault(),a&&a();return}},[t,r,o,l,n,a]);f.useEffect(()=>{if(t)return window.addEventListener("keydown",c),()=>{window.removeEventListener("keydown",c)}},[t,c])}const he={SEARCH:"Ctrl+K",NEW_MESSAGE:"Ctrl+N",PLAY_PAUSE:"Space",NEXT_TRACK:"Ctrl+Right",PREVIOUS_TRACK:"Ctrl+Left",VOLUME_UP:"Ctrl+Up",VOLUME_DOWN:"Ctrl+Down",MUTE:"Ctrl+M",HELP:"?",ESCAPE:"Escape"};function Ii({open:e,onClose:t}){const{t:r}=Rs(),a=[{key:he.SEARCH,description:r("keyboard.shortcuts.search","Focus search or navigate to search page")},{key:he.NEW_MESSAGE,description:r("keyboard.shortcuts.newMessage","Open new chat/message")},{key:he.PLAY_PAUSE,description:r("keyboard.shortcuts.playPause","Play or pause current track")},{key:he.NEXT_TRACK,description:r("keyboard.shortcuts.nextTrack","Play next track")},{key:he.PREVIOUS_TRACK,description:r("keyboard.shortcuts.previousTrack","Play previous track")},{key:he.VOLUME_UP,description:r("keyboard.shortcuts.volumeUp","Increase volume")},{key:he.VOLUME_DOWN,description:r("keyboard.shortcuts.volumeDown","Decrease volume")},{key:he.MUTE,description:r("keyboard.shortcuts.mute","Toggle mute")},{key:"Ctrl+B / Cmd+B",description:r("keyboard.shortcuts.toggleSidebar","Toggle sidebar")},{key:he.ESCAPE,description:r("keyboard.shortcuts.escape","Close modals or go back")},{key:he.HELP,description:r("keyboard.shortcuts.help","Show this help dialog")}];return s.jsx(Ct,{open:e,onClose:t,title:r("keyboard.shortcuts.title","Keyboard Shortcuts"),size:"lg",children:s.jsx("div",{className:"space-y-4",children:a.map((o,l)=>s.jsxs("div",{className:"flex items-center justify-between border-b border-kodo-steel dark:border-kodo-steel pb-2 last:border-0",children:[s.jsx("span",{className:"text-sm text-kodo-content-dim dark:text-kodo-content-dim",children:o.description}),s.jsx("kbd",{className:"px-2 py-1 text-xs font-semibold text-kodo-text-main dark:text-kodo-text-main bg-kodo-void dark:bg-kodo-graphite border border-kodo-steel dark:border-kodo-steel rounded",children:o.key})]},l))})})}const Pi=tt()(Jt(st(e=>({filters:{},setFilters:t=>{e({filters:t})}}),{name:"library-storage",partialize:e=>({filters:e.filters})}),{name:"LibraryStore",enabled:!1}));async function Li(e={}){const{hydrateAuth:t=!0,hydrateLibrary:r=!1,hydrateChat:a=!1,requireAuth:o=!0}=e,l={success:!0,hydrated:[],errors:[]};try{if(o){const{isAuthenticated:n}=Z.getState();if(!n)return m.debug("[StateHydration] User not authenticated, skipping hydration"),l}if(t)try{const{isAuthenticated:n,isLoading:c}=Z.getState(),i=ce.hasTokens();n&&i&&!c||(await qi(),l.hydrated.push("auth"),m.debug("[StateHydration] Auth state hydrated"))}catch(n){const c=n instanceof Error?n:new Error(String(n));l.errors.push({store:"auth",error:c}),l.success=!1,m.error("[StateHydration] Failed to hydrate auth state",{error:c.message})}if(r)try{await Di(),l.hydrated.push("library"),m.debug("[StateHydration] Library state hydrated")}catch(n){const c=n instanceof Error?n:new Error(String(n));l.errors.push({store:"library",error:c}),l.success=!1,m.error("[StateHydration] Failed to hydrate library state",{error:c.message})}if(a)try{await Oi(),l.hydrated.push("chat"),m.debug("[StateHydration] Chat state hydrated")}catch(n){const c=n instanceof Error?n:new Error(String(n));l.errors.push({store:"chat",error:c}),l.success=!1,m.error("[StateHydration] Failed to hydrate chat state",{error:c.message})}}catch(n){const c=n instanceof Error?n:new Error(String(n));m.error("[StateHydration] Fatal error during hydration",{error:c.message}),l.success=!1}return l}async function qi(){const{refreshUser:e,isAuthenticated:t}=Z.getState();await e()}async function Di(){const{fetchFavorites:e}=Pi.getState();await e()}async function Oi(){m.debug("[StateHydration] Chat state hydration skipped - using React Query")}function Mi(e={}){const[t,r]=f.useState(!0),[a,o]=f.useState(null);return f.useEffect(()=>{let l=!0;return Li(e).then(n=>{l&&(o(n),r(!1))}).catch(n=>{l&&(m.error("[StateHydration] Hook error:",n),o({success:!1,hydrated:[],errors:[{store:"unknown",error:n instanceof Error?n:new Error(String(n))}]}),r(!1))}),()=>{l=!1}},[]),{isHydrating:t,hydrationResult:a}}function zi(){const e=jt();f.useEffect(()=>{const t=r=>{const{queryKeys:a,resourceType:o,resourceId:l}=r.detail;if(a&&a.length>0)for(const n of a)e.invalidateQueries({queryKey:n});if(o){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:[]}[o]||[];for(const i of c)e.invalidateQueries({queryKey:l?[...i,l]:i})}};return window.addEventListener("veza:invalidate-queries",t),()=>{window.removeEventListener("veza:invalidate-queries",t)}},[e])}function Ui(e){if(typeof window>"u"||!window.BroadcastChannel)return m.warn("[ReactQuerySync] BroadcastChannel not supported in this environment"),null;try{return new BroadcastChannel(e)}catch(t){return m.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 Fi(){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 Yt(){return`${Date.now()}-${Math.random().toString(36).substring(2,9)}`}function Vi(e,t={}){const r=t.channelName||"veza-react-query-sync",a=t.enabled!==!1,o=t.shouldSync||(()=>!0);if(!a)return()=>{};const l=Ui(r);if(!l)return m.warn("[ReactQuerySync] BroadcastChannel not available, sync disabled"),()=>{};const n=Fi(),c=new Set;let i=!1;function h(x){if(i||!o(x,"query-invalidate"))return;const y={type:"query-invalidate",queryKey:x,timestamp:Date.now(),messageId:Yt(),tabId:n};try{l&&(l.postMessage(y),m.debug("[ReactQuerySync] Broadcasted query invalidation",{queryKey:x,messageId:y.messageId}))}catch(k){m.error("[ReactQuerySync] Failed to broadcast invalidation",{error:k instanceof Error?k.message:String(k),queryKey:x})}}function u(x){const y=x.data;if(!(!y||typeof y!="object"||!y.type||!Array.isArray(y.queryKey)||typeof y.timestamp!="number"||typeof y.messageId!="string")&&!(y.type!=="query-invalidate"&&y.type!=="query-set-data"&&y.type!=="mutation-success")&&y.tabId!==n&&!c.has(y.messageId)&&(c.add(y.messageId),c.size>1e3&&Array.from(c).slice(0,500).forEach(C=>c.delete(C)),!!o(y.queryKey,y.type))){i=!0;try{switch(y.type){case"query-invalidate":e.invalidateQueries({queryKey:y.queryKey}),m.debug("[ReactQuerySync] Invalidated query from other tab",{queryKey:y.queryKey,messageId:y.messageId});break;case"query-set-data":y.data!==void 0&&(e.setQueryData(y.queryKey,y.data),m.debug("[ReactQuerySync] Updated query data from other tab",{queryKey:y.queryKey,messageId:y.messageId}));break;case"mutation-success":e.invalidateQueries({queryKey:y.queryKey}),m.debug("[ReactQuerySync] Invalidated queries after mutation from other tab",{queryKey:y.queryKey,messageId:y.messageId});break;default:m.warn("[ReactQuerySync] Unknown message type",{type:y.type,messageId:y.messageId})}}catch(k){m.error("[ReactQuerySync] Error processing sync message",{error:k instanceof Error?k.message:String(k),messageId:y.messageId,queryKey:y.queryKey})}finally{setTimeout(()=>{i=!1},50)}}}l.addEventListener("message",u);const p=e.getMutationCache().subscribe(x=>{if(!(!x||!l)&&x.type==="updated"&&x.mutation.state.status==="success"){const y=x.mutation.options.mutationKey;if(y){const k={type:"mutation-success",queryKey:y,timestamp:Date.now(),messageId:Yt(),tabId:n};try{l.postMessage(k),m.debug("[ReactQuerySync] Broadcasted mutation success",{queryKey:y,messageId:k.messageId})}catch(C){m.error("[ReactQuerySync] Failed to broadcast mutation",{error:C instanceof Error?C.message:String(C),queryKey:y})}}}}),g=e.getQueryCache().subscribe(x=>{if(x?.type==="removed"||x?.type==="updated"&&x.query?.state.isInvalidated){const y=x.query.queryKey;h(y)}});return m.info("[ReactQuerySync] React Query cache synchronization enabled",{channelName:r,tabId:n}),()=>{l.removeEventListener("message",u),p(),g(),l.close(),m.info("[ReactQuerySync] React Query cache synchronization disabled")}}function $i(){const{refreshUser:e}=Z(),{theme:t,setTheme:r,language:a,setLanguage:o}=Ee(),[l,n]=f.useState(!1),c=jt();return Ai({enabled:!0,onHelpOpen:()=>n(!0)}),Mi({hydrateAuth:!0,hydrateLibrary:!1,hydrateChat:!1,requireAuth:!1}),zi(),f.useEffect(()=>Vi(c,{enabled:!0,channelName:"veza-react-query-sync"}),[c]),f.useEffect(()=>{if((async()=>{await new Promise(u=>setTimeout(u,100));const{isAuthenticated:h}=Z.getState();h&&oe.refreshToken().catch(u=>{m.warn("Failed to fetch CSRF token on app init",{error:u instanceof Error?u.message:String(u),stack:u instanceof Error?u.stack:void 0})})})(),!t||t==="system"){const h=document.documentElement;!h.classList.contains("dark")&&!h.classList.contains("light")?r("dark"):r(t)}else r(t);if(typeof window<"u"&&window.i18n){const h=window.i18n.language||a;h!==a?window.i18n.changeLanguage(a):a!==h&&o(h)}},[e,r,t,a,o]),f.useEffect(()=>{if(t!=="system")return;const i=window.matchMedia("(prefers-color-scheme: dark)"),h=u=>{const p=document.documentElement;u.matches?p.classList.add("dark"):p.classList.remove("dark")};return i.addEventListener?i.addEventListener("change",h):i.addListener(h),()=>{i.removeEventListener?i.removeEventListener("change",h):i.removeListener(h)}},[t]),s.jsx(L,{children:s.jsx(_o,{children:s.jsxs(Ko,{children:[s.jsx(Io,{}),s.jsx(Ri,{}),s.jsx(xo,{}),s.jsx(Ii,{open:l,onClose:()=>n(!1)})]})})})}const Qi={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"},Bi={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é"}},Wi={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"},Ki={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..."}},Hi={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"}},Gi={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..."}},Yi={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..."},Xi={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"}},Ji={dashboard:"Tableau de bord",chat:"Chat",library:"Bibliothèque",profile:"Profil",settings:"Paramètres",menu:"Menu",close:"Fermer"},Zi={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é"},en={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"}}},tn={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"},sn={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"},rn={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"},an={title:"Recherche",placeholder:"Rechercher des pistes, playlists, utilisateurs...",results:"Résultats",noResults:"Aucun résultat trouvé",tracks:"Pistes",playlists:"Playlists",users:"Utilisateurs",all:"Tout"},on={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"},nn={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é"},ln={title:"Tableau de bord administrateur",users:"Utilisateurs",systemStats:"Statistiques système",auditLogs:"Journaux d'audit",suspiciousActivity:"Activité suspecte"},cn={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"}},dn={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"},un={common:Qi,auth:Bi,dashboard:Wi,chat:Ki,library:Hi,profile:Gi,settings:Yi,errors:Xi,navigation:Ji,validation:Zi,pwa:en,tracks:tn,playlists:sn,notifications:rn,search:an,analytics:on,webhooks:nn,admin:ln,keyboard:cn,player:dn},mn={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"},hn={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"}},fn={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"},pn={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..."}},gn={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"}},yn={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..."}},xn={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..."},vn={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"}},bn={dashboard:"Dashboard",chat:"Chat",library:"Library",profile:"Profile",settings:"Settings",menu:"Menu",close:"Close"},wn={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"},kn={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"}}},Sn={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"},_n={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"},jn={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"},En={title:"Search",placeholder:"Search tracks, playlists, users...",results:"Results",noResults:"No results found",tracks:"Tracks",playlists:"Playlists",users:"Users",all:"All"},Nn={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"},Tn={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"},Cn={title:"Admin Dashboard",users:"Users",systemStats:"System Statistics",auditLogs:"Audit Logs",suspiciousActivity:"Suspicious Activity"},Rn={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"}},An={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"},In={common:mn,auth:hn,dashboard:fn,chat:pn,library:gn,profile:yn,settings:xn,errors:vn,navigation:bn,validation:wn,pwa:kn,tracks:Sn,playlists:_n,notifications:jn,search:En,analytics:Nn,webhooks:Tn,admin:Cn,keyboard:Rn,player:An},Pn={fr:{translation:un},en:{translation:In}};rs.use(Hs).use(Gs).init({resources:Pn,fallbackLng:"en",debug:!1,interpolation:{escapeValue:!1},detection:{order:["localStorage","navigator","htmlTag"],caches:["localStorage"]}});typeof window<"u"&&(window.i18n=rs);function Ln(){const e="production";{m.debug("[Sentry] Error tracking disabled",{reason:"DSN not configured",environment:e});return}}const qn={theme:"system",setTheme:()=>null},Dn=f.createContext(qn);function On({children:e,defaultTheme:t="system",storageKey:r="vite-ui-theme"}){const[a,o]=f.useState(()=>localStorage.getItem(r)||t);f.useEffect(()=>{const n=window.document.documentElement;if(n.classList.remove("light","dark"),a==="system"){const c=window.matchMedia("(prefers-color-scheme: dark)").matches?"dark":"light";n.classList.add(c);return}n.classList.add(a)},[a]),f.useEffect(()=>{if(a!=="system")return;const n=window.matchMedia("(prefers-color-scheme: dark)"),c=()=>{const i=window.document.documentElement;n.matches?(i.classList.add("dark"),i.classList.remove("light")):(i.classList.add("light"),i.classList.remove("dark"))};return n.addEventListener("change",c),()=>n.removeEventListener("change",c)},[a]);const l={theme:a,setTheme:n=>{localStorage.setItem(r,n),o(n)}};return s.jsx(Dn.Provider,{value:l,value:l,children:e})}typeof window<"u"&&(window.addEventListener("error",e=>{},!0),window.addEventListener("unhandledrejection",e=>{}));Ln();const Ls=new Qs({defaultOptions:{queries:{retry:!1,refetchOnWindowFocus:!1,staleTime:60*1e3,gcTime:300*1e3,refetchOnMount:!0,refetchOnReconnect:!0}}});Yr(Ls);async function Mn(){lt.USE_MSW}const zn=()=>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 o of r)try{(o.cssRules!==null||o.href===null)&&a++}catch{o.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,o=setInterval(()=>{r++,(t()||r>=a)&&(clearInterval(o),requestAnimationFrame(()=>{requestAnimationFrame(()=>{requestAnimationFrame(()=>{setTimeout(()=>{e()},50)})})}))},50)},{once:!0});else{let r=0;const a=20,o=setInterval(()=>{r++,(t()||r>=a)&&(clearInterval(o),requestAnimationFrame(()=>{requestAnimationFrame(()=>{requestAnimationFrame(()=>{setTimeout(()=>{e()},50)})})}))},50)}}),Un=()=>{Us.createRoot(document.getElementById("root")).render(s.jsx(fe.StrictMode,{children:s.jsx(Bs,{client:Ls,children:s.jsx(On,{defaultTheme:"dark",storageKey:"vite-ui-theme",children:s.jsxs($s,{future:{v7_startTransition:!0,v7_relativeSplatPath:!0},children:[s.jsx($i,{}),s.jsx(Zr,{position:"top-right"})]})})})}))},Fn=T(()=>import("./vendor-IYr-MHu4.js").then(e=>e.W),__vite__mapDeps([0,1,2])).then(e=>e).catch(e=>{});Promise.all([Mn(),Fn]).then(()=>{}).catch(e=>{m.error("[Init] Failed to initialize; continuing",{error:e instanceof Error?e.message:String(e),stack:e instanceof Error?e.stack:void 0})}).then(()=>zn()).finally(()=>{Un()});export{Go as A,z as B,vs as C,Ct as D,Ss as E,Ma as F,Do as G,qo as H,lo as I,Lo as J,Xa as K,Xo as L,Za as M,St as N,Zn as P,Is as S,Vo as T,T as _,O as a,Ha as b,Ga as c,S as d,bs as e,_s as f,Oo as g,Z as h,lt as i,Cs as j,Xn as k,m as l,Jn as m,Wo as n,ct as o,$ as p,Gn as q,Rs as r,no as s,Ee as t,Ts as u,Ya as v,Hn as w,Yn as x,ee as y,kt as z};