veza/apps/web/dist_verification/assets/index-BMBS6scK.js
senke 670282989b chore(refactor/sumi-migration): commit pending changes — tests, stream server, dist_verification
- apps/web: test updates (Vitest/setup), playbackAnalyticsService, TrackGrid, serviceErrorHandler
- veza-common: logging, metrics, traits, validation, random
- veza-stream-server: audio pipeline, codecs, cache, monitoring, routes
- apps/web/dist_verification: refresh build assets (content-hashed filenames)

Co-authored-by: Cursor <cursoragent@cursor.com>
2026-02-13 19:39:18 +01:00

5 lines
227 KiB
JavaScript
Raw Blame History

This file contains invisible Unicode characters

This file contains invisible Unicode characters that are indistinguishable to humans but may be processed differently by a computer. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

const __vite__mapDeps=(i,m=__vite__mapDeps,d=(m.f||(m.f=["assets/vendor-CjLUfV8Y.js","assets/vendor-react-C9dYU-TK.js","assets/vendor-security-DsrNJhpn.js","assets/vendor-BD_zwJK7.css","assets/DashboardPage-D6OLFNKT.js","assets/vendor-router-Dr0ZB7zf.js","assets/vendor-tanstack-C4XaEYj2.js","assets/chatStore-Cmmpwqns.js","assets/vendor-motion-CbAtAbUE.js","assets/AnimatedNumber-C7V3zEin.js","assets/vendor-icons-BSV6HBy1.js","assets/vendor-http-CctT3C58.js","assets/vendor-utils-D0JLFg89.js","assets/vendor-i18n-PN7w4axr.js","assets/ChatPage-sofPTFXq.js","assets/input-DeoQfymd.js","assets/Select-EdCpbbCo.js","assets/dropdown-CPqsiWN7.js","assets/useIsRateLimited-8kuXO8Mx.js","assets/confirmation-dialog-BlZmJOYR.js","assets/avatar-DAue0w7u.js","assets/LibraryPage-Xac4xZs3.js","assets/ContentFadeIn-BtLzuDVj.js","assets/tracks-0_sMTeS6.js","assets/trackService-Dud99AaM.js","assets/progress-DFVonymQ.js","assets/alert-Bql2WpQW.js","assets/UserProfilePage-BY1UfRZ4.js","assets/users-DUDxrQC-.js","assets/PlaylistCard-CqgUraN5.js","assets/features-YjpC8xHw.js","assets/socialService-686c7vsx.js","assets/Tabs-CJTCBu5-.js","assets/SettingsPage-BMJ_8iej.js","assets/checkbox-BKePitYZ.js","assets/LoginPage-BPKFxiYA.js","assets/AuthInput-b0K9khMl.js","assets/AuthLayout-JL7y5GL_.js","assets/RegisterPage-Cbos2bd-.js","assets/PasswordStrengthIndicator-BcWVshm9.js","assets/ForgotPasswordPage-RlEQXPkX.js","assets/usePasswordReset-PwlpCC1O.js","assets/VerifyEmailPage-aMulf8Pk.js","assets/ResetPasswordPage-DNSUNR25.js","assets/SessionsPage-BPgyk4mW.js","assets/NotFoundPage-AehFEVgj.js","assets/ServerErrorPage-BoBd7eZS.js","assets/RolesPage-i5tov1x5.js","assets/textarea-BawmBRjl.js","assets/TrackDetailPage-BzykkTeC.js","assets/useCopyToClipboard-BDqgiukK.js","assets/routes-KmsO9QV6.js","assets/Pagination-CkOjBWBf.js","assets/useDebounce-DiZU1F-R.js","assets/routes-B3giLbLK.css","assets/AdminDashboardView-Cmv8FbBs.js","assets/AnalyticsView-D_bU_Pla.js","assets/StatCard-DakRAUmq.js","assets/WebhooksView-C8RuIjXM.js","assets/webhookService-tqAepGmM.js","assets/DesignSystemDemo-De2IQDmR.js","assets/SocialView-BmPOCTMY.js","assets/GearView-B_mOp1cS.js","assets/LiveView-DqMcTM99.js","assets/EducationView-BV-pE4DL.js","assets/QueueView-Bd8wdqCc.js","assets/DeveloperDashboardView-CdZjYMe3.js","assets/NotificationsView-DebhDPTK.js","assets/MarketplaceHome-D5kxjtO5.js","assets/marketplaceService-CrW-4Obb.js","assets/cartStore-DGmCKIAR.js","assets/SearchPage-C2Q4Rdlj.js","assets/SellerDashboardView-drijru-x.js","assets/commerceService-bs-xd9qB.js","assets/WishlistView-Becoqfzm.js","assets/PurchasesView-Dc_dipW8.js"])))=>i.map(i=>d[i]);
import{a as f,j as r,R as Rt,c as xr,d as ds}from"./vendor-react-C9dYU-TK.js";import{N as et,a as at,L as tt,d as ms,R as fs,c as xe,B as hs}from"./vendor-router-Dr0ZB7zf.js";import{b as br,u as At,a as Kt,Q as ps,c as gs}from"./vendor-tanstack-C4XaEYj2.js";import{ab as nt,ac as it,ad as vs,av as ys,aw as xs,ax as bs,ay as wr,az as ws}from"./vendor-CjLUfV8Y.js";import{a as Le,A as De}from"./vendor-http-CctT3C58.js";import{s as x,o as R,Z as Pt,r as Me,b as se,e as ae,d as fe,n as $,g as oe,a as ks,c as Es}from"./vendor-utils-D0JLFg89.js";import{g as ye,b as Oe,R as kr,H as Er,I as ot,e as Ee,d as Ss,X as he,c as Ae,i as js,a6 as Ns,b1 as _s,aE as Ht,a3 as Ts,b2 as Cs,b3 as Rs,a1 as Sr,A as As,a7 as jr,C as Ps,aL as Is,b4 as Ls,S as Ds,b5 as qs,ad as Ms,ai as Nr,aw as _r,au as Os,b6 as zs,b7 as Fs,b8 as Vs,l as Us,n as $s,_ as Qs,f as Bs,b9 as Ks,u as It,ba as Hs,o as Lt,D as Ws,aH as Gs,W as Xs,ah as Ys,V as Js,U as Zs,bb as ea,bc as ta,bd as ra,be as sa,b0 as Tr,bf as Cr,q as Rr,r as Ar,bg as Pr,bh as Ir,v as aa,m as na,af as ia,bi as Wt,bj as oa,bk as la,bl as ca,aj as Gt}from"./vendor-icons-BSV6HBy1.js";import{A as Dt,m as we}from"./vendor-motion-CbAtAbUE.js";import{u as qt,i as Lr,B as ua,a as da}from"./vendor-i18n-PN7w4axr.js";import"./vendor-security-DsrNJhpn.js";(function(){const t=document.createElement("link").relList;if(t&&t.supports&&t.supports("modulepreload"))return;for(const n of document.querySelectorAll('link[rel="modulepreload"]'))a(n);new MutationObserver(n=>{for(const i of n)if(i.type==="childList")for(const o of i.addedNodes)o.tagName==="LINK"&&o.rel==="modulepreload"&&a(o)}).observe(document,{childList:!0,subtree:!0});function s(n){const i={};return n.integrity&&(i.integrity=n.integrity),n.referrerPolicy&&(i.referrerPolicy=n.referrerPolicy),n.crossOrigin==="use-credentials"?i.credentials="include":n.crossOrigin==="anonymous"?i.credentials="omit":i.credentials="same-origin",i}function a(n){if(n.ep)return;n.ep=!0;const i=s(n);fetch(n.href,i)}})();const ma="modulepreload",fa=function(e){return"/"+e},Xt={},T=function(t,s,a){let n=Promise.resolve();if(s&&s.length>0){let l=function(h){return Promise.all(h.map(u=>Promise.resolve(u).then(d=>({status:"fulfilled",value:d}),d=>({status:"rejected",reason:d}))))};document.getElementsByTagName("link");const o=document.querySelector("meta[property=csp-nonce]"),c=o?.nonce||o?.getAttribute("nonce");n=l(s.map(h=>{if(h=fa(h),h in Xt)return;Xt[h]=!0;const u=h.endsWith(".css"),d=u?'[rel="stylesheet"]':"";if(document.querySelector(`link[href="${h}"]${d}`))return;const m=document.createElement("link");if(m.rel=u?"stylesheet":ma,u||(m.as="script"),m.crossOrigin="",m.href=h,c&&m.setAttribute("nonce",c),document.head.appendChild(m),u)return new Promise((v,p)=>{m.addEventListener("load",v),m.addEventListener("error",()=>p(new Error(`Unable to preload CSS for ${h}`)))})}))}function i(o){const c=new Event("vite:preloadError",{cancelable:!0});if(c.payload=o,window.dispatchEvent(c),!c.defaultPrevented)throw o}return n.then(o=>{for(const c of o||[])c.status==="rejected"&&i(c.reason);return t().catch(i)})};let Dr=null;function ha(e){Dr=e}function pa(){return Dr}const ga=f.lazy(()=>T(()=>import("./vendor-CjLUfV8Y.js").then(e=>e.aB),__vite__mapDeps([0,1,2,3])).then(e=>({default:e.Toaster})));function va(e){return r.jsx(f.Suspense,{fallback:null,children:r.jsx(ga,{...e})})}const Yt="veza_access_token",Jt="veza_refresh_token";class te{static setTokens(t,s){try{localStorage.removeItem(Yt),localStorage.removeItem(Jt)}catch{}}static getAccessToken(){return null}static getRefreshToken(){return null}static clearTokens(){try{localStorage.removeItem(Yt),localStorage.removeItem(Jt)}catch{}}static hasTokens(){return!1}}const ya="WARN".toUpperCase();let rt={};function Zt(e){rt={...rt,...e}}function xa(){return{...rt}}function Be(e,t,s,...a){const n={...rt,...s},i=new Date().toISOString();{const o={timestamp:i,level:e,message:t,...n,...a.length>0&&{data:a}},c=JSON.stringify(o);console.log(c);const l="https://api.veza.com/api/v1/logs/frontend";l&&ba(l,o).catch(()=>{})}}async function ba(e,t){try{if(navigator.sendBeacon){const s=new Blob([JSON.stringify(t)],{type:"application/json"});navigator.sendBeacon(e,s)}else await fetch(e,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(t),keepalive:!0})}catch{}}function Ke(e){const t=["DEBUG","INFO","WARN","ERROR"],s=t.indexOf(ya),a=t.indexOf(e);return s===-1||a===-1?!0:a>=s}const g={debug:(e,t,...s)=>{Ke("DEBUG")&&Be("DEBUG",e,t,...s)},info:(e,t,...s)=>{Ke("INFO")&&Be("INFO",e,t,...s)},warn:(e,t,...s)=>{Ke("WARN")&&Be("WARN",e,t,...s)},error:(e,t,...s)=>{Ke("ERROR")&&Be("ERROR",e,t,...s)}},de=T(()=>import("./vendor-CjLUfV8Y.js").then(e=>e.aB),__vite__mapDeps([0,1,2,3]));let Je=null,Et=!1;de.then(e=>{Je=e,Et=!0}).catch(()=>{Et=!0});function er(){return!Je&&Et?(g.error("Toast module failed to load"),{success:()=>{},error:()=>{},loading:()=>{},custom:()=>{},dismiss:()=>{},remove:()=>{},promise:()=>Promise.resolve()}):Je?Je.default:{success:(...e)=>{de.then(t=>t.default.success(...e))},error:(...e)=>{de.then(t=>t.default.error(...e))},loading:(...e)=>{de.then(t=>t.default.loading(...e))},custom:(...e)=>{de.then(t=>t.default.custom(...e))},dismiss:(...e)=>{de.then(t=>t.default.dismiss(...e))},remove:(...e)=>{de.then(t=>t.default.remove(...e))},promise:(...e)=>de.then(t=>t.default.promise(...e))}}const B=new Proxy({},{get(e,t){const s=er();if(t in s){const a=s[t];return typeof a=="function"?a.bind(s):a}},apply(e,t,s){const a=er();return typeof a=="function"?a(...s):de.then(n=>n.default(...s))}});let vt=null;const wa=60*1e3,ka=240*1e3;let Pe=null,ke=null;function Ea(){return vt||(vt=Le.create({baseURL:"https://api.veza.com/api/v1",timeout:1e4,headers:{"Content-Type":"application/json"},withCredentials:!0})),vt}async function qe(){try{const t=await Ea().post("/auth/refresh",{});let s;if(t.data?.success&&t.data?.data)s=t.data.data.expires_in;else if(t.data?.access_token)s=t.data.expires_in||3600;else throw new Error(`Invalid refresh response format. Expected { success: true, data: { access_token, refresh_token, expires_in } } or { access_token, refresh_token, expires_in }, got: ${JSON.stringify(t.data)}`);te.setTokens("","cookie-based"),qr(s)}catch(e){throw te.clearTokens(),lt(),e}}function qr(e=300){lt(),Sa();const t=e*1e3,s=Math.max(0,t-wa);if(s<=0){qe().catch(a=>{g.warn("Proactive token refresh failed",{error:a instanceof Error?a.message:String(a),stack:a instanceof Error?a.stack:void 0})});return}Pe=setTimeout(()=>{qe().catch(a=>{g.warn("Proactive token refresh failed",{error:a instanceof Error?a.message:String(a),stack:a instanceof Error?a.stack:void 0})}),Pe=null},s)}function Sa(){ke&&clearInterval(ke),ke=setInterval(()=>{qe().catch(e=>{g.warn("Periodic token refresh failed",{error:e instanceof Error?e.message:String(e),stack:e instanceof Error?e.stack:void 0}),lt()})},ka)}function lt(){Pe&&(clearTimeout(Pe),Pe=null),ke&&(clearInterval(ke),ke=null)}function Mt(){qr(300)}function Mr(){lt()}const ja=Object.freeze(Object.defineProperty({__proto__:null,cleanupProactiveRefresh:Mr,initializeProactiveRefresh:Mt,refreshToken:qe},Symbol.toStringTag,{value:"Module"})),He=x().refine(e=>{if(!e)return!1;if(/^https?:\/\//.test(e)||/^wss?:\/\//.test(e))try{return new URL(e),!0}catch{return!1}return e.startsWith("/")},{message:"Must be a valid URL or a path starting with /"}),tr="veza.fr",Na=R({VITE_DOMAIN:x().default("veza.fr"),VITE_API_URL:He.default("/api/v1"),VITE_WS_URL:He.default(`ws://${tr}:8081/ws`),VITE_STREAM_URL:He.default(`ws://${tr}:8082/stream`),VITE_UPLOAD_URL:He.default("/upload"),VITE_APP_NAME:x().default("Veza"),VITE_API_VERSION:x().default("v1"),VITE_DEBUG:x().transform(e=>e==="true"||e==="1").default("false"),VITE_USE_MSW:x().transform(e=>e==="1"||e==="true").default("0"),VITE_FCM_VAPID_KEY:x().optional(),VITE_SENTRY_DSN:x().url().optional()}),_a=()=>{try{return Na.parse({VITE_DOMAIN:"veza.fr",VITE_API_URL:"https://api.veza.com/api/v1",VITE_WS_URL:"wss://api.veza.com/ws",VITE_STREAM_URL:"https://api.veza.com/stream",VITE_UPLOAD_URL:"https://api.veza.com/upload",VITE_APP_NAME:void 0,VITE_API_VERSION:"v1",VITE_DEBUG:void 0,VITE_USE_MSW:void 0,VITE_FCM_VAPID_KEY:void 0,VITE_SENTRY_DSN:void 0})}catch(e){throw e instanceof Pt?(g.error("❌ Invalid environment variables",{errors:e.errors}),new Error(`Environment variables validation failed: ${e.errors.map(t=>`${t.path.join(".")}: ${t.message}`).join(", ")}`)):e}},ne=_a(),ct={DOMAIN:ne.VITE_DOMAIN,API_URL:ne.VITE_API_URL,WS_URL:ne.VITE_WS_URL,STREAM_URL:ne.VITE_STREAM_URL,UPLOAD_URL:ne.VITE_UPLOAD_URL,APP_NAME:ne.VITE_APP_NAME,API_VERSION:ne.VITE_API_VERSION,DEBUG:ne.VITE_DEBUG,USE_MSW:ne.VITE_USE_MSW,FCM_VAPID_KEY:ne.VITE_FCM_VAPID_KEY,SENTRY_DSN:ne.VITE_SENTRY_DSN},ie={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."},Ta={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 Ca(e,t){return e in ie?ie[e]:t||ie.UNKNOWN}function Ra(e,t,s){const a=Ta[e];return a&&t in a?a[t]:s||ie.UNKNOWN}function Or(e,t,s=!1){if(e&&typeof e=="object"&&"code"in e&&"message"in e){const a=e,n=typeof a.code=="number"?a.code:0;if(t&&n>=400&&n<500){const i=Aa(a.message),o=Ra(t,i,void 0);if(o!==ie.UNKNOWN)return o}if(n>0){const i=Ca(n,a.message);if(s&&a.details&&Array.isArray(a.details)){const o=a.details.map(c=>c.message||c.field).filter(Boolean).join(", ");if(o)return`${i} (${o})`}return i}return a.message||ie.UNKNOWN}if(e instanceof Error)return e.message||ie.UNKNOWN;if(e&&typeof e=="object"&&"code"in e){const a=e.code;if(a==="ECONNABORTED"||a==="ETIMEDOUT")return ie.TIMEOUT;if(a==="ERR_NETWORK"||!e.response)return ie.NETWORK}return ie.UNKNOWN}function Aa(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 zr={timeout:ie.TIMEOUT};function Pa(e){if(e instanceof Error)return e.message===zr.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 Ia(){return typeof navigator>"u"?!0:navigator.onLine}function La(){return!Ia()}function W(e){if(qa(e))return e;if(Ma(e)){const t=e,s=t.response?.data,a=l=>typeof l=="object"&&l!==null&&"success"in l&&l.success===!1&&"error"in l,n=l=>typeof l=="object"&&l!==null&&"error"in l&&typeof l.error=="object",i=l=>typeof l=="object"&&l!==null&&"code"in l&&"message"in l;if(s){if(a(s))return yt(s.error);if(n(s)){const l=s.error;if(l&&("code"in l||"message"in l))return yt(l)}if(i(s))return yt(s)}if(t.request&&!t.response)return Pa(t)?{code:0,message:zr.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"||La()?{code:0,message:"No internet connection: Please check your network settings and try again.",timestamp:new Date().toISOString()}:{code:0,message:"Network error: Unable to connect to server. Please check your connection and try again.",timestamp:new Date().toISOString()};const o=t.response?.status;if(o===429){const l=t.response?.headers||{},h=s,u=l["x-ratelimit-limit"]?parseInt(String(l["x-ratelimit-limit"]),10):void 0,d=l["x-ratelimit-remaining"]?parseInt(String(l["x-ratelimit-remaining"]),10):void 0,m=l["x-ratelimit-reset"]?parseInt(String(l["x-ratelimit-reset"]),10):void 0,v=l["retry-after"]?parseInt(String(l["retry-after"]),10):h?.error?.retry_after||60,p=m?new Date(m*1e3):void 0,w=p?Math.max(0,Math.ceil((p.getTime()-Date.now())/1e3)):v;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 ${w} seconde${w>1?"s":""}.`},...d!==void 0?[{field:"remaining",message:`${d} requête${d>1?"s":""} restante${d>1?"s":""}`}]:[]],retry_after:w}}if(o===503){const l=s;return{code:503,message:l?.message||"Service temporairement indisponible. Veuillez réessayer dans quelques instants.",timestamp:new Date().toISOString(),details:St(l?.details)}}if(o===502){const l=s;return{code:502,message:l?.message||"Erreur de communication avec le serveur. Veuillez réessayer plus tard.",timestamp:new Date().toISOString(),details:St(l?.details)}}return o===423?{code:423,message:s?.message||"This action cannot be completed right now. The resource may be locked or your account may be temporarily restricted. Please try again later.",timestamp:new Date().toISOString()}:{code:o||0,message:s?.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 St(e){if(!Array.isArray(e))return;const t=e.filter(s=>typeof s=="object"&&s!==null&&"field"in s&&"message"in s&&typeof s.field=="string"&&typeof s.message=="string");return t.length>0?t:void 0}function Da(e){if(typeof e=="object"&&e!==null&&!Array.isArray(e))return e}function yt(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:St(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:Da(t.context)}}function ec(e,t=!1){const s=typeof e.message=="string"?e.message:"An error occurred";let a=s;if(e.details&&Array.isArray(e.details)&&e.details.length>0){const n=e.details.map(i=>{const o=typeof i.field=="string"?i.field:String(i.field),c=typeof i.message=="string"?i.message:String(i.message);return`${o}: ${c}`}).join(", ");a=`${s} (${n})`}return t&&e.request_id&&(a=`${a} [Request ID: ${e.request_id}]`),a}function ut(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,s=typeof t.code=="number"?t.code:parseInt(String(t.code||0),10);if(s===0)return"network";if(s>=400&&s<500)return s===401?"authentication":s===403?"authorization":s===404?"not_found":s===422?(t.details&&Array.isArray(t.details)&&t.details.length>0,"validation"):s===429?"rate_limit":"validation";if(s>=500&&s<600)return s===504||s===408?"timeout":"server_error"}if(e instanceof Error){const t=e.message.toLowerCase(),s=e.name.toLowerCase();if(t.includes("network")||t.includes("fetch")||t.includes("connection")||t.includes("offline")||s==="networkerror"||s==="typeerror")return"network";if(t.includes("timeout")||s==="timeouterror")return"timeout";if(t.includes("abort")||s==="aborterror")return"network"}return"unknown"}function qa(e){return typeof e=="object"&&e!==null&&"code"in e&&"message"in e&&typeof e.code=="number"&&typeof e.message=="string"}function Ma(e){return typeof e=="object"&&e!==null&&"isAxiosError"in e&&e.isAxiosError===!0}class Oa{token=null;refreshPromise=null;async refreshToken(){return this.refreshPromise?this.refreshPromise:(this.refreshPromise=(async()=>{try{const s=(await F.get("/csrf-token")).data;return this.token=s.csrf_token,this.token}catch(t){const s=t instanceof Error?t.message:String(t);throw s.includes("HTML page instead of JSON")||g.error("Failed to fetch CSRF token",{message:s}),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 Z=new Oa;class za{queue=[];isProcessing=!1;maxQueueSize=100;defaultMaxRetries=3;defaultRetryDelay=1e3;constructor(){this.loadQueue(),typeof window<"u"&&(window.addEventListener("online",()=>{g.info("[OfflineQueue] Connection restored, processing queue"),this.processQueue()}),navigator.onLine&&this.queue.length>0&&setTimeout(()=>{this.processQueue()},1e3))}isOffline(){return typeof navigator>"u"?!1:!navigator.onLine}generateRequestId(){return`req_${Date.now()}_${Math.random().toString(36).substr(2,9)}`}async queueRequest(t,s={}){const{priority:a="normal"}=s;if(this.queue.length>=this.maxQueueSize){const c=this.queue.findIndex(l=>l.priority==="low");c!==-1?this.queue.splice(c,1):this.queue.shift()}const n={id:this.generateRequestId(),config:t,timestamp:Date.now(),retryCount:0,priority:a},i={high:0,normal:1,low:2},o=this.queue.findIndex(c=>i[c.priority]>i[a]);return o===-1?this.queue.push(n):this.queue.splice(o,0,n),await this.saveQueue(),g.info(`[OfflineQueue] Request queued: ${t.method?.toUpperCase()} ${t.url}`,{requestId:n.id,priority:a,queueSize:this.queue.length}),n.id}async processQueue(){if(!(this.isProcessing||this.isOffline()||this.queue.length===0)){for(this.isProcessing=!0,g.info(`[OfflineQueue] Processing ${this.queue.length} queued requests`);this.queue.length>0&&!this.isOffline();){const t=this.queue[0];if(!t)break;try{await F.request(t.config),this.queue.shift(),await this.saveQueue(),g.info(`[OfflineQueue] Request succeeded: ${t.config.method?.toUpperCase()} ${t.config.url}`,{requestId:t.id}),await new Promise(s=>setTimeout(s,100))}catch(s){t.retryCount++;const a=this.defaultMaxRetries;if(t.retryCount>=a?(g.error(`[OfflineQueue] Request failed after ${a} retries: ${t.config.method?.toUpperCase()} ${t.config.url}`,{requestId:t.id,error:s}),this.queue.shift(),await this.saveQueue()):(this.queue.shift(),this.queue.push(t),await this.saveQueue(),await new Promise(n=>setTimeout(n,this.defaultRetryDelay*t.retryCount))),this.isOffline()){g.warn("[OfflineQueue] Connection lost, stopping queue processing");break}}}this.isProcessing=!1,this.queue.length>0?g.info(`[OfflineQueue] Queue processing complete, ${this.queue.length} requests remaining`):g.info("[OfflineQueue] All queued requests processed successfully")}}getQueueSize(){return this.queue.length}getQueue(){return[...this.queue]}async clearQueue(){this.queue=[],await this.saveQueue(),g.info("[OfflineQueue] Queue cleared")}async removeRequest(t){const s=this.queue.findIndex(a=>a.id===t);return s!==-1?(this.queue.splice(s,1),await this.saveQueue(),g.info(`[OfflineQueue] Request removed from queue: ${t}`),!0):!1}async saveQueue(){try{if(typeof window<"u"&&window.localStorage){const t=JSON.stringify(this.queue);localStorage.setItem("veza_offline_queue",t)}}catch(t){g.error("[OfflineQueue] Failed to save queue to localStorage",{error:t})}}async loadQueue(){try{if(typeof window<"u"&&window.localStorage){const t=localStorage.getItem("veza_offline_queue");if(t){const s=JSON.parse(t),a=Date.now()-1440*60*1e3;this.queue=s.filter(n=>n.timestamp>a),this.queue.length!==s.length&&await this.saveQueue(),g.info(`[OfflineQueue] Loaded ${this.queue.length} requests from storage`)}}}catch(t){g.error("[OfflineQueue] Failed to load queue from localStorage",{error:t}),this.queue=[]}}shouldQueueRequest(t){const s=t.method?.toUpperCase();return s==="GET"?!1:["POST","PUT","DELETE","PATCH"].includes(s||"")}}const me=new za;class Fa{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 s=(t.method||"GET").toUpperCase(),a=t.url||"",n=t.baseURL||"",i=a.startsWith("http")?a:`${n}${a}`,o=t.params?Object.keys(t.params).sort().map(l=>`${l}=${JSON.stringify(t.params[l])}`).join("&"):"",c=t.headers?.Authorization||"";return`${s}:${i}${o?`?${o}`:""}:${c}`}parseCacheControl(t){if(!t)return{};const s={},a=t.split(",").map(n=>n.trim());for(const n of a)if(n.includes("=")){const[i,o]=n.split("=").map(c=>c.trim());i&&(s[i.toLowerCase()]=o??!0)}else s[n.toLowerCase()]=!0;return{maxAge:s["max-age"]?parseInt(String(s["max-age"]),10):void 0,noCache:s["no-cache"]===!0,noStore:s["no-store"]===!0,mustRevalidate:s["must-revalidate"]===!0}}isCacheValid(t,s){const n=Date.now()-t.timestamp;if(t.maxAge){const i=t.maxAge*1e3;if(n>i)return!1}else if(n>this.defaultTTL)return!1;if(this.enableETag&&t.etag){const i=s.headers?.["If-None-Match"];if(i&&i!==t.etag)return!1}if(t.lastModified){const i=s.headers?.["If-Modified-Since"];if(i){const o=new Date(t.lastModified).getTime(),c=new Date(i).getTime();if(o<c)return!1}}return!0}get(t){if((t.method||"GET").toUpperCase()!=="GET"||t?._disableCache===!0)return null;const a=this.generateCacheKey(t),n=this.cache.get(a);if(!n)return null;if(!this.isCacheValid(n,t))return this.cache.delete(a),g.debug(`[ResponseCache] Cache expired: ${t.url}`),null;const i={data:n.data,status:n.status,statusText:n.statusText,headers:n.headers,config:t,request:{}};return g.debug(`[ResponseCache] Cache hit: ${t.url}`,{key:a,age:Date.now()-n.timestamp}),i}set(t,s){if((t.method||"GET").toUpperCase()!=="GET"||t?._disableCache===!0)return;const n=s.headers["cache-control"]||s.headers["Cache-Control"],i=this.parseCacheControl(n);if(i.noStore||i.noCache){g.debug(`[ResponseCache] Not caching (no-store/no-cache): ${t.url}`);return}let o;this.respectCacheControl&&i.maxAge?o=i.maxAge:o=Math.floor(this.defaultTTL/1e3);const c=s.headers.etag||s.headers.ETag,l=s.headers["last-modified"]||s.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:s.data,headers:s.headers,status:s.status,statusText:s.statusText,timestamp:Date.now(),etag:c,lastModified:l,maxAge:o}),g.debug(`[ResponseCache] Cached: ${t.url}`,{key:h,maxAge:o,etag:c?"present":"none"})}invalidate(t){let s=0;for(const a of this.cache.keys())(typeof t=="string"?a.includes(t):t.test(a))&&(this.cache.delete(a),s++);return s>0&&g.info(`[ResponseCache] Invalidated ${s} cache entries for pattern: ${t}`),s}clear(){const t=this.cache.size;this.cache.clear(),g.info(`[ResponseCache] Cache cleared (${t} entries)`)}getStats(){const t=Array.from(this.cache.entries()).map(([s,a])=>({key:s,age:Date.now()-a.timestamp,maxAge:a.maxAge}));return{size:this.cache.size,maxSize:this.maxSize,entries:t}}cleanup(){const t=Date.now();let s=0;for(const[a,n]of this.cache.entries()){const i=t-n.timestamp,o=(n.maxAge||Math.floor(this.defaultTTL/1e3))*1e3;i>o&&(this.cache.delete(a),s++)}return s>0&&g.debug(`[ResponseCache] Cleaned up ${s} expired cache entries`),s}}const ve=new Fa({defaultTTL:300*1e3,maxSize:100,respectCacheControl:!0,enableETag:!0});typeof window<"u"&&setInterval(()=>{ve.cleanup()},60*1e3);function rr(e={}){const{target:t="all",resourceType:s,resourceId:a,invalidateAll:n=!1,queryKeys:i=[],storeNames:o=[]}=e;try{(t==="cache"||t==="all")&&(n?(ve.clear(),g.debug("[StateInvalidation] Cleared all response cache")):s&&Va(s,a)),(t==="queries"||t==="all")&&Ua(i,s,a),(t==="stores"||t==="all")&&$a(o,s,a),g.debug("[StateInvalidation] State invalidated",{target:t,resourceType:s,resourceId:a,invalidateAll:n})}catch(c){g.error("[StateInvalidation] Error invalidating state",{error:String(c)})}}function Va(e,t){const s={tracks:["/tracks","/library/tracks"],playlists:["/playlists"],users:["/users","/auth/me"],conversations:["/conversations"],roles:["/roles"],library:["/library","/tracks"],auth:["/auth"],ui:[],all:[]};if(e==="all"){ve.clear();return}const a=s[e]||[];for(const n of a)ve.invalidate(n);if(t)for(const n of a)ve.invalidate(`${n}/${t}`)}function Ua(e,t,s){const a=pa();if(!a){if(g.warn("[StateInvalidation] QueryClient not available, falling back to event system"),typeof window<"u"){const n=new CustomEvent("veza:invalidate-queries",{detail:{queryKeys:e,resourceType:t,resourceId:s}});window.dispatchEvent(n)}return}if(e&&e.length>0)for(const n of e)a.invalidateQueries({queryKey:n});if(t){const i={tracks:[["tracks"],["track"],["library"]],playlists:[["playlists"],["playlist"]],users:[["users"],["user"],["auth"],["userProfile"]],conversations:[["conversations"],["conversation"],["chat"],["chatConversations"]],roles:[["roles"],["role"]],library:[["library"],["tracks"],["favorites"],["libraryItems"]],auth:[["auth"],["user"]],ui:[],all:[]}[t]||[];for(const o of i)a.invalidateQueries({queryKey:s?[...o,s]:o})}g.debug("[StateInvalidation] Invalidated React Query cache",{queryKeys:e,resourceType:t,resourceId:s})}function $a(e,t,s){const a={tracks:["library"],playlists:["library"],users:["auth"],conversations:["chat"],roles:[],library:["library"],auth:["auth"],ui:["ui"],all:["auth","library","chat","ui"]},n=e.length>0?e:t?a[t]||[]:[];for(const i of n)Qa(i).catch(o=>{g.warn(`[StateInvalidation] Failed to invalidate store ${i}`,{error:String(o)})})}async function Qa(e,t,s){try{switch(e){case"auth":{const{useAuthStore:a}=await T(async()=>{const{useAuthStore:n}=await Promise.resolve().then(()=>be);return{useAuthStore:n}},void 0);a.getState().refreshUser?.();break}case"library":break;case"chat":break;case"ui":break;default:g.warn(`[StateInvalidation] Unknown store: ${e}`)}}catch(a){g.error(`[StateInvalidation] Error invalidating store ${e}`,{error:String(a)})}}function Ba(e,t){if(!e)return;let s,a;if(e.includes("/tracks/")){s="tracks";const n=e.match(/\/tracks\/([^/]+)/);a=n?n[1]:void 0}else if(e.includes("/playlists/")){s="playlists";const n=e.match(/\/playlists\/([^/]+)/);a=n?n[1]:void 0}else if(e.includes("/users/")||e.includes("/auth/")){s="users";const n=e.match(/\/(users|auth)\/([^/]+)/);a=n?n[2]:void 0}else if(e.includes("/conversations/")){s="conversations";const n=e.match(/\/conversations\/([^/]+)/);a=n?n[1]:void 0}else if(e.includes("/roles/")){s="roles";const n=e.match(/\/roles\/([^/]+)/);a=n?n[1]:void 0}rr(s?{resourceType:s,resourceId:a,target:"all"}:{target:"cache",invalidateAll:!0})}function Ka(e){if(e!=null)return typeof e=="string"?e:String(e)}function jt(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 s={...e};for(const[a,n]of Object.entries(s))t.includes(a)?s[a]=Ka(n):n&&typeof n=="object"&&!Array.isArray(n)&&!(n instanceof Date)?s[a]=jt(n,t):Array.isArray(n)&&n.length>0&&typeof n[0]=="object"&&(s[a]=n.map(i=>typeof i=="object"&&i!==null?jt(i,t):i));return s}const je="1.2.0";function ze(e,t=je,s){return Object.defineProperty(e,"_version",{value:t,enumerable:!1,writable:!1}),s&&Object.defineProperty(e,"_description",{value:s,enumerable:!1,writable:!1}),e}const D=x().uuid("Invalid UUID format"),K=x().datetime({message:"Invalid ISO8601 date format"}),Fe=ze(R({id:D,username:x().min(1),slug:x().optional(),email:x().email(),first_name:x().optional().nullable(),last_name:x().optional().nullable(),avatar:x().optional().nullable(),bio:x().optional().nullable(),location:x().optional().nullable(),birthdate:K.optional().nullable(),gender:x().optional().nullable(),username_changed_at:K.optional().nullable(),role:ae(["user","admin","super_admin"]),is_active:se(),is_verified:se(),is_banned:se().optional(),is_admin:se(),is_public:se(),last_login_at:K.optional().nullable(),created_at:K,updated_at:K,is_2fa_enabled:se().optional(),social_links:Me(fe()).optional().nullable()}),je,"User response schema - matches backend User model"),Ha=R({id:D,conversation_id:D,sender_id:D,content:x(),message_type:ae(["text","image","audio","file"]),attachment_url:x().url().optional(),created_at:K,updated_at:K,sender:Fe.optional()});R({id:D,name:x(),type:ae(["direct","group"]),creator_id:D,created_at:K,updated_at:K,participants:oe(Fe).optional(),last_message:Ha.optional(),unread_count:$().int().nonnegative().optional()});const Fr=ze(R({id:D,creator_id:D,file_id:D.optional().nullable(),title:x().min(1),artist:x().min(1),album:x(),duration:$().int().nonnegative(),genre:x(),year:$().int().min(1900).max(2100),file_path:x(),file_size:$().nonnegative(),format:x(),bitrate:$().nonnegative(),sample_rate:$().nonnegative(),waveform_path:x().optional().nullable(),cover_art_path:x().optional().nullable(),is_public:se(),status:ae(["uploading","processing","completed","failed"]),status_message:x().optional().nullable(),stream_status:ae(["pending","processing","ready","error"]),stream_manifest_url:x().url().optional().nullable(),play_count:$().int().nonnegative(),like_count:$().int().nonnegative(),created_at:K,updated_at:K,user:Fe.optional(),is_premium:se().optional(),lyrics:oe(R({time:$(),text:x()})).optional(),waveform_data:oe($()).optional(),tags:oe(x()).optional()}),je,"Track response schema - matches backend Track model");ze(R({id:D,user_id:D,title:x().min(1),description:x().optional().nullable(),visibility:ae(["public","private","unlisted"]).optional(),is_public:se(),cover_url:x().url().optional().nullable(),track_count:$().int().nonnegative(),follower_count:$().int().nonnegative(),created_at:K,updated_at:K,tracks:oe(Fr).optional(),user:Fe.optional(),playlist_tracks:oe(fe()).optional(),collaborators:oe(fe()).optional()}),je,"Playlist response schema - matches backend Playlist model");R({id:D,user_id:D,ip_address:x(),user_agent:x(),revoked_at:K.optional().nullable(),expires_at:K,created_at:K});R({id:D,user_id:D.optional().nullable(),action:x(),resource:x(),resource_id:D.optional().nullable(),metadata:Me(fe()).optional().nullable(),ip_address:x().optional().nullable(),user_agent:x().optional().nullable(),timestamp:K});ze(R({code:$().int(),message:x(),details:oe(R({field:x(),message:x(),value:x().optional()})).optional(),request_id:x().optional(),timestamp:K,context:Me(fe()).optional(),retry_after:$().int().positive().optional()}),je,"API Error response schema - matches backend error format");ze(R({page:$().int().positive(),limit:$().int().positive(),total:$().int().nonnegative(),total_pages:$().int().nonnegative(),has_next:se(),has_prev:se(),next_cursor:x().optional(),prev_cursor:x().optional()}),je,"Pagination metadata schema");R({id:D,user_id:D,type:ae(["new_message","track_uploaded","user_mentioned","system"]),content:x(),read:se(),created_at:K});R({id:D,playlist_id:D,track_id:D,position:$().int().nonnegative(),added_by:D,added_at:K,track:Fr.optional()});R({id:D,playlist_id:D,user_id:D,role:ae(["owner","editor","viewer"]),created_at:K,user:Fe.optional()});function Wa(e,t,s={}){const{normalizeIds:a=!0}=s;let n=t;return a&&typeof t=="object"&&t!==null&&(n=jt(t)),e.parse(n)}function sr(e,t,s={}){try{return{success:!0,data:Wa(e,t,s)}}catch(a){if(a instanceof Pt)return{success:!1,error:a};throw a}}const Ve=x().email("Invalid email format"),dt=x().min(8,"Password must be at least 8 characters"),mt=x().min(3,"Username must be at least 3 characters").max(30,"Username must be at most 30 characters").regex(/^[a-zA-Z0-9_]+$/,"Username can only contain letters, numbers, and underscores");R({email:Ve,password:x().min(1,"Password is required")});R({username:mt,email:Ve,password:dt,first_name:x().max(100).optional(),last_name:x().max(100).optional()});R({code:x().min(6,"TOTP code must be at least 6 characters").max(6,"TOTP code must be exactly 6 characters"),secret:x().min(1,"Secret is required")});R({password:dt});R({username:mt,email:Ve,password:dt});R({username:mt.optional(),email:Ve.optional(),password:dt.optional()});R({first_name:x().max(100).optional(),last_name:x().max(100).optional(),username:mt.optional(),bio:x().max(500).optional(),location:x().max(100).optional(),birthdate:x().regex(/^\d{4}-\d{2}-\d{2}$/,"Invalid date format. Use YYYY-MM-DD").optional(),gender:ae(["Male","Female","Other","Prefer not to say"]).optional()});R({conversation_id:D,content:x().min(1,"Message content is required"),message_type:ae(["text","image","audio","file"]).optional(),attachment_url:x().url().optional()});R({content:x().min(1,"Message content is required").optional()});R({name:x().min(1,"Conversation name is required"),type:ae(["direct","group"]),participant_ids:oe(D).min(1,"At least one participant is required")});R({name:x().min(1,"Conversation name is required").optional()});R({track_ids:oe(D).min(1,"At least one track ID is required")});R({filename:x().min(1,"Filename is required"),total_chunks:$().int().min(1,"Total chunks must be at least 1"),total_size:$().int().min(1,"Total size must be at least 1")});R({upload_id:x().min(1,"Upload ID is required")});R({upload_id:x().min(1,"Upload ID is required"),chunk_number:$().int().min(0,"Chunk number must be non-negative"),total_chunks:$().int().min(1,"Total chunks must be at least 1"),total_size:$().int().min(1,"Total size must be at least 1"),filename:x().min(1,"Filename is required")});R({event_name:x().min(1,"Event name is required").max(100,"Event name must be at most 100 characters"),payload:Me(fe()).optional()});R({url:x().url("Invalid webhook URL"),events:oe(x()).min(1,"At least one event is required"),secret:x().min(1,"Secret is required").optional()});R({level:x().optional(),message:x().optional(),context:Me(fe()).optional(),timestamp:x().optional(),data:fe().optional()});R({email:Ve});R({title:x().min(1,"Track title is required"),artist_id:D,album_id:D.optional(),genre:x().min(1,"Genre is required")});R({title:x().min(1,"Track title is required").optional(),artist_id:D.optional(),album_id:D.optional(),genre:x().min(1,"Genre is required").optional()});const Ue=R({page:$().int().positive().optional(),limit:$().int().positive().max(100).optional(),cursor:x().optional()});Ue.extend({query:x().optional()});Ue.extend({conversation_id:D});Ue.extend({query:x().optional()});Ue.extend({artist:x().optional(),genre:x().optional()});Ue.extend({query:x().min(1,"Search query is required")});R({type:ae(["image","audio","document"])});function Ga(e,t){return e.parse(t)}function Xa(e,t){try{return{success:!0,data:Ga(e,t)}}catch(s){if(s instanceof Pt)return{success:!1,error:s};throw s}}const ar={limit:null,remaining:null,reset:null,retryAfter:null,isLimited:!1,lastUpdated:null},Nt=nt()(it(e=>({...ar,updateRateLimit:t=>{const s=t.limit!==null&&t.limit!==void 0?typeof t.limit=="string"?parseInt(t.limit,10):t.limit:null,a=t.remaining!==null&&t.remaining!==void 0?typeof t.remaining=="string"?parseInt(t.remaining,10):t.remaining:null,n=t.reset!==null&&t.reset!==void 0?typeof t.reset=="string"?parseInt(t.reset,10):t.reset:null,i=t.retryAfter!==null&&t.retryAfter!==void 0?typeof t.retryAfter=="string"?parseInt(t.retryAfter,10):t.retryAfter:null,o=a!==null&&a<=0||i!==null;e({limit:s,remaining:a,reset:n,retryAfter:i,isLimited:o,lastUpdated:Date.now()})},clearRateLimit:()=>{e(ar)}}),{name:"rate-limit-storage",partialize:e=>({limit:e.limit,remaining:e.remaining,reset:e.reset,retryAfter:e.retryAfter,isLimited:e.isLimited,lastUpdated:null})})),Ya={DEFAULT:1e4,UPLOAD:3e5,LONG_POLLING:3e4},nr=1e3,F=Le.create({baseURL:ct.API_URL,timeout:Ya.DEFAULT,headers:{"Content-Type":"application/json"},withCredentials:!0});class Ja{metrics={totalValidations:0,successfulValidations:0,failedValidations:0,failureRate:0,failuresByEndpoint:{}};recordSuccess(t){this.metrics.totalValidations++,this.metrics.successfulValidations++,this.metrics.lastSuccessTime=new Date().toISOString(),this.updateFailureRate()}recordFailure(t){if(this.metrics.totalValidations++,this.metrics.failedValidations++,this.metrics.lastFailureTime=new Date().toISOString(),t){const s=this.normalizeEndpoint(t);this.metrics.failuresByEndpoint[s]=(this.metrics.failuresByEndpoint[s]||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 _t=new Ja,ir={failureRateThreshold:5,minValidationsForAlert:10,checkInterval:300*1e3};class Za{config=ir;checkIntervalId=null;lastAlertTime=0;alertCooldown=900*1e3;start(t){this.checkIntervalId&&this.stop(),this.config={...ir,...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=_t.getMetrics();if(!(t.totalValidations<this.config.minValidationsForAlert)&&t.failureRate>this.config.failureRateThreshold){const s=Date.now();if(s-this.lastAlertTime<this.alertCooldown)return;this.lastAlertTime=s,g.error("[API Validation Alert] High validation failure rate detected",{alert_type:"high_validation_failure_rate",failure_rate:t.failureRate.toFixed(2),threshold:this.config.failureRateThreshold,total_validations:t.totalValidations,failed_validations:t.failedValidations,successful_validations:t.successfulValidations,last_failure_time:t.lastFailureTime,failures_by_endpoint:t.failuresByEndpoint,timestamp:new Date().toISOString()})}}updateConfig(t){this.config={...this.config,...t}}}const en=new Za;typeof window<"u"&&en.start();const tn=e=>new Promise(t=>setTimeout(t,e)),pe={maxRetries:3,baseDelay:1e3,maxDelay:1e4,retryableStatusCodes:[500,502,503,504],retryableNetworkErrors:["ECONNABORTED","ETIMEDOUT","ENOTFOUND","ECONNREFUSED","ECONNRESET","EAI_AGAIN","Network Error"]},Tt=e=>e?["GET","HEAD","OPTIONS"].includes(e.toUpperCase()):!1;class rn{recentRequests=[];windowSize=10;windowMs=3e4;recordRequest(t){const s=Date.now();this.recentRequests.push({success:t,timestamp:s}),this.recentRequests=this.recentRequests.filter(a=>s-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,s=this.recentRequests.filter(a=>!a.success).length;return t>0&&s>0}isCompleteFailure(){return this.recentRequests.length===0?!1:this.recentRequests.every(t=>!t.success)}reset(){this.recentRequests=[]}}const Ot=new rn,Ze=e=>!!(e.response?.status===206||e.code==="ECONNABORTED"&&e.message?.toLowerCase().includes("timeout")&&e.request||e.code==="ECONNRESET"&&e.response||Ot.isPartialFailure()),xt=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"||Ot.isCompleteFailure()),sn=(e,t=pe)=>{if(Le.isCancel(e)||e.code==="ERR_BAD_RESPONSE"||e.message?.includes("HTML page instead of JSON")||e.config?._disableRetry)return!1;if(Ze(e))return Tt(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 s=e.message.toLowerCase();return["network","timeout","connection","econn","etimedout","enotfound"].some(n=>s.includes(n))}return!e.response&&e.request?Tt(e.config?.method):!1},an=(e,t,s=pe.baseDelay,a=pe.maxDelay)=>{const n=e.response?.headers["retry-after"]||e.response?.headers["Retry-After"];if(n){const c=parseInt(String(n),10);if(!isNaN(c)&&c>0)return Math.min(c*1e3,a)}const i=s*Math.pow(2,t),o=Math.random()*s;return Math.min(i+o,a)};let We=!1,Te=0;const nn=3;let Ct=[];const bt=e=>{Ct.forEach(t=>{e?t.reject(e):t.resolve(void 0)}),Ct=[]},ge=e=>{if(!e||typeof e!="object")return e;const t=["password","token","access_token","refresh_token","secret","authorization","x-csrf-token"],s=Array.isArray(e)?[...e]:{...e};for(const a in s){const n=a.toLowerCase();t.some(i=>n.includes(i))?s[a]="[REDACTED]":typeof s[a]=="object"&&s[a]!==null&&(s[a]=ge(s[a]))}return s},Ie=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};function on(e){const t=e.headers?.["content-type"];if(typeof t=="string"&&t.toLowerCase().includes("text/html"))return!0;const s=e.data;if(typeof s=="string"){const a=s.trim().toLowerCase();return a.startsWith("<!doctype")||a.startsWith("<html")}return!1}function ln(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""}}F.interceptors.request.use(async e=>{const t=Date.now();e._requestStartTime=t,e._isSlowRequest=!1,e.headers&&(e.headers["X-API-Version"]=ct.API_VERSION),e.data instanceof FormData&&e.headers&&delete e.headers["Content-Type"];const s=e.method?.toUpperCase(),a=["POST","PUT","DELETE","PATCH"].includes(s||""),n=e.url?.includes("/auth/login")||e.url?.includes("/auth/register"),i=e.url?.includes("/csrf-token");if(a&&!i&&!n&&e.headers){let c=Z.getToken();if(!c)try{c=await Z.ensureToken()}catch{g.warn("[API] Failed to fetch CSRF token before request, will retry on 403",{url:e.url,method:e.method})}c&&e.headers&&(e.headers["X-CSRF-Token"]=c)}const o=e?._requestSchema;if(o&&e.data!==void 0&&e.data!==null&&!(e.data instanceof FormData)){const c=Xa(o,e.data);if(!c.success){const l=Ie(e);g.warn("[API Request Validation Error]",{request_id:l,url:e.url,method:e.method?.toUpperCase(),errors:c.error?.errors.map(u=>({path:u.path.join("."),message:u.message,code:u.code}))},c.error);const 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=Ie(e);g.debug(`[API Request] ${s||"GET"} ${e.url}`,{request_id:c,method:s||"GET",url:e.url,baseURL:e.baseURL,headers:ge({...e.headers}),params:e.params,data:ge(e.data),timeout:e.timeout,signal:e.signal?"AbortController":void 0})}return e},e=>Promise.reject(e));F.interceptors.response.use(e=>{if(on(e)){const m="The API returned an HTML page instead of JSON. Another application may be using port 8080. Stop any other server (e.g. phishing lab) and ensure the Veza backend is running.";if(typeof window<"u"){const v="veza_wrong_server_shown";sessionStorage.getItem(v)||(sessionStorage.setItem(v,"true"),B(m,{icon:"⚠️",duration:12e3}))}return Promise.reject(new De(m,"ERR_BAD_RESPONSE",e.config,e.request,e))}Ot.recordRequest(!0);const t=e.config?._requestStartTime;if(t){const m=Date.now()-t;m>nr&&(e.config._isSlowRequest=!0,e.config._requestDuration=m,e.config?._enableLogging&&g.debug(`[API Slow Request] ${e.config?.method?.toUpperCase()} ${e.config?.url} took ${m}ms`,{duration:m,threshold:nr}))}const a=e.headers["x-request-id"]||e.headers["X-Request-ID"]||e.config?._requestId;a&&Zt({request_id:a});const n=e.headers["x-ratelimit-limit"]||e.headers["X-RateLimit-Limit"],i=e.headers["x-ratelimit-remaining"]||e.headers["X-RateLimit-Remaining"],o=e.headers["x-ratelimit-reset"]||e.headers["X-RateLimit-Reset"];if((n||i||o)&&Nt.getState().updateRateLimit({limit:n,remaining:i,reset:o,retryAfter:null}),e.config?._enableLogging&&g.debug(`[API Response] ${e.config.method?.toUpperCase()||"GET"} ${e.config.url} ${e.status}`,{request_id:a,status:e.status,statusText:e.statusText,headers:ge(e.headers),data:ge(e.data),duration:e.config?._requestStartTime?Date.now()-e.config._requestStartTime:void 0}),(e.headers["x-api-deprecated"]||e.headers["X-API-Deprecated"])==="true"){const m="api_deprecation_warning_shown";if(typeof window<"u"&&!sessionStorage.getItem(m)){const v=e.headers.sunset||e.headers.Sunset,p=v?`This API version is deprecated and will be removed on ${v}. Please update to the latest version.`:"This API version is deprecated. Please update to the latest version.";B(p,{icon:"⚠️",duration:1e4}),sessionStorage.setItem(m,"true"),g.warn("[API] Deprecated API version detected",{url:e.config.url,version:e.headers["x-api-version"]||e.headers["X-API-Version"],sunset_date:v})}}if(!e.data||typeof e.data!="object")return e;const h=e.config.method?.toUpperCase(),u=["POST","PUT","PATCH","DELETE"].includes(h||"");if(u&&e.config?._showSuccessToast&&typeof window<"u"){const m=e.config?._successMessage||e.data?.message||ln(h||"");m&&B.success(m)}if(h==="GET"&&!e.config?._disableCache&&ve.set(e.config,e),u){const m=e.config.url||"";e.config.method,Ba(m)}if("success"in e.data){if(e.data.success===!0){const m=e.data.data!==void 0?e.data.data:null,v=e.config?._responseSchema;if(v&&m!==null){const p=sr(v,m);if(p.success){const w=Ie(e.config);g.debug("[API Response Validation Success]",{request_id:w,url:e.config.url}),_t.recordSuccess(e.config.url)}else{const w=Ie(e.config);g.error("[API Response Validation Failed]",{request_id:w,url:e.config.url,method:e.config.method?.toUpperCase(),status:e.status,error_type:"api_response_validation_failed",validation_errors:p.error?.errors.map(I=>({path:I.path.join("."),message:I.message,code:I.code,received:I.code==="invalid_type"?I.received:void 0,expected:I.code==="invalid_type"?I.expected:void 0})),response_data_preview:JSON.stringify(m).substring(0,200),schema_provided:!!v,timestamp:new Date().toISOString()},p.error),_t.recordFailure(e.config.url);const E=e.config?._validationRecovery,N=E?.useCache!==!1,S=E?.retry===!0,L=E?.notifyUser!==!1;if(N&&h==="GET"){const I=ve.get(e.config);if(I){let b=I.data;if(b&&typeof b=="object"&&"success"in b&&b.success===!0&&(b=b.data!==void 0?b.data:null),b!==null&&sr(v,b).success)return g.warn("[API Validation Recovery] Using cached response due to validation failure",{request_id:w,url:e.config.url,recovery_type:"cache_fallback"}),L&&typeof window<"u"&&B("Data may be outdated. Please refresh if issues persist.",{icon:"⚠️",duration:5e3}),{...I,data:b}}}if(S&&!e.config?._validationRetryAttempted)return e.config._validationRetryAttempted=!0,g.warn("[API Validation Recovery] Retrying request due to validation failure",{request_id:w,url:e.config.url,recovery_type:"retry"}),F.request(e.config);L&&typeof window<"u"&&B("Some data may be incomplete. Please refresh if issues persist.",{icon:"⚠️",duration:5e3})}}return{...e,data:m}}if(e.data.success===!1){const m=e.data.error||e.data;g.error("[API] Response with success=false:",{url:e.config.url,error:m});const v=new De(m?.message||"Request failed","API_ERROR",e.config,e.request,{...e,status:e.status||400,statusText:e.statusText||"Bad Request",data:{success:!1,error:m}});return Promise.reject(v)}}if(e.data&&typeof e.data=="object"&&!("success"in e.data)){const m=Ie(e.config);g.warn("[API] Received non-wrapped response format (unexpected)",{request_id:m,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(Le.isCancel(e))return e.config?._enableLogging&&g.debug(`[API Request Cancelled] ${e.config?.method?.toUpperCase()||"GET"} ${e.config?.url}`,{request_id:e.config?._requestId}),Promise.reject(e);const t=e.config;let s=t?._requestId;if(e.response?.headers){const k=e.response.headers["x-request-id"]||e.response.headers["X-Request-ID"];k&&(s=k,Zt({request_id:s}));const j=e.response.headers["x-ratelimit-limit"]||e.response.headers["X-RateLimit-Limit"],C=e.response.headers["x-ratelimit-remaining"]||e.response.headers["X-RateLimit-Remaining"],O=e.response.headers["x-ratelimit-reset"]||e.response.headers["X-RateLimit-Reset"],V=e.response.headers["retry-after"]||e.response.headers["Retry-After"];(j||C||O||V)&&Nt.getState().updateRateLimit({limit:j,remaining:C,reset:O,retryAfter:V})}const a=t?._enableLogging;if(a&&e.response){const j=e.response.headers?.["content-type"]?.toLowerCase?.().includes("text/html")||typeof e.response.data=="string"&&e.response.data.trim().toLowerCase().startsWith("<!doctype")?"[HTML response omitted - wrong server on port 8080?]":ge(e.response.data);g.error(`[API Error Response] ${t?.method?.toUpperCase()||"GET"} ${t?.url} ${e.response.status}`,{request_id:s,status:e.response.status,statusText:e.response.statusText,headers:ge(e.response.headers),data:j,duration:t?._requestStartTime?Date.now()-t._requestStartTime:void 0})}else a&&e.request&&!e.response&&g.error(`[API Network Error] ${t?.method?.toUpperCase()||"GET"} ${t?.url}`,{request_id:s,message:e.message,code:e.code,duration:t?._requestStartTime?Date.now()-t._requestStartTime:void 0});const n=t?.url?.includes("/csrf-token"),i=t?.url?.includes("/auth/login")||t?.url?.includes("/auth/register");if(e.response?.status===403&&t&&!t._csrfRetry&&!n&&!i){const k=e.response?.data,j=(typeof k?.error=="string"?k.error:k?.message||"").toLowerCase();if(j.includes("csrf")||j.includes("token")||j.includes("forbidden")){t._csrfRetry=!0,g.info("[API] CSRF token invalid (403), refreshing and retrying",{request_id:s,url:t?.url,method:t?.method});try{const O=await Z.ensureToken();return t.headers&&(t.headers["X-CSRF-Token"]=O),F.request(t)}catch(O){const V=O instanceof Error?O.message:String(O);V.includes("HTML page instead of JSON")||g.error("[API] CSRF token refresh failed",{request_id:s,url:t?.url,message:V})}}}const o=t?.url?.includes("/auth/refresh"),c=t?.url?.includes("/auth/logout"),l=t?.url?.includes("/auth/me");if((e.response?.status===401||e.response?.status===400)&&o)return g.error(`[API] ${e.response?.status} on /auth/refresh - logging out`,{request_id:s,url:t?.url,status:e.response?.status}),te.clearTokens(),Z.clearToken(),typeof window<"u"&&(T(async()=>{const{useAuthStore:k}=await Promise.resolve().then(()=>be);return{useAuthStore:k}},void 0).then(({useAuthStore:k})=>k.getState().logoutLocal()).catch(k=>g.error("[API] Failed to import auth store for logout",{error:k})),sessionStorage.setItem("auth_error","Votre session a expiré. Veuillez vous reconnecter."),window.location.href="/login"),Promise.reject(W(e));if(e.response?.status===401&&c)return g.warn("[API] 401 on /auth/logout - clearing tokens locally",{request_id:s,url:t?.url}),te.clearTokens(),Z.clearToken(),typeof window<"u"&&T(async()=>{const{useAuthStore:k}=await Promise.resolve().then(()=>be);return{useAuthStore:k}},void 0).then(({useAuthStore:k})=>k.getState().logoutLocal()).catch(k=>g.error("[API] Failed to import auth store for logout",{error:k})),Promise.reject(W(e));if(e.response?.status===401&&t&&!t._retry&&!o&&!c&&!l){if(We)return new Promise((k,j)=>{Ct.push({resolve:k,reject:j})}).then(()=>F(t)).catch(k=>{const j=k,C=j?.response?.status??j?.code,O=t?.url??"";return C!=null&&C>=500&&O.includes("/webhooks")||g.error("[API] Queued request failed after refresh",{request_id:s,url:t?.url,error:k}),Promise.reject(k)});if(t._retry=!0,We=!0,Te>=nn)return Te=0,We=!1,te.clearTokens(),Z.clearToken(),typeof window<"u"&&(T(async()=>{const{useAuthStore:k}=await Promise.resolve().then(()=>be);return{useAuthStore:k}},void 0).then(({useAuthStore:k})=>k.getState().logoutLocal()).catch(k=>g.error("[API] Failed to import auth store for logout",{error:k})),sessionStorage.setItem("auth_error","Votre session a expiré après plusieurs tentatives. Veuillez vous reconnecter."),window.location.href="/login"),bt(new Error("Max refresh attempts reached")),Promise.reject(W(e));Te++;try{return await qe(),Te=0,bt(null),F(t)}catch(k){return g.error("[API] Token refresh failed",{attempt:Te,request_id:s,error:k}),bt(k),te.clearTokens(),Z.clearToken(),typeof window<"u"&&(T(async()=>{const{useAuthStore:j}=await Promise.resolve().then(()=>be);return{useAuthStore:j}},void 0).then(({useAuthStore:j})=>j.getState().logoutLocal()).catch(j=>g.error("[API] Failed to import auth store for logout",{error:j})),sessionStorage.setItem("auth_error","Votre session a expiré. Veuillez vous reconnecter."),window.location.href="/login"),Promise.reject(k)}finally{We=!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 k=t.method?.toUpperCase();if(["POST","PUT","DELETE","PATCH"].includes(k||"")){t._csrfRetry=!0;try{const C=await Z.refreshToken();return t.headers&&C&&(t.headers["X-CSRF-Token"]=C),F(t)}catch(C){const O=C instanceof Error?C.message:String(C);return O.includes("HTML page instead of JSON")||g.error("[API] Failed to refresh CSRF token after CSRF error",{message:O}),Promise.reject(W(e))}}}const u=e.response?.status,d=t?._retryCount||0,m=pe.maxRetries;if(u===429){const k=W(e),j=e.response?.headers["retry-after"]||e.response?.headers["Retry-After"],C=j?parseInt(j,10):60;return g.warn("[API] Rate limit exceeded, not retrying",{url:t?.url,retry_after:C,request_id:k.request_id}),k.message&&B.error(k.message,{duration:C*1e3}),Promise.reject(k)}const v=t?.url?.includes("/marketplace/products");if(u===500&&v){const k=W(e);return k.httpStatus=u,Promise.reject(k)}if(sn(e,pe)&&t&&d<m){const k=t.method?.toUpperCase(),j=Tt(k);if(!j&&u&&u!==500&&u!==502&&u!==503&&u!==504)return Promise.reject(W(e));t._retryCount=d+1;const C=an(e,d,pe.baseDelay,pe.maxDelay);if(d===0){const O=W(e),V=u?`HTTP ${u}`:e.code||"Network Error";g.warn(`[API Retry] ${V} error, retrying (1/${m})`,{status:u||"N/A",error_code:e.code||"N/A",retry_count:1,max_retries:m,delay_ms:Math.round(C),request_id:O.request_id,url:t?.url,method:t?.method,is_idempotent:j})}return tn(C).then(()=>F(t))}if(d>=m){const k=W(e),j=u?`HTTP ${u}`:e.code||"Network Error";return g.error(`[API Error] ${j} error after ${m} retries`,{code:k.code,message:k.message,request_id:k.request_id,url:t?.url,method:t?.method}),Promise.reject(k)}const p=W(e);u===401&&!o&&!c&&!l&&typeof window<"u"&&ut(p)==="authentication"&&(te.clearTokens(),Z.clearToken(),T(async()=>{const{useAuthStore:j}=await Promise.resolve().then(()=>be);return{useAuthStore:j}},void 0).then(({useAuthStore:j})=>j.getState().logoutLocal()).catch(j=>g.error("[API] Failed to import auth store for logout",{error:j})),sessionStorage.setItem("auth_error","Votre session a expiré. Veuillez vous reconnecter."),window.location.href="/login");const w=p.message?.includes("HTML page instead of JSON")??!1,E=t?.url??"",N=u&&u>=500&&E.includes("/webhooks"),S=!t?._disableToast&&u!==401&&u!==404&&!Le.isCancel(e)&&!w&&!N,L=!e.response;if(L){const{recordNetworkError:k}=await T(async()=>{const{recordNetworkError:j}=await Promise.resolve().then(()=>Sn);return{recordNetworkError:j}},void 0);k(p)}const I=L?"network-error-toast":void 0;if(S&&typeof window<"u"){const k=t?.url||"";let j;k.includes("/auth/")?j="auth":k.includes("/tracks")||k.includes("/track/")?j="track":k.includes("/playlists")||k.includes("/playlist/")?j="playlist":k.includes("/upload")?j="upload":k.includes("/conversations")||k.includes("/chat")?j="conversation":k.includes("/search")&&(j="search");const O=Or(p,j,u===422);if(!e.response&&t&&me.shouldQueueRequest(t)&&(typeof navigator<"u"&&!navigator.onLine||!e.response&&e.request)){const H=t.method?.toUpperCase(),Y=H==="DELETE"?"low":H==="POST"?"high":"normal";try{await me.queueRequest(t,{priority:Y}),B.success("Requête mise en file d'attente. Elle sera envoyée à la reconnexion.",{duration:4e3,id:"offline-queue-toast"})}catch(re){g.error("[API] Failed to queue request for offline replay",{error:re})}}let V=O;L&&(Ze(e)?V=`${O} ⚠️ Connexion intermittente détectée. Certaines requêtes réussissent, d'autres échouent. La connexion devrait se rétablir automatiquement.`:xt(e)?V=`${O} ❌ Aucune connexion réseau. Vérifiez votre connexion internet et réessayez.`:V=`${O} 💡 Vérifiez votre connexion internet. Si le problème persiste, le serveur pourrait être temporairement indisponible.`),(Ze(e)||xt(e))&&L&&g.warn("[API] Network failure detected",{request_id:s,is_partial_failure:Ze(e),is_complete_failure:xt(e),url:t?.url,method:t?.method,error_code:e.code,error_message:e.message}),B.error(V,{duration:8e3,id:I})}const b=e.response?.status,_=t?.url??"";return b&&b>=500&&_.includes("/webhooks")||g.error(`[API Error] ${p.message}`,{request_id:p.request_id||s,code:p.code,message:p.message,timestamp:p.timestamp,details:p.details,context:p.context,url:t?.url,method:t?.method}),Promise.reject(p)});class cn{cache=new Map;defaultCacheTime=1e3;generateRequestKey(t){const s=(t.method||"GET").toUpperCase(),a=t.url||"",n=t.baseURL||"",i=a.startsWith("http")?a:`${n}${a}`,o=t.params?Object.keys(t.params).sort().map(l=>`${l}=${JSON.stringify(t.params[l])}`).join("&"):"";let c="";if(t.data)if(t.data instanceof FormData)c="[FormData]";else try{c=JSON.stringify(t.data)}catch{c=String(t.data)}return`${s}:${i}${o?`?${o}`:""}${c?`|${c}`:""}`}shouldDeduplicate(t){const s=(t.method||"GET").toUpperCase();if(["GET","HEAD","OPTIONS"].includes(s))return!0;const a=t?._enableDeduplication!==!1;return t?._disableDeduplication===!0?!1:a}async getOrCreateRequest(t,s,a={}){const{enabled:n=!0,cacheTime:i=this.defaultCacheTime}=a;if(!n||!this.shouldDeduplicate(t))return s();const o=this.generateRequestKey(t),c=this.cache.get(o);if(c)return c.resolveCount++,g.debug(`[RequestDeduplication] Reusing request: ${t.method?.toUpperCase()} ${t.url}`,{key:o,resolveCount:c.resolveCount}),c.promise;const l=s().then(h=>(setTimeout(()=>{const u=this.cache.get(o);u&&u.promise===l&&(this.cache.delete(o),g.debug(`[RequestDeduplication] Removed from cache: ${o}`))},i),h)).catch(h=>{const u=this.cache.get(o);throw u&&u.promise===l&&(this.cache.delete(o),g.debug(`[RequestDeduplication] Removed from cache (error): ${o}`)),h});return this.cache.set(o,{promise:l,timestamp:Date.now(),resolveCount:1}),g.debug(`[RequestDeduplication] New request: ${t.method?.toUpperCase()} ${t.url}`,{key:o,cacheSize:this.cache.size}),l}clearCache(){const t=this.cache.size;this.cache.clear(),g.info(`[RequestDeduplication] Cache cleared (${t} entries)`)}getCacheStats(){const t=Array.from(this.cache.entries()).map(([s,a])=>({key:s,resolveCount:a.resolveCount,age:Date.now()-a.timestamp}));return{size:this.cache.size,entries:t}}cleanup(t=6e4){const s=Date.now();let a=0;for(const[n,i]of this.cache.entries())s-i.timestamp>t&&(this.cache.delete(n),a++);a>0&&g.debug(`[RequestDeduplication] Cleaned up ${a} old cache entries`)}}const un=new cn;typeof window<"u"&&setInterval(()=>{un.cleanup(6e4)},300*1e3);async function Vr(e){try{const t=await F.post("/auth/register",{email:e.email,password:e.password,password_confirmation:e.password_confirm,username:e.username});let s,a,n,i;if(t.data?.token?.access_token?(s=t.data.token.access_token,a=t.data.token.refresh_token||"",n=t.data.token.expires_in,i=t.data.user):t.data?.access_token?(s=t.data.access_token,a=t.data.refresh_token||"",n=t.data.expires_in,i=t.data.user):t.data?.Token?.AccessToken?(s=t.data.Token.AccessToken,a=t.data.Token.RefreshToken||"",n=t.data.Token.ExpiresIn,i=t.data.User||t.data.user):(t.data?.User||t.data?.user)&&(i=t.data.User||t.data.user),s&&(te.setTokens(s,a||""),Mt()),!i)throw new Error("Registration response missing user data");if(!s||n===void 0)throw new Error("Registration response missing tokens. Email verification may be required.");return{user:i,token:{access_token:s,refresh_token:a||"",expires_in:n}}}catch(t){throw W(t)}}async function Ur(e){try{const t=await F.post("/auth/login",{email:e.email,password:e.password,remember_me:e.remember_me||!1});let s,a,n,i;if(t.data?.token?.access_token?(s=t.data.token.access_token,a=t.data.token.refresh_token||"",n=t.data.token.expires_in,i=t.data.user):t.data?.access_token?(s=t.data.access_token,a=t.data.refresh_token||"",n=t.data.expires_in,i=t.data.user):t.data?.Token?.AccessToken&&(s=t.data.Token.AccessToken,a=t.data.Token.RefreshToken||"",n=t.data.Token.ExpiresIn,i=t.data.User||t.data.user),t.data?.requires_2fa){if(i||(i=t.data.user||t.data.User),!i)throw new Error("Login response missing user data");return{user:i,token:{access_token:"",refresh_token:"",expires_in:0},requires_2fa:!0}}if(s)te.setTokens(s,a||""),e.remember_me?localStorage.setItem("remember_me","true"):localStorage.removeItem("remember_me"),Mt();else throw g.error("[AUTH] Tokens not found in login response",{responseData:t.data}),new Error("Login response missing tokens");return{user:i,token:{access_token:s,refresh_token:a||"",expires_in:n||3600},requires_2fa:t.data?.requires_2fa}}catch(t){throw W(t)}}async function $r(){try{await F.post("/auth/logout",{},{_disableToast:!0})}catch(e){e?.response?.status===400&&(e?.response?.data?.error?.includes("RefreshToken")||e?.response?.data?.message?.includes("RefreshToken"))||g.warn("Logout API call failed, but tokens will be cleared locally",{error:e instanceof Error?e.message:String(e),stack:e instanceof Error?e.stack:void 0})}finally{Mr(),te.clearTokens()}}async function zt(){try{return(await F.get("/auth/me")).data}catch(e){throw W(e)}}const tc={login:Ur,register:Vr,logout:$r,getMe:zt,refresh:async e=>{const{data:t}=await F.post("/auth/refresh",{refresh_token:e});return t},verifyEmail:async e=>{const{data:t}=await F.post("/auth/verify-email",void 0,{params:{token:e.token}});return t},resendVerification:async e=>{const{data:t}=await F.post("/auth/resend-verification",e);return t},checkUsername:async e=>{const{data:t}=await F.get("/auth/check-username",{params:{username:e.username}});return t},requestPasswordReset:async e=>{const{data:t}=await F.post("/auth/password/reset-request",e);return t},resetPassword:async e=>{const{data:t}=await F.post("/auth/password/reset",e);return t},getOAuthProviders:async()=>{const{data:e}=await F.get("/auth/oauth/providers");return e},initiateOAuth:e=>{window.location.href=`${ct.API_URL}/auth/oauth/${e}`},setup2FA:async()=>{const{data:e}=await F.post("/auth/2fa/setup");return e},verify2FA:async e=>{const{data:t}=await F.post("/auth/2fa/verify",{code:e});return t},disable2FA:async e=>{const{data:t}=await F.post("/auth/2fa/disable",{code:e});return t},get2FAStatus:async()=>{const{data:e}=await F.get("/auth/2fa/status");return e}};function dn(e){if(typeof window>"u"||!window.BroadcastChannel)return g.warn("[BroadcastSync] BroadcastChannel not supported in this environment"),null;try{return new BroadcastChannel(`veza-store-${e}`)}catch(t){return g.warn(`[BroadcastSync] Failed to create BroadcastChannel for ${e}`,{error:t instanceof Error?t.message:String(t),stack:t instanceof Error?t.stack:void 0,storeName:e}),null}}function Qr(e,t={}){return(s,a,n)=>{const i=t.channelName||"default-store",o=t.enabled!==!1,c=t.shouldSync||(()=>!0),l=t.onStateSync;let h=null,u=!1,d=null,m=0;const v=new Set,p=[];if(o&&(h=dn(i),h)){const E=()=>{if(p.length===0||u)return;p.sort((S,L)=>L.timestamp-S.timestamp);const N=p.shift();N&&N.timestamp>m&&(u=!0,s(N.state),d=N.state,m=N.timestamp,v.size>100&&Array.from(v).slice(0,50).forEach(L=>v.delete(L)),setTimeout(()=>{u=!1,E()},50))};h.onmessage=N=>{const S=N.data;if(!S||typeof S!="object"||!S.type||!S.storeName||typeof S.timestamp!="number"||S.type!=="state-update"&&S.type!=="state-request"&&S.type!=="state-response"||S.storeName!==i)return;const L=S.messageId||`${S.type}-${S.timestamp}-${Math.random()}`;if(!v.has(L)){if(S.type==="state-update"&&S.state){if(u){p.push({state:S.state,timestamp:S.timestamp,messageId:L}),E();return}if(S.timestamp<=m){v.add(L);return}if(c(S.state,d)){v.add(L),u=!0;const I=d;s(S.state);const b=S.state;if(d=b,m=S.timestamp,l)try{l(b,I)}catch(_){g.warn("[BroadcastSync] Error in onStateSync callback",{error:_ instanceof Error?_.message:String(_),stack:_ instanceof Error?_.stack:void 0,storeName:i})}setTimeout(()=>{u=!1,E()},50)}else v.add(L)}else if(S.type==="state-request"){const I=a(),b=JSON.parse(JSON.stringify(I));h&&h.postMessage({type:"state-response",storeName:i,state:b,timestamp:Date.now()})}else if(S.type==="state-response"&&S.state)if(!d||S.timestamp>m){v.add(L),u=!0;const I=d;s(S.state);const b=S.state;if(d=b,m=S.timestamp,l)try{l(b,I)}catch(_){g.warn("[BroadcastSync] Error in onStateSync callback",{error:_ instanceof Error?_.message:String(_),stack:_ instanceof Error?_.stack:void 0,storeName:i})}setTimeout(()=>{u=!1,E()},50)}else v.add(L)}},h.postMessage({type:"state-request",storeName:i,timestamp:Date.now()})}return e((...E)=>{if(u)s(...E);else if(s(...E),h&&o){const N=a();if(c(N,d)){const S=Date.now(),L=`update-${S}-${Math.random()}`,I=JSON.parse(JSON.stringify(N));if(h.postMessage({type:"state-update",storeName:i,state:I,timestamp:S,messageId:L}),l)try{l(N,d)}catch(b){g.warn("[BroadcastSync] Error in onStateSync callback",{error:b instanceof Error?b.message:String(b),stack:b instanceof Error?b.stack:void 0,storeName:i})}d=N,m=S}}},a,n)}}const ee=nt()(it(Qr(e=>({isAuthenticated:!1,isLoading:!1,error:null,login:async t=>{e({isLoading:!0,error:null});try{const s=await Ur(t);return e({isAuthenticated:!0,isLoading:!1,error:null}),Z.refreshToken().catch(a=>{g.warn("Failed to fetch CSRF token after login",{error:a instanceof Error?a.message:String(a),stack:a instanceof Error?a.stack:void 0})}),s}catch(s){throw e({error:W(s),isLoading:!1,isAuthenticated:!1}),s}},register:async t=>{e({isLoading:!0,error:null});try{const a=!!(await Vr(t)).token?.access_token;e({isAuthenticated:a,isLoading:!1,error:null}),a&&Z.refreshToken().catch(n=>{g.warn("Failed to fetch CSRF token after register",{error:n instanceof Error?n.message:String(n),stack:n instanceof Error?n.stack:void 0})})}catch(s){throw e({error:W(s),isLoading:!1,isAuthenticated:!1}),s}},logout:async()=>{e({isLoading:!0});try{await $r()}catch(t){g.error("Logout error",{error:t instanceof Error?t.message:String(t),stack:t instanceof Error?t.stack:void 0})}finally{e({isAuthenticated:!1,isLoading:!1,error:null}),Z.clearToken()}},logoutLocal:()=>{g.info("[Auth] Performing local logout (no API call)",{}),te.clearTokens(),T(async()=>{const{cleanupProactiveRefresh:t}=await Promise.resolve().then(()=>ja);return{cleanupProactiveRefresh:t}},void 0).then(({cleanupProactiveRefresh:t})=>{t()}).catch(t=>{g.warn("Failed to cleanup proactive refresh",{error:t instanceof Error?t.message:String(t)})}),Z.clearToken(),e({isAuthenticated:!1,isLoading:!1,error:null})},refreshUser:async()=>{const s=ee.getState().isAuthenticated;e({isLoading:!0});try{await zt(),e({isAuthenticated:!0,isLoading:!1,error:null}),Z.refreshToken().catch(a=>{g.warn("Failed to fetch CSRF token after refresh user",{error:a instanceof Error?a.message:String(a),stack:a instanceof Error?a.stack:void 0})})}catch(a){const n=W(a),i=typeof n.code=="number"?n.code:0;i===401||i===1001||i===1002?(te.clearTokens(),e({error:n,isLoading:!1,isAuthenticated:!1})):e({error:n,isLoading:!1,isAuthenticated:!!s})}},checkAuthStatus:async()=>{{ee.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 s=e,a=t;return s.isAuthenticated!==a?.isAuthenticated}}),{name:"auth-storage",partialize:e=>({isAuthenticated:e.isAuthenticated})})),be=Object.freeze(Object.defineProperty({__proto__:null,useAuthStore:ee},Symbol.toStringTag,{value:"Module"}));function mn(){return!1}const ue=nt()(vs(it(Qr(e=>({theme:"dark",language:"en",sidebarOpen:!0,notifications:[],setTheme:t=>{e({theme:t});const s=document.documentElement;if(t==="system"){const a=window.matchMedia("(prefers-color-scheme: dark)").matches;s.classList.remove("light","dark"),s.classList.add(a?"dark":"light"),s.setAttribute("data-theme",a?"dark":"light")}else s.classList.remove("light","dark"),s.classList.add(t),s.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 s={...t,id:crypto.randomUUID(),timestamp:new Date().toISOString()};e(a=>({notifications:[...a.notifications,s]}))},removeNotification:t=>{e(s=>({notifications:s.notifications.filter(a=>a.id!==t)}))},markNotificationAsRead:t=>{e(s=>({notifications:s.notifications.map(a=>a.id===t?{...a,read:!0}:a)}))},clearNotifications:()=>e({notifications:[]})}),{channelName:"ui-store",enabled:!0,shouldSync:(e,t)=>{const s=e,a=t;return s.theme!==a?.theme||s.language!==a?.language||s.sidebarOpen!==a?.sidebarOpen}}),{name:"ui-storage",partialize:e=>({theme:e.theme,language:e.language,sidebarOpen:e.sidebarOpen})}),{name:"UIStore",enabled:mn()}));function y(...e){return ys(xs(e))}const fn=wr("inline-flex items-center justify-center whitespace-nowrap rounded-full text-sm font-sans font-medium tracking-tight transition-[color,box-shadow,border-color,background-color] duration-[var(--sumi-duration-normal)] ease-out focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring focus-visible:ring-offset-2 focus-visible:ring-offset-background focus-visible:shadow-[var(--sumi-shadow-glow)] disabled:pointer-events-none disabled:opacity-50 gap-2",{variants:{variant:{default:"bg-primary text-primary-foreground hover:bg-primary/90 border border-transparent font-semibold",primary:"bg-primary text-primary-foreground hover:bg-primary/90 border border-transparent font-semibold",destructive:"bg-destructive/10 text-destructive hover:bg-destructive/20 border border-destructive/30 hover:border-destructive/50",outline:"border border-border bg-transparent text-foreground hover:bg-muted/50 hover:border-border",secondary:"bg-muted/30 text-foreground hover:bg-muted/50 border border-border hover:border-border",ghost:"text-muted-foreground hover:text-foreground hover:bg-muted/50",link:"text-primary underline-offset-4 hover:underline",glass:"bg-[var(--sumi-glass-bg)] text-foreground backdrop-blur-[var(--sumi-glass-blur)] border border-[var(--sumi-glass-border)] hover:bg-white/15 font-medium"},size:{default:"h-10 px-4 py-2",sm:"h-9 rounded-full px-4 text-xs",lg:"h-12 rounded-full px-8 text-base",icon:"h-10 w-10 rounded-full"}},defaultVariants:{variant:"default",size:"default"}}),P=f.forwardRef(({className:e,variant:t,size:s,asChild:a=!1,icon:n,loading:i=!1,children:o,disabled:c,...l},h)=>{const u=a?bs:"button",d=c||i;return r.jsx(u,{className:y(fn({variant:t,size:s,className:e}),i&&"opacity-70"),ref:h,disabled:d,...l,children:a?o:r.jsxs(r.Fragment,{children:[i&&r.jsx(ye,{className:"mr-2 h-4 w-4 animate-spin"}),!i&&n&&r.jsx("span",{className:"flex items-center justify-center pointer-events-none","aria-hidden":"true",children:n}),o]})})});P.displayName="Button";let hn=class extends Rt.Component{constructor(t){super(t),this.state={hasError:!1,error:null}}static getDerivedStateFromError(t){return{hasError:!0,error:t}}handleReset=()=>{this.setState({hasError:!1,error:null}),this.props.onReset?.()};render(){return this.state.hasError?this.props.fallback?this.props.fallback:r.jsxs("div",{className:"flex flex-col items-center justify-center min-h-layout-page p-6 text-center animate-fade-in",children:[r.jsxs("div",{className:"relative mb-6",children:[r.jsx("div",{className:"absolute inset-0 bg-destructive/20 rounded-full blur-2xl animate-pulse"}),r.jsx("div",{className:"relative bg-destructive/10 rounded-full p-6",children:r.jsx(Oe,{className:"h-12 w-12 text-destructive"})})]}),r.jsx("h2",{className:"text-heading-2 mb-2",children:"Something went wrong"}),r.jsx("p",{className:"text-muted-foreground max-w-md mb-6",children:"An unexpected error occurred. This has been logged and we'll look into it."}),this.state.error&&r.jsxs("details",{className:"mb-6 w-full max-w-md text-left",children:[r.jsx("summary",{className:"text-caption cursor-pointer hover:text-foreground transition-colors",children:"Technical details"}),r.jsx("pre",{className:"mt-2 p-3 rounded-lg bg-muted text-xs text-muted-foreground overflow-auto max-h-32",children:this.state.error.message})]}),r.jsxs("div",{className:"flex gap-3",children:[r.jsxs(P,{onClick:this.handleReset,className:"gap-2",children:[r.jsx(kr,{className:"h-4 w-4"})," Try again"]}),r.jsxs(P,{variant:"outline",onClick:()=>window.location.href="/",className:"gap-2",children:[r.jsx(Er,{className:"h-4 w-4"})," Go home"]})]})]}):this.props.children}};const pn=wr("flex flex-col rounded-lg text-card-foreground transition-[box-shadow,background-color,border-color] duration-[var(--sumi-duration-normal)] ease-out relative overflow-hidden",{variants:{variant:{default:"bg-card border border-border shadow-card hover:shadow-card-hover hover:bg-card/95",elevated:"bg-card border border-border shadow-lg hover:shadow-xl hover:bg-card/95",ghost:"bg-transparent border-0",outline:"bg-transparent border border-border",muted:"bg-muted/50 border border-border",interactive:"bg-card border border-transparent shadow-card cursor-pointer hover:shadow-card-hover hover:border-primary/20 focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring focus-visible:ring-offset-2",spotlight:"bg-card/80 border border-border hover:border-border",surface:"bg-card border border-border shadow-none hover:bg-card/90 hover:border-border hover:shadow-card-hover transition-all duration-[var(--sumi-duration-slow)] ease-in-out",glass:"bg-card/80 dark:bg-black/20 backdrop-blur-xl border border-border"},padding:{none:"",sm:"p-4",default:"p-6",lg:"p-8"}},defaultVariants:{variant:"default",padding:"none"}});function Ft({className:e,variant:t,padding:s,spotlight:a,spotlightColor:n="rgba(255, 255, 255, 0.1)",...i}){const o=f.useRef(null),[c,l]=f.useState({x:0,y:0}),[h,u]=f.useState(0),d=w=>{if(!o.current||t!=="spotlight"&&!a)return;const N=o.current.getBoundingClientRect();l({x:w.clientX-N.left,y:w.clientY-N.top})},m=()=>{u(1)},v=()=>{u(0)},p=t==="spotlight"||a;return r.jsxs("div",{ref:o,onMouseMove:d,onMouseEnter:m,onMouseLeave:v,"data-slot":"card",className:y(pn({variant:t,padding:s}),e),...i,children:[p&&r.jsx("div",{className:"pointer-events-none absolute -inset-px opacity-0 transition duration-[var(--sumi-duration-normal)]",style:{opacity:h,background:`radial-gradient(600px circle at ${c.x}px ${c.y}px, ${n}, transparent 40%)`}}),r.jsx("div",{className:"relative z-10 w-full h-full flex flex-col",children:i.children})]})}function sc({className:e,...t}){return r.jsx("div",{"data-slot":"card-header",className:y("flex flex-col gap-1.5 p-6 pb-0",e),...t})}function ac({className:e,...t}){return r.jsx("h3",{"data-slot":"card-title",className:y("text-lg font-semibold leading-tight tracking-tight text-foreground",e),...t})}function nc({className:e,...t}){return r.jsx("p",{"data-slot":"card-description",className:y("text-sm text-muted-foreground/90",e),...t})}function Br({className:e,...t}){return r.jsx("div",{"data-slot":"card-content",className:y("p-6 pt-4",e),...t})}function ic({className:e,...t}){return r.jsx("div",{"data-slot":"card-footer",className:y("flex items-center gap-3 p-6 pt-0",e),...t})}const gn={success:Ss,error:Ee,warning:Oe,info:ot},or={success:"border-success/30 bg-success/10 text-success",error:"border-destructive/30 bg-destructive/10 text-destructive",warning:"border-warning/30 bg-warning/10 text-warning",info:"border-info/30 bg-info/10 text-info"},lr=5e3;function vn({toast:e,onDismiss:t}){const[s,a]=f.useState(!1),[n,i]=f.useState(!1),o=f.useCallback(()=>{i(!0),setTimeout(()=>{t(e.id)},300)},[e.id,t]);f.useEffect(()=>{requestAnimationFrame(()=>a(!0));const h=e.duration??lr;let u=null;return h>0&&(u=setTimeout(()=>{o()},h)),()=>{u&&clearTimeout(u)}},[e.duration,e.id,o]);const c=e.type?gn[e.type]:ot,l=e.type?or[e.type]:or.info;return r.jsxs(Ft,{variant:"glass",className:y("relative flex min-w-80 max-w-sm items-start gap-4 p-4 shadow-modal transition-all duration-[var(--sumi-duration-normal)] transform",l,s&&!n?"opacity-100 translate-x-0 translate-y-0 scale-100":"opacity-0 translate-x-full scale-95","backdrop-blur-xl"),role:"alert","data-testid":"toast-alert","aria-live":"polite",children:[r.jsx(c,{className:"h-5 w-5 flex-shrink-0 animate-[pulse-ring_2s_infinite]"}),r.jsxs("div",{className:"flex-1 min-w-0",children:[r.jsx("p",{className:"text-sm font-medium leading-relaxed font-sans",children:e.message}),e.action&&r.jsx("button",{onClick:()=>{e.action?.onClick(),o()},className:"mt-1.5 text-xs font-semibold underline underline-offset-2 hover:no-underline transition-colors",children:e.action.label})]}),r.jsx("button",{onClick:o,className:"flex-shrink-0 rounded-md p-1 opacity-60 transition-opacity duration-[var(--duration-fast)] hover:opacity-100 hover:bg-muted/50 focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-primary/50 focus-visible:ring-offset-2 focus-visible:ring-offset-background","aria-label":"Close",children:r.jsx(he,{className:"h-4 w-4"})}),r.jsx("div",{className:y("absolute bottom-0 left-0 h-0.5 bg-current opacity-20 transition-all ease-linear",s&&!n?"w-full":"w-0"),style:{transitionDuration:`${(e.duration||lr)-300}ms`}})]})}const Kr=f.createContext(void 0);function yn(){const e=f.useContext(Kr);if(!e)throw new Error("useToastContext must be used within ToastProvider");return e}function oc(){const e=yn();return{...e,addToast:(s,a)=>{typeof s=="string"?e.addToast({message:s,type:a||"info"}):e.addToast(s)}}}const xn={"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 bn({children:e,position:t="top-right",className:s}){const[a,n]=f.useState([]),i=f.useCallback(l=>{const h=`toast-${Date.now()}-${Math.random().toString(36).substr(2,9)}`,u={...l,id:h};n(d=>[...d,u])},[]),o=f.useCallback(l=>{n(h=>h.filter(u=>u.id!==l))},[]),c={toasts:a,addToast:i,removeToast:o};return r.jsxs(Kr.Provider,{value:c,children:[e,r.jsx("div",{className:y("fixed z-50 flex flex-col gap-2",xn[t],s),children:a.map(l=>r.jsx(vn,{toast:l,onDismiss:o},l.id))})]})}function Hr(){const e=f.useRef(null),{theme:t}=ue();return f.useEffect(()=>{const s=e.current;if(!s)return;const a=s.getContext("2d");if(!a)return;const n=document.documentElement.classList.contains("light");let i,o=[];const c=window.innerWidth<768?20:50,l=150,h=n?"14, 165, 233":"102, 252, 241",u=n?"148, 163, 184":"102, 252, 241",d=()=>{s.width=window.innerWidth,s.height=window.innerHeight},m=()=>{o=[];for(let p=0;p<c;p++)o.push({x:Math.random()*s.width,y:Math.random()*s.height,size:Math.random()*(n?3:2),speedX:(Math.random()-.5)*.2,speedY:(Math.random()-.5)*.2,opacity:Math.random()*.5+.1})},v=()=>{a.clearRect(0,0,s.width,s.height),o.forEach((p,w)=>{p.x+=p.speedX,p.y+=p.speedY,p.x<0&&(p.x=s.width),p.x>s.width&&(p.x=0),p.y<0&&(p.y=s.height),p.y>s.height&&(p.y=0),a.beginPath(),a.arc(p.x,p.y,p.size,0,Math.PI*2),a.fillStyle=`rgba(${h}, ${p.opacity})`,a.fill();for(let E=w+1;E<o.length;E++){const N=o[E];if(!N)continue;const S=p.x-N.x,L=p.y-N.y,I=Math.sqrt(S*S+L*L);if(I<l){a.beginPath();const b=n?.05:.1;a.strokeStyle=`rgba(${u}, ${b*(1-I/l)})`,a.lineWidth=.5,a.moveTo(p.x,p.y),a.lineTo(N.x,N.y),a.stroke()}}}),i=requestAnimationFrame(v)};return window.addEventListener("resize",d),d(),m(),v(),()=>{window.removeEventListener("resize",d),cancelAnimationFrame(i)}},[t]),r.jsxs("div",{className:"fixed inset-0 z-0 pointer-events-none overflow-hidden transition-colors duration-700",children:[r.jsx("div",{className:"absolute inset-0 bg-background transition-colors duration-700"}),r.jsx("div",{className:"absolute inset-0 bg-gradient-to-b from-transparent via-transparent to-black/20 dark:to-black/80"}),r.jsx("div",{className:"absolute top-[-20%] left-[-10%] w-[60%] h-[60%] rounded-full bg-cyan/5 dark:bg-cyan/5 blur-[120px] animate-pulse"}),r.jsx("div",{className:"absolute bottom-[-20%] right-[-10%] w-[60%] h-[60%] rounded-full bg-magenta/5 dark:bg-magenta/5 blur-[120px] animate-pulse",style:{animationDelay:"2s"}}),r.jsx("canvas",{ref:e,className:"absolute inset-0 opacity-60 dark:opacity-40"}),r.jsx("div",{className:"absolute inset-0 opacity-[0.02] dark:opacity-[0.03]",style:{backgroundImage:"linear-gradient(rgb(var(--sidebar-border)) 1px, transparent 1px)",backgroundSize:"100px 100px"}})]})}function wn(){const[e,t]=f.useState(()=>typeof navigator<"u"?navigator.onLine:!0);return f.useEffect(()=>{const s=()=>t(!0),a=()=>t(!1);return window.addEventListener("online",s),window.addEventListener("offline",a),()=>{window.removeEventListener("online",s),window.removeEventListener("offline",a)}},[]),e}let Vt=null,st=null;const kn=3e4;function En(e){const t=ut(e);(t==="network"||t==="timeout")&&(Vt=e instanceof Error||e&&typeof e=="object"&&"message"in e?e:new Error(String(e)),st=Date.now())}function Wr(){Vt=null,st=null}function Gr(){return!Vt||!st?!1:Date.now()-st>kn?(Wr(),!1):!0}const Sn=Object.freeze(Object.defineProperty({__proto__:null,clearNetworkError:Wr,hasRecentNetworkError:Gr,recordNetworkError:En},Symbol.toStringTag,{value:"Module"}));function Ut({children:e,active:t=!0,onEscape:s}){const a=f.useRef(null),n=f.useRef(null);return f.useEffect(()=>{if(!t||!a.current)return;n.current=document.activeElement;const i=a.current.querySelectorAll('button, [href], input, select, textarea, [tabindex]:not([tabindex="-1"])'),o=i[0],c=i[i.length-1];o&&o.focus();const l=h=>{if(h.key==="Escape"){s?.();return}h.key==="Tab"&&(h.shiftKey?document.activeElement===o&&(h.preventDefault(),c?.focus()):document.activeElement===c&&(h.preventDefault(),o?.focus()))};return document.addEventListener("keydown",l),()=>{document.removeEventListener("keydown",l),n.current instanceof HTMLElement&&n.current.focus()}},[t,s]),r.jsx("div",{ref:a,tabIndex:-1,children:e})}const jn={sm:"max-w-sm",md:"max-w-md",lg:"max-w-2xl",xl:"max-w-4xl",full:"max-w-full m-4 h-layout-modal-full"};function Nn({open:e,onClose:t,children:s,title:a,closeOnOverlayClick:n=!0,closeOnEscape:i=!0,size:o="md",className:c,footer:l}){const h=f.useRef(null),u=f.useId();f.useEffect(()=>{if(e)return document.body.style.overflow="hidden",()=>{document.body.style.overflow=""}},[e]),f.useEffect(()=>{if(!i||!e)return;const m=v=>{v.key==="Escape"&&t()};return document.addEventListener("keydown",m),()=>document.removeEventListener("keydown",m)},[e,i,t]);const d=m=>{n&&m.target===m.currentTarget&&t()};return xr.createPortal(r.jsx(Dt,{children:e&&r.jsxs(we.div,{className:"fixed inset-0 z-[var(--sumi-z-modal)] flex items-center justify-center p-4",onClick:d,exit:{opacity:0},transition:{duration:.2},children:[r.jsx(we.div,{className:"absolute inset-0 bg-black/60 backdrop-blur-sm",initial:{opacity:0},animate:{opacity:1},exit:{opacity:0},transition:{duration:.2}}),r.jsx(Ut,{children:r.jsxs(we.div,{ref:h,role:"dialog","aria-modal":"true","aria-labelledby":a?u:void 0,initial:{opacity:0,scale:.95},animate:{opacity:1,scale:1},exit:{opacity:0,scale:.95},transition:{duration:.2,ease:[.33,1,.68,1]},className:y("relative w-full bg-popover border border-border rounded-xl shadow-2xl flex flex-col overflow-hidden",jn[o],c),onClick:m=>m.stopPropagation(),children:[a&&r.jsxs("div",{className:"p-4 border-b border-border bg-card flex justify-between items-center shrink-0",children:[r.jsx("h3",{id:u,className:"font-bold text-foreground text-lg font-heading",children:a}),r.jsx(P,{variant:"ghost",size:"icon",onClick:t,className:"ml-auto","aria-label":"Fermer",children:r.jsx(he,{className:"w-5 h-5"})})]}),r.jsx("div",{className:"p-8 overflow-y-auto custom-scrollbar flex-1",children:s}),l&&r.jsx("div",{className:"p-4 border-t border-border bg-card shrink-0 flex justify-end gap-4",children:l})]})})]},"modal")}),document.body)}const _n={alert:Ee,confirm:Ee,info:ot,default:void 0},Tn={alert:"text-destructive",confirm:"text-primary",info:"text-muted-foreground",default:""};function Xr({open:e,onClose:t,onOpenChange:s,title:a,children:n,footer:i,variant:o="default",onConfirm:c,onCancel:l,confirmLabel:h="Confirm",cancelLabel:u="Cancel",showCancel:d=!0,size:m="md",className:v}){const p=()=>{s?s(!1):t&&t()},w=async()=>{c&&await c(),p()},E=()=>{l&&l(),p()},N=_n[o],S=Tn[o];return r.jsxs(Nn,{open:e,onClose:p,size:m,className:v,closeOnOverlayClick:o==="default",title:a,footer:i||c||l?i||r.jsxs("div",{className:"flex justify-end gap-2",children:[d&&r.jsx(P,{variant:"outline",onClick:E,children:u}),c&&r.jsx(P,{variant:o==="alert"?"destructive":"default",onClick:w,children:h})]}):void 0,children:[a&&N&&r.jsx("div",{className:"flex items-center gap-4 mb-4",children:r.jsx(N,{className:y("h-5 w-5",S)})}),n]})}const Cn=f.forwardRef(({variant:e="rectangular",width:t,height:s,className:a,...n},i)=>{const o="relative overflow-hidden bg-muted/50",c={text:"rounded h-4 w-full",circular:"rounded-full",rectangular:"rounded-lg"},l={width:t,height:s};return r.jsx("div",{ref:i,className:y(o,c[e],a),style:l,"aria-hidden":"true",...n,children:r.jsx("div",{className:"absolute inset-0 skeleton-shimmer"})})});Cn.displayName="Skeleton";function Rn(e){return new Date(e).toLocaleString()}function An(e){const t=e.config.method?.toUpperCase()||"UNKNOWN",s=e.config.url||"Unknown URL";return`${t} ${s}`}function Pn(e){switch(e){case"high":return"bg-destructive/20 text-destructive border-destructive/30";case"normal":return"bg-muted/20 text-muted-foreground border-border/30";case"low":return"bg-muted/30 text-muted-foreground border-border/50";default:return"bg-muted/30 text-muted-foreground border-border/50"}}function cr({open:e,onClose:t}){const[s,a]=f.useState([]),[n,i]=f.useState(null),[o,c]=f.useState(!1);f.useEffect(()=>{if(!e)return;const u=()=>{a(me.getQueue())};u();const d=setInterval(u,1e3);return()=>clearInterval(d)},[e]);const l=async u=>{i(u);try{await me.removeRequest(u),a(me.getQueue())}catch(d){g.error("Failed to remove request",{error:d instanceof Error?d.message:String(d),stack:d instanceof Error?d.stack:void 0,requestId:u})}finally{i(null)}},h=async()=>{c(!0);try{await me.clearQueue(),a([]),t()}catch(u){g.error("Failed to clear queue",{error:u instanceof Error?u.message:String(u),stack:u instanceof Error?u.stack:void 0})}finally{c(!1)}};return r.jsx(Xr,{open:e,onClose:t,title:"Offline Queue Manager",size:"lg",variant:"info",children:r.jsxs("div",{className:"space-y-4",children:[r.jsxs("div",{className:"flex items-center justify-between p-4 bg-card/50 rounded-lg border border-border",children:[r.jsxs("div",{className:"flex items-center gap-2",children:[r.jsx(Ae,{className:"w-5 h-5 text-muted-foreground"}),r.jsx("span",{className:"text-sm text-muted-foreground",children:s.length===0?"No queued requests":`${s.length} ${s.length===1?"request":"requests"} queued`})]}),s.length>0&&r.jsxs(P,{variant:"destructive",size:"sm",onClick:h,disabled:o,children:[r.jsx(js,{className:"w-4 h-4 mr-2"}),"Clear All"]})]}),s.length===0?r.jsxs("div",{className:"text-center py-8 text-muted-foreground",children:[r.jsx(Ns,{className:"w-12 h-12 mx-auto mb-4 text-primary/50"}),r.jsx("p",{className:"text-sm",children:"All requests have been processed"})]}):r.jsx("div",{className:"space-y-2 max-h-layout-list overflow-y-auto custom-scrollbar",children:s.map(u=>r.jsx("div",{className:"p-4 bg-card/30 rounded-lg border border-border hover:border-border/50 transition-colors",children:r.jsxs("div",{className:"flex items-start justify-between gap-4",children:[r.jsxs("div",{className:"flex-1 min-w-0",children:[r.jsx("div",{className:"flex items-center gap-2 mb-2",children:r.jsx("span",{className:"font-mono text-sm font-semibold text-foreground truncate",children:An(u)})}),r.jsxs("div",{className:"flex items-center gap-4 flex-wrap text-xs text-muted-foreground",children:[r.jsx("span",{className:y("px-2 py-0.5 rounded border",Pn(u.priority)),children:u.priority}),r.jsxs("span",{className:"flex items-center gap-1",children:[r.jsx(Ae,{className:"w-3 h-3"}),Rn(u.timestamp)]}),u.retryCount>0&&r.jsxs("span",{className:"flex items-center gap-1 text-destructive",children:[r.jsx(Ee,{className:"w-3 h-3"}),u.retryCount," retry",u.retryCount>1?"ies":""]})]})]}),r.jsx(P,{variant:"ghost",size:"icon",onClick:()=>l(u.id),disabled:n===u.id,className:"shrink-0",children:n===u.id?r.jsx(Ae,{className:"w-4 h-4 animate-spin"}):r.jsx(he,{className:"w-4 h-4"})})]})},u.id))}),s.length>0&&r.jsx("div",{className:"p-4 bg-muted/10 border border-border/20 rounded-lg text-xs text-muted-foreground",children:r.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 In(){const e=wn(),[t,s]=f.useState(0),[a,n]=f.useState(!1),[i,o]=f.useState(!1),[c,l]=f.useState(!1),[h,u]=f.useState(!1);return f.useEffect(()=>{const d=()=>{const v=me.getQueueSize();s(v)};d();const m=setInterval(d,1e3);return()=>clearInterval(m)},[]),f.useEffect(()=>{if(e&&t>0){n(!0);const d=setInterval(()=>{me.getQueueSize()===0&&(n(!1),clearInterval(d))},500);return()=>clearInterval(d)}else{n(!1);return}},[e,t]),f.useEffect(()=>{const d=()=>{o(Gr())};d();const m=setInterval(d,2e3);return()=>clearInterval(m)},[]),f.useEffect(()=>{if(a&&t>0&&e){const d=setTimeout(()=>{u(!0)},500);return()=>{clearTimeout(d),u(!1)}}else{u(!1);return}},[a,t,e]),e&&t===0&&!a&&!i?null:!e||i?r.jsxs(r.Fragment,{children:[r.jsxs("div",{className:"fixed top-0 left-0 right-0 bg-destructive/90 backdrop-blur-sm text-foreground px-4 py-2.5 text-sm z-50 flex items-center justify-center gap-2 shadow-lg border-b border-destructive",children:[r.jsx(_s,{className:"w-4 h-4"}),r.jsxs("span",{children:["Mode hors ligne",t>0&&r.jsxs("span",{className:"ml-2 font-semibold",children:["- ",t," ",t===1?"requête":"requêtes"," en attente"]})]}),t>0&&r.jsxs("button",{onClick:()=>l(!0),className:"ml-3 px-2 py-1 bg-white/10 hover:bg-white/20 rounded border border-white/20 transition-colors flex items-center gap-1.5 text-xs font-medium",title:"View queued requests",children:[r.jsx(Ht,{className:"w-3.5 h-3.5"}),"View Queue"]})]}),r.jsx(cr,{open:c,onClose:()=>l(!1)})]}):a&&t>0&&h?r.jsxs(r.Fragment,{children:[r.jsxs("div",{className:"fixed top-0 left-0 right-0 bg-primary/90 backdrop-blur-sm text-foreground px-4 py-2.5 text-sm z-50 flex items-center justify-center gap-2 shadow-lg border-b border-border",children:[r.jsx(ye,{className:"w-4 h-4 animate-spin"}),r.jsxs("span",{children:["Synchronisation en cours",t>0&&r.jsxs("span",{className:"ml-2 font-semibold",children:["- ",t," ",t===1?"requête":"requêtes"," restante",t>1?"s":""]})]}),t>0&&r.jsxs(r.Fragment,{children:[r.jsx("button",{onClick:async()=>{await me.clearQueue(),s(0)},className:"ml-2 px-2 py-1 bg-destructive/20 hover:bg-destructive/30 rounded border border-destructive/30 transition-colors flex items-center gap-1.5 text-xs font-medium",title:"Clear queued requests",children:"Clear Queue"}),r.jsxs("button",{onClick:()=>l(!0),className:"ml-2 px-2 py-1 bg-background/20 hover:bg-background/30 rounded border border-border/30 transition-colors flex items-center gap-1.5 text-xs font-medium",title:"View queued requests",children:[r.jsx(Ht,{className:"w-3.5 h-3.5"}),"View Queue"]})]})]}),r.jsx(cr,{open:c,onClose:()=>l(!1)})]}):null}function Ln(e,t){const s=W(e),a=ut(s),n=typeof navigator<"u"?navigator.userAgent:"Unknown",i=typeof window<"u"?window.location.href:"Unknown",o=new Date().toISOString(),c=`[${a.toUpperCase()}] ${s.message||"Unknown error"}`,l=[];l.push("## 🐞 Error Details"),l.push(""),l.push(`**Message:** ${s.message||"No message provided"}`),s.code!==void 0&&l.push(`**Error Code:** ${s.code}`),s.code!==void 0&&l.push(`**HTTP Status:** ${s.code}`),s.request_id&&l.push(`**Request ID:** \`${s.request_id}\``),l.push(`**Category:** ${a}`),l.push(`**Timestamp:** ${o}`),l.push(""),t&&(l.push("## 📍 Context"),l.push(""),t.component&&l.push(`**Component:** ${t.component}`),t.action&&l.push(`**Action:** ${t.action}`),t.userId&&l.push(`**User ID:** ${t.userId}`),t.additionalInfo&&Object.keys(t.additionalInfo).length>0&&(l.push("**Additional Info:**"),l.push("```json"),l.push(JSON.stringify(t.additionalInfo,null,2)),l.push("```")),l.push("")),s.details&&(l.push("## 🔍 Error Details"),l.push(""),l.push("```json"),l.push(JSON.stringify(s.details,null,2)),l.push("```"),l.push("")),s.details&&s.details.length>0&&(l.push("## ⚠️ Validation Errors"),l.push(""),s.details.forEach(u=>{l.push(`- **${u.field}:** ${u.message}${u.value?` (value: ${u.value})`:""}`)}),l.push("")),l.push("## 💻 Environment"),l.push(""),l.push(`**URL:** ${i}`),l.push(`**User Agent:** ${n}`),l.push(`**Browser:** ${Mn(n)}`),l.push(`**Platform:** ${On(n)}`),typeof window<"u"&&(l.push(`**Screen:** ${window.screen.width}x${window.screen.height}`),l.push(`**Viewport:** ${window.innerWidth}x${window.innerHeight}`)),l.push(""),l.push("## 🔁 Steps to Reproduce"),l.push(""),l.push("1. [Describe step 1]"),l.push("2. [Describe step 2]"),l.push("3. [Describe step 3]"),l.push(""),l.push("## ✅ Expected Behavior"),l.push(""),l.push("[Describe what should have happened]"),l.push("");const h=l.join(`
`);return{title:c,body:h,metadata:{requestId:s.request_id,errorCode:s.code,statusCode:s.code,category:a,timestamp:o,userAgent:n,url:i}}}async function Yr(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 s=document.createElement("textarea");s.value=t,s.style.position="fixed",s.style.opacity="0",document.body.appendChild(s),s.select();try{document.execCommand("copy")}finally{document.body.removeChild(s)}}function Dn(e,t){const s=qn();if(!s){Yr(e);return}const a=new URLSearchParams({title:e.title,body:e.body}),n=`${s}/issues/new?${a.toString()}`;window.open(n,"_blank")}function qn(){return null}function Mn(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 On(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 zn(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=W(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 Jr=f.forwardRef(({error:e,onRetry:t,onDismiss:s,showDetails:a,context:n,variant:i="inline",severity:o="error",size:c="md",className:l,dismissible:h,title:u,icon:d,actions:m=[],...v},p)=>{const[w,E]=f.useState(!1),[N,S]=f.useState(!1),[L,I]=f.useState(!0),b=f.useMemo(()=>zn(e),[e]),_=f.useMemo(()=>W(e),[e]),G=f.useMemo(()=>ut(_),[_]),k=f.useMemo(()=>G==="server_error"||b.status!==void 0&&b.status>=500,[G,e]),C=a??!1,O=f.useMemo(()=>{if(b.message)try{return Or(b,n?.resource,!1)}catch{return b.message}return"An unexpected error occurred"},[b,n]),V=f.useMemo(()=>{if(u)return u;if(n?.action)return`Error ${n.action}`;switch(o){case"error":return"Error";case"warning":return"Warning";case"info":return"Information";default:return"Error"}},[u,n,o]),J=f.useMemo(()=>{if(d)return d;const U=c==="sm"?"w-4 h-4":c==="lg"?"w-6 h-6":"w-5 h-5";switch(o){case"error":return r.jsx(Ee,{className:y(U,"text-destructive")});case"warning":return r.jsx(Oe,{className:y(U,"text-warning")});case"info":return r.jsx(ot,{className:y(U,"text-info")});default:return r.jsx(Ee,{className:y(U,"text-destructive")})}},[d,o,c]),H=f.useMemo(()=>{switch(o){case"error":return{bg:"bg-destructive/10",border:"border-destructive/30",text:"text-destructive",icon:"text-destructive"};case"warning":return{bg:"bg-warning/10",border:"border-warning/30",text:"text-warning",icon:"text-warning"};case"info":return{bg:"bg-info/10",border:"border-info/30",text:"text-info",icon:"text-info"};default:return{bg:"bg-destructive/10",border:"border-destructive/30",text:"text-destructive",icon:"text-destructive"}}},[o]),Y=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]),re=f.useCallback(async()=>{if(!(!t||N)){S(!0);try{await t()}finally{S(!1)}}},[t,N]),Ne=f.useCallback(()=>{s&&s(),i==="modal"&&I(!1)},[s,i]),ft=f.useCallback(async()=>{try{const U=Ln(e,{component:n?.resource,action:n?.action,userId:n?.userId,additionalInfo:n});try{Dn(U),B.success("Opening GitHub issue...")}catch{await Yr(U),B.success("Issue report copied to clipboard")}}catch{B.error("Failed to generate issue report")}},[e,n]),ht=f.useCallback(async()=>{if(_.request_id)try{await navigator.clipboard.writeText(_.request_id),B.success("Request ID copied to clipboard")}catch{B.error("Failed to copy request ID")}},[_.request_id]),pt=h??(s!==void 0||i==="modal"),$e=()=>{if(!C||!w)return null;const U=[];return _.request_id&&U.push({label:"Request ID",value:_.request_id}),b.code&&U.push({label:"Error Code",value:String(b.code)}),b.status&&U.push({label:"HTTP Status",value:String(b.status)}),b.details&&U.push({label:"Details",value:JSON.stringify(b.details,null,2)}),b.stack&&U.push({label:"Stack Trace",value:b.stack}),n&&U.push({label:"Context",value:JSON.stringify(n,null,2)}),U.length===0?null:r.jsx("div",{className:"mt-4 pt-4 border-t border-white/10",children:r.jsx("div",{className:"space-y-2",children:U.map((le,gt)=>r.jsxs("div",{className:"text-xs",children:[r.jsxs("span",{className:"font-semibold opacity-70",children:[le.label,":"]}),r.jsx("pre",{className:"mt-1 p-2 bg-black/20 rounded text-xs overflow-x-auto",children:typeof le.value=="string"?le.value:JSON.stringify(le.value,null,2)})]},gt))})})},_e=r.jsxs("div",{ref:p,role:"alert","aria-live":"polite",className:y("rounded-lg border flex shadow-card",H.bg,H.border,H.text,Y.padding,Y.gap,l),...v,children:[r.jsx("div",{className:"flex-shrink-0 pt-0.5",children:J}),r.jsxs("div",{className:"flex-1 min-w-0",children:[r.jsx("div",{className:y("font-semibold mb-1",Y.title),children:V}),r.jsx("div",{className:y("opacity-90",Y.text),children:O}),$e(),(t||m.length>0||k||C&&(b.code||b.details||b.stack||n))&&r.jsxs("div",{className:"mt-4 flex flex-wrap gap-2 items-center",children:[t&&r.jsx(P,{variant:"outline",size:c==="sm"?"sm":"default",onClick:re,disabled:N,className:"border-current text-current hover:bg-current/10 bg-transparent",children:N?"Retrying...":"Retry"}),k&&_.request_id&&r.jsxs(r.Fragment,{children:[r.jsxs(P,{variant:"outline",size:c==="sm"?"sm":"default",onClick:ht,className:"border-current text-current hover:bg-current/10 bg-transparent",title:"Copy Request ID",children:[r.jsx(Ts,{className:"w-4 h-4 mr-1.5"}),"Copy ID"]}),r.jsxs(P,{variant:"outline",size:c==="sm"?"sm":"default",onClick:ft,className:"border-current text-current hover:bg-current/10 bg-transparent",children:[r.jsx(Cs,{className:"w-4 h-4 mr-1.5"}),"Report"]})]}),m.map((U,le)=>r.jsx(P,{variant:U.variant||"outline",size:c==="sm"?"sm":"default",onClick:U.onClick,className:"border-current text-current hover:bg-current/10 bg-transparent",children:U.label},le)),C&&(b.code||b.details||b.stack||n)&&r.jsx(P,{variant:"ghost",size:c==="sm"?"sm":"default",onClick:()=>E(!w),className:"text-current hover:bg-current/10 hover:text-current",children:w?r.jsxs(r.Fragment,{children:[r.jsx(Rs,{className:"w-4 h-4 mr-1"}),"Hide Details"]}):r.jsxs(r.Fragment,{children:[r.jsx(Sr,{className:"w-4 h-4 mr-1"}),"Show Details"]})})]})]}),pt&&r.jsx("button",{onClick:Ne,className:"opacity-70 hover:opacity-100 transition-opacity flex-shrink-0 self-start","aria-label":"Dismiss error",children:r.jsx(he,{className:y(c==="sm"?"w-4 h-4":"w-5 h-5")})})]});switch(i){case"banner":return r.jsx("div",{className:"w-full",children:_e});case"card":return r.jsx(Ft,{className:y(H.border,l,"glass"),children:r.jsx(Br,{className:y(Y.padding,"pt-6"),children:_e})});case"modal":return r.jsx(Xr,{open:L,onClose:Ne,title:V,variant:o==="error"?"alert":"default",footer:r.jsxs("div",{className:"flex gap-2 justify-end",children:[t&&r.jsx(P,{variant:"outline",onClick:re,disabled:N,children:N?"Retrying...":"Retry"}),m.map((U,le)=>r.jsx(P,{variant:U.variant||"outline",onClick:U.onClick,children:U.label},le)),r.jsx(P,{variant:"default",onClick:Ne,children:t?"Close":"Dismiss"})]}),children:r.jsxs("div",{className:y(H.text),children:[r.jsx("div",{className:y("opacity-90 mb-4",Y.text),children:O}),$e()]})});default:return _e}});Jr.displayName="ErrorDisplay";class Se extends f.Component{constructor(t){super(t),this.state={hasError:!1}}static getDerivedStateFromError(t){return{hasError:!0,error:t}}componentDidCatch(t,s){this.setState({error:t,errorInfo:s});const a=xa(),n={...a,component:"ErrorBoundary",errorType:t.name||"Error",errorMessage:t.message,stack:t.stack,componentStack:s.componentStack,url:typeof window<"u"?window.location.href:void 0,userAgent:typeof navigator<"u"?navigator.userAgent:void 0,timestamp:new Date().toISOString()};g.error("[ErrorBoundary] React error caught",n),typeof window<"u"&&ws(t,{contexts:{react:{componentStack:s.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:r.jsxs("div",{className:"min-h-screen flex items-center justify-center bg-background p-4 relative overflow-hidden",children:[r.jsx("div",{className:"absolute inset-0 bg-[radial-gradient(ellipse_at_center,_var(--tw-gradient-stops))] from-primary/5 via-background to-background pointer-events-none"}),r.jsx("div",{className:"w-full max-w-md relative z-10",children:r.jsx(Jr,{error:this.state.error||new Error("An unexpected error occurred"),variant:"card",severity:"error",size:"lg",showDetails:!1,context:{component:"ErrorBoundary",action:"rendering component",componentStack:this.state.errorInfo?.componentStack},onRetry:this.handleReset,actions:[{label:"Return Home",onClick:()=>{window.location.href="/"},variant:"outline"}]})})]}):this.props.children}}function Zr(){const{isAuthenticated:e}=ee();return br({queryKey:["user","me"],queryFn:zt,enabled:e,retry:!1,staleTime:300*1e3,gcTime:600*1e3})}const es=()=>{const{isAuthenticated:e,logout:t}=ee(),{data:s}=Zr();return{user:s??null,accessToken:null,refreshToken:null,isAuthenticated:e,logout:async()=>{await t()}}};function Fn({children:e}){const{isAuthenticated:t}=es(),[s,a]=f.useState(!0),n=!1,{isLoading:i}=ee();return f.useEffect(()=>{const c=setTimeout(()=>{a(!1)},200);return()=>clearTimeout(c)},[]),s||i?null:t||n?r.jsx(r.Fragment,{children:e}):r.jsx(et,{to:"/login",replace:!0})}function Vn(e){try{return e?typeof e=="string"?e:e instanceof Error?e.message:String(e):"Currently unable to access this component. Please check your connection."}catch{return"An unknown error occurred."}}function ts({pageName:e,error:t,onRetry:s}){return r.jsx("div",{className:"flex flex-col items-center justify-center min-h-layout-page-sm p-8 text-center animate-in fade-in zoom-in duration-[var(--sumi-duration-normal)]",children:r.jsxs("div",{className:"bg-card/50 border border-border/30 rounded-xl p-8 max-w-md w-full shadow-lg backdrop-blur-sm",children:[r.jsx("div",{className:"w-16 h-16 bg-destructive/10 rounded-full flex items-center justify-center mx-auto mb-6",children:r.jsx(Oe,{className:"h-8 w-8 text-destructive"})}),r.jsxs("h2",{className:"text-xl font-bold mb-2",children:["Failed to load ",e]}),r.jsx("p",{className:"text-muted-foreground mb-6 text-sm",children:Vn(t)}),r.jsxs("div",{className:"flex flex-col gap-3",children:[s&&r.jsxs(P,{onClick:s,variant:"outline",className:"w-full flex items-center justify-center gap-2",children:[r.jsx(kr,{className:"h-4 w-4"}),"Try Again"]}),r.jsx(P,{onClick:()=>window.location.reload(),variant:"default",className:"w-full flex items-center justify-center gap-2",children:"Refresh Page"})]})]})})}class Un extends f.Component{constructor(t){super(t),this.state={hasError:!1}}static getDerivedStateFromError(t){return{hasError:!0,error:t}}componentDidCatch(t,s){g.error("[LazyComponent] Failed to load lazy component",{pageName:this.props.pageName,error:t instanceof Error?t.message:String(t),stack:t instanceof Error?t.stack:void 0,componentStack:s.componentStack}),this.props.onError?.(t,s)}handleRetry=()=>{this.setState({hasError:!1,error:void 0})};render(){return this.state.hasError?r.jsx(ts,{pageName:this.props.pageName,error:this.state.error,onRetry:this.handleRetry}):this.props.children}}const $n={default:"text-primary",muted:"text-muted-foreground",white:"text-foreground",current:"text-current"},Qn={sm:"h-4 w-4",md:"h-8 w-8",lg:"h-12 w-12"},Bn={sm:"h-4 w-4",md:"h-5 w-5",lg:"h-6 w-6"};function Kn({size:e="md",className:t,text:s,inline:a=!1,variant:n="default","aria-label":i="Chargement en cours"}){return a?r.jsxs(r.Fragment,{children:[r.jsx(ye,{className:y("animate-spin",Bn[e],$n[n],t),"aria-hidden":"true"}),r.jsx("span",{className:"sr-only",children:i})]}):r.jsxs("div",{className:y("flex flex-col items-center justify-center min-h-48",t),children:[r.jsx("div",{className:y("animate-spin rounded-full border-2 border-muted border-t-primary",Qn[e]),role:"status","aria-label":i,children:r.jsx("span",{className:"sr-only",children:"Chargement..."})}),s&&r.jsx("p",{className:"mt-2 text-sm text-muted-foreground dark:text-muted-foreground",children:s})]})}function Hn(e,t){return e().then(s=>s).catch(s=>{const a=s instanceof Error?s.message:String(s);return g.error("[LazyComponent] Failed to import lazy component",{pageName:t,error:a,stack:s instanceof Error?s.stack:void 0}),Promise.resolve({default:()=>r.jsx(ts,{pageName:t,error:s instanceof Error?s:new Error(a)})})})}function q(e,t,s){const a=s?()=>Hn(e,s):e,n=f.lazy(a);return function(o){const{fallback:c,...l}=o,h=r.jsx(f.Suspense,{fallback:r.jsx(Kn,{}),children:r.jsx(n,{...l})});return s?r.jsx(Un,{pageName:s,children:h}):h}}const Wn=q(()=>T(()=>import("./DashboardPage-D6OLFNKT.js"),__vite__mapDeps([4,1,0,2,3,5,6,7,8,9,10,11,12,13])),void 0,"Dashboard"),Gn=q(()=>T(()=>import("./ChatPage-sofPTFXq.js"),__vite__mapDeps([14,1,0,2,3,6,15,10,16,17,8,7,18,19,20,5,11,12,13])).then(e=>({default:e.ChatPage})),void 0,"Chat"),Xn=q(()=>T(()=>import("./LibraryPage-Xac4xZs3.js"),__vite__mapDeps([21,1,0,2,3,22,8,6,23,11,24,18,17,10,25,26,15,12,5,13])).then(e=>({default:e.LibraryPage})),void 0,"Library"),Yn=q(()=>T(()=>import("./UserProfilePage-BY1UfRZ4.js"),__vite__mapDeps([27,1,0,2,3,6,28,11,23,24,29,30,5,10,31,12,20,9,32,8,13])).then(e=>({default:e.UserProfilePage})),void 0,"Profile"),Jn=q(()=>T(()=>import("./SettingsPage-BMJ_8iej.js"),__vite__mapDeps([33,1,0,2,3,28,11,32,15,10,16,17,8,34,26,30,12,5,6,13])).then(e=>({default:e.SettingsPage})),void 0,"Settings"),Zn=q(()=>T(()=>import("./LoginPage-BPKFxiYA.js"),__vite__mapDeps([35,1,0,2,3,5,36,10,37,6,34,11,12,8,13])),void 0,"Login"),ei=q(()=>T(()=>import("./RegisterPage-Cbos2bd-.js"),__vite__mapDeps([38,1,0,2,3,37,5,6,34,10,36,39,11,12,8,13])),void 0,"Register"),ti=q(()=>T(()=>import("./ForgotPasswordPage-RlEQXPkX.js"),__vite__mapDeps([40,1,0,2,3,5,37,36,10,41,6,11,12,8,13])),void 0,"Forgot Password"),ri=q(()=>T(()=>import("./VerifyEmailPage-aMulf8Pk.js"),__vite__mapDeps([42,1,0,2,3,5,37,6,11,12,10,8,13])),void 0,"Verify Email"),si=q(()=>T(()=>import("./ResetPasswordPage-DNSUNR25.js"),__vite__mapDeps([43,1,0,2,3,5,37,36,10,39,41,6,11,12,8,13])),void 0,"Reset Password"),ai=q(()=>T(()=>import("./SessionsPage-BPgyk4mW.js"),__vite__mapDeps([44,1,0,2,3,19,10,5,6,11,12,8,13])),void 0,"Sessions"),ni=q(()=>T(()=>import("./NotFoundPage-AehFEVgj.js"),__vite__mapDeps([45,1,0,2,3,5,10,6,11,12,8,13])),void 0,"Not Found"),ii=q(()=>T(()=>import("./ServerErrorPage-BoBd7eZS.js"),__vite__mapDeps([46,1,0,2,3,5,10,6,11,12,8,13])),void 0,"Server Error"),oi=q(()=>T(()=>import("./UserProfilePage-BY1UfRZ4.js"),__vite__mapDeps([27,1,0,2,3,6,28,11,23,24,29,30,5,10,31,12,20,9,32,8,13])).then(e=>({default:e.UserProfilePage})),void 0,"User Profile"),li=q(()=>T(()=>import("./RolesPage-i5tov1x5.js"),__vite__mapDeps([47,1,0,2,3,11,30,15,10,48,16,17,8,5,6,12,13])).then(e=>({default:e.RolesPage})),void 0,"Roles"),ci=q(()=>T(()=>import("./TrackDetailPage-BzykkTeC.js"),__vite__mapDeps([49,1,0,2,3,6,11,24,18,17,8,10,32,20,15,19,12,23,50,26,5,13])).then(e=>({default:e.TrackDetailPage})),void 0,"Track Detail"),ui=q(()=>T(()=>import("./routes-KmsO9QV6.js"),__vite__mapDeps([51,1,0,2,3,22,8,6,29,30,5,10,52,12,15,48,34,16,17,20,19,32,53,11,13,54])).then(e=>({default:e.PlaylistRoutes})),void 0,"Playlists"),di=q(()=>T(()=>import("./AdminDashboardView-Cmv8FbBs.js"),__vite__mapDeps([55,1,0,2,3,10,9,32,8,5,6,11,12,13])).then(e=>({default:e.AdminDashboardView})),void 0,"Admin Dashboard"),mi=q(()=>T(()=>import("./AnalyticsView-D_bU_Pla.js"),__vite__mapDeps([56,1,0,2,3,10,57,9,5,6,11,12,8,13])).then(e=>({default:e.AnalyticsView})),void 0,"Analytics"),fi=q(()=>T(()=>import("./WebhooksView-C8RuIjXM.js"),__vite__mapDeps([58,1,0,2,3,15,10,59,5,6,11,12,8,13])).then(e=>({default:e.WebhooksView})),void 0,"Webhooks"),hi=q(()=>T(()=>import("./DesignSystemDemo-De2IQDmR.js"),__vite__mapDeps([60,1,0,2,3])).then(e=>({default:e.DesignSystemDemo})),void 0,"Design System Demo"),pi=q(()=>T(()=>import("./SocialView-BmPOCTMY.js"),__vite__mapDeps([61,1,0,2,3,24,11,10,20,8,5,6,12,13])).then(e=>({default:e.SocialView})),void 0,"Social");q(()=>T(()=>import("./GearView-B_mOp1cS.js"),__vite__mapDeps([62,1,0,2,3,10,15,5,6,11,12,8,13])).then(e=>({default:e.GearView})),void 0,"Gear");q(()=>T(()=>import("./LiveView-DqMcTM99.js"),__vite__mapDeps([63,1,0,2,3,10,8,5,6,11,12,13])).then(e=>({default:e.LiveView})),void 0,"Live");q(()=>T(()=>import("./EducationView-BV-pE4DL.js"),__vite__mapDeps([64,1,0,2,3,25,10,15,8,5,6,11,12,13])).then(e=>({default:e.EducationView})),void 0,"Education");q(()=>T(()=>import("./QueueView-Bd8wdqCc.js"),__vite__mapDeps([65,1,0,2,3,15,10,5,6,11,12,8,13])).then(e=>({default:e.QueueView})),void 0,"Queue");q(()=>T(()=>import("./DeveloperDashboardView-CdZjYMe3.js"),__vite__mapDeps([66,1,0,2,3,57,9,10,15,50,59,32,5,6,11,12,8,13])).then(e=>({default:e.DeveloperDashboardView})),void 0,"Developer");const gi=q(()=>T(()=>import("./NotificationsView-DebhDPTK.js"),__vite__mapDeps([67,1,0,2,3,10,31,5,6,11,12,8,13])).then(e=>({default:e.NotificationsView})),void 0,"Notifications"),vi=q(()=>T(()=>import("./MarketplaceHome-D5kxjtO5.js"),__vite__mapDeps([68,1,0,2,3,69,10,15,70,8,52,5,6,11,12,13])).then(e=>({default:e.MarketplaceHome})),void 0,"Marketplace"),yi=q(()=>T(()=>import("./SearchPage-C2Q4Rdlj.js"),__vite__mapDeps([71,1,0,2,3,5,53,10,32,20,12,6,11,8,13])).then(e=>({default:e.SearchPage})),void 0,"Search"),xi=q(()=>T(()=>import("./SellerDashboardView-drijru-x.js"),__vite__mapDeps([72,1,0,2,3,10,69,73,5,6,11,12,8,13])).then(e=>({default:e.SellerDashboardView})),void 0,"Seller Dashboard"),bi=q(()=>T(()=>import("./WishlistView-Becoqfzm.js"),__vite__mapDeps([74,1,0,2,3,70,10,8,5,6,11,12,13])).then(e=>({default:e.WishlistView})),void 0,"Wishlist"),wi=q(()=>T(()=>import("./PurchasesView-Dc_dipW8.js"),__vite__mapDeps([75,1,0,2,3,10,73,15,8,5,6,11,12,13])).then(e=>({default:e.PurchasesView})),void 0,"Purchases");function rs(){const{i18n:e,t}=qt(),{language:s,setLanguage:a}=ue(),n=i=>{e.changeLanguage(i),a(i)};return{t,i18n:{...e,changeLanguage:async i=>{await e.changeLanguage(i)},isInitialized:e.isInitialized},language:s,changeLanguage:n,isReady:e.isInitialized}}function ki(){return r.jsx("div",{className:"relative mb-6",children:r.jsx("div",{className:"w-24 h-24 mx-auto rounded-2xl bg-gradient-to-br from-primary/30 via-primary/20 to-secondary/20 flex items-center justify-center",children:r.jsx("svg",{viewBox:"0 0 24 24",className:"w-12 h-12 text-primary",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round","aria-hidden":!0,children:r.jsx("path",{d:"M12 3v18M6 9l6 6 6-6"})})})})}function Ce({feature:e,onGoBack:t}){const{t:s}=rs();return r.jsxs("div",{className:"flex min-h-layout-page flex-col items-center justify-center gap-6 px-6 text-center",children:[r.jsx(ki,{}),r.jsx("h1",{className:"text-3xl font-bold tracking-tight text-foreground",children:e}),r.jsx("p",{className:"max-w-md text-lg text-muted-foreground",children:s("comingSoon.description")}),r.jsxs("div",{className:"flex flex-wrap items-center justify-center gap-3",children:[t&&r.jsxs(P,{variant:"outline",onClick:t,className:"gap-2",children:[r.jsx(As,{className:"h-4 w-4"}),s("comingSoon.goBack")]}),r.jsx(P,{variant:"default",disabled:!0,children:s("comingSoon.notifyMe")})]})]})}function Ei({children:e}){const{isAuthenticated:t}=es(),s=!1,{isLoading:a}=ee();return a?null:t||s?r.jsx(et,{to:"/dashboard",replace:!0}):r.jsx(r.Fragment,{children:e})}function Si({verified:e}){return e?r.jsx("span",{className:"inline-flex items-center px-2 py-1 rounded-full text-xs font-medium bg-success/20 text-success",children:"✓ Email Verified"}):r.jsx("span",{className:"inline-flex items-center px-2 py-1 rounded-full text-xs font-medium bg-warning/20 text-warning",children:"⚠ Email Not Verified"})}async function ji(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 s=await F.get(`/notifications?${t.toString()}`);return{notifications:s.data.notifications||[],total:s.data.total,page:s.data.page||e?.page||1,limit:s.data.limit||e?.limit||20,totalPages:s.data.totalPages,unreadCount:s.data.unread_count}}catch(t){throw t instanceof De?new Error(t.response?.data?.error||t.message||"Failed to fetch notifications"):t}}async function Ni(e){try{await F.post(`/notifications/${e}/read`)}catch(t){throw t instanceof De?new Error(t.response?.data?.error||t.message||"Failed to mark notification as read"):t}}async function _i(){try{await F.post("/notifications/read-all")}catch(e){throw e instanceof De?new Error(e.response?.data?.error||e.message||"Failed to mark all notifications as read"):e}}function Ti(){return{success:(e,t)=>B.success(e,{duration:t}),error:(e,t)=>B.error(e,{duration:t}),warning:(e,t)=>B(e,{icon:"⚠️",duration:t}),info:(e,t)=>B(e,{icon:"",duration:t}),toast:e=>{const t={duration:e.duration};switch(e.type){case"success":B.success(e.message,t);break;case"error":B.error(e.message,t);break;case"warning":B(e.message,{...t,icon:"⚠️"});break;default:B(e.message,t)}}}}const Ci=3e4,Ri=50;function Ai(e){const[t,s]=f.useState(!1),a=f.useRef(null),n=at(),i=At(),{success:o,error:c}=Ti(),l=br({queryKey:["notifications","menu"],queryFn:()=>ji({limit:Ri}),refetchInterval:Ci,staleTime:1e4,enabled:e?.notificationsOverride===void 0&&e?.isLoadingOverride===void 0&&e?.errorOverride===void 0}),h=e?.notificationsOverride!==void 0?e.notificationsOverride??[]:l.data?.notifications??[],u=e?.isLoadingOverride??l.isLoading,d=e?.errorOverride!==void 0?e.errorOverride:l.error?String(l.error):null,m=h.filter(b=>!b.read).length,v=l.refetch,p=["notifications","menu"],w=Kt({mutationFn:Ni,onMutate:async b=>{await i.cancelQueries({queryKey:p});const _=i.getQueryData(p);return _&&i.setQueryData(p,{..._,notifications:_.notifications.map(G=>G.id===b?{...G,read:!0}:G),unreadCount:Math.max((_.unreadCount??1)-1,0)}),{previous:_}},onError:(b,_,G)=>{G?.previous&&i.setQueryData(p,G.previous),c("Erreur lors du marquage")},onSuccess:()=>{i.invalidateQueries({queryKey:p})}}),E=Kt({mutationFn:_i,onMutate:async()=>{await i.cancelQueries({queryKey:p});const b=i.getQueryData(p);return b&&i.setQueryData(p,{...b,notifications:b.notifications.map(_=>({..._,read:!0})),unreadCount:0}),{previous:b}},onError:(b,_,G)=>{G?.previous&&i.setQueryData(p,G.previous),c("Erreur lors du marquage")},onSuccess:()=>{i.invalidateQueries({queryKey:p}),o("Toutes les notifications ont été marquées comme lues")}});f.useEffect(()=>{function b(_){a.current&&!a.current.contains(_.target)&&s(!1)}return t&&document.addEventListener("mousedown",b),()=>document.removeEventListener("mousedown",b)},[t]),f.useEffect(()=>{t&&v()},[t,v]);const N=f.useCallback(b=>w.mutate(b),[w]),S=f.useCallback(()=>E.mutate(),[E]),L=f.useCallback(b=>{b.read||N(b.id),b.link&&(n(b.link),s(!1))},[N,n]),I=f.useCallback(()=>{n("/notifications"),s(!1)},[n]);return{menuRef:a,isOpen:t,setIsOpen:s,notifications:h,isLoading:u,error:d,unreadCount:m,handleMarkAsRead:N,handleMarkAllAsRead:S,handleNotificationClick:L,handleViewAll:I,markAsReadMutation:w,markAllAsReadMutation:E}}function Pi({isOpen:e,unreadCount:t,onClick:s}){return r.jsxs(P,{variant:"ghost",size:"icon",className:"relative",onClick:s,"aria-label":"Notifications","aria-expanded":e,"aria-haspopup":"true",children:[r.jsx(jr,{className:"h-5 w-5"}),t>0&&r.jsx(r.Fragment,{children:r.jsxs("span",{className:"absolute -top-1 -right-1 flex h-5 w-5",children:[r.jsx("span",{className:"animate-ping absolute inline-flex h-full w-full rounded-full bg-destructive opacity-75"}),r.jsx("span",{className:"relative inline-flex h-5 w-5 bg-destructive rounded-full text-xs text-destructive-foreground items-center justify-center font-semibold","aria-label":`${t} notifications non lues`,children:t>9?"9+":t})]})})]})}function Ii({notification:e,onMarkAsRead:t,onClick:s,isMarking:a}){return r.jsx("button",{type:"button",tabIndex:0,className:y("appearance-none bg-transparent border-0 text-left w-full","p-4 hover:bg-accent transition-colors cursor-pointer","focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring focus-visible:ring-offset-2 focus-visible:ring-offset-background",!e.read&&"bg-accent/50"),onClick:()=>s(e),children:r.jsxs("div",{className:"flex items-start justify-between gap-2",children:[r.jsxs("div",{className:"flex-1 min-w-0",children:[r.jsxs("div",{className:"flex items-center space-x-2 mb-1",children:[!e.read&&r.jsx("span",{className:"h-2 w-2 bg-primary rounded-full flex-shrink-0 mt-1.5"}),r.jsx("p",{className:y("text-sm font-medium",!e.read&&"font-semibold"),children:e.title})]}),e.content&&r.jsx("p",{className:"text-sm text-muted-foreground mb-2 line-clamp-2",children:e.content}),r.jsx("p",{className:"text-xs text-muted-foreground",children:ks(new Date(e.created_at),{addSuffix:!0,locale:Es})})]}),r.jsx("div",{className:"flex items-center space-x-1 ml-2 shrink-0",children:!e.read&&r.jsx(P,{variant:"ghost",size:"icon",className:"h-6 w-6",onClick:n=>{n.stopPropagation(),t(e.id)},"aria-label":"Marquer comme lu",disabled:a,children:a?r.jsx(ye,{className:"h-3 w-3 animate-spin"}):r.jsx(Ps,{className:"h-3 w-3"})})})]})})}const ss=Rt.memo(Ii);ss.displayName="NotificationMenuItem";function Li({isLoading:e,error:t,notifications:s,onMarkAsRead:a,onNotificationClick:n,isMarkingAsRead:i}){return t?r.jsx("div",{className:"p-4 text-center text-destructive text-sm",children:t}):e?r.jsx("div",{className:"flex items-center justify-center py-8",children:r.jsx(ye,{className:"h-6 w-6 animate-spin text-muted-foreground"})}):s.length===0?r.jsxs("div",{className:"p-8 text-center text-muted-foreground",children:[r.jsx(jr,{className:"h-12 w-12 mx-auto mb-2 opacity-50"}),r.jsx("p",{className:"text-sm",children:"Aucune notification"})]}):r.jsx("div",{className:"divide-y",children:s.map((o,c)=>r.jsx("div",{className:"animate-stagger-in",style:{animationDelay:`${Math.min(c*50,500)}ms`},children:r.jsx(ss,{notification:o,onMarkAsRead:a,onClick:n,isMarking:i})},o.id))})}function Di({unreadCount:e,notifications:t,isLoading:s,onMarkAllAsRead:a,onMarkAsRead:n,onNotificationClick:i,onViewAll:o,markAllPending:c,markPending:l,error:h}){return r.jsxs(we.div,{initial:{opacity:0,y:-8,scale:.96},animate:{opacity:1,y:0,scale:1},exit:{opacity:0,y:-8,scale:.96},transition:{duration:.15,ease:"easeOut"},className:"absolute right-0 mt-2 w-80 bg-background border rounded-lg shadow-lg z-50 max-h-96 flex flex-col",children:[r.jsxs("div",{className:"p-4 border-b flex items-center justify-between shrink-0",children:[r.jsx("h3",{className:"font-semibold text-sm",children:"Notifications"}),r.jsx("div",{className:"flex items-center space-x-2",children:e>0&&r.jsxs(P,{variant:"ghost",size:"sm",onClick:a,className:"h-7 text-xs",disabled:c,children:[c?r.jsx(ye,{className:"h-3 w-3 mr-1 animate-spin"}):r.jsx(Is,{className:"h-3 w-3 mr-1"}),"Tout marquer comme lu"]})})]}),r.jsx("div",{className:"overflow-y-auto flex-1 min-h-0",children:r.jsx(Li,{isLoading:s,error:h??null,notifications:t,onMarkAsRead:n,onNotificationClick:i,isMarkingAsRead:l})}),t.length>0&&r.jsx("div",{className:"p-4 border-t shrink-0",children:r.jsx(P,{variant:"ghost",size:"sm",className:"w-full",onClick:o,children:"Voir toutes les notifications"})})]})}function qi({isLoadingOverride:e,errorOverride:t,notificationsOverride:s}={}){const{menuRef:a,isOpen:n,setIsOpen:i,notifications:o,isLoading:c,error:l,unreadCount:h,handleMarkAsRead:u,handleMarkAllAsRead:d,handleNotificationClick:m,handleViewAll:v,markAsReadMutation:p,markAllAsReadMutation:w}=Ai({isLoadingOverride:e,errorOverride:t,notificationsOverride:s??void 0});return r.jsxs("div",{className:"relative",ref:a,children:[r.jsx(Pi,{isOpen:n,unreadCount:h,onClick:()=>i(!n)}),r.jsx(Dt,{children:n&&r.jsx(Di,{unreadCount:h,notifications:o,isLoading:c,error:l,onMarkAllAsRead:d,onMarkAsRead:u,onNotificationClick:m,onViewAll:v,markAllPending:w.isPending,markPending:p.isPending})})]})}function Mi(){const{limit:e,remaining:t,reset:s,isLimited:a}=Nt(),[n,i]=f.useState(null);f.useEffect(()=>{if(!s){i(null);return}const u=()=>{const m=Math.floor(Date.now()/1e3),v=s-m;i(v>0?v:0)};u();const d=setInterval(u,1e3);return()=>clearInterval(d)},[s]);const o=e!==null&&t!==null&&e>0?t/e*100:null;if(!(a||e!==null&&t!==null&&o!==null&&o<20)||e===null)return null;const l=u=>{if(u<=0)return"0s";if(u<60)return`${u}s`;const d=Math.floor(u/60),m=u%60;if(d<60)return m>0?`${d}m ${m}s`:`${d}m`;const v=Math.floor(d/60),p=d%60;return p>0?`${v}h ${p}m`:`${v}h`},h=a||t!==null&&t<=0;return r.jsxs("div",{className:y("flex items-center gap-2 px-4 py-1.5 rounded-lg text-xs font-medium transition-all",h?"bg-destructive/10 text-destructive border border-destructive/30":"bg-warning/10 text-warning border border-warning/30"),role:"alert","aria-live":"polite",children:[r.jsx(Oe,{className:"w-4 h-4 flex-shrink-0"}),r.jsx("div",{className:"flex items-center gap-2",children:a?r.jsxs(r.Fragment,{children:[r.jsx("span",{children:"Rate limit exceeded"}),n!==null&&r.jsxs("span",{className:"flex items-center gap-1",children:[r.jsx(Ae,{className:"w-3 h-3"}),l(n)]})]}):r.jsxs(r.Fragment,{children:[r.jsx("span",{children:t!==null?`${t}/${e} requests`:`${e} requests`}),n!==null&&r.jsxs("span",{className:"flex items-center gap-1 opacity-75",children:[r.jsx(Ae,{className:"w-3 h-3"}),"resets in ",l(n)]})]})})]})}function Oi(e,t,s,a){const[n,i]=f.useState(!1),[o,c]=f.useState(!1),[l,h]=f.useState(e),[u,d]=f.useState({}),m=f.useRef(null),v=f.useRef(null),p=f.useRef(null),w=f.useRef(null),E=f.useCallback(()=>{if(!p.current||!w.current||!n)return;const b=p.current.getBoundingClientRect(),_=w.current.getBoundingClientRect(),G=window.innerWidth,k=window.innerHeight,j=8;let C=e,O=0,V=0;switch(e){case"top":b.top-_.height-j<0&&(C="bottom");break;case"bottom":b.bottom+_.height+j>k&&(C="top");break;case"left":b.left-_.width-j<0&&(C="right");break;case"right":b.right+_.width+j>G&&(C="left");break}if(C==="top"||C==="bottom"){const J=b.left+b.width/2,H=_.width/2,Y=j,re=G-j;J-H<Y?O=Y-(J-H):J+H>re&&(O=re-(J+H))}else{const J=b.top+b.height/2,H=_.height/2,Y=j,re=k-j;J-H<Y?V=Y-(J-H):J+H>re&&(V=re-(J+H))}h(C),d({...O!==0&&{transform:`translate(calc(-50% + ${O}px), 0)`},...V!==0&&{transform:`translate(0, calc(-50% + ${V}px))`}})},[e,n]);f.useEffect(()=>{n&&E()},[n,E]),f.useEffect(()=>{o&&n&&E()},[o,n,E]);const N=f.useCallback(()=>{m.current&&clearTimeout(m.current),m.current=setTimeout(()=>{i(!0),c(!0)},s)},[s]),S=f.useCallback(()=>{m.current&&clearTimeout(m.current),v.current&&clearTimeout(v.current),v.current=setTimeout(()=>{i(!1)},100)},[]),L=f.useCallback(()=>{t==="click"&&i(b=>{const _=!b;return _&&c(!0),_})},[t]),I=t==="hover"?{onMouseEnter:N,onMouseLeave:S}:t==="click"?{onClick:L}:{onFocus:N,onBlur:S};return f.useEffect(()=>()=>{m.current&&clearTimeout(m.current),v.current&&clearTimeout(v.current)},[]),{visible:n,isMounted:o,calculatedPosition:l,tooltipStyle:u,wrapperRef:p,tooltipRef:w,triggerProps:a?{}:I}}const zi={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"},Fi={top:"top-full left-1/2 -translate-x-1/2 border-t-card border-l-transparent border-r-transparent border-b-transparent",bottom:"bottom-full left-1/2 -translate-x-1/2 border-b-card border-l-transparent border-r-transparent border-t-transparent",left:"left-full top-1/2 -translate-y-1/2 border-l-card border-t-transparent border-b-transparent border-r-transparent",right:"right-full top-1/2 -translate-y-1/2 border-r-card border-t-transparent border-b-transparent border-l-transparent"};function Vi({content:e,visible:t,calculatedPosition:s,tooltipStyle:a,tooltipRef:n,showArrow:i,maxWidth:o,className:c}){return r.jsxs("div",{ref:n,className:y("absolute z-50 max-w-xs px-4 py-1.5 text-sm text-foreground bg-card rounded-xl shadow-lg","border border-border pointer-events-none","transition-all duration-[var(--sumi-duration-normal)]",zi[s],t?"opacity-100 scale-100":"opacity-0 scale-95",c),role:"tooltip",style:{...o!=null&&{maxWidth:`${o}px`},...a},children:[e,i&&r.jsx("div",{className:y("absolute w-0 h-0 border-4",Fi[s])})]})}function ce({content:e,children:t,position:s="top",trigger:a="hover",delay:n=200,showArrow:i=!0,maxWidth:o,disabled:c=!1,className:l}){const{visible:h,isMounted:u,calculatedPosition:d,tooltipStyle:m,wrapperRef:v,tooltipRef:p,triggerProps:w}=Oi(s,a,n,c);if(c)return r.jsx(r.Fragment,{children:t});const E=a==="hover",N=E?w:{},S=!E&&f.isValidElement(t)&&f.Children.only(t)?f.cloneElement(t,w):t;return r.jsxs("div",{ref:v,className:"relative inline-block",...N,children:[S,u&&r.jsx(Vi,{content:e,visible:h,calculatedPosition:d,tooltipStyle:m,tooltipRef:p,showArrow:i,maxWidth:o,className:l})]})}function Ui(e){const[t,s]=f.useState(!1),{logout:a}=ee(),{data:n}=Zr(),{theme:i,setTheme:o,sidebarOpen:c,setSidebarOpen:l}=ue(),{t:h}=rs(),u=at(),d=async()=>{await a(),u("/login")},m=()=>{o(i==="light"?"dark":i==="dark"?"system":"light")},v=()=>{switch(i){case"light":return r.jsx(Fs,{className:"h-4 w-4"});case"dark":return r.jsx(zs,{className:"h-4 w-4"});default:return r.jsx(Os,{className:"h-4 w-4"})}};return r.jsx("header",{className:"fixed top-0 left-0 right-0 h-header z-[var(--sumi-z-sticky)] pointer-events-none",children:r.jsxs("div",{className:y("absolute top-0 right-0 h-header bg-[var(--sumi-glass-bg)] backdrop-blur-[12px] border-b border-[var(--sumi-border-faint)] flex items-center justify-between px-4 md:px-6 pointer-events-auto transition-all duration-[var(--sumi-duration-fast)]",c?"left-header-expanded":"left-header-collapsed","max-lg:left-0"),children:[r.jsx("button",{onClick:()=>l(!c),className:"lg:hidden p-2 rounded-lg hover:bg-muted/50 text-muted-foreground hover:text-foreground mr-2 transition-colors duration-[var(--duration-fast)]",children:r.jsx(Ls,{className:"w-5 h-5"})}),r.jsx("div",{className:"flex-1 max-w-md relative hidden md:block group",children:r.jsxs("div",{role:"search",className:"relative flex items-center group/search rounded-full focus-within:ring-2 focus-within:ring-primary/50 transition-all duration-[var(--duration-fast)]",children:[r.jsx(Ds,{className:"absolute left-3 w-4 h-4 text-muted-foreground pointer-events-none"}),r.jsx("input",{type:"search",placeholder:h("header.searchPlaceholder"),"aria-label":h("header.searchAriaLabel"),className:"w-full h-10 pl-10 pr-4 bg-muted/30 border-0 rounded-full text-sm text-foreground placeholder:text-muted-foreground focus:outline-none focus:ring-0 focus-visible:ring-2 focus-visible:ring-primary/50 focus-visible:ring-inset transition-all duration-[var(--duration-fast)]",onKeyDown:p=>{if(p.key==="Enter"){p.preventDefault();const w=(p.currentTarget.value||"").trim();u(w?`/search?q=${encodeURIComponent(w)}`:"/search")}}}),r.jsxs("kbd",{className:"absolute right-3 hidden sm:inline-flex items-center gap-0.5 px-2 py-0.5 rounded bg-muted/50 text-xs font-medium text-muted-foreground",children:[r.jsx(qs,{className:"w-3 h-3"}),"K"]})]})}),r.jsxs("div",{className:"flex items-center gap-1 ml-2",children:[r.jsxs("div",{className:"hidden xl:flex items-center gap-2 mr-2 px-2.5 py-1 rounded-full bg-muted/30 text-muted-foreground",children:[r.jsx("span",{className:"w-1.5 h-1.5 rounded-full bg-primary shrink-0"}),r.jsx("span",{className:"text-xs",children:h("header.online")})]}),r.jsx(qi,{}),r.jsx(Mi,{}),r.jsx("div",{className:"h-6 w-px bg-border mx-1","aria-hidden":!0}),r.jsx(ce,{content:h("common.changeTheme"),children:r.jsx(P,{variant:"ghost",size:"icon",onClick:m,className:"min-h-10 min-w-10 rounded-full hover:bg-muted/50 text-muted-foreground hover:text-foreground transition-colors duration-[var(--duration-fast)]",children:v()})}),r.jsxs("div",{className:"relative",children:[r.jsxs("button",{onClick:()=>s(!t),className:"flex items-center gap-2 pl-0.5 pr-2 py-0.5 rounded-full hover:bg-muted/50 transition-colors duration-[var(--duration-fast)] focus:outline-none focus:ring-2 focus:ring-ring group",children:[r.jsx("div",{className:"w-8 h-8 rounded-full bg-primary/20 flex items-center justify-center shrink-0 group-hover:ring-2 group-hover:ring-primary/50 group-hover:scale-105 transition-all",children:r.jsx("span",{className:"text-xs font-semibold text-primary",children:n?.username?.substring(0,2).toUpperCase()||"VZ"})}),r.jsx("span",{className:"hidden lg:block text-sm font-medium text-foreground truncate max-w-24",children:n?.username})]}),t&&r.jsx(Ut,{active:t,onEscape:()=>s(!1),children:r.jsxs("div",{className:"absolute right-0 top-full mt-2 w-56 bg-card backdrop-blur-xl border border-border rounded-xl shadow-xl p-2 z-50 animate-scaleIn origin-top-right",children:[r.jsxs("div",{className:"px-3 py-2.5 border-b border-border mb-1",children:[r.jsx("p",{className:"text-sm font-semibold text-foreground truncate",children:n?.username}),r.jsx("p",{className:"text-xs text-muted-foreground truncate",children:n?.email}),!n?.is_verified&&r.jsx("div",{className:"mt-2 flex justify-center",children:r.jsx(Si,{verified:!1})})]}),r.jsxs("div",{className:"p-1 space-y-0.5",children:[r.jsxs(tt,{to:"/profile",className:"flex items-center gap-3 px-3 py-2.5 text-sm text-muted-foreground hover:text-foreground hover:bg-muted rounded-xl transition-colors duration-[var(--duration-fast)]",children:[r.jsx(Ms,{className:"w-4 h-4"})," ",h("header.profile")]}),r.jsxs(tt,{to:"/settings",className:"flex items-center gap-3 px-3 py-2.5 text-sm text-muted-foreground hover:text-foreground hover:bg-muted rounded-xl transition-colors duration-[var(--duration-fast)]",children:[r.jsx(Nr,{className:"w-4 h-4"})," ",h("nav.settings")]})]}),r.jsx("div",{className:"h-px bg-border my-1","aria-hidden":!0}),r.jsx("div",{className:"p-1",children:r.jsxs("button",{onClick:d,className:"w-full flex items-center gap-3 px-3 py-2.5 text-sm text-destructive hover:bg-destructive/10 rounded-xl transition-colors duration-[var(--duration-fast)]",children:[r.jsx(_r,{className:"w-4 h-4"})," ",h("header.signOut")]})})]})})]})]})]})})}const $i=1024;function Qi(){const e=at(),{logout:t}=ee(),{setSidebarOpen:s}=ue(),a=f.useCallback(()=>{typeof window<"u"&&window.innerWidth<$i&&s(!1)},[s]),n=f.useCallback(()=>{t(),e("/login")},[t,e]);return{handleMobileNav:a,handleLogout:n}}const Bi={myStudio:"nav.sections.myStudio",vezaNetwork:"nav.sections.vezaNetwork",commerce:"nav.sections.commerce",library:"nav.sections.library",system:"nav.sections.system"},Ki={dashboard:r.jsx(Er,{className:"w-4 h-4"}),studio:r.jsx(sa,{className:"w-4 h-4"}),tracks:r.jsx(ra,{className:"w-4 h-4"}),gear:r.jsx(ta,{className:"w-4 h-4"}),analytics:r.jsx(ea,{className:"w-4 h-4"}),social:r.jsx(Zs,{className:"w-4 h-4"}),marketplace:r.jsx(Js,{className:"w-4 h-4"}),live:r.jsx(Ys,{className:"w-4 h-4"}),chat:r.jsx(Xs,{className:"w-4 h-4"}),education:r.jsx(Gs,{className:"w-4 h-4"}),sell:r.jsx(Ws,{className:"w-4 h-4"}),wishlist:r.jsx(Lt,{className:"w-4 h-4"}),purchases:r.jsx(Hs,{className:"w-4 h-4"}),playlists:r.jsx(It,{className:"w-4 h-4"}),queue:r.jsx(Ks,{className:"w-4 h-4"}),developer:r.jsx(Bs,{className:"w-4 h-4"}),admin:r.jsx(Qs,{className:"w-4 h-4"})},ur={live:3,chat:12},Hi=[{sectionKey:"myStudio",itemIds:["dashboard","studio","tracks","gear","analytics"]},{sectionKey:"vezaNetwork",itemIds:["social","marketplace","live","chat","education"]},{sectionKey:"commerce",itemIds:["sell","wishlist","purchases"]},{sectionKey:"library",itemIds:["playlists","queue"]},{sectionKey:"system",itemIds:["developer","admin"]}];function Wi(e){return Hi.map(({sectionKey:t,itemIds:s})=>({section:e(Bi[t]??t),items:s.map(a=>({id:a,label:e(`nav.items.${a}`),icon:Ki[a],...ur[a]!=null?{badge:ur[a]}:{}}))}))}const wt={dashboard:"/dashboard",studio:"/library",tracks:"/library",gear:"/gear",analytics:"/analytics",social:"/social",marketplace:"/marketplace",live:"/live",chat:"/chat",education:"/education",sell:"/sell",wishlist:"/wishlist",purchases:"/purchases",playlists:"/playlists",queue:"/queue",developer:"/developer",admin:"/admin",settings:"/settings"},dr=y("w-full flex items-center px-3 py-2 rounded-lg text-sm font-medium transition-all duration-[var(--duration-fast)] group relative","focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-primary/50 focus-visible:ring-offset-2 focus-visible:ring-offset-background"),mr="text-muted-foreground hover:text-foreground hover:bg-sidebar-accent active:bg-sidebar-accent/80",fr="bg-primary/10 text-primary sidebar-active-indicator",hr=1024,Gi=({currentView:e})=>{const{t}=qt(),s=ms(),{sidebarOpen:a,setSidebarOpen:n}=ue(),{handleMobileNav:i,handleLogout:o}=Qi(),c=f.useMemo(()=>Wi(t),[t]),[l,h]=f.useState(()=>typeof window<"u"?window.innerWidth<hr:!1);f.useEffect(()=>{const d=window.matchMedia(`(max-width: ${hr-1}px)`),m=()=>h(d.matches);return m(),d.addEventListener("change",m),()=>d.removeEventListener("change",m)},[]);const u=e||Object.keys(wt).find(d=>wt[d]===s.pathname)||"dashboard";return r.jsxs(r.Fragment,{children:[a&&r.jsx("div",{className:"fixed inset-0 bg-background/80 backdrop-blur-sm lg:hidden z-sidebar-overlay",onClick:()=>n(!1),"aria-hidden":"true",role:"presentation"}),r.jsx(Ut,{active:a&&l,onEscape:()=>n(!1),children:r.jsxs("aside",{"data-testid":"app-sidebar",className:y("fixed left-sidebar bottom-sidebar top-sidebar rounded-xl flex flex-col transition-shell z-sidebar overflow-hidden","bg-[var(--sumi-bg-raised)] backdrop-blur-md border-r border-[var(--sumi-border-faint)]",a?"w-sidebar-expanded translate-x-0 opacity-100":"-translate-x-full lg:translate-x-0 lg:opacity-100 lg:w-sidebar-collapsed"),"aria-label":"Main sidebar",children:[r.jsxs("div",{className:"px-4 py-4 flex items-center gap-3 relative",children:[r.jsx("div",{className:"w-8 h-8 rounded-lg bg-sidebar-accent flex items-center justify-center flex-shrink-0",children:r.jsx(Vs,{className:"w-4 h-4 text-muted-foreground"})}),r.jsxs("div",{className:y("transition-shell overflow-hidden min-w-0",a?"opacity-100":"w-0 opacity-0"),children:[r.jsx("h2",{className:"text-sm font-semibold text-foreground truncate",children:"System Hub"}),r.jsxs("div",{className:"flex items-center gap-1.5 mt-0.5",children:[r.jsx("span",{className:"w-1.5 h-1.5 rounded-full bg-primary shrink-0 animate-pulse","aria-hidden":"true"}),r.jsx("span",{className:"text-xs text-muted-foreground truncate",children:"Online"})]})]}),r.jsx(P,{variant:"ghost",size:"icon",onClick:()=>n(!a),className:y("ml-auto text-muted-foreground hover:text-foreground hidden lg:flex hover:bg-sidebar-accent",!a&&"absolute left-1/2 -translate-x-1/2 top-1/2 -translate-y-1/2"),"aria-label":a?"Collapse sidebar":"Expand sidebar",children:a?r.jsx(Us,{className:"w-4 h-4"}):r.jsx($s,{className:"w-4 h-4"})})]}),r.jsx("nav",{className:"flex-1 overflow-y-auto custom-scrollbar px-3 py-2",role:"navigation","aria-label":"Main navigation",children:c.map((d,m)=>r.jsxs("div",{children:[m>0&&r.jsx("div",{className:y("h-px bg-border/50 mx-3 my-1.5 transition-opacity duration-[var(--sumi-duration-normal)]",!a&&"mx-1"),"aria-hidden":"true"}),r.jsx("h3",{className:y("text-xs font-medium text-muted-foreground mb-2 px-3 transition-all duration-[var(--sumi-duration-normal)] uppercase tracking-wider",!a&&"opacity-0 h-0 overflow-hidden mb-0 px-0"),id:`sidebar-section-${d.section.replace(/\s+/g,"-").toLowerCase()}`,children:d.section}),r.jsx("ul",{className:"space-y-0.5 list-none m-0 p-0","aria-labelledby":`sidebar-section-${d.section.replace(/\s+/g,"-").toLowerCase()}`,children:d.items.map(v=>{const p=wt[v.id]||"/dashboard",w=u===v.id;return r.jsx("li",{className:"list-none m-0 p-0",children:r.jsx(ce,{content:v.label,position:"right",disabled:a,children:r.jsxs(tt,{to:p,onClick:i,"aria-current":w?"page":void 0,className:y(dr,w?fr:mr,!a&&"justify-center px-0"),children:[r.jsxs("div",{className:y("flex items-center gap-3 relative z-10 min-w-0",!a&&"justify-center"),children:[r.jsx("span",{className:y("shrink-0 transition-all duration-[var(--duration-fast)]","group-hover:scale-110",w?"text-primary":"text-muted-foreground group-hover:text-foreground"),children:v.icon}),r.jsx("span",{className:y("transition-all duration-[var(--sumi-duration-normal)] whitespace-nowrap truncate",a?"opacity-100":"w-0 opacity-0 overflow-hidden"),children:v.label})]}),v.badge!=null&&a&&r.jsx("span",{className:"ml-auto flex h-5 min-w-5 items-center justify-center rounded-full bg-primary/15 text-primary text-xs font-semibold tabular-nums shrink-0",children:v.badge}),v.badge!=null&&!a&&r.jsxs("span",{className:"absolute top-1.5 right-1.5 flex h-2 w-2","aria-hidden":"true",children:[r.jsx("span",{className:"animate-ping absolute inline-flex h-full w-full rounded-full bg-primary opacity-75"}),r.jsx("span",{className:"relative inline-flex rounded-full h-2 w-2 bg-primary"})]})]})})},v.id)})})]},d.section))}),r.jsxs("div",{className:"p-2 border-t border-[var(--sumi-border-faint)] space-y-0.5",children:[r.jsx(ce,{content:t("nav.settings"),position:"right",disabled:a,children:r.jsxs(tt,{to:"/settings",onClick:i,"aria-current":u==="settings"?"page":void 0,className:y(dr,u==="settings"?fr:mr,!a&&"justify-center px-0"),children:[r.jsx(Nr,{className:y("w-4 h-4 shrink-0 transition-all duration-[var(--duration-fast)]","group-hover:scale-110",u==="settings"?"text-primary":"text-muted-foreground group-hover:text-foreground")}),r.jsx("span",{className:y("truncate transition-all duration-[var(--sumi-duration-normal)]",a?"opacity-100":"w-0 opacity-0 overflow-hidden"),children:t("nav.settings")})]})}),r.jsx(ce,{content:t("nav.logout"),position:"right",disabled:a,children:r.jsxs(P,{variant:"ghost",onClick:o,className:y("w-full text-muted-foreground hover:text-destructive hover:bg-destructive/10 gap-3 justify-start rounded-lg group","focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-primary/50 focus-visible:ring-offset-2 focus-visible:ring-offset-background",!a&&"justify-center px-0"),"aria-label":t("nav.logout"),children:[r.jsx(_r,{className:"w-4 h-4 shrink-0 transition-transform duration-[var(--duration-fast)] group-hover:scale-110"}),r.jsx("span",{className:y("whitespace-nowrap transition-all duration-[var(--sumi-duration-normal)]",a?"opacity-100":"w-0 opacity-0 overflow-hidden"),children:t("nav.logout")})]})})]})]})})]})},$t=nt()(it((e,t)=>({currentTrack:null,isPlaying:!1,currentTime:0,duration:0,volume:100,muted:!1,queue:[],currentIndex:-1,repeat:"off",shuffle:!1,play:s=>{if(!s){e({isPlaying:!0});return}const{queue:a}=t(),n=a.findIndex(i=>i.id===s.id);if(n>=0)e({currentTrack:s,currentIndex:n,isPlaying:!0,currentTime:0});else{const i=[...a,s];e({currentTrack:s,currentIndex:i.length-1,queue:i,isPlaying:!0,currentTime:0})}},pause:()=>{e({isPlaying:!1})},resume:()=>{e({isPlaying:!0})},stop:()=>{e({isPlaying:!1,currentTime:0})},next:()=>{const{queue:s,currentIndex:a,repeat:n,shuffle:i}=t();if(s.length===0)return;let o=a;if(i)o=Math.floor(Math.random()*s.length);else if(a<s.length-1)o=a+1;else if(n==="playlist")o=0;else return;const c=s[o];o!==a&&c&&e({currentIndex:o,currentTrack:c,currentTime:0,isPlaying:!0})},previous:()=>{const{queue:s,currentIndex:a}=t();if(s.length===0||a<=0)return;const n=a-1,i=s[n];i&&e({currentIndex:n,currentTrack:i,currentTime:0,isPlaying:!0})},seek:s=>{const{duration:a}=t(),n=Math.max(0,Math.min(s,a||0));e({currentTime:n})},setCurrentTime:s=>{const{duration:a}=t(),n=Math.max(0,Math.min(s,a||0));e({currentTime:n})},setDuration:s=>{e({duration:Math.max(0,s)})},setVolume:s=>{const a=Math.max(0,Math.min(100,s));e({volume:a})},toggleMute:()=>{e({muted:!t().muted})},toggleShuffle:()=>{e({shuffle:!t().shuffle})},setRepeat:s=>{e({repeat:s})},addToQueue:s=>{const{queue:a}=t(),n=[...a,...s];e({queue:n})},removeFromQueue:s=>{const{queue:a,currentIndex:n}=t();if(s<0||s>=a.length)return;const i=a.filter((c,l)=>l!==s);let o=n;if(s<n)o=n-1;else if(s===n)if(i.length>0){o=Math.min(o,i.length-1),e({queue:i,currentIndex:o,currentTrack:i[o]||null,isPlaying:i[o]?t().isPlaying:!1});return}else{o=-1,e({queue:i,currentIndex:o,currentTrack:null,isPlaying:!1});return}e({queue:i,currentIndex:o})},reorderQueue:(s,a)=>{const{queue:n,currentIndex:i}=t();if(s<0||s>=n.length||a<0||a>=n.length||s===a)return;const o=[...n],[c]=o.splice(s,1);if(!c)return;o.splice(a,0,c);let l=i;s===i?l=a:s<i&&a>=i?l=i-1:s>i&&a<=i&&(l=i+1),e({queue:o,currentIndex:l})},clearQueue:()=>{e({queue:[],currentIndex:-1,currentTrack:null,isPlaying:!1,currentTime:0})}}),{name:"player-storage",partialize:e=>({volume:e.volume,muted:e.muted,repeat:e.repeat,shuffle:e.shuffle,queue:e.queue,currentIndex:e.currentIndex,currentTrack:e.currentTrack})}));function pr(e){if(isNaN(e)||!isFinite(e)||e<0)return"0:00";const t=Math.floor(e/60),s=Math.floor(e%60);return`${t}:${s.toString().padStart(2,"0")}`}function Xi(e){return e?!!(e.id&&e.title&&e.url):!1}class Qt{audioElement=null;timeUpdateCallback=null;durationChangeCallback=null;endedCallback=null;errorCallback=null;playCallback=null;pauseCallback=null;initialize(t){this.audioElement=t,this.setupEventListeners()}setupEventListeners(){this.audioElement&&(this.audioElement.addEventListener("timeupdate",this.handleTimeUpdate),this.audioElement.addEventListener("loadedmetadata",this.handleLoadedMetadata),this.audioElement.addEventListener("durationchange",this.handleDurationChange),this.audioElement.addEventListener("ended",this.handleEnded),this.audioElement.addEventListener("error",this.handleError),this.audioElement.addEventListener("play",this.handlePlay),this.audioElement.addEventListener("pause",this.handlePause))}cleanup(){this.audioElement&&(this.audioElement.removeEventListener("timeupdate",this.handleTimeUpdate),this.audioElement.removeEventListener("loadedmetadata",this.handleLoadedMetadata),this.audioElement.removeEventListener("durationchange",this.handleDurationChange),this.audioElement.removeEventListener("ended",this.handleEnded),this.audioElement.removeEventListener("error",this.handleError),this.audioElement.removeEventListener("play",this.handlePlay),this.audioElement.removeEventListener("pause",this.handlePause),this.audioElement=null)}static isValidMediaUrl(t){if(!t||typeof t!="string"||t.trim()===""||t==="undefined"||t==="null")return!1;try{const s=new URL(t,window.location.origin);return s.protocol==="http:"||s.protocol==="https:"||s.protocol==="blob:"}catch{return!1}}async loadTrack(t){if(!this.audioElement)throw new Error("Audio element not initialized");if(!t){this.audioElement.src="";return}if(!Xi(t))throw new Error("Invalid track");if(!Qt.isValidMediaUrl(t.url)){this.audioElement.src="";return}this.audioElement.src=t.url,this.audioElement.load()}async play(){if(!this.audioElement)throw new Error("Audio element not initialized");try{await this.audioElement.play()}catch(t){throw new Error(`Failed to play audio: ${t}`)}}pause(){if(!this.audioElement)throw new Error("Audio element not initialized");this.audioElement.pause()}stop(){if(!this.audioElement)throw new Error("Audio element not initialized");this.audioElement.pause(),this.audioElement.currentTime=0}seek(t){if(!this.audioElement)throw new Error("Audio element not initialized");const s=this.audioElement.duration||0,a=Math.max(0,Math.min(t,s));this.audioElement.currentTime=a}setVolume(t){if(!this.audioElement)throw new Error("Audio element not initialized");const s=Math.max(0,Math.min(1,t));this.audioElement.volume=s}setMuted(t){if(!this.audioElement)throw new Error("Audio element not initialized");this.audioElement.muted=t}getCurrentTime(){return this.audioElement&&this.audioElement.currentTime||0}getDuration(){return this.audioElement&&this.audioElement.duration||0}getVolume(){return this.audioElement?this.audioElement.volume:1}isPlaying(){return this.audioElement?!this.audioElement.paused&&!this.audioElement.ended:!1}isMuted(){return this.audioElement?this.audioElement.muted:!1}handleTimeUpdate=()=>{this.timeUpdateCallback&&this.audioElement&&this.timeUpdateCallback(this.audioElement.currentTime)};handleLoadedMetadata=()=>{this.durationChangeCallback&&this.audioElement&&this.durationChangeCallback(this.audioElement.duration)};handleDurationChange=()=>{this.durationChangeCallback&&this.audioElement&&this.durationChangeCallback(this.audioElement.duration)};handleEnded=()=>{this.endedCallback&&this.endedCallback()};handleError=()=>{if(this.errorCallback&&this.audioElement){const t=new Error(this.audioElement.error?.message||"Unknown audio error");this.errorCallback(t)}};handlePlay=()=>{this.playCallback&&this.playCallback()};handlePause=()=>{this.pauseCallback&&this.pauseCallback()};onTimeUpdate(t){this.timeUpdateCallback=t}onDurationChange(t){this.durationChangeCallback=t}onEnded(t){this.endedCallback=t}onError(t){this.errorCallback=t}onPlay(t){this.playCallback=t}onPause(t){this.pauseCallback=t}}const z=new Qt;function Yi(e){const t=$t(),s=f.useRef(null),a=e?.current||s.current;f.useEffect(()=>{if(a)return z.initialize(a),()=>{z.cleanup()}},[a]),f.useEffect(()=>{if(!a)return;const d=t.muted?0:t.volume/100;z.setVolume(d),z.setMuted(t.muted)},[a,t.volume,t.muted]),f.useEffect(()=>{if(!a)return;(async()=>{try{await z.loadTrack(t.currentTrack)}catch(m){g.error("Failed to load track:",{error:m})}})()},[a,t.currentTrack]),f.useEffect(()=>{if(!a)return;(async()=>{try{t.isPlaying?await z.play():z.pause()}catch(m){g.error("Failed to sync playback:",{error:m}),t.pause()}})()},[a,t.isPlaying,t]),f.useEffect(()=>{if(a)return z.onTimeUpdate(d=>{t.setCurrentTime(d)}),z.onDurationChange(d=>{t.setDuration(d)}),z.onEnded(()=>{t.repeat==="track"?(z.seek(0),z.play().catch(d=>g.error("Failed to reply track:",{error:d}))):t.next()}),z.onError(d=>{const m=d instanceof Error?d.message:String(d);m.includes("fetch")||m.includes("Invalid")||m.includes("MEDIA_ERR")?g.debug("Audio playback error (invalid URL or network):",{error:m}):g.error("Audio playback error:",{error:d}),t.pause()}),z.onPlay(()=>{t.isPlaying||t.resume()}),z.onPause(()=>{t.isPlaying&&t.pause()}),()=>{z.onTimeUpdate(null),z.onDurationChange(null),z.onEnded(null),z.onError(null),z.onPlay(null),z.onPause(null)}},[a,t]);const n=f.useCallback(async d=>{if(t.play(d),d&&a)try{await z.loadTrack(d),await z.play()}catch(m){g.error("Failed to play track:",{error:m}),t.pause()}},[t,a]),i=f.useCallback(()=>{t.pause(),a&&z.pause()},[t,a]),o=f.useCallback(async()=>{if(t.resume(),a)try{await z.play()}catch(d){g.error("Failed to resume playback:",{error:d}),t.pause()}},[t,a]),c=f.useCallback(()=>{t.stop(),a&&z.stop()},[t,a]),l=f.useCallback(d=>{t.seek(d),a&&z.seek(d)},[t,a]),h=f.useCallback(d=>{if(t.setVolume(d),a){const m=t.muted?0:d/100;z.setVolume(m)}},[t,a]),u=f.useCallback(()=>{t.toggleMute(),a&&z.setMuted(!t.muted)},[t,a]);return{currentTrack:t.currentTrack,isPlaying:t.isPlaying,currentTime:t.currentTime,duration:t.duration,volume:t.volume,muted:t.muted,queue:t.queue,currentIndex:t.currentIndex,repeat:t.repeat,shuffle:t.shuffle,play:n,pause:i,resume:o,stop:c,next:t.next,previous:t.previous,seek:l,setVolume:h,toggleMute:u,toggleShuffle:t.toggleShuffle,setRepeat:t.setRepeat,addToQueue:t.addToQueue,clearQueue:t.clearQueue}}const Ji=5,Zi=5;function eo(e,t={}){const{enabled:s=!0,seekStep:a=Ji,volumeStep:n=Zi,preventDefault:i=!0}=t,o=f.useCallback(c=>{if(!s)return;const l=c.target;if(!(l&&(l.tagName==="INPUT"||l.tagName==="TEXTAREA"||l.isContentEditable===!0)))switch(c.code){case"Space":{i&&c.preventDefault(),e.isPlaying?e.pause():e.resume();break}case"ArrowLeft":{i&&c.preventDefault();const h=Math.max(0,e.currentTime-a);e.seek(h);break}case"ArrowRight":{i&&c.preventDefault();const h=Math.min(e.duration||0,e.currentTime+a);e.seek(h);break}case"ArrowUp":{i&&c.preventDefault();const h=Math.min(100,e.volume+n);e.setVolume(h);break}case"ArrowDown":{i&&c.preventDefault();const h=Math.max(0,e.volume-n);e.setVolume(h);break}}},[s,i,a,n,e.isPlaying,e.currentTime,e.duration,e.volume,e.pause,e.resume,e.seek,e.setVolume]);f.useEffect(()=>{if(s)return window.addEventListener("keydown",o),()=>{window.removeEventListener("keydown",o)}},[s,o])}const Ge=24,to=.7;function ro(e,t){const[s,a]=f.useState(()=>Array(Ge).fill(0)),n=f.useRef(null),i=f.useRef(null),o=f.useRef(null),c=f.useRef(null);return f.useEffect(()=>e?((()=>{try{const h=new AudioContext,u=h.createMediaElementSource(e),d=h.createAnalyser();d.fftSize=256,d.smoothingTimeConstant=to,d.minDecibels=-60,d.maxDecibels=-10,u.connect(d),d.connect(h.destination),n.current=h,i.current=d,o.current=u}catch{}})(),()=>{c.current&&cancelAnimationFrame(c.current),o.current?.disconnect(),i.current?.disconnect(),n.current?.close(),n.current=null,i.current=null,o.current=null}):void 0,[e]),f.useEffect(()=>{const l=i.current,h=n.current;if(!l||!h||!t){t||a(Array(Ge).fill(0));return}h.state==="suspended"&&h.resume();const u=new Uint8Array(l.frequencyBinCount),d=()=>{if(!i.current)return;i.current.getByteFrequencyData(u);const m=Math.floor(u.length/Ge),v=Array.from({length:Ge},(p,w)=>(u[Math.min(w*m,u.length-1)]??0)/255);a(v),c.current=requestAnimationFrame(d)};return c.current=requestAnimationFrame(d),()=>{c.current&&cancelAnimationFrame(c.current)}},[t]),s}const Xe="flex items-center justify-center rounded-full flex-shrink-0 transition-all duration-[var(--sumi-duration-normal)] active:scale-95";function so({isPlaying:e,onPlayPause:t,onNext:s,onPrevious:a,onShuffle:n,onRepeat:i,shuffle:o,repeat:c,isExpanded:l=!1,compact:h=!1}){const u=h?"w-8 h-8":"w-10 h-10",d=l?"w-16 h-16":h?"w-10 h-10":"w-12 h-12",m=l?"w-6 h-6":h?"w-4 h-4":"w-5 h-5",v=l?"w-8 h-8":h?"w-5 h-5":"w-6 h-6",p=h?"gap-1.5":l?"gap-6":"gap-2 sm:gap-3 md:gap-4";return r.jsxs("div",{className:y("flex items-center justify-center",p),children:[r.jsx(ce,{content:"Shuffle",children:r.jsx("button",{onClick:n,className:y(Xe,u,o?"text-primary bg-primary/10 shadow-queue-item-current":"text-muted-foreground hover:text-foreground hover:bg-white/5"),children:r.jsx(Tr,{className:y("w-4 h-4",l&&"w-5 h-5")})})}),r.jsx("button",{onClick:a,className:y(Xe,u,"text-foreground hover:text-primary hover:bg-white/5"),children:r.jsx(Cr,{className:y(m,"fill-current")})}),r.jsx("button",{onClick:t,className:y("flex items-center justify-center rounded-full bg-primary text-black flex-shrink-0 active:scale-95 transition-all shadow-sm",d),children:e?r.jsx(Rr,{className:y(v,"fill-current")}):r.jsx(Ar,{className:y(v,"fill-current ml-0.5")})}),r.jsx("button",{onClick:s,className:y(Xe,u,"text-foreground hover:text-primary hover:bg-white/5"),children:r.jsx(Pr,{className:y(m,"fill-current")})}),r.jsx(ce,{content:"Repeat",children:r.jsxs("button",{onClick:i,className:y(Xe,u,"relative",c!=="off"?"text-primary bg-primary/10 shadow-queue-item-current":"text-muted-foreground hover:text-foreground hover:bg-white/5"),children:[r.jsx(Ir,{className:y("w-4 h-4",l&&"w-5 h-5")}),c==="track"&&r.jsx("span",{className:"absolute -top-0.5 -right-0.5 text-[8px] font-bold bg-primary text-black px-1 rounded-full",children:"1"})]})})]})}const as=f.forwardRef(({label:e,variant:t="cyan",icon:s,size:a="md",dot:n,count:i,children:o,className:c,onDismiss:l,pulse:h,...u},d)=>{const v={default:"cyan",primary:"cyan",success:"lime",warning:"gold",error:"magenta",secondary:"magenta",terminal:"lime"}[t]||t,p={cyan:"bg-muted/10 text-muted-foreground border-border/30",magenta:"bg-destructive/10 text-destructive border-destructive/30",lime:"bg-success/10 text-success border-success/30",gold:"bg-warning/10 text-warning border-warning/30"},w={sm:"px-2 py-0.5 text-xs",md:"px-2.5 py-0.5 text-xs",lg:"px-4 py-1 text-xs"},E={cyan:"bg-muted-foreground",magenta:"bg-destructive",lime:"bg-success",gold:"bg-warning"},N=e||o,S=v;return n&&!N&&!s&&i===void 0?r.jsx("span",{ref:d,className:y("inline-block h-2 w-2 rounded-full",E[S]||E.cyan,h&&"animate-pulse",c),...u}):r.jsxs("span",{ref:d,className:y("inline-flex items-center gap-1.5 rounded-full font-bold uppercase tracking-widest border",p[S]||p.cyan,w[a],h&&"animate-pulse",c),...u,children:[n&&r.jsx("span",{className:"w-3 h-3 rounded-full bg-current"}),s&&r.jsx("span",{className:"w-3 h-3",children:s}),N,i!==void 0&&i>0&&r.jsx("span",{className:"ml-1 px-1.5 py-0.5 rounded-full bg-current/20 text-xs",children:i}),l&&r.jsx("button",{type:"button",onClick:L=>{L.stopPropagation(),l()},className:"ml-1 -mr-0.5 inline-flex items-center justify-center rounded-full p-0.5 hover:bg-black/10 transition-colors","aria-label":"Remove",children:r.jsx(he,{className:"h-3 w-3"})})]})});as.displayName="Badge";const ns=f.forwardRef(({className:e,children:t,...s},a)=>r.jsx("div",{ref:a,className:y("relative overflow-auto custom-scrollbar",e),...s,children:t}));ns.displayName="ScrollArea";const ao=f.forwardRef(({className:e,...t},s)=>r.jsx("div",{ref:s,className:y("flex touch-none select-none transition-colors",e),...t}));ao.displayName="ScrollBar";function no({icon:e,title:t,description:s,action:a,className:n,size:i="md",variant:o="default"}){const c={sm:"py-6",md:"py-12",lg:"py-16"},l={sm:"h-8 w-8",md:"h-12 w-12",lg:"h-16 w-16"},h={sm:"p-3",md:"p-4",lg:"p-5"},u=r.jsxs("div",{className:"flex flex-col items-center animate-empty-state-in",children:[e&&r.jsx("div",{className:"flex justify-center mb-4",children:r.jsx("div",{className:y("bg-muted rounded-full flex items-center justify-center",h[i]),children:r.jsx("div",{className:y("text-muted-foreground",l[i]),children:e})})}),r.jsx("h3",{className:"text-lg font-semibold mb-2 text-foreground font-heading",children:t}),s&&r.jsx("p",{className:"text-sm text-muted-foreground mb-4 max-w-md mx-auto text-center",children:s}),a&&r.jsx(P,{onClick:a.onClick,variant:a.variant||"default",size:i==="sm"?"sm":"default",children:a.label})]});return o==="centered"?r.jsx("div",{className:y("flex flex-1 items-center justify-center text-center",c[i],n),children:u}):o==="card"?r.jsx("div",{className:y("border-2 border-dashed border-border rounded-xl text-center",c[i],n),children:u}):r.jsx(Ft,{className:y(n),children:r.jsx(Br,{className:y("text-center",c[i]),children:u})})}function io({isOpen:e,onClose:t,onPlay:s}){const{queue:a,currentIndex:n,removeFromQueue:i,clearQueue:o}=$t(),{sidebarOpen:c}=ue();return e?r.jsxs("div",{className:y("fixed bottom-24 left-4 right-4 z-40 transition-all duration-[var(--sumi-duration-normal)] ease-[var(--sumi-ease-out)] transform",c?"lg:left-main-expanded":"lg:left-main-collapsed","lg:right-4",e?"translate-y-0 opacity-100":"translate-y-10 opacity-0 pointer-events-none"),children:[r.jsxs("div",{className:"max-w-4xl mx-auto bg-black/80 backdrop-blur-2xl border border-white/10 rounded-2xl shadow-2xl overflow-hidden max-h-layout-drawer flex flex-col",children:[r.jsxs("div",{className:"flex items-center justify-between p-4 border-b border-white/5 bg-white/5",children:[r.jsxs("div",{className:"flex items-center gap-2",children:[r.jsx("h3",{className:"text-foreground font-bold font-heading tracking-wide",children:"Play Queue"}),r.jsxs(as,{variant:"secondary",className:"border-primary/20 text-primary bg-primary/10",children:[a.length," Tracks"]})]}),r.jsxs("div",{className:"flex items-center gap-2",children:[r.jsx("button",{onClick:o,className:"px-3 py-1.5 text-xs text-muted-foreground hover:text-foreground hover:bg-white/10 rounded-md transition-colors duration-[var(--duration-fast)] focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-primary/50 focus-visible:ring-offset-2 focus-visible:ring-offset-background",children:"Clear"}),r.jsx("button",{onClick:t,className:"p-1.5 text-muted-foreground hover:text-foreground hover:bg-white/10 rounded-full transition-colors duration-[var(--duration-fast)] focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-primary/50 focus-visible:ring-offset-2 focus-visible:ring-offset-background",children:r.jsx(he,{className:"w-5 h-5"})})]})]}),r.jsx("div",{className:"flex-1 overflow-hidden relative",children:a.length===0?r.jsx(no,{icon:r.jsx(It,{className:"w-full h-full"}),title:"Your queue is empty",description:"Add tracks to keep the vibe going.",size:"sm",className:"border-0 shadow-none bg-transparent"}):r.jsx(ns,{className:"h-full max-h-layout-list",children:r.jsx("div",{className:"p-2 space-y-1",children:a.map((l,h)=>{const u=h===n,d=h<n;return r.jsxs("div",{className:y("group flex items-center gap-3 p-2 rounded-lg transition-all duration-[var(--duration-fast)] border border-transparent",u?"bg-primary/10 border-primary/20 shadow-queue-item-current":"hover:bg-white/5 hover:border-white/5",d&&"opacity-50"),children:[r.jsx("div",{className:"text-white/20 group-hover:text-white/40 cursor-grab px-1",children:r.jsx(aa,{className:"w-4 h-4"})}),r.jsx("div",{className:"w-6 text-center text-xs font-mono text-muted-foreground",children:u?r.jsx("div",{className:"w-2 h-2 rounded-full bg-primary mx-auto animate-pulse shadow-queue-item-current"}):h+1}),r.jsxs("div",{className:"flex-1 min-w-0 cursor-pointer",onClick:()=>!u&&s(l),children:[r.jsx("h4",{className:y("text-sm font-medium truncate transition-colors",u?"text-primary":"text-foreground group-hover:text-foreground"),children:l.title}),r.jsx("p",{className:"text-xs text-muted-foreground truncate opacity-70 group-hover:opacity-100",children:l.artist})]}),r.jsx("button",{onClick:m=>{m.stopPropagation(),i(h)},className:"opacity-0 group-hover:opacity-100 p-2 text-muted-foreground hover:text-destructive hover:bg-destructive/10 rounded-full transition-all duration-[var(--duration-fast)] focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-primary/50 focus-visible:ring-offset-2 focus-visible:ring-offset-background",children:r.jsx(he,{className:"w-3 h-3"})})]},`${l.id}-${h}`)})})})})]}),r.jsx("div",{className:"fixed inset-0 bg-black/20 -z-10 backdrop-blur-sm md:hidden",onClick:t})]}):null}const Bt=f.forwardRef(({className:e,value:t=[0],onValueChange:s,min:a=0,max:n=100,step:i=1,disabled:o,"aria-label":c,"aria-labelledby":l,...h},u)=>{const d=v=>{const p=[Number(v.target.value)];s&&s(p)},m=((t[0]??a)-a)/(n-a)*100;return r.jsxs("div",{className:y("group relative flex w-full touch-none select-none items-center",e),children:[r.jsx("div",{className:"relative h-1 group-hover:h-1.5 w-full grow overflow-hidden rounded-full bg-muted transition-all duration-150",children:r.jsx("div",{className:"absolute h-full bg-primary transition-all duration-[var(--duration-fast)] shadow-slider-thumb group-hover:shadow-[0_0_8px_var(--primary)]",style:{width:`${m}%`}})}),r.jsx("input",{ref:u,type:"range",min:a,max:n,step:i,value:t[0],onChange:d,disabled:o,className:"absolute inset-0 w-full h-full opacity-0 cursor-pointer disabled:cursor-not-allowed","aria-label":c,"aria-labelledby":l,"aria-valuenow":t[0],"aria-valuemin":a,"aria-valuemax":n,...h}),r.jsx("div",{className:y("absolute h-5 w-5 rounded-full border-2 border-primary bg-background ring-offset-background pointer-events-none shadow-slider-thumb","scale-0 opacity-0 group-hover:scale-100 group-hover:opacity-100 transition-all duration-150",o&&"opacity-50"),style:{left:`calc(${m}% - 10px)`}})]})});Bt.displayName="Slider";function oo({isPlaying:e,isLoading:t=!1,size:s="md",variant:a="default",className:n,disabled:i,onClick:o,...c}){const l={sm:"h-8 w-8",md:"h-10 w-10",lg:"h-12 w-12"},h={sm:"h-4 w-4",md:"h-5 w-5",lg:"h-6 w-6"},u={default:"bg-primary text-primary-foreground hover:bg-primary focus:ring-primary",ghost:"bg-transparent text-foreground hover:bg-muted focus:ring-primary",outline:"border border-border bg-card text-foreground hover:bg-muted focus:ring-muted"},d=m=>{i||t||o?.(m)};return r.jsx("button",{type:"button",className:y("rounded-full flex items-center justify-center transition-colors focus:outline-none focus:ring-2 focus:ring-offset-2",l[s],u[a],(i||t)&&"opacity-50 cursor-not-allowed",n),disabled:i||t,onClick:d,"aria-label":e?"Mettre en pause":"Lire","aria-busy":t,...c,children:t?r.jsxs(r.Fragment,{children:[r.jsx(ye,{className:y(h[s],"animate-spin"),"aria-hidden":"true"}),r.jsx("span",{className:"sr-only",children:"Chargement..."})]}):e?r.jsxs(r.Fragment,{children:[r.jsx(Rr,{className:h[s],"aria-hidden":"true"}),r.jsx("span",{className:"sr-only",children:"Mettre en pause"})]}):r.jsxs(r.Fragment,{children:[r.jsx(Ar,{className:y(h[s],"ml-0.5"),"aria-hidden":"true"}),r.jsx("span",{className:"sr-only",children:"Lire"})]})})}function gr({onNext:e,onPrevious:t,canGoNext:s,canGoPrevious:a,size:n="md",variant:i="ghost",className:o,disabled:c=!1}){const l={sm:"h-8 w-8",md:"h-10 w-10",lg:"h-12 w-12"},h={sm:"h-4 w-4",md:"h-5 w-5",lg:"h-6 w-6"},u={default:"bg-primary text-primary-foreground hover:bg-primary focus:ring-primary",ghost:"bg-transparent text-foreground hover:bg-muted focus:ring-primary",outline:"border border-border bg-card text-foreground hover:bg-muted focus:ring-muted"},d=c||!a,m=c||!s;return r.jsxs("div",{className:y("flex items-center gap-2",o),children:[r.jsxs("button",{type:"button",onClick:t,disabled:d,className:y("rounded-full flex items-center justify-center transition-colors focus:outline-none focus:ring-2 focus:ring-offset-2",l[n],u[i],d&&"opacity-50 cursor-not-allowed"),"aria-label":"Piste précédente","aria-disabled":d,children:[r.jsx(Cr,{className:h[n],"aria-hidden":"true"}),r.jsx("span",{className:"sr-only",children:"Piste précédente"})]}),r.jsxs("button",{type:"button",onClick:e,disabled:m,className:y("rounded-full flex items-center justify-center transition-colors focus:outline-none focus:ring-2 focus:ring-offset-2",l[n],u[i],m&&"opacity-50 cursor-not-allowed"),"aria-label":"Piste suivante","aria-disabled":m,children:[r.jsx(Pr,{className:h[n],"aria-hidden":"true"}),r.jsx("span",{className:"sr-only",children:"Piste suivante"})]})]})}function lo({repeat:e,shuffle:t,onRepeatChange:s,onShuffleToggle:a,className:n,disabled:i=!1,size:o="md",variant:c="ghost"}){const l={sm:"h-8 w-8",md:"h-10 w-10",lg:"h-12 w-12"},h={sm:"h-4 w-4",md:"h-5 w-5",lg:"h-6 w-6"},u={default:"bg-primary text-primary-foreground hover:bg-primary focus:ring-primary",ghost:"bg-transparent text-foreground hover:bg-muted focus:ring-muted",outline:"border border-border bg-card text-foreground hover:bg-muted focus:ring-muted"},d=()=>{i||s(e==="off"?"track":e==="track"?"playlist":"off")},m=()=>{switch(e){case"track":return"Répéter la piste";case"playlist":return"Répéter la playlist";default:return"Répéter désactivé"}},v=()=>{switch(e){case"track":return"Répéter la piste (actif)";case"playlist":return"Répéter la playlist (actif)";default:return"Répéter désactivé"}};return r.jsxs("div",{className:y("flex items-center gap-2",n),children:[r.jsx(ce,{content:m(),disabled:i,children:r.jsxs("button",{type:"button",onClick:d,disabled:i,className:y("rounded-full flex items-center justify-center transition-colors focus:outline-none focus:ring-2 focus:ring-offset-2 relative",l[o],u[c],e!=="off"&&"bg-primary text-primary-foreground hover:bg-primary",i&&"opacity-50 cursor-not-allowed"),"aria-label":v(),"aria-pressed":e!=="off","aria-disabled":i,children:[r.jsx(Ir,{className:y(h[o],e==="track"&&"fill-current"),"aria-hidden":"true"}),e==="playlist"&&r.jsx("span",{className:"absolute bottom-0 right-0 text-[8px] font-bold leading-none bg-primary rounded-full w-3 h-3 flex items-center justify-center","aria-hidden":"true",children:"1"}),r.jsx("span",{className:"sr-only",children:m()})]})}),r.jsx(ce,{content:t?"Mélanger activé":"Mélanger désactivé",disabled:i,children:r.jsxs("button",{type:"button",onClick:a,disabled:i,className:y("rounded-full flex items-center justify-center transition-colors focus:outline-none focus:ring-2 focus:ring-offset-2",l[o],u[c],t&&"bg-primary text-primary-foreground hover:bg-primary",i&&"opacity-50 cursor-not-allowed"),"aria-label":t?"Mélanger activé":"Mélanger désactivé","aria-pressed":t,"aria-disabled":i,children:[r.jsx(Tr,{className:y(h[o],t&&"fill-current"),"aria-hidden":"true"}),r.jsx("span",{className:"sr-only",children:t?"Mélanger activé":"Mélanger désactivé"})]})})]})}function co({isOpen:e,onClose:t,currentTime:s,duration:a,onSeek:n,player:i}){const{currentTrack:o}=$t(),[c,l]=f.useState(!1),[h,u]=f.useState(!0),d=f.useRef(null);if(!e||!o)return null;const m=o.lyrics,v=p=>{if(!p&&p!==0)return"0:00";const w=Math.floor(p/60),E=Math.floor(p%60);return`${w}:${E.toString().padStart(2,"0")}`};return f.useEffect(()=>{if(!h||!m?.length||!d.current)return;const p=m.findIndex((w,E)=>s>=w.time&&(E===m.length-1||s<(m[E+1]?.time??1/0)));p>=0&&d.current.children[p]?.scrollIntoView({behavior:"smooth",block:"center"})},[s,m,h]),r.jsxs("div",{className:y("fixed inset-0 z-[var(--sumi-z-popover)] bg-black/95 backdrop-blur-3xl overflow-hidden flex flex-col transition-all duration-[var(--sumi-duration-slow)]",e?"opacity-100 translate-y-0":"opacity-0 translate-y-full pointer-events-none"),children:[r.jsxs("div",{className:"absolute inset-0 overflow-hidden pointer-events-none",children:[r.jsx("div",{className:"absolute inset-0 bg-cover bg-center opacity-30 blur-[100px] scale-110 transition-all duration-1000",style:{backgroundImage:`url(${o.cover||"/placeholder.svg"})`}}),r.jsx("div",{className:"absolute inset-0 bg-gradient-to-b from-black/20 via-black/60 to-black/90"})]}),r.jsxs("div",{className:"relative z-10 flex items-center justify-between p-6",children:[r.jsx(P,{variant:"ghost",className:"text-foreground hover:bg-white/10 rounded-full",onClick:t,children:r.jsx(Sr,{className:"w-6 h-6"})}),r.jsx("span",{className:"text-xs font-bold tracking-widest uppercase text-white/50",children:"Following the Signal"}),r.jsx(P,{variant:"ghost",className:"text-foreground hover:bg-white/10 rounded-full",children:r.jsx(na,{className:"w-6 h-6"})})]}),r.jsxs("div",{className:y("flex-1 flex flex-col md:flex-row items-center justify-center gap-12 px-8 pb-12 relative z-10 max-w-7xl mx-auto w-full transition-all duration-[var(--sumi-duration-slow)]",c&&"md:gap-8"),children:[r.jsxs("div",{className:y("relative group transition-all duration-[var(--sumi-duration-slow)]",c?"w-full max-w-md md:max-w-sm aspect-square":"w-full max-w-md md:max-w-xl aspect-square"),children:[r.jsx("div",{className:"absolute inset-0 bg-gradient-to-br from-primary/20 to-secondary/20 rounded-xl blur-2xl transform group-hover:scale-105 transition-transform duration-700"}),r.jsx("img",{src:o.cover||"/placeholder.svg",alt:o.title,className:"w-full h-full object-cover rounded-xl shadow-cover-depth relative z-10 border border-white/10"})]}),r.jsxs("div",{className:"w-full max-w-xl flex flex-col justify-end space-y-8",children:[r.jsxs("div",{className:"flex items-end justify-between",children:[r.jsxs("div",{className:"space-y-2",children:[r.jsx("h2",{className:"text-4xl md:text-5xl font-heading font-bold text-foreground leading-tight",children:o.title}),r.jsx("p",{className:"text-xl md:text-2xl text-muted-foreground font-medium",children:o.artist})]}),r.jsx(P,{size:"icon",variant:"ghost",className:"text-muted-foreground hover:text-destructive hover:bg-destructive/10 rounded-full h-12 w-12 transition-all",children:r.jsx(Lt,{className:"w-6 h-6"})})]}),r.jsxs("div",{className:"space-y-4 group/progress",children:[r.jsx(Bt,{value:[s],onValueChange:p=>n(p[0]??0),max:a||100,step:.1,className:"py-2"}),r.jsxs("div",{className:"flex items-center justify-between text-xs font-mono text-muted-foreground",children:[r.jsx("span",{children:v(s)}),r.jsx("span",{children:v(a)})]})]}),r.jsxs("div",{className:"flex items-center justify-between",children:[r.jsx("div",{className:"flex items-center gap-4",children:r.jsx(lo,{repeat:i.repeat,shuffle:i.shuffle,onRepeatChange:i.setRepeat,onShuffleToggle:i.toggleShuffle,size:"lg"})}),r.jsxs("div",{className:"flex items-center gap-6 md:gap-8",children:[r.jsx(gr,{onNext:i.next,onPrevious:i.previous,canGoNext:!0,canGoPrevious:!0,size:"lg"}),r.jsx(oo,{isPlaying:i.isPlaying,onClick:()=>i.isPlaying?i.pause():i.resume(),size:"lg",className:"scale-125"}),r.jsx(gr,{onNext:i.next,onPrevious:i.previous,canGoNext:!0,canGoPrevious:!0,size:"lg",className:"hidden"})]}),r.jsxs("div",{className:"flex items-center gap-4",children:[r.jsx(P,{size:"icon",variant:"ghost",className:"text-muted-foreground hover:text-foreground",children:r.jsx(ia,{className:"w-5 h-5"})}),r.jsx(ce,{content:c?"Hide lyrics":"Show lyrics",children:r.jsx(P,{size:"icon",variant:"ghost",className:y("transition-colors",c?"text-primary":"text-muted-foreground hover:text-foreground"),onClick:()=>l(!c),children:r.jsx(Wt,{className:"w-5 h-5"})})})]})]})]}),c&&r.jsxs("div",{className:y("group/lyrics w-full md:flex-1 h-layout-lyrics-sm md:h-layout-lyrics flex flex-col relative rounded-xl overflow-hidden border border-white/10 bg-black/30 backdrop-blur-md","animate-in slide-in-from-right-4 duration-300"),onMouseEnter:()=>u(!1),onMouseLeave:()=>u(!0),children:[r.jsx("div",{className:"absolute top-2 right-2 z-10 opacity-0 group-hover/lyrics:opacity-100 transition-opacity",children:r.jsx(ce,{content:"Auto-scroll",children:r.jsx(P,{variant:"ghost",size:"icon",className:h?"bg-primary/20 text-primary":"text-muted-foreground",onClick:()=>u(!h),children:r.jsx(oa,{className:"w-4 h-4"})})})}),m?.length?r.jsx("div",{ref:d,className:"flex-1 overflow-y-auto custom-scrollbar px-6 py-8 space-y-6 text-center",children:m.map((p,w)=>{const E=s>=p.time&&(w===m.length-1||s<(m[w+1]?.time??1/0));return r.jsx("p",{className:y("text-xl md:text-2xl font-bold transition-all duration-[var(--sumi-duration-slow)] cursor-pointer hover:text-foreground",E?"text-foreground scale-105":"text-white/20"),onClick:()=>n(p.time),children:p.text},w)})}):r.jsxs("div",{className:"flex-1 flex flex-col items-center justify-center text-muted-foreground",children:[r.jsx(Wt,{className:"w-12 h-12 mb-3 opacity-50"}),r.jsx("p",{children:"No lyrics available for this track."})]})]})]})]})}const vr=24;function uo({levels:e,playing:t,className:s}){const a=e.length===vr?e:Array(vr).fill(0);return r.jsx("div",{className:y("flex items-center gap-0.5 h-8","opacity-80",s),role:"img","aria-label":t?"Audio waveform":"Paused",children:a.map((n,i)=>r.jsx("div",{className:y("w-0.5 rounded-full min-h-[4px] flex-shrink-0","bg-gradient-to-t from-[var(--chart-2)] to-[var(--chart-1)]","transition-all duration-75 ease-out"),style:{height:t?`${Math.max(4,4+n*28)}px`:"4px"}},i))})}function mo({children:e,isHovered:t,className:s}){return r.jsxs("div",{className:y("relative w-full rounded-xl overflow-hidden","backdrop-blur-[16px]","bg-[var(--sumi-glass-bg)]","border border-[var(--sumi-glass-border)]","transition-all duration-[var(--sumi-duration-normal)] ease-[var(--sumi-ease-out)]","shadow-[var(--sumi-shadow-xl)] player-bar-entrance",t&&"shadow-[var(--sumi-shadow-xl)] border-[var(--sumi-border-accent)]",!t&&"shadow-[var(--sumi-shadow-lg)]",s),children:[e,r.jsx("div",{className:y("absolute inset-0 pointer-events-none -z-10","bg-[var(--sumi-accent-subtle)]","opacity-0 transition-opacity duration-[var(--sumi-duration-slow)] ease-[var(--sumi-ease-out)]",t&&"opacity-100")})]})}function fo({currentTime:e,duration:t,onSeek:s,className:a}){const n=f.useRef(null),i=t>0?Math.max(0,Math.min(1,e/t)):0,o=c=>{if(!n.current)return;const l=n.current.getBoundingClientRect(),h=c.clientX-l.left;s(Math.max(0,Math.min(1,h/l.width)))};return r.jsx("div",{ref:n,role:"slider","aria-label":"Progression","aria-valuemin":0,"aria-valuemax":t,"aria-valuenow":e,tabIndex:0,className:y("absolute bottom-0 left-0 right-0 h-1.5 z-20 cursor-pointer","bg-[var(--sumi-border-default)] hover:bg-[var(--sumi-border-strong)] transition-colors duration-[var(--sumi-duration-fast)]",a),onClick:o,children:r.jsx("div",{className:"h-full rounded-r bg-[var(--sumi-accent)] transition-[transform] duration-75 ease-out will-change-transform",style:{transform:`scaleX(${i})`,transformOrigin:"left"}})})}const kt="h-8 w-8 sm:h-9 sm:w-9 rounded-full transition-transform duration-150 active:scale-95";function ho({volume:e,muted:t,onVolumeChange:s,onToggleMute:a,showQueue:n,onToggleQueue:i,waveformLevels:o,isPlaying:c}){return r.jsxs("section",{className:"flex items-center justify-end gap-1 sm:gap-2 flex-shrink-0 min-w-32 shrink-0","aria-label":"Volume and queue",children:[r.jsx("div",{className:"hidden xl:block shrink-0",children:r.jsx(uo,{levels:o,playing:c})}),r.jsxs("div",{className:"flex items-center gap-0.5 group/volume flex-shrink-0",children:[r.jsx(P,{variant:"ghost",size:"icon",className:y(kt,"text-muted-foreground hover:text-foreground"),onClick:a,children:t||e===0?r.jsx(la,{className:"w-4 h-4"}):r.jsx(ca,{className:"w-4 h-4"})}),r.jsx("div",{className:"w-0 group-hover/volume:w-14 overflow-hidden transition-all duration-150 ease-out",children:r.jsx(Bt,{value:[t?0:e],onValueChange:l=>s(l[0]??0),max:100,className:"w-14 min-w-0"})})]}),r.jsx("div",{className:"w-px h-5 bg-[var(--sumi-border-faint)] flex-shrink-0"}),r.jsx(P,{variant:"ghost",size:"icon",className:y(kt,n?"text-primary bg-primary/10":"text-muted-foreground hover:text-foreground"),onClick:i,children:r.jsx(It,{className:"w-4 h-4"})}),r.jsx(P,{variant:"ghost",size:"icon",className:y(kt,"text-muted-foreground hover:text-[var(--chart-2)] hover:bg-[var(--chart-2)]/10"),children:r.jsx(Lt,{className:"w-4 h-4"})})]})}function po({title:e,artist:t,cover:s,isIdle:a,isPlaying:n,onExpand:i}){return r.jsxs("section",{className:"flex items-center gap-2 min-w-24 flex-1 overflow-hidden","aria-label":"Track info",children:[r.jsxs("div",{className:y("relative w-10 h-10 sm:w-11 sm:h-11 rounded-lg overflow-hidden flex-shrink-0","transition-transform duration-300 ease-out","hover:scale-105 active:scale-95",!a&&"cursor-pointer group/art"),onClick:a?void 0:i,children:[s?r.jsx("img",{src:s,alt:"",className:y("w-full h-full object-cover transition-transform duration-700",n&&"scale-110")}):r.jsx("div",{className:"w-full h-full bg-[var(--sumi-border-faint)] flex items-center justify-center",children:r.jsx(Gt,{className:y("w-5 h-5 text-muted-foreground",a&&"opacity-20")})}),!a&&r.jsx("div",{className:"absolute inset-0 bg-black/50 flex items-center justify-center opacity-0 group-hover/art:opacity-100 transition-opacity duration-150",children:r.jsx(Gt,{className:"w-5 h-5 text-foreground"})})]}),r.jsxs("div",{className:"flex flex-col justify-center min-w-0 overflow-hidden cursor-pointer",onClick:a?void 0:i,children:[r.jsx("h3",{className:y("font-heading font-bold text-xs sm:text-sm text-foreground truncate","transition-colors duration-150",!a&&"hover:text-primary"),children:e}),r.jsx("p",{className:y("text-xs text-muted-foreground truncate","transition-colors duration-150",!a&&"hover:text-foreground"),children:t})]})]})}const go={title:"System Online",artist:"Select a track to play",cover:""};function vo(){const e=f.useRef(null),[t,s]=f.useState(null),a=f.useCallback(E=>{e.current=E,s(E)},[]),{sidebarOpen:n}=ue(),i=Yi(e);eo(i);const[o,c]=f.useState(!1),[l,h]=f.useState(!1),[u,d]=f.useState(!1),m=ro(t,i.isPlaying),v=i.currentTrack,p=v||go,w=!v;return r.jsxs(r.Fragment,{children:[r.jsx("audio",{ref:a}),r.jsx(co,{isOpen:l,onClose:()=>h(!1),currentTime:i.currentTime,duration:i.duration,onSeek:i.seek,player:i}),r.jsx(io,{isOpen:u,onClose:()=>d(!1),currentTrackId:v?.id,onPlay:E=>i.play(E)}),xr.createPortal(r.jsx("div",{"data-testid":"global-player",role:"region","aria-label":"Global player",className:y("fixed bottom-6 left-4 right-4 z-player transition-all duration-[var(--sumi-duration-slow)] ease-[var(--sumi-ease-out)]","lg:right-4 w-player-bar",n?"lg:left-main-expanded lg:w-player-bar-expanded":"lg:left-main-collapsed lg:w-player-bar-collapsed",l&&"translate-y-full opacity-0 pointer-events-none"),onMouseEnter:()=>c(!0),onMouseLeave:()=>c(!1),children:r.jsxs(mo,{isHovered:o,children:[r.jsxs("div",{className:"flex items-center justify-between gap-2 sm:gap-3 h-14 sm:h-16 px-3 sm:px-4 relative z-10 min-w-0 flex-nowrap",children:[r.jsx(po,{title:p.title,artist:p.artist||"Unknown Artist",cover:p.cover,isIdle:w,isPlaying:i.isPlaying,onExpand:()=>!w&&h(!0)}),r.jsxs("section",{className:"flex flex-col items-center justify-center gap-0.5 flex-shrink-0","aria-label":"Playback controls",children:[r.jsx(so,{compact:!0,isPlaying:i.isPlaying,onPlayPause:()=>{i.isPlaying?i.pause():w||i.resume()},onNext:i.next,onPrevious:i.previous,onShuffle:i.toggleShuffle,onRepeat:()=>{const E=["off","track","playlist"],N=i.repeat??"off",S=E[(E.indexOf(N)+1)%E.length]??"off";i.setRepeat(S)},shuffle:i.shuffle,repeat:i.repeat}),r.jsxs("div",{className:y("flex items-center gap-1.5 text-xs font-mono text-muted-foreground whitespace-nowrap",w?"opacity-50":"opacity-90"),children:[r.jsx("span",{children:pr(i.currentTime)}),r.jsx("span",{className:"opacity-30",children:"/"}),r.jsx("span",{children:pr(i.duration)})]})]}),r.jsx(ho,{volume:i.volume,muted:i.muted,onVolumeChange:i.setVolume,onToggleMute:i.toggleMute,showQueue:u,onToggleQueue:()=>d(!u),waveformLevels:m,isPlaying:i.isPlaying})]}),!w&&r.jsx(fo,{currentTime:i.currentTime,duration:i.duration,onSeek:E=>i.seek(E*i.duration)})]})}),document.body)]})}function yo({children:e}){const{sidebarOpen:t}=ue();return r.jsxs("div",{className:"flex h-screen w-full overflow-hidden relative bg-background",children:[r.jsx(Hr,{}),r.jsx(Gi,{}),r.jsxs("div",{className:y("flex-1 flex flex-col h-full min-w-0 relative z-[var(--sumi-z-raised)] transition-all duration-[var(--sumi-duration-slow)] ease-[var(--sumi-ease-in-out)]",t?"lg:ml-main-expanded":"lg:ml-main-collapsed","max-lg:ml-0"),children:[r.jsx(Ui,{}),r.jsx("main",{id:"main-content",className:"flex-1 overflow-y-auto overflow-x-hidden pt-main pb-main px-4 md:px-8 custom-scrollbar","data-scroll-container":"main",children:r.jsx("div",{className:"max-w-layout-content mx-auto w-full",children:e})}),r.jsx("div",{className:"absolute bottom-0 left-0 right-0 z-50 w-full min-w-0","aria-label":"Player bar container",children:r.jsx(vo,{})})]})]})}function xo({children:e}){return r.jsx(yo,{children:e})}function Re(e){return r.jsx(Ei,{children:r.jsx(Se,{children:e})})}function Q(e){return r.jsx(Fn,{children:r.jsx(xo,{children:r.jsx(Se,{children:e})})})}function bo(){return[{path:"/login",element:Re(r.jsx(Zn,{}))},{path:"/register",element:Re(r.jsx(ei,{}))},{path:"/forgot-password",element:Re(r.jsx(ti,{}))},{path:"/verify-email",element:Re(r.jsx(ri,{}))},{path:"/reset-password",element:Re(r.jsx(si,{}))}]}function wo(){return[{path:"/design-system",element:r.jsx(Se,{children:r.jsx(hi,{})})},{path:"/u/:username",element:r.jsx(Se,{children:r.jsx(oi,{})})}]}function ko(){return[{path:"/dashboard",element:Q(r.jsx(Wn,{}))},{path:"/marketplace",element:Q(r.jsx(vi,{}))},{path:"/sell",element:Q(r.jsx(xi,{onCreateProduct:()=>{}}))},{path:"/wishlist",element:Q(r.jsx(bi,{}))},{path:"/purchases",element:Q(r.jsx(wi,{}))},{path:"/chat",element:Q(r.jsx(Gn,{}))},{path:"/library",element:Q(r.jsx(Xn,{}))},{path:"/profile",element:Q(r.jsx(Yn,{}))},{path:"/settings",element:Q(r.jsx(Jn,{}))},{path:"/settings/sessions",element:Q(r.jsx(ai,{}))},{path:"/admin/roles",element:Q(r.jsx(li,{}))},{path:"/tracks/:id",element:Q(r.jsx(ci,{}))},{path:"/playlists/*",element:Q(r.jsx(ui,{}))},{path:"/search",element:Q(r.jsx(yi,{}))},{path:"/notifications",element:Q(r.jsx(gi,{}))},{path:"/analytics",element:Q(r.jsx(mi,{onNavigateTrack:()=>{}}))},{path:"/webhooks",element:Q(r.jsx(fi,{}))},{path:"/admin",element:Q(r.jsx(di,{}))},{path:"/social",element:Q(r.jsx(pi,{onViewProfile:()=>{}}))},{path:"/gear",element:Q(r.jsx(Ce,{feature:"Gear"}))},{path:"/live",element:Q(r.jsx(Ce,{feature:"Live"}))},{path:"/education",element:Q(r.jsx(Ce,{feature:"Education"}))},{path:"/queue",element:Q(r.jsx(Ce,{feature:"Queue"}))},{path:"/developer",element:Q(r.jsx(Ce,{feature:"Developer"}))}]}function Eo(){return[{path:"/404",element:r.jsx(Se,{children:r.jsx(ni,{})})},{path:"/500",element:r.jsx(Se,{children:r.jsx(ii,{})})}]}function So(){const e=bo(),t=wo(),s=ko(),a=Eo();return r.jsxs(fs,{children:[e.map(({path:n,element:i})=>r.jsx(xe,{path:n,element:i},n)),t.map(({path:n,element:i})=>r.jsx(xe,{path:n,element:i},n)),s.map(({path:n,element:i})=>r.jsx(xe,{path:n,element:i},n)),a.map(({path:n,element:i})=>r.jsx(xe,{path:n,element:i},n)),r.jsx(xe,{path:"/",element:r.jsx(et,{to:"/dashboard",replace:!0})}),r.jsx(xe,{path:"*",element:r.jsx(et,{to:"/404",replace:!0})})]})}function jo(e={}){const{enabled:t=!0,preventDefault:s=!0,onHelpOpen:a}=e,n=at(),{setSidebarOpen:i,sidebarOpen:o}=ue(),c=f.useCallback(l=>{if(!t)return;const h=l.target;if(h&&(h.tagName==="INPUT"||h.tagName==="TEXTAREA"||h.isContentEditable===!0||h.getAttribute("role")==="textbox")){if(l.key==="k"&&(l.ctrlKey||l.metaKey)){s&&l.preventDefault();const u=document.querySelector('input[type="search"], input[placeholder*="search" i], input[placeholder*="rechercher" i]');u?(u.focus(),u.select()):n("/search");return}return}if((l.ctrlKey||l.metaKey)&&l.key==="k"){s&&l.preventDefault();const u=document.querySelector('input[type="search"], input[placeholder*="search" i], input[placeholder*="rechercher" i]');u?(u.focus(),u.select()):n("/search");return}if((l.ctrlKey||l.metaKey)&&l.key==="n"){s&&l.preventDefault(),n("/chat");return}if((l.ctrlKey||l.metaKey)&&l.key==="b"){s&&l.preventDefault(),i(!o);return}if(l.key==="Escape"){document.querySelectorAll('[role="menu"][aria-expanded="true"]').forEach(d=>{const m=d.previousElementSibling;m&&m.click()});return}if(l.key==="?"&&!l.ctrlKey&&!l.metaKey){s&&l.preventDefault(),a&&a();return}},[t,s,n,i,o,a]);f.useEffect(()=>{if(t)return window.addEventListener("keydown",c),()=>{window.removeEventListener("keydown",c)}},[t,c])}const No=[{title:"General",shortcuts:[{keys:["Ctrl","K"],description:"Open search"},{keys:["?"],description:"Show keyboard shortcuts"},{keys:["Esc"],description:"Close dialog / panel"}]},{title:"Playback",shortcuts:[{keys:["Space"],description:"Play / Pause"},{keys:["N"],description:"Next track"},{keys:["P"],description:"Previous track"},{keys:["M"],description:"Toggle mute"},{keys:["↑"],description:"Volume up"},{keys:["↓"],description:"Volume down"}]},{title:"Navigation",shortcuts:[{keys:["G","H"],description:"Go to Home"},{keys:["G","L"],description:"Go to Library"},{keys:["G","S"],description:"Go to Settings"}]}];function _o({isOpen:e,onClose:t}){return f.useEffect(()=>{if(!e)return;const s=a=>{(a.key==="Escape"||a.key==="?")&&(a.preventDefault(),t())};return window.addEventListener("keydown",s),()=>window.removeEventListener("keydown",s)},[e,t]),r.jsx(Dt,{children:e&&r.jsxs(r.Fragment,{children:[r.jsx(we.div,{initial:{opacity:0},animate:{opacity:1},exit:{opacity:0},transition:{duration:.15},onClick:t,className:"fixed inset-0 z-50 bg-black/60 backdrop-blur-sm"}),r.jsxs(we.div,{initial:{opacity:0,scale:.95,y:20},animate:{opacity:1,scale:1,y:0},exit:{opacity:0,scale:.95,y:20},transition:{duration:.2,ease:[.16,1,.3,1]},className:"fixed inset-x-4 top-[10%] bottom-[10%] z-50 mx-auto max-w-2xl overflow-y-auto rounded-2xl border border-border bg-background/95 backdrop-blur-md p-6 shadow-2xl sm:inset-x-auto",role:"dialog","aria-modal":"true","aria-label":"Keyboard Shortcuts",children:[r.jsxs("div",{className:"flex items-center justify-between mb-6",children:[r.jsx("h2",{className:"text-xl font-semibold text-foreground",children:"Keyboard Shortcuts"}),r.jsx("button",{onClick:t,className:"p-2 rounded-lg hover:bg-muted transition-colors","aria-label":"Close",children:r.jsx(he,{className:"h-5 w-5"})})]}),r.jsx("div",{className:"space-y-6",children:No.map(s=>r.jsxs("div",{children:[r.jsx("h3",{className:"text-xs font-semibold uppercase tracking-wider text-muted-foreground mb-3",children:s.title}),r.jsx("div",{className:"space-y-1",children:s.shortcuts.map(a=>r.jsxs("div",{className:"flex items-center justify-between py-2 px-3 rounded-lg hover:bg-muted/50 transition-colors",children:[r.jsx("span",{className:"text-sm text-foreground",children:a.description}),r.jsx("div",{className:"flex items-center gap-1",children:a.keys.map((n,i)=>r.jsxs("span",{children:[r.jsx("kbd",{className:"inline-flex h-6 min-w-6 items-center justify-center rounded-md border border-border bg-muted px-1.5 text-[11px] font-medium text-muted-foreground",children:n}),i<a.keys.length-1&&r.jsx("span",{className:"mx-0.5 text-xs text-muted-foreground",children:"+"})]},i))})]},a.description))})]},s.title))}),r.jsx("div",{className:"mt-6 pt-4 border-t border-border",children:r.jsxs("p",{className:"text-xs text-muted-foreground text-center",children:["Press"," ",r.jsx("kbd",{className:"inline-flex h-5 min-w-5 items-center justify-center rounded border border-border bg-muted px-1 text-[10px] font-medium",children:"?"})," ","to toggle this panel"]})})]})]})})}async function To(e={}){const{hydrateAuth:t=!0,hydrateLibrary:s=!1,hydrateChat:a=!1,requireAuth:n=!0}=e,i={success:!0,hydrated:[],errors:[]};try{if(n){const{isAuthenticated:o}=ee.getState();if(!o)return g.debug("[StateHydration] User not authenticated, skipping hydration"),i}if(t)try{const{isAuthenticated:o,isLoading:c}=ee.getState(),l=te.hasTokens();o&&l&&!c||(await Co(),i.hydrated.push("auth"),g.debug("[StateHydration] Auth state hydrated"))}catch(o){const c=o instanceof Error?o:new Error(String(o));i.errors.push({store:"auth",error:c}),i.success=!1,g.error("[StateHydration] Failed to hydrate auth state",{error:c.message})}if(s)try{await Ro(),i.hydrated.push("library"),g.debug("[StateHydration] Library state hydrated")}catch(o){const c=o instanceof Error?o:new Error(String(o));i.errors.push({store:"library",error:c}),i.success=!1,g.error("[StateHydration] Failed to hydrate library state",{error:c.message})}if(a)try{await Ao(),i.hydrated.push("chat"),g.debug("[StateHydration] Chat state hydrated")}catch(o){const c=o instanceof Error?o:new Error(String(o));i.errors.push({store:"chat",error:c}),i.success=!1,g.error("[StateHydration] Failed to hydrate chat state",{error:c.message})}}catch(o){const c=o instanceof Error?o:new Error(String(o));g.error("[StateHydration] Fatal error during hydration",{error:c.message}),i.success=!1}return i}async function Co(){const{refreshUser:e,isAuthenticated:t}=ee.getState();await e()}async function Ro(){g.debug("[StateHydration] Library state hydration skipped - using React Query")}async function Ao(){g.debug("[StateHydration] Chat state hydration skipped - using React Query")}function Po(e={}){const[t,s]=f.useState(!0),[a,n]=f.useState(null);return f.useEffect(()=>{let i=!0;return To(e).then(o=>{i&&(n(o),s(!1))}).catch(o=>{i&&(g.error("[StateHydration] Hook error:",o),n({success:!1,hydrated:[],errors:[{store:"unknown",error:o instanceof Error?o:new Error(String(o))}]}),s(!1))}),()=>{i=!1}},[]),{isHydrating:t,hydrationResult:a}}function Io(){const e=At();f.useEffect(()=>{const t=s=>{const{queryKeys:a,resourceType:n,resourceId:i}=s.detail;if(a&&a.length>0)for(const o of a)e.invalidateQueries({queryKey:o});if(n){const c={tracks:[["tracks"],["track"],["library"]],playlists:[["playlists"],["playlist"]],users:[["users"],["user"],["auth"]],conversations:[["conversations"],["conversation"],["chat"]],roles:[["roles"],["role"]],library:[["library"],["tracks"],["favorites"]],auth:[["auth"],["user"]],ui:[],all:[]}[n]||[];for(const l of c)e.invalidateQueries({queryKey:i?[...l,i]:l})}};return window.addEventListener("veza:invalidate-queries",t),()=>{window.removeEventListener("veza:invalidate-queries",t)}},[e])}function Lo(e){if(typeof window>"u"||!window.BroadcastChannel)return g.warn("[ReactQuerySync] BroadcastChannel not supported in this environment"),null;try{return new BroadcastChannel(e)}catch(t){return g.warn("[ReactQuerySync] Failed to create BroadcastChannel",{error:t instanceof Error?t.message:String(t),stack:t instanceof Error?t.stack:void 0,channelName:e}),null}}function Do(){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 yr(){return`${Date.now()}-${Math.random().toString(36).substring(2,9)}`}function qo(e,t={}){const s=t.channelName||"veza-react-query-sync",a=t.enabled!==!1,n=t.shouldSync||(()=>!0);if(!a)return()=>{};const i=Lo(s);if(!i)return g.warn("[ReactQuerySync] BroadcastChannel not available, sync disabled"),()=>{};const o=Do(),c=new Set;let l=!1;function h(v){if(l||!n(v,"query-invalidate"))return;const p={type:"query-invalidate",queryKey:v,timestamp:Date.now(),messageId:yr(),tabId:o};try{i&&(i.postMessage(p),g.debug("[ReactQuerySync] Broadcasted query invalidation",{queryKey:v,messageId:p.messageId}))}catch(w){g.error("[ReactQuerySync] Failed to broadcast invalidation",{error:w instanceof Error?w.message:String(w),queryKey:v})}}function u(v){const p=v.data;if(!(!p||typeof p!="object"||!p.type||!Array.isArray(p.queryKey)||typeof p.timestamp!="number"||typeof p.messageId!="string")&&!(p.type!=="query-invalidate"&&p.type!=="query-set-data"&&p.type!=="mutation-success")&&p.tabId!==o&&!c.has(p.messageId)&&(c.add(p.messageId),c.size>1e3&&Array.from(c).slice(0,500).forEach(E=>c.delete(E)),!!n(p.queryKey,p.type))){l=!0;try{switch(p.type){case"query-invalidate":e.invalidateQueries({queryKey:p.queryKey}),g.debug("[ReactQuerySync] Invalidated query from other tab",{queryKey:p.queryKey,messageId:p.messageId});break;case"query-set-data":p.data!==void 0&&(e.setQueryData(p.queryKey,p.data),g.debug("[ReactQuerySync] Updated query data from other tab",{queryKey:p.queryKey,messageId:p.messageId}));break;case"mutation-success":e.invalidateQueries({queryKey:p.queryKey}),g.debug("[ReactQuerySync] Invalidated queries after mutation from other tab",{queryKey:p.queryKey,messageId:p.messageId});break;default:g.warn("[ReactQuerySync] Unknown message type",{type:p.type,messageId:p.messageId})}}catch(w){g.error("[ReactQuerySync] Error processing sync message",{error:w instanceof Error?w.message:String(w),messageId:p.messageId,queryKey:p.queryKey})}finally{setTimeout(()=>{l=!1},50)}}}i.addEventListener("message",u);const d=e.getMutationCache().subscribe(v=>{if(!(!v||!i)&&v.type==="updated"&&v.mutation.state.status==="success"){const p=v.mutation.options.mutationKey;if(p){const w={type:"mutation-success",queryKey:p,timestamp:Date.now(),messageId:yr(),tabId:o};try{i.postMessage(w),g.debug("[ReactQuerySync] Broadcasted mutation success",{queryKey:p,messageId:w.messageId})}catch(E){g.error("[ReactQuerySync] Failed to broadcast mutation",{error:E instanceof Error?E.message:String(E),queryKey:p})}}}}),m=e.getQueryCache().subscribe(v=>{if(v?.type==="removed"||v?.type==="updated"&&v.query?.state.isInvalidated){const p=v.query.queryKey;h(p)}});return g.debug("[ReactQuerySync] React Query cache synchronization enabled",{channelName:s,tabId:o}),()=>{i.removeEventListener("message",u),d(),m(),i.close(),g.debug("[ReactQuerySync] React Query cache synchronization disabled")}}const Ye=[{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())}],Mo={mode:"waveform",color:"#7c9dd6",sensitivity:50};function Oo(){const[e,t]=f.useState(null),[s,a]=f.useState([]),[n,i]=f.useState([]),[o,c]=f.useState(!1),[l,h]=f.useState(0),[u,d]=f.useState(0),[m,v]=f.useState(80),[p,w]=f.useState(!1),[E,N]=f.useState(!1),[S,L]=f.useState("off"),[I,b]=f.useState(1),[_,G]=f.useState(!0),[k,j]=f.useState(Mo),[C,O]=f.useState(!0),V=f.useRef(null);f.useEffect(()=>{t(Ye[0]??null),a(Ye.slice(1))},[]);const J=()=>{if(s.length>0){const A=E?s[Math.floor(Math.random()*s.length)]:s[0];if(!A)return;i(M=>e?[...M,e]:M),a(S!=="all"?M=>M.filter(X=>X.id!==A.id):M=>[...M.filter(X=>X.id!==A.id),A]),t(A),d(0),c(!0)}else if(C){const A=Math.floor(Math.random()*Ye.length),M=Ye[A];if(!M)return;i(X=>e?[...X,e]:X),t({...M,id:`auto-${Date.now()}`,title:`Autoplay: ${M.title}`}),d(0),c(!0)}else c(!1),d(0)};f.useEffect(()=>(o&&e?V.current=window.setInterval(()=>{d(A=>{if(e?.durationSec&&A>=e.durationSec){if(S==="one")return 0;if(s.length>0||C)J();else return c(!1),A;return 0}return A+1*I})},1e3/I):V.current&&clearInterval(V.current),()=>{V.current&&clearInterval(V.current)}),[o,e,S,I,s.length,C]),f.useEffect(()=>{e?.durationSec&&h(u/e.durationSec*100)},[u,e]);const H=(A,M)=>{if(e&&e.id!==A.id&&i(X=>[...X,e]),t(A),M){const X=M.findIndex(Qe=>Qe.id===A.id);X!==-1&&a(M.slice(X+1))}c(!0),d(0)},Y=()=>c(!o),re=()=>{if(u>3)d(0);else if(n.length>0){const A=n[n.length-1];if(!A)return;a(M=>e?[e,...M]:M),i(M=>M.slice(0,-1)),t(A),d(0),c(!0)}},Ne=A=>{if(e?.durationSec){const M=A/100*e.durationSec;d(M),h(A)}},ft=A=>v(A),ht=()=>w(A=>!A),pt=()=>N(!E),$e=()=>{const A=["off","all","one"],M=A[(A.indexOf(S)+1)%A.length]??"off";L(M)},_e=()=>G(!_),U=()=>O(!C),le=A=>a(M=>[...M,A]),gt=A=>a(M=>[A,...M]),ls=A=>a(M=>M.filter(X=>X.id!==A)),cs=()=>a([]),us=(A,M)=>{const X=Array.from(s),[Qe]=X.splice(A,1);Qe&&(X.splice(M,0,Qe),a(X))};return{currentTrack:e,isPlaying:o,queue:s,history:n,progress:l,currentTime:u,duration:e?.durationSec||0,volume:m,isMuted:p,shuffle:E,repeatMode:S,playbackRate:I,pitchCorrection:_,visualizerSettings:k,autoplay:C,playTrack:H,togglePlay:Y,nextTrack:J,prevTrack:re,seek:Ne,setVolume:ft,toggleMute:ht,toggleShuffle:pt,toggleRepeat:$e,setPlaybackRate:b,togglePitchCorrection:_e,setVisualizerSettings:j,toggleAutoplay:U,addToQueue:le,removeFromQueue:ls,playNext:gt,reorderQueue:us,clearQueue:cs}}const is=f.createContext(void 0),lc=()=>{const e=f.useContext(is);if(!e)throw new Error("useAudio must be used within AudioProvider");return e},zo=({children:e})=>{const t=Oo();return r.jsx(is.Provider,{value:t,children:e})};function Fo(){const{t:e}=qt(),{refreshUser:t}=ee(),{theme:s,setTheme:a,language:n,setLanguage:i}=ue(),[o,c]=f.useState(!1),[l,h]=f.useState(!1),u=At();return jo({enabled:!0,onHelpOpen:()=>c(!0)}),Po({hydrateAuth:!0,hydrateLibrary:!1,hydrateChat:!1,requireAuth:!1}),Io(),f.useEffect(()=>qo(u,{enabled:!0,channelName:"veza-react-query-sync"}),[u]),f.useEffect(()=>{if((async()=>{await new Promise(v=>setTimeout(v,100));const{isAuthenticated:m}=ee.getState();m&&Z.refreshToken().catch(v=>{const p=v instanceof Error?v.message:String(v);p.includes("HTML page instead of JSON")||g.warn("Failed to fetch CSRF token on app init",{message:p})})})(),!s||s==="system"){const m=document.documentElement;!m.classList.contains("dark")&&!m.classList.contains("light")?a("dark"):a(s)}else a(s);if(typeof window<"u"&&window.i18n){const m=window.i18n.language||n;m!==n?window.i18n.changeLanguage(n):n!==m&&i(m)}},[a,s,n,i]),f.useEffect(()=>{(async()=>{try{await t()}catch(m){g.error("[App] Auth initialization failed",{error:m instanceof Error?m.message:String(m),stack:m instanceof Error?m.stack:void 0})}finally{h(!0)}})()},[t]),f.useEffect(()=>{if(s!=="system")return;const d=window.matchMedia("(prefers-color-scheme: dark)"),m=v=>{const p=document.documentElement;v.matches?p.classList.add("dark"):p.classList.remove("dark")};return d.addEventListener?d.addEventListener("change",m):d.addListener(m),()=>{d.removeEventListener?d.removeEventListener("change",m):d.removeListener(m)}},[s]),l?r.jsx(hn,{children:r.jsx(bn,{children:r.jsxs(zo,{children:[r.jsx("a",{href:"#main-content",className:"sr-only focus:not-sr-only focus:fixed focus:top-4 focus:left-4 focus:z-[var(--sumi-z-max)] focus:bg-primary focus:text-primary-foreground focus:px-4 focus:py-2 focus:rounded-lg focus:shadow-lg",children:e("nav.skipToContent")}),r.jsx(Hr,{}),r.jsx(In,{}),r.jsx(So,{}),r.jsx(_o,{isOpen:o,onClose:()=>c(!1)})]})})}):r.jsxs("div",{className:"flex flex-col items-center justify-center min-h-screen bg-[var(--sumi-bg-void)]",children:[r.jsx("div",{className:"relative mb-8 animate-[sumi-fade-in_0.6s_ease-out]",children:r.jsxs("svg",{width:"56",height:"56",viewBox:"0 0 56 56",fill:"none",xmlns:"http://www.w3.org/2000/svg",className:"text-primary","aria-hidden":"true",children:[r.jsx("rect",{width:"56",height:"56",rx:"16",fill:"currentColor",fillOpacity:"0.15"}),r.jsx("path",{d:"M18 38V18l20 10-20 10z",fill:"currentColor",className:"animate-pulse"})]})}),r.jsx("h1",{className:"text-2xl font-heading font-bold text-foreground mb-6 animate-[sumi-fade-in_0.8s_ease-out_0.2s_both]",children:"Veza"}),r.jsx("div",{className:"w-48 h-0.5 bg-muted/30 rounded-full overflow-hidden animate-[sumi-fade-in_1s_ease-out_0.4s_both]",children:r.jsx("div",{className:"h-full bg-primary rounded-full animate-[loading-progress_1.5s_ease-in-out_infinite]"})})]})}const Vo={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"},Uo={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é"}},$o={title:"Tableau de bord",welcome:"Bienvenue, {{name}} !",goodMorning:"Bonjour",goodAfternoon:"Bon après-midi",goodEvening:"Bonsoir",subtitle:"Voici ce qui se passe avec votre musique aujourd'hui.",stats:{totalTracks:"Pistes totales",totalPlaylists:"Playlists",totalFavorites:"Favoris",totalStorage:"Stockage utilisé",tracksListened:"Pistes écoutées",messagesSent:"Messages envoyés",favorites:"Favoris",activeFriends:"Amis actifs"},fromLastMonth:"par rapport au mois dernier",viewAll:"Voir tout",recentActivity:"Activité récente",recentActivityDescription:"Vos dernières interactions sur la plateforme",recentTracks:"Pistes récentes",recentTracksDescription:"Derniers ajouts à votre bibliothèque",noTracksInLibrary:"Aucune piste dans votre bibliothèque",quickActions:"Actions rapides",quickActionsDescription:"Accès rapide aux fonctionnalités principales",uploadTrack:"Téléverser une piste",createPlaylist:"Créer une playlist",discoverMusic:"Découvrir de la musique",openChat:"Ouvrir le chat",startChat:"Démarrer un chat",newTrack:"Nouvelle piste",newChat:"Nouveau chat",library:"Bibliothèque",inviteFriends:"Inviter des amis",activity:{newTrackAdded:"Nouvelle piste ajoutée",messageFrom:"Message de @{{user}}",newFavoriteAdded:"Nouveau favori ajouté"}},Qo={title:"Bientôt disponible",description:"Cette fonctionnalité est en cours de développement et sera bientôt disponible.",notifyMe:"Me notifier",goBack:"Retour"},Bo={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"},Ko={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..."}},Ho={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"}},Wo={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..."}},Go={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..."},Xo={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"}},Yo={dashboard:"Tableau de bord",chat:"Chat",library:"Bibliothèque",profile:"Profil",settings:"Paramètres",menu:"Menu",close:"Fermer"},Jo={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é"},Zo={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"}}},el={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"},tl={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"},rl={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"},sl={title:"Recherche",placeholder:"Rechercher des pistes, playlists, utilisateurs...",results:"Résultats",noResults:"Aucun résultat trouvé",tracks:"Pistes",playlists:"Playlists",users:"Utilisateurs",all:"Tout"},al={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"},nl={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é"},il={title:"Tableau de bord administrateur",users:"Utilisateurs",systemStats:"Statistiques système",auditLogs:"Journaux d'audit",suspiciousActivity:"Activité suspecte"},ol={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"}},ll={searchPlaceholder:"Que voulez-vous écouter ?",searchAriaLabel:"Rechercher des pistes, artistes, playlists",online:"En ligne",profile:"Profil",signOut:"Déconnexion"},cl={sections:{myStudio:"Mon Studio",vezaNetwork:"Réseau Veza",commerce:"Commerce",library:"Bibliothèque",system:"Système"},items:{dashboard:"Centre de contrôle",studio:"Fichiers Cloud",tracks:"Projets",gear:"Arsenal",analytics:"Performances",social:"Communauté",marketplace:"Marketplace",live:"Sessions Live",chat:"Canaux",education:"Académie",sell:"Tableau vendeur",wishlist:"Liste de souhaits",purchases:"Achats",playlists:"Playlists",queue:"File de lecture",developer:"API Développeur",admin:"Admin"},settings:"Paramètres",logout:"Déconnexion",skipToContent:"Aller au contenu"},ul={common:Vo,auth:Uo,dashboard:$o,comingSoon:Qo,player:Bo,chat:Ko,library:Ho,profile:Wo,settings:Go,errors:Xo,navigation:Yo,validation:Jo,pwa:Zo,tracks:el,playlists:tl,notifications:rl,search:sl,analytics:al,webhooks:nl,admin:il,keyboard:ol,header:ll,nav:cl},dl={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"},ml={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"}},fl={title:"Dashboard",welcome:"Welcome, {{name}}!",goodMorning:"Good morning",goodAfternoon:"Good afternoon",goodEvening:"Good evening",subtitle:"Here's what's happening with your music today.",stats:{totalTracks:"Total Tracks",totalPlaylists:"Playlists",totalFavorites:"Favorites",totalStorage:"Storage Used",tracksListened:"Tracks Listened",messagesSent:"Messages Sent",favorites:"Favorites",activeFriends:"Active Friends"},fromLastMonth:"from last month",viewAll:"View all",recentActivity:"Recent Activity",recentActivityDescription:"Your latest interactions on the platform",recentTracks:"Recent Tracks",recentTracksDescription:"Latest additions to your library",noTracksInLibrary:"No tracks in your library",quickActions:"Quick Actions",quickActionsDescription:"Fast access to main features",uploadTrack:"Upload Track",createPlaylist:"Create Playlist",discoverMusic:"Discover Music",openChat:"Open Chat",startChat:"Start Chat",newTrack:"New Track",newChat:"New Chat",library:"Library",inviteFriends:"Invite Friends",activity:{newTrackAdded:"New track added",messageFrom:"Message from @{{user}}",newFavoriteAdded:"New favorite added"}},hl={title:"Coming Soon",description:"This feature is currently under development and will be available soon.",notifyMe:"Notify me",goBack:"Go back"},pl={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"},gl={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..."}},vl={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"}},yl={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..."}},xl={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..."},bl={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"}},wl={dashboard:"Dashboard",chat:"Chat",library:"Library",profile:"Profile",settings:"Settings",menu:"Menu",close:"Close"},kl={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"},El={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"}}},Sl={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"},jl={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"},Nl={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"},_l={title:"Search",placeholder:"Search tracks, playlists, users...",results:"Results",noResults:"No results found",tracks:"Tracks",playlists:"Playlists",users:"Users",all:"All"},Tl={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"},Cl={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"},Rl={title:"Admin Dashboard",users:"Users",systemStats:"System Statistics",auditLogs:"Audit Logs",suspiciousActivity:"Suspicious Activity"},Al={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"}},Pl={searchPlaceholder:"What do you want to play?",searchAriaLabel:"Search tracks, artists, playlists",online:"Online",profile:"Profile",signOut:"Sign Out"},Il={sections:{myStudio:"My Studio",vezaNetwork:"Veza Network",commerce:"Commerce",library:"Library",system:"System"},items:{dashboard:"Command Center",studio:"Cloud Files",tracks:"Projects",gear:"Gear Locker",analytics:"Performance",social:"Community Feed",marketplace:"Marketplace",live:"Live Sessions",chat:"Channels",education:"Academy",sell:"Seller Dashboard",wishlist:"Wishlist",purchases:"Purchases",playlists:"Playlists",queue:"Play Queue",developer:"Developer API",admin:"Admin Panel"},settings:"Settings",logout:"Logout",skipToContent:"Skip to content"},Ll={common:dl,auth:ml,dashboard:fl,comingSoon:hl,player:pl,chat:gl,library:vl,profile:yl,settings:xl,errors:bl,navigation:wl,validation:kl,pwa:El,tracks:Sl,playlists:jl,notifications:Nl,search:_l,analytics:Tl,webhooks:Cl,admin:Rl,keyboard:Al,header:Pl,nav:Il},Dl={fr:{translation:ul},en:{translation:Ll}};Lr.use(ua).use(da).init({resources:Dl,fallbackLng:"en",debug:!1,interpolation:{escapeValue:!1},detection:{order:["localStorage","navigator","htmlTag"],caches:["localStorage"]}});typeof window<"u"&&(window.i18n=Lr);function ql(){const e="production";{g.debug("[Sentry] Error tracking disabled",{reason:"DSN not configured",environment:e});return}}const Ml={theme:"system",setTheme:()=>null},Ol=f.createContext(Ml);function zl({children:e,defaultTheme:t="system",storageKey:s="vite-ui-theme"}){const[a,n]=f.useState(()=>localStorage.getItem(s)||t);f.useEffect(()=>{const o=window.document.documentElement;if(a==="system"){const c=window.matchMedia("(prefers-color-scheme: dark)").matches?"dark":"light";o.setAttribute("data-theme",c);return}o.setAttribute("data-theme",a)},[a]),f.useEffect(()=>{if(a!=="system")return;const o=window.matchMedia("(prefers-color-scheme: dark)"),c=()=>{window.document.documentElement.setAttribute("data-theme",o.matches?"dark":"light")};return o.addEventListener("change",c),()=>o.removeEventListener("change",c)},[a]);const i={theme:a,setTheme:o=>{localStorage.setItem(s,o),n(o)}};return r.jsx(Ol.Provider,{value:i,children:e})}typeof window<"u"&&(window.addEventListener("error",e=>{},!0),window.addEventListener("unhandledrejection",e=>{}));ql();const os=new ps({defaultOptions:{queries:{retry:!1,refetchOnWindowFocus:!1,staleTime:60*1e3,gcTime:300*1e3,refetchOnMount:!0,refetchOnReconnect:!0}}});ha(os);async function Fl(){ct.USE_MSW}const Vl=()=>new Promise(e=>{const t=()=>{try{if(document.readyState!=="complete"&&document.readyState!=="interactive")return!1;const s=Array.from(document.styleSheets);if(s.length===0)return!1;let a=0;for(const n of s)try{(n.cssRules!==null||n.href===null)&&a++}catch{n.href!==null&&a++}return a===s.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 s=0;const a=20,n=setInterval(()=>{s++,(t()||s>=a)&&(clearInterval(n),requestAnimationFrame(()=>{requestAnimationFrame(()=>{requestAnimationFrame(()=>{setTimeout(()=>{e()},50)})})}))},50)},{once:!0});else{let s=0;const a=20,n=setInterval(()=>{s++,(t()||s>=a)&&(clearInterval(n),requestAnimationFrame(()=>{requestAnimationFrame(()=>{requestAnimationFrame(()=>{setTimeout(()=>{e()},50)})})}))},50)}}),Ul=()=>{ds.createRoot(document.getElementById("root")).render(r.jsx(Rt.StrictMode,{children:r.jsx(gs,{client:os,children:r.jsx(zl,{defaultTheme:"dark",storageKey:"vite-ui-theme",children:r.jsxs(hs,{future:{v7_startTransition:!0,v7_relativeSplatPath:!0},children:[r.jsx(Fo,{}),r.jsx(va,{position:"top-right"})]})})})}))},$l=T(()=>import("./vendor-CjLUfV8Y.js").then(e=>e.aB),__vite__mapDeps([0,1,2,3])).then(e=>e).catch(e=>{});Promise.all([Fl(),$l]).then(()=>{}).catch(e=>{g.error("[Init] Failed to initialize; continuing",{error:e instanceof Error?e.message:String(e),stack:e instanceof Error?e.stack:void 0})}).then(()=>Vl()).finally(()=>{Ul()});export{Ya as A,P as B,Ft as C,Xr as D,no as E,es as F,$t as G,nr as H,_t as I,en as J,Kn as L,Cn as S,ce as T,T as _,tc as a,sc as b,y as c,ac as d,nc as e,Br as f,F as g,Jr as h,lc as i,ee as j,zt as k,g as l,ec as m,as as n,ic as o,W as p,Ti as q,Bt as r,mn as s,rs as t,oc as u,Zr as v,B as w,ct as x,Vr as y,Nt as z};