veza/apps/web/dist_verification/assets/index-CYK_b1Uz.js
senke 04c25aa24f Phase 2 stabilisation: code mort, Modal→Dialog, feature flags, tests, router split, Rust legacy
Bloc A - Code mort:
- Suppression Studio (components, views, features)
- Suppression gamification + services mock (projectService, storageService, gamificationService)
- Mise à jour Sidebar, Navbar, locales

Bloc B - Frontend:
- Suppression modal.tsx deprecated, Modal.stories (doublon Dialog)
- Feature flags: PLAYLIST_SEARCH, PLAYLIST_RECOMMENDATIONS, ROLE_MANAGEMENT = true
- Suppression 19 tests orphelins, retrait exclusions vitest.config

Bloc C - Backend:
- Extraction routes_auth.go depuis router.go

Bloc D - Rust:
- Suppression security_legacy.rs (code mort, patterns déjà dans security/)
2026-02-14 17:23:32 +01:00

5 lines
226 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-CveO81sn.js","assets/vendor-react-yWUy5XPk.js","assets/vendor-security-DsrNJhpn.js","assets/vendor-BD_zwJK7.css","assets/DashboardPage-B-iSrgp-.js","assets/vendor-router-BNNHboN9.js","assets/vendor-tanstack-kPY9uK0s.js","assets/chatStore-673HMl5Y.js","assets/vendor-motion-B3XPS3Jc.js","assets/AnimatedNumber-e5YD_LEJ.js","assets/vendor-icons-DJFb1Tiw.js","assets/vendor-http-Cz8wfb0q.js","assets/vendor-utils-DtoSyhX2.js","assets/vendor-i18n-CMcqpBLz.js","assets/ChatPage-CblRq44g.js","assets/input-CGdBHtsQ.js","assets/Select-DA2I33Xz.js","assets/dropdown-CA3EXRNb.js","assets/useIsRateLimited-BzrZ3iht.js","assets/confirmation-dialog-DS4X89Bi.js","assets/avatar-iUZRi_fz.js","assets/LibraryPage-_jEblTu2.js","assets/ContentFadeIn-DAssD8gZ.js","assets/tracks-3QM2Gqjj.js","assets/trackService-B9PLsYbw.js","assets/progress-C_BG9DJ7.js","assets/alert-FT0GWKW4.js","assets/UserProfilePage-CQ7fZ2k2.js","assets/users-CZ92MzeH.js","assets/PlaylistCard-C4g5-M9j.js","assets/playlistService-Ibr1CVA5.js","assets/features-DItyhINc.js","assets/socialService-BgeMqoR7.js","assets/Tabs-jry2MOtG.js","assets/SettingsPage-CSSzd1W-.js","assets/checkbox-DgTIon8S.js","assets/LoginPage-p0io7VQ6.js","assets/AuthInput-DUoVAqr-.js","assets/AuthLayout-BT3tl6R-.js","assets/RegisterPage-BDtil_L9.js","assets/PasswordStrengthIndicator-DoWFr4QD.js","assets/ForgotPasswordPage-ReoHn_Ds.js","assets/usePasswordReset-0vtOXL17.js","assets/VerifyEmailPage-D6Xy8Bf-.js","assets/ResetPasswordPage-GoxeiCUp.js","assets/SessionsPage-Bf46A7Ge.js","assets/NotFoundPage-Clc8zsY1.js","assets/ServerErrorPage-KZ-LUqM6.js","assets/RolesPage-CkteR03X.js","assets/textarea-Dn-lpNpV.js","assets/TrackDetailPage-anfAR6Sx.js","assets/useCopyToClipboard-B0J_nZ9-.js","assets/routes-DOpzcRDM.js","assets/Pagination-OD6LbhK5.js","assets/useDebounce-B1fFOcpX.js","assets/routes-B3giLbLK.css","assets/AdminDashboardView-CyXR3eeG.js","assets/AnalyticsView-DOCH2HDI.js","assets/StatCard-D6gRz6p3.js","assets/WebhooksView-BNyrs3j-.js","assets/webhookService-Bf4_1ebI.js","assets/DesignSystemDemo-evd169sp.js","assets/SocialView-Btb90uBJ.js","assets/GearView-ZVOHN4tS.js","assets/LiveView-CfyW_3Yz.js","assets/EducationView-CbR_C7CK.js","assets/QueueView-C0ORvlAn.js","assets/DeveloperDashboardView-B2Z9Gz1F.js","assets/NotificationsView-DR29OiUl.js","assets/MarketplaceHome-DLm6-klV.js","assets/marketplaceService-DWfxNVms.js","assets/cartStore-D5whk71m.js","assets/SearchPage-B5C5XA5d.js","assets/SellerDashboardView-DWQLxmBy.js","assets/commerceService-bs-xd9qB.js","assets/WishlistView-DGHnFMPQ.js","assets/PurchasesView-E5u00cpv.js"])))=>i.map(i=>d[i]);
import{a as m,j as r,R as Rt,c as xr,d as us}from"./vendor-react-yWUy5XPk.js";import{N as Ze,a as st,L as et,d as ds,R as ms,c as xe,B as fs}from"./vendor-router-BNNHboN9.js";import{a as br,u as At,b as Bt,Q as hs,c as ps}from"./vendor-tanstack-kPY9uK0s.js";import{ab as at,ac as nt,ad as gs,av as vs,aw as ys,ax as xs,ay as wr,az as bs}from"./vendor-CveO81sn.js";import{a as Ie,A as Le,i as Kt}from"./vendor-http-Cz8wfb0q.js";import{s as x,o as R,Z as Pt,r as qe,b as se,e as ae,d as fe,n as $,g as oe,a as ws,c as ks}from"./vendor-utils-DtoSyhX2.js";import{g as ye,b as Me,R as kr,H as Er,I as it,e as Ee,d as Es,X as he,c as Re,i as Ss,a6 as Ns,b1 as js,aE as Ht,a3 as _s,b2 as Ts,b3 as Cs,a1 as Sr,a7 as Nr,C as Rs,aL as As,b4 as Ps,S as Is,b5 as Ls,ad as Ds,aj as jr,aw as _r,au as qs,b6 as Ms,b7 as Os,b8 as zs,l as Fs,n as Vs,W as Us,f as $s,b9 as Qs,v as It,ba as Bs,o as Lt,F as Ks,aH as Hs,Y as Ws,ai as Gs,Q as Xs,U as Ys,bb as Js,bc as Zs,bd as ea,b0 as Tr,be as Cr,q as Rr,r as Ar,bf as Pr,bg as Ir,w as ta,m as ra,af as sa,bh as Wt,bi as aa,bj as na,bk as ia,ak as Gt}from"./vendor-icons-DJFb1Tiw.js";import{A as Dt,m as we}from"./vendor-motion-B3XPS3Jc.js";import{u as qt,i as Lr,B as oa,a as la}from"./vendor-i18n-CMcqpBLz.js";import"./vendor-security-DsrNJhpn.js";(function(){const t=document.createElement("link").relList;if(t&&t.supports&&t.supports("modulepreload"))return;for(const i of document.querySelectorAll('link[rel="modulepreload"]'))a(i);new MutationObserver(i=>{for(const n of i)if(n.type==="childList")for(const o of n.addedNodes)o.tagName==="LINK"&&o.rel==="modulepreload"&&a(o)}).observe(document,{childList:!0,subtree:!0});function s(i){const n={};return i.integrity&&(n.integrity=i.integrity),i.referrerPolicy&&(n.referrerPolicy=i.referrerPolicy),i.crossOrigin==="use-credentials"?n.credentials="include":i.crossOrigin==="anonymous"?n.credentials="omit":n.credentials="same-origin",n}function a(i){if(i.ep)return;i.ep=!0;const n=s(i);fetch(i.href,n)}})();const ca="modulepreload",ua=function(e){return"/"+e},Xt={},T=function(t,s,a){let i=Promise.resolve();if(s&&s.length>0){let l=function(f){return Promise.all(f.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");i=l(s.map(f=>{if(f=ua(f),f in Xt)return;Xt[f]=!0;const u=f.endsWith(".css"),d=u?'[rel="stylesheet"]':"";if(document.querySelector(`link[href="${f}"]${d}`))return;const h=document.createElement("link");if(h.rel=u?"stylesheet":ca,u||(h.as="script"),h.crossOrigin="",h.href=f,c&&h.setAttribute("nonce",c),document.head.appendChild(h),u)return new Promise((v,p)=>{h.addEventListener("load",v),h.addEventListener("error",()=>p(new Error(`Unable to preload CSS for ${f}`)))})}))}function n(o){const c=new Event("vite:preloadError",{cancelable:!0});if(c.payload=o,window.dispatchEvent(c),!c.defaultPrevented)throw o}return i.then(o=>{for(const c of o||[])c.status==="rejected"&&n(c.reason);return t().catch(n)})};let Dr=null;function da(e){Dr=e}function ma(){return Dr}const fa=m.lazy(()=>T(()=>import("./vendor-CveO81sn.js").then(e=>e.aB),__vite__mapDeps([0,1,2,3])).then(e=>({default:e.Toaster})));function ha(e){return r.jsx(m.Suspense,{fallback:null,children:r.jsx(fa,{...e})})}const Yt="veza_access_token",Jt="veza_refresh_token";class ee{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 pa="WARN".toUpperCase();let tt={};function Zt(e){tt={...tt,...e}}function ga(){return{...tt}}function Qe(e,t,s,...a){const i={...tt,...s},n=new Date().toISOString();{const o={timestamp:n,level:e,message:t,...i,...a.length>0&&{data:a}},c=JSON.stringify(o);console.log(c)}}function Be(e){const t=["DEBUG","INFO","WARN","ERROR"],s=t.indexOf(pa),a=t.indexOf(e);return s===-1||a===-1?!0:a>=s}const g={debug:(e,t,...s)=>{Be("DEBUG")&&Qe("DEBUG",e,t,...s)},info:(e,t,...s)=>{Be("INFO")&&Qe("INFO",e,t,...s)},warn:(e,t,...s)=>{Be("WARN")&&Qe("WARN",e,t,...s)},error:(e,t,...s)=>{Be("ERROR")&&Qe("ERROR",e,t,...s)}},de=T(()=>import("./vendor-CveO81sn.js").then(e=>e.aB),__vite__mapDeps([0,1,2,3]));let Ye=null,Et=!1;de.then(e=>{Ye=e,Et=!0}).catch(()=>{Et=!0});function er(){return!Ye&&Et?(g.error("Toast module failed to load"),{success:()=>{},error:()=>{},loading:()=>{},custom:()=>{},dismiss:()=>{},remove:()=>{},promise:()=>Promise.resolve()}):Ye?Ye.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 K=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(i=>i.default(...s))}});let vt=null;const va=60*1e3,ya=240*1e3;let Ae=null,ke=null;function xa(){if(!vt){const e=(()=>{throw new Error("VITE_API_URL must be defined in production")})();vt=Ie.create({baseURL:e,timeout:1e4,headers:{"Content-Type":"application/json"},withCredentials:!0})}return vt}async function De(){try{const t=await xa().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)}`);ee.setTokens("","cookie-based"),qr(s)}catch(e){throw ee.clearTokens(),ot(),e}}function qr(e=300){ot(),ba();const t=e*1e3,s=Math.max(0,t-va);if(s<=0){De().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}Ae=setTimeout(()=>{De().catch(a=>{g.warn("Proactive token refresh failed",{error:a instanceof Error?a.message:String(a),stack:a instanceof Error?a.stack:void 0})}),Ae=null},s)}function ba(){ke&&clearInterval(ke),ke=setInterval(()=>{De().catch(e=>{g.warn("Periodic token refresh failed",{error:e instanceof Error?e.message:String(e),stack:e instanceof Error?e.stack:void 0}),ot()})},ya)}function ot(){Ae&&(clearTimeout(Ae),Ae=null),ke&&(clearInterval(ke),ke=null)}function lt(){qr(300)}function Mr(){ot()}const wa=Object.freeze(Object.defineProperty({__proto__:null,cleanupProactiveRefresh:Mr,initializeProactiveRefresh:lt,refreshToken:De},Symbol.toStringTag,{value:"Module"})),Ke=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",ka=R({VITE_DOMAIN:x().default("veza.fr"),VITE_API_URL:Ke.default("/api/v1"),VITE_WS_URL:Ke.default(`ws://${tr}:8081/ws`),VITE_STREAM_URL:Ke.default(`ws://${tr}:8082/stream`),VITE_UPLOAD_URL:Ke.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()}),Ea=()=>{try{return ka.parse({VITE_DOMAIN:void 0,VITE_API_URL:void 0,VITE_WS_URL:void 0,VITE_STREAM_URL:void 0,VITE_UPLOAD_URL:void 0,VITE_APP_NAME:void 0,VITE_API_VERSION:void 0,VITE_DEBUG:void 0,VITE_USE_MSW:void 0,VITE_FCM_VAPID_KEY:void 0,VITE_SENTRY_DSN:void 0})}catch(e){throw e instanceof 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=Ea(),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."},Sa={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 Na(e,t){return e in ie?ie[e]:t||ie.UNKNOWN}function ja(e,t,s){const a=Sa[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,i=typeof a.code=="number"?a.code:0;if(t&&i>=400&&i<500){const n=_a(a.message),o=ja(t,n,void 0);if(o!==ie.UNKNOWN)return o}if(i>0){const n=Na(i,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`${n} (${o})`}return n}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 _a(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 Ta(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 Ca(){return typeof navigator>"u"?!0:navigator.onLine}function Ra(){return!Ca()}function B(e){if(Pa(e))return e;if(Ia(e)){const t=e,s=t.response?.data,a=l=>typeof l=="object"&&l!==null&&"success"in l&&l.success===!1&&"error"in l,i=l=>typeof l=="object"&&l!==null&&"error"in l&&typeof l.error=="object",n=l=>typeof l=="object"&&l!==null&&"code"in l&&"message"in l;if(s){if(a(s))return yt(s.error);if(i(s)){const l=s.error;if(l&&("code"in l||"message"in l))return yt(l)}if(n(s))return yt(s)}if(t.request&&!t.response)return Ta(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"||Ra()?{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||{},f=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,h=l["x-ratelimit-reset"]?parseInt(String(l["x-ratelimit-reset"]),10):void 0,v=l["retry-after"]?parseInt(String(l["retry-after"]),10):f?.error?.retry_after||60,p=h?new Date(h*1e3):void 0,w=p?Math.max(0,Math.ceil((p.getTime()-Date.now())/1e3)):v;return{code:429,message:f?.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 Aa(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:Aa(t.context)}}function tc(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 i=e.details.map(n=>{const o=typeof n.field=="string"?n.field:String(n.field),c=typeof n.message=="string"?n.message:String(n.message);return`${o}: ${c}`}).join(", ");a=`${s} (${i})`}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 Pa(e){return typeof e=="object"&&e!==null&&"code"in e&&"message"in e&&typeof e.code=="number"&&typeof e.message=="string"}function Ia(e){return typeof e=="object"&&e!==null&&"isAxiosError"in e&&e.isAxiosError===!0}class La{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 J=new La;class Da{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 i={id:this.generateRequestId(),config:t,timestamp:Date.now(),retryCount:0,priority:a},n={high:0,normal:1,low:2},o=this.queue.findIndex(c=>n[c.priority]>n[a]);return o===-1?this.queue.push(i):this.queue.splice(o,0,i),await this.saveQueue(),g.info(`[OfflineQueue] Request queued: ${t.method?.toUpperCase()} ${t.url}`,{requestId:i.id,priority:a,queueSize:this.queue.length}),i.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(i=>setTimeout(i,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(i=>i.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 Da;class qa{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||"",i=t.baseURL||"",n=a.startsWith("http")?a:`${i}${a}`,o=t.params?Object.keys(t.params).sort().map(l=>`${l}=${JSON.stringify(t.params[l])}`).join("&"):"",c=t.headers?.Authorization||"";return`${s}:${n}${o?`?${o}`:""}:${c}`}parseCacheControl(t){if(!t)return{};const s={},a=t.split(",").map(i=>i.trim());for(const i of a)if(i.includes("=")){const[n,o]=i.split("=").map(c=>c.trim());n&&(s[n.toLowerCase()]=o??!0)}else s[i.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 i=Date.now()-t.timestamp;if(t.maxAge){const n=t.maxAge*1e3;if(i>n)return!1}else if(i>this.defaultTTL)return!1;if(this.enableETag&&t.etag){const n=s.headers?.["If-None-Match"];if(n&&n!==t.etag)return!1}if(t.lastModified){const n=s.headers?.["If-Modified-Since"];if(n){const o=new Date(t.lastModified).getTime(),c=new Date(n).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),i=this.cache.get(a);if(!i)return null;if(!this.isCacheValid(i,t))return this.cache.delete(a),g.debug(`[ResponseCache] Cache expired: ${t.url}`),null;const n={data:i.data,status:i.status,statusText:i.statusText,headers:i.headers,config:t,request:{}};return g.debug(`[ResponseCache] Cache hit: ${t.url}`,{key:a,age:Date.now()-i.timestamp}),n}set(t,s){if((t.method||"GET").toUpperCase()!=="GET"||t?._disableCache===!0)return;const i=s.headers["cache-control"]||s.headers["Cache-Control"],n=this.parseCacheControl(i);if(n.noStore||n.noCache){g.debug(`[ResponseCache] Not caching (no-store/no-cache): ${t.url}`);return}let o;this.respectCacheControl&&n.maxAge?o=n.maxAge:o=Math.floor(this.defaultTTL/1e3);const c=s.headers.etag||s.headers.ETag,l=s.headers["last-modified"]||s.headers["Last-Modified"],f=this.generateCacheKey(t);if(this.cache.size>=this.maxSize&&!this.cache.has(f)){const u=this.cache.keys().next().value;u&&this.cache.delete(u)}this.cache.set(f,{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:f,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,i]of this.cache.entries()){const n=t-i.timestamp,o=(i.maxAge||Math.floor(this.defaultTTL/1e3))*1e3;n>o&&(this.cache.delete(a),s++)}return s>0&&g.debug(`[ResponseCache] Cleaned up ${s} expired cache entries`),s}}const ve=new qa({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:i=!1,queryKeys:n=[],storeNames:o=[]}=e;try{(t==="cache"||t==="all")&&(i?(ve.clear(),g.debug("[StateInvalidation] Cleared all response cache")):s&&Ma(s,a)),(t==="queries"||t==="all")&&Oa(n,s,a),(t==="stores"||t==="all")&&za(o,s,a),g.debug("[StateInvalidation] State invalidated",{target:t,resourceType:s,resourceId:a,invalidateAll:i})}catch(c){g.error("[StateInvalidation] Error invalidating state",{error:String(c)})}}function Ma(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 i of a)ve.invalidate(i);if(t)for(const i of a)ve.invalidate(`${i}/${t}`)}function Oa(e,t,s){const a=ma();if(!a){if(g.warn("[StateInvalidation] QueryClient not available, falling back to event system"),typeof window<"u"){const i=new CustomEvent("veza:invalidate-queries",{detail:{queryKeys:e,resourceType:t,resourceId:s}});window.dispatchEvent(i)}return}if(e&&e.length>0)for(const i of e)a.invalidateQueries({queryKey:i});if(t){const n={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 n)a.invalidateQueries({queryKey:s?[...o,s]:o})}g.debug("[StateInvalidation] Invalidated React Query cache",{queryKeys:e,resourceType:t,resourceId:s})}function za(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"]},i=e.length>0?e:t?a[t]||[]:[];for(const n of i)Fa(n).catch(o=>{g.warn(`[StateInvalidation] Failed to invalidate store ${n}`,{error:String(o)})})}async function Fa(e,t,s){try{switch(e){case"auth":{const{useAuthStore:a}=await T(async()=>{const{useAuthStore:i}=await Promise.resolve().then(()=>be);return{useAuthStore:i}},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 Va(e,t){if(!e)return;let s,a;if(e.includes("/tracks/")){s="tracks";const i=e.match(/\/tracks\/([^/]+)/);a=i?i[1]:void 0}else if(e.includes("/playlists/")){s="playlists";const i=e.match(/\/playlists\/([^/]+)/);a=i?i[1]:void 0}else if(e.includes("/users/")||e.includes("/auth/")){s="users";const i=e.match(/\/(users|auth)\/([^/]+)/);a=i?i[2]:void 0}else if(e.includes("/conversations/")){s="conversations";const i=e.match(/\/conversations\/([^/]+)/);a=i?i[1]:void 0}else if(e.includes("/roles/")){s="roles";const i=e.match(/\/roles\/([^/]+)/);a=i?i[1]:void 0}rr(s?{resourceType:s,resourceId:a,target:"all"}:{target:"cache",invalidateAll:!0})}function Ua(e){if(e!=null)return typeof e=="string"?e:String(e)}function Nt(e,t=["id","user_id","track_id","playlist_id","conversation_id","message_id","sender_id","creator_id","created_by","parent_id","parent_message_id"]){if(!e||typeof e!="object")return e;const s={...e};for(const[a,i]of Object.entries(s))t.includes(a)?s[a]=Ua(i):i&&typeof i=="object"&&!Array.isArray(i)&&!(i instanceof Date)?s[a]=Nt(i,t):Array.isArray(i)&&i.length>0&&typeof i[0]=="object"&&(s[a]=i.map(n=>typeof n=="object"&&n!==null?Nt(n,t):n));return s}const Ne="1.2.0";function Oe(e,t=Ne,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"),H=x().datetime({message:"Invalid ISO8601 date format"}),ze=Oe(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:H.optional().nullable(),gender:x().optional().nullable(),username_changed_at:H.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:H.optional().nullable(),created_at:H,updated_at:H,is_2fa_enabled:se().optional(),social_links:qe(fe()).optional().nullable()}),Ne,"User response schema - matches backend User model"),$a=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:H,updated_at:H,sender:ze.optional()});R({id:D,name:x(),type:ae(["direct","group"]),creator_id:D,created_at:H,updated_at:H,participants:oe(ze).optional(),last_message:$a.optional(),unread_count:$().int().nonnegative().optional()});const Fr=Oe(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:H,updated_at:H,user:ze.optional(),is_premium:se().optional(),lyrics:oe(R({time:$(),text:x()})).optional(),waveform_data:oe($()).optional(),tags:oe(x()).optional()}),Ne,"Track response schema - matches backend Track model");Oe(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:H,updated_at:H,tracks:oe(Fr).optional(),user:ze.optional(),playlist_tracks:oe(fe()).optional(),collaborators:oe(fe()).optional()}),Ne,"Playlist response schema - matches backend Playlist model");R({id:D,user_id:D,ip_address:x(),user_agent:x(),revoked_at:H.optional().nullable(),expires_at:H,created_at:H});R({id:D,user_id:D.optional().nullable(),action:x(),resource:x(),resource_id:D.optional().nullable(),metadata:qe(fe()).optional().nullable(),ip_address:x().optional().nullable(),user_agent:x().optional().nullable(),timestamp:H});Oe(R({code:$().int(),message:x(),details:oe(R({field:x(),message:x(),value:x().optional()})).optional(),request_id:x().optional(),timestamp:H,context:qe(fe()).optional(),retry_after:$().int().positive().optional()}),Ne,"API Error response schema - matches backend error format");Oe(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()}),Ne,"Pagination metadata schema");R({id:D,user_id:D,type:ae(["new_message","track_uploaded","user_mentioned","system"]),content:x(),read:se(),created_at:H});R({id:D,playlist_id:D,track_id:D,position:$().int().nonnegative(),added_by:D,added_at:H,track:Fr.optional()});R({id:D,playlist_id:D,user_id:D,role:ae(["owner","editor","viewer"]),created_at:H,user:ze.optional()});function Qa(e,t,s={}){const{normalizeIds:a=!0}=s;let i=t;return a&&typeof t=="object"&&t!==null&&(i=Nt(t)),e.parse(i)}function sr(e,t,s={}){try{return{success:!0,data:Qa(e,t,s)}}catch(a){if(a instanceof Pt)return{success:!1,error:a};throw a}}const Fe=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:Fe,password:x().min(1,"Password is required")});R({username:mt,email:Fe,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:Fe,password:dt});R({username:mt.optional(),email:Fe.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:qe(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:qe(fe()).optional(),timestamp:x().optional(),data:fe().optional()});R({email:Fe});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 Ve=R({page:$().int().positive().optional(),limit:$().int().positive().max(100).optional(),cursor:x().optional()});Ve.extend({query:x().optional()});Ve.extend({conversation_id:D});Ve.extend({query:x().optional()});Ve.extend({artist:x().optional(),genre:x().optional()});Ve.extend({query:x().min(1,"Search query is required")});R({type:ae(["image","audio","document"])});function Ba(e,t){return e.parse(t)}function Ka(e,t){try{return{success:!0,data:Ba(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},jt=at()(nt(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,i=t.reset!==null&&t.reset!==void 0?typeof t.reset=="string"?parseInt(t.reset,10):t.reset:null,n=t.retryAfter!==null&&t.retryAfter!==void 0?typeof t.retryAfter=="string"?parseInt(t.retryAfter,10):t.retryAfter:null,o=a!==null&&a<=0||n!==null;e({limit:s,remaining:a,reset:i,retryAfter:n,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})})),Ha={DEFAULT:1e4,UPLOAD:3e5,LONG_POLLING:3e4},nr=1e3,F=Ie.create({baseURL:ct.API_URL,timeout:Ha.DEFAULT,headers:{"Content-Type":"application/json"},withCredentials:!0});class Wa{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 Wa,ir={failureRateThreshold:5,minValidationsForAlert:10,checkInterval:300*1e3};class Ga{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 Xa=new Ga;typeof window<"u"&&Xa.start();const Ya=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 Ja{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 Mt=new Ja,Je=e=>!!(e.response?.status===206||e.code==="ECONNABORTED"&&e.message?.toLowerCase().includes("timeout")&&e.request||e.code==="ECONNRESET"&&e.response||Mt.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"||Mt.isCompleteFailure()),Za=(e,t=pe)=>{if(Ie.isCancel(e)||e.code==="ERR_BAD_RESPONSE"||e.message?.includes("HTML page instead of JSON")||e.config?._disableRetry)return!1;if(Je(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(i=>s.includes(i))}return!e.response&&e.request?Tt(e.config?.method):!1},en=(e,t,s=pe.baseDelay,a=pe.maxDelay)=>{const i=e.response?.headers["retry-after"]||e.response?.headers["Retry-After"];if(i){const c=parseInt(String(i),10);if(!isNaN(c)&&c>0)return Math.min(c*1e3,a)}const n=s*Math.pow(2,t),o=Math.random()*s;return Math.min(n+o,a)};let He=!1,Te=0;const tn=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 i=a.toLowerCase();t.some(n=>i.includes(n))?s[a]="[REDACTED]":typeof s[a]=="object"&&s[a]!==null&&(s[a]=ge(s[a]))}return s},Pe=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 rn(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 sn(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||""),i=e.url?.includes("/auth/login")||e.url?.includes("/auth/register"),n=e.url?.includes("/csrf-token");if(a&&!n&&!i&&e.headers){let c=J.getToken();if(!c)try{c=await J.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=Ka(o,e.data);if(!c.success){const l=Pe(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 f=c.error?.errors.map(u=>`${u.path.join(".")}: ${u.message}`).join(", ")||"Request validation failed";throw new Error(`Request validation failed: ${f}`)}e.data=c.data}if(e._requestStartTime=Date.now(),e?._enableLogging){const c=Pe(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(rn(e)){const h="The API returned an HTML page instead of JSON. Another application may be using port 8080. Stop any other server (e.g. phishing lab) and ensure the Veza backend is running.";if(typeof window<"u"){const v="veza_wrong_server_shown";sessionStorage.getItem(v)||(sessionStorage.setItem(v,"true"),K(h,{icon:"⚠️",duration:12e3}))}return Promise.reject(new Le(h,"ERR_BAD_RESPONSE",e.config,e.request,e))}Mt.recordRequest(!0);const t=e.config?._requestStartTime;if(t){const h=Date.now()-t;h>nr&&(e.config._isSlowRequest=!0,e.config._requestDuration=h,e.config?._enableLogging&&g.debug(`[API Slow Request] ${e.config?.method?.toUpperCase()} ${e.config?.url} took ${h}ms`,{duration:h,threshold:nr}))}const a=e.headers["x-request-id"]||e.headers["X-Request-ID"]||e.config?._requestId;a&&Zt({request_id:a});const i=e.headers["x-ratelimit-limit"]||e.headers["X-RateLimit-Limit"],n=e.headers["x-ratelimit-remaining"]||e.headers["X-RateLimit-Remaining"],o=e.headers["x-ratelimit-reset"]||e.headers["X-RateLimit-Reset"];if((i||n||o)&&jt.getState().updateRateLimit({limit:i,remaining:n,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 h="api_deprecation_warning_shown";if(typeof window<"u"&&!sessionStorage.getItem(h)){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.";K(p,{icon:"⚠️",duration:1e4}),sessionStorage.setItem(h,"true"),g.warn("[API] Deprecated API version detected",{url:e.config.url,version:e.headers["x-api-version"]||e.headers["X-API-Version"],sunset_date:v})}}if(!e.data||typeof e.data!="object")return e;const f=e.config.method?.toUpperCase(),u=["POST","PUT","PATCH","DELETE"].includes(f||"");if(u&&e.config?._showSuccessToast&&typeof window<"u"){const h=e.config?._successMessage||e.data?.message||sn(f||"");h&&K.success(h)}if(f==="GET"&&!e.config?._disableCache&&ve.set(e.config,e),u){const h=e.config.url||"";e.config.method,Va(h)}if("success"in e.data){if(e.data.success===!0){const h=e.data.data!==void 0?e.data.data:null,v=e.config?._responseSchema;if(v&&h!==null){const p=sr(v,h);if(p.success){const w=Pe(e.config);g.debug("[API Response Validation Success]",{request_id:w,url:e.config.url}),_t.recordSuccess(e.config.url)}else{const w=Pe(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(A=>({path:A.path.join("."),message:A.message,code:A.code,received:A.code==="invalid_type"?A.received:void 0,expected:A.code==="invalid_type"?A.expected:void 0})),response_data_preview:JSON.stringify(h).substring(0,200),schema_provided:!!v,timestamp:new Date().toISOString()},p.error),_t.recordFailure(e.config.url);const E=e.config?._validationRecovery,j=E?.useCache!==!1,S=E?.retry===!0,I=E?.notifyUser!==!1;if(j&&f==="GET"){const A=ve.get(e.config);if(A){let b=A.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"}),I&&typeof window<"u"&&K("Data may be outdated. Please refresh if issues persist.",{icon:"⚠️",duration:5e3}),{...A,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);I&&typeof window<"u"&&K("Some data may be incomplete. Please refresh if issues persist.",{icon:"⚠️",duration:5e3})}}return{...e,data:h}}if(e.data.success===!1){const h=e.data.error||e.data;g.error("[API] Response with success=false:",{url:e.config.url,error:h});const v=new Le(h?.message||"Request failed","API_ERROR",e.config,e.request,{...e,status:e.status||400,statusText:e.statusText||"Bad Request",data:{success:!1,error:h}});return Promise.reject(v)}}if(e.data&&typeof e.data=="object"&&!("success"in e.data)){const h=Pe(e.config);g.warn("[API] Received non-wrapped response format (unexpected)",{request_id:h,url:e.config.url,method:e.config.method?.toUpperCase(),status:e.status,response_preview:JSON.stringify(e.data).substring(0,200),timestamp:new Date().toISOString()})}return e},async e=>{if(Ie.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 N=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"];(N||C||O||V)&&jt.getState().updateRateLimit({limit:N,remaining:C,reset:O,retryAfter:V})}const a=t?._enableLogging;if(a&&e.response){const N=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:N,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 i=t?.url?.includes("/csrf-token"),n=t?.url?.includes("/auth/login")||t?.url?.includes("/auth/register");if(e.response?.status===403&&t&&!t._csrfRetry&&!i&&!n){const k=e.response?.data,N=(typeof k?.error=="string"?k.error:k?.message||"").toLowerCase();if(N.includes("csrf")||N.includes("token")||N.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 J.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}),ee.clearTokens(),J.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(B(e));if(e.response?.status===401&&c)return g.warn("[API] 401 on /auth/logout - clearing tokens locally",{request_id:s,url:t?.url}),ee.clearTokens(),J.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(B(e));if(e.response?.status===401&&t&&!t._retry&&!o&&!c&&!l){if(He)return new Promise((k,N)=>{Ct.push({resolve:k,reject:N})}).then(()=>F(t)).catch(k=>{const N=k,C=N?.response?.status??N?.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,He=!0,Te>=tn)return Te=0,He=!1,ee.clearTokens(),J.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(B(e));Te++;try{return await De(),Te=0,bt(null),F(t)}catch(k){return g.error("[API] Token refresh failed",{attempt:Te,request_id:s,error:k}),bt(k),ee.clearTokens(),J.clearToken(),typeof window<"u"&&(T(async()=>{const{useAuthStore:N}=await Promise.resolve().then(()=>be);return{useAuthStore:N}},void 0).then(({useAuthStore:N})=>N.getState().logoutLocal()).catch(N=>g.error("[API] Failed to import auth store for logout",{error:N})),sessionStorage.setItem("auth_error","Votre session a expiré. Veuillez vous reconnecter."),window.location.href="/login"),Promise.reject(k)}finally{He=!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 J.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(B(e))}}}const u=e.response?.status,d=t?._retryCount||0,h=pe.maxRetries;if(u===429){const k=B(e),N=e.response?.headers["retry-after"]||e.response?.headers["Retry-After"],C=N?parseInt(N,10):60;return g.warn("[API] Rate limit exceeded, not retrying",{url:t?.url,retry_after:C,request_id:k.request_id}),k.message&&K.error(k.message,{duration:C*1e3}),Promise.reject(k)}const v=t?.url?.includes("/marketplace/products");if(u===500&&v){const k=B(e);return k.httpStatus=u,Promise.reject(k)}if(Za(e,pe)&&t&&d<h){const k=t.method?.toUpperCase(),N=Tt(k);if(!N&&u&&u!==500&&u!==502&&u!==503&&u!==504)return Promise.reject(B(e));t._retryCount=d+1;const C=en(e,d,pe.baseDelay,pe.maxDelay);if(d===0){const O=B(e),V=u?`HTTP ${u}`:e.code||"Network Error";g.warn(`[API Retry] ${V} error, retrying (1/${h})`,{status:u||"N/A",error_code:e.code||"N/A",retry_count:1,max_retries:h,delay_ms:Math.round(C),request_id:O.request_id,url:t?.url,method:t?.method,is_idempotent:N})}return Ya(C).then(()=>F(t))}if(d>=h){const k=B(e),N=u?`HTTP ${u}`:e.code||"Network Error";return g.error(`[API Error] ${N} error after ${h} retries`,{code:k.code,message:k.message,request_id:k.request_id,url:t?.url,method:t?.method}),Promise.reject(k)}const p=B(e);u===401&&!o&&!c&&!l&&typeof window<"u"&&ut(p)==="authentication"&&(ee.clearTokens(),J.clearToken(),T(async()=>{const{useAuthStore:N}=await Promise.resolve().then(()=>be);return{useAuthStore:N}},void 0).then(({useAuthStore:N})=>N.getState().logoutLocal()).catch(N=>g.error("[API] Failed to import auth store for logout",{error:N})),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??"",j=u&&u>=500&&E.includes("/webhooks"),S=!t?._disableToast&&u!==401&&u!==404&&!Ie.isCancel(e)&&!w&&!j,I=!e.response;if(I){const{recordNetworkError:k}=await T(async()=>{const{recordNetworkError:N}=await Promise.resolve().then(()=>wn);return{recordNetworkError:N}},void 0);k(p)}const A=I?"network-error-toast":void 0;if(S&&typeof window<"u"){const k=t?.url||"";let N;k.includes("/auth/")?N="auth":k.includes("/tracks")||k.includes("/track/")?N="track":k.includes("/playlists")||k.includes("/playlist/")?N="playlist":k.includes("/upload")?N="upload":k.includes("/conversations")||k.includes("/chat")?N="conversation":k.includes("/search")&&(N="search");const O=Or(p,N,u===422);if(!e.response&&t&&me.shouldQueueRequest(t)&&(typeof navigator<"u"&&!navigator.onLine||!e.response&&e.request)){const G=t.method?.toUpperCase(),Y=G==="DELETE"?"low":G==="POST"?"high":"normal";try{await me.queueRequest(t,{priority:Y}),K.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;I&&(Je(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.`),(Je(e)||xt(e))&&I&&g.warn("[API] Network failure detected",{request_id:s,is_partial_failure:Je(e),is_complete_failure:xt(e),url:t?.url,method:t?.method,error_code:e.code,error_message:e.message}),K.error(V,{duration:8e3,id:A})}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 an{cache=new Map;defaultCacheTime=1e3;generateRequestKey(t){const s=(t.method||"GET").toUpperCase(),a=t.url||"",i=t.baseURL||"",n=a.startsWith("http")?a:`${i}${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}:${n}${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:i=!0,cacheTime:n=this.defaultCacheTime}=a;if(!i||!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(f=>(setTimeout(()=>{const u=this.cache.get(o);u&&u.promise===l&&(this.cache.delete(o),g.debug(`[RequestDeduplication] Removed from cache: ${o}`))},n),f)).catch(f=>{const u=this.cache.get(o);throw u&&u.promise===l&&(this.cache.delete(o),g.debug(`[RequestDeduplication] Removed from cache (error): ${o}`)),f});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[i,n]of this.cache.entries())s-n.timestamp>t&&(this.cache.delete(i),a++);a>0&&g.debug(`[RequestDeduplication] Cleaned up ${a} old cache entries`)}}const nn=new an;typeof window<"u"&&setInterval(()=>{nn.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,i,n;if(t.data?.token?.access_token?(s=t.data.token.access_token,a=t.data.token.refresh_token||"",i=t.data.token.expires_in,n=t.data.user):t.data?.access_token?(s=t.data.access_token,a=t.data.refresh_token||"",i=t.data.expires_in,n=t.data.user):t.data?.Token?.AccessToken?(s=t.data.Token.AccessToken,a=t.data.Token.RefreshToken||"",i=t.data.Token.ExpiresIn,n=t.data.User||t.data.user):(t.data?.User||t.data?.user)&&(n=t.data.User||t.data.user),s&&(ee.setTokens(s,a||""),lt()),!n)throw new Error("Registration response missing user data");if(!s||i===void 0)throw new Error("Registration response missing tokens. Email verification may be required.");return{user:n,token:{access_token:s,refresh_token:a||"",expires_in:i}}}catch(t){throw B(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,i,n;if(t.data?.token?.access_token?(s=t.data.token.access_token,a=t.data.token.refresh_token||"",i=t.data.token.expires_in,n=t.data.user):t.data?.access_token?(s=t.data.access_token,a=t.data.refresh_token||"",i=t.data.expires_in,n=t.data.user):t.data?.Token?.AccessToken&&(s=t.data.Token.AccessToken,a=t.data.Token.RefreshToken||"",i=t.data.Token.ExpiresIn,n=t.data.User||t.data.user),t.data?.requires_2fa){if(n||(n=t.data.user||t.data.User),!n)throw new Error("Login response missing user data");return{user:n,token:{access_token:"",refresh_token:"",expires_in:0},requires_2fa:!0}}if(s)ee.setTokens(s,a||""),e.remember_me?localStorage.setItem("remember_me","true"):localStorage.removeItem("remember_me"),lt();else throw g.error("[AUTH] Tokens not found in login response",{responseData:t.data}),new Error("Login response missing tokens");return{user:n,token:{access_token:s,refresh_token:a||"",expires_in:i||3600},requires_2fa:t.data?.requires_2fa}}catch(t){throw B(t)}}async function on(e,t,s,a=!1){try{const n=(await F.post("/auth/login/2fa",{email:e,password:t,code:s,remember_me:a})).data,o=n?.token?.access_token,c=n?.token?.refresh_token??"",l=n?.token?.expires_in,f=n?.user;if(!f)throw new Error("2FA login response missing user data");if(!o||l===void 0)throw new Error("2FA login response missing tokens");return ee.setTokens(o,c),a?localStorage.setItem("remember_me","true"):localStorage.removeItem("remember_me"),lt(),{user:f,token:{access_token:o,refresh_token:c,expires_in:l}}}catch(i){throw B(i)}}async function $r(){try{await F.post("/auth/logout",{},{_disableToast:!0})}catch(e){const t=Kt(e)?e.response?.status:void 0,s=Kt(e)?e.response?.data:void 0;t===400&&(s?.error?.includes("RefreshToken")??s?.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(),ee.clearTokens()}}async function Ot(){try{return(await F.get("/auth/me")).data}catch(e){throw B(e)}}const rc={login:Ur,register:Vr,logout:$r,getMe:Ot,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 ln(e){if(typeof window>"u"||!window.BroadcastChannel)return g.warn("[BroadcastSync] BroadcastChannel not supported in this environment"),null;try{return new BroadcastChannel(`veza-store-${e}`)}catch(t){return g.warn(`[BroadcastSync] Failed to create BroadcastChannel for ${e}`,{error:t instanceof Error?t.message:String(t),stack:t instanceof Error?t.stack:void 0,storeName:e}),null}}function Qr(e,t={}){return(s,a,i)=>{const n=t.channelName||"default-store",o=t.enabled!==!1,c=t.shouldSync||(()=>!0),l=t.onStateSync;let f=null,u=!1,d=null,h=0;const v=new Set,p=[];if(o&&(f=ln(n),f)){const E=()=>{if(p.length===0||u)return;p.sort((S,I)=>I.timestamp-S.timestamp);const j=p.shift();j&&j.timestamp>h&&(u=!0,s(j.state),d=j.state,h=j.timestamp,v.size>100&&Array.from(v).slice(0,50).forEach(I=>v.delete(I)),setTimeout(()=>{u=!1,E()},50))};f.onmessage=j=>{const S=j.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!==n)return;const I=S.messageId||`${S.type}-${S.timestamp}-${Math.random()}`;if(!v.has(I)){if(S.type==="state-update"&&S.state){if(u){p.push({state:S.state,timestamp:S.timestamp,messageId:I}),E();return}if(S.timestamp<=h){v.add(I);return}if(c(S.state,d)){v.add(I),u=!0;const A=d;s(S.state);const b=S.state;if(d=b,h=S.timestamp,l)try{l(b,A)}catch(_){g.warn("[BroadcastSync] Error in onStateSync callback",{error:_ instanceof Error?_.message:String(_),stack:_ instanceof Error?_.stack:void 0,storeName:n})}setTimeout(()=>{u=!1,E()},50)}else v.add(I)}else if(S.type==="state-request"){const A=a(),b=JSON.parse(JSON.stringify(A));f&&f.postMessage({type:"state-response",storeName:n,state:b,timestamp:Date.now()})}else if(S.type==="state-response"&&S.state)if(!d||S.timestamp>h){v.add(I),u=!0;const A=d;s(S.state);const b=S.state;if(d=b,h=S.timestamp,l)try{l(b,A)}catch(_){g.warn("[BroadcastSync] Error in onStateSync callback",{error:_ instanceof Error?_.message:String(_),stack:_ instanceof Error?_.stack:void 0,storeName:n})}setTimeout(()=>{u=!1,E()},50)}else v.add(I)}},f.postMessage({type:"state-request",storeName:n,timestamp:Date.now()})}return e((...E)=>{if(u)s(...E);else if(s(...E),f&&o){const j=a();if(c(j,d)){const S=Date.now(),I=`update-${S}-${Math.random()}`,A=JSON.parse(JSON.stringify(j));if(f.postMessage({type:"state-update",storeName:n,state:A,timestamp:S,messageId:I}),l)try{l(j,d)}catch(b){g.warn("[BroadcastSync] Error in onStateSync callback",{error:b instanceof Error?b.message:String(b),stack:b instanceof Error?b.stack:void 0,storeName:n})}d=j,h=S}}},a,i)}}const te=at()(nt(Qr(e=>({isAuthenticated:!1,isLoading:!1,error:null,login:async t=>{e({isLoading:!0,error:null});try{const s=await Ur(t);return s.requires_2fa?(e({isAuthenticated:!1,isLoading:!1,error:null}),s):(e({isAuthenticated:!0,isLoading:!1,error:null}),J.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:B(s),isLoading:!1,isAuthenticated:!1}),s}},complete2FALogin:async t=>{e({isLoading:!0,error:null});try{const s=await on(t.email,t.password,t.code,t.remember_me??!1);return e({isAuthenticated:!0,isLoading:!1,error:null}),J.refreshToken().catch(a=>{g.warn("Failed to fetch CSRF token after 2FA login",{error:a instanceof Error?a.message:String(a),stack:a instanceof Error?a.stack:void 0})}),s}catch(s){throw e({error:B(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&&J.refreshToken().catch(i=>{g.warn("Failed to fetch CSRF token after register",{error:i instanceof Error?i.message:String(i),stack:i instanceof Error?i.stack:void 0})})}catch(s){throw e({error:B(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}),J.clearToken()}},logoutLocal:()=>{g.info("[Auth] Performing local logout (no API call)",{}),ee.clearTokens(),T(async()=>{const{cleanupProactiveRefresh:t}=await Promise.resolve().then(()=>wa);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)})}),J.clearToken(),e({isAuthenticated:!1,isLoading:!1,error:null})},refreshUser:async()=>{const s=te.getState().isAuthenticated;e({isLoading:!0});try{await Ot(),e({isAuthenticated:!0,isLoading:!1,error:null}),J.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 i=B(a),n=typeof i.code=="number"?i.code:0;n===401||n===1001||n===1002?(ee.clearTokens(),e({error:i,isLoading:!1,isAuthenticated:!1})):e({error:i,isLoading:!1,isAuthenticated:!!s})}},checkAuthStatus:async()=>{{te.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:te},Symbol.toStringTag,{value:"Module"}));function cn(){return!1}const ue=at()(gs(nt(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:cn()}));function y(...e){return vs(ys(e))}const un=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"}}),L=m.forwardRef(({className:e,variant:t,size:s,asChild:a=!1,icon:i,loading:n=!1,children:o,disabled:c,...l},f)=>{const u=a?xs:"button",d=c||n;return r.jsx(u,{className:y(un({variant:t,size:s,className:e}),n&&"opacity-70"),ref:f,disabled:d,...l,children:a?o:r.jsxs(r.Fragment,{children:[n&&r.jsx(ye,{className:"mr-2 h-4 w-4 animate-spin"}),!n&&i&&r.jsx("span",{className:"flex items-center justify-center pointer-events-none","aria-hidden":"true",children:i}),o]})})});L.displayName="Button";let dn=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(Me,{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(L,{onClick:this.handleReset,className:"gap-2",children:[r.jsx(kr,{className:"h-4 w-4"})," Try again"]}),r.jsxs(L,{variant:"outline",onClick:()=>window.location.href="/",className:"gap-2",children:[r.jsx(Er,{className:"h-4 w-4"})," Go home"]})]})]}):this.props.children}};const mn=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 zt({className:e,variant:t,padding:s,spotlight:a,spotlightColor:i="rgba(255, 255, 255, 0.1)",...n}){const o=m.useRef(null),[c,l]=m.useState({x:0,y:0}),[f,u]=m.useState(0),d=w=>{if(!o.current||t!=="spotlight"&&!a)return;const j=o.current.getBoundingClientRect();l({x:w.clientX-j.left,y:w.clientY-j.top})},h=()=>{u(1)},v=()=>{u(0)},p=t==="spotlight"||a;return r.jsxs("div",{ref:o,onMouseMove:d,onMouseEnter:h,onMouseLeave:v,"data-slot":"card",className:y(mn({variant:t,padding:s}),e),...n,children:[p&&r.jsx("div",{className:"pointer-events-none absolute -inset-px opacity-0 transition duration-[var(--sumi-duration-normal)]",style:{opacity:f,background:`radial-gradient(600px circle at ${c.x}px ${c.y}px, ${i}, transparent 40%)`}}),r.jsx("div",{className:"relative z-10 w-full h-full flex flex-col",children:n.children})]})}function ac({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 nc({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 ic({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 oc({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 fn={success:Es,error:Ee,warning:Me,info:it},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 hn({toast:e,onDismiss:t}){const[s,a]=m.useState(!1),[i,n]=m.useState(!1),o=m.useCallback(()=>{n(!0),setTimeout(()=>{t(e.id)},300)},[e.id,t]);m.useEffect(()=>{requestAnimationFrame(()=>a(!0));const f=e.duration??lr;let u=null;return f>0&&(u=setTimeout(()=>{o()},f)),()=>{u&&clearTimeout(u)}},[e.duration,e.id,o]);const c=e.type?fn[e.type]:it,l=e.type?or[e.type]:or.info;return r.jsxs(zt,{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&&!i?"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&&!i?"w-full":"w-0"),style:{transitionDuration:`${(e.duration||lr)-300}ms`}})]})}const Kr=m.createContext(void 0);function pn(){const e=m.useContext(Kr);if(!e)throw new Error("useToastContext must be used within ToastProvider");return e}function lc(){const e=pn();return{...e,addToast:(s,a)=>{typeof s=="string"?e.addToast({message:s,type:a||"info"}):e.addToast(s)}}}const gn={"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 vn({children:e,position:t="top-right",className:s}){const[a,i]=m.useState([]),n=m.useCallback(l=>{const f=`toast-${Date.now()}-${Math.random().toString(36).substr(2,9)}`,u={...l,id:f};i(d=>[...d,u])},[]),o=m.useCallback(l=>{i(f=>f.filter(u=>u.id!==l))},[]),c={toasts:a,addToast:n,removeToast:o};return r.jsxs(Kr.Provider,{value:c,children:[e,r.jsx("div",{className:y("fixed z-50 flex flex-col gap-2",gn[t],s),children:a.map(l=>r.jsx(hn,{toast:l,onDismiss:o},l.id))})]})}function Hr(){const e=m.useRef(null),{theme:t}=ue();return m.useEffect(()=>{const s=e.current;if(!s)return;const a=s.getContext("2d");if(!a)return;const i=document.documentElement.classList.contains("light");let n,o=[];const c=window.innerWidth<768?20:50,l=150,f=i?"14, 165, 233":"102, 252, 241",u=i?"148, 163, 184":"102, 252, 241",d=()=>{s.width=window.innerWidth,s.height=window.innerHeight},h=()=>{o=[];for(let p=0;p<c;p++)o.push({x:Math.random()*s.width,y:Math.random()*s.height,size:Math.random()*(i?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(${f}, ${p.opacity})`,a.fill();for(let E=w+1;E<o.length;E++){const j=o[E];if(!j)continue;const S=p.x-j.x,I=p.y-j.y,A=Math.sqrt(S*S+I*I);if(A<l){a.beginPath();const b=i?.05:.1;a.strokeStyle=`rgba(${u}, ${b*(1-A/l)})`,a.lineWidth=.5,a.moveTo(p.x,p.y),a.lineTo(j.x,j.y),a.stroke()}}}),n=requestAnimationFrame(v)};return window.addEventListener("resize",d),d(),h(),v(),()=>{window.removeEventListener("resize",d),cancelAnimationFrame(n)}},[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 yn(){const[e,t]=m.useState(()=>typeof navigator<"u"?navigator.onLine:!0);return m.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 Ft=null,rt=null;const xn=3e4;function bn(e){const t=ut(e);(t==="network"||t==="timeout")&&(Ft=e instanceof Error||e&&typeof e=="object"&&"message"in e?e:new Error(String(e)),rt=Date.now())}function Wr(){Ft=null,rt=null}function Gr(){return!Ft||!rt?!1:Date.now()-rt>xn?(Wr(),!1):!0}const wn=Object.freeze(Object.defineProperty({__proto__:null,clearNetworkError:Wr,hasRecentNetworkError:Gr,recordNetworkError:bn},Symbol.toStringTag,{value:"Module"}));function Vt({children:e,active:t=!0,onEscape:s}){const a=m.useRef(null),i=m.useRef(null);return m.useEffect(()=>{if(!t||!a.current)return;i.current=document.activeElement;const n=a.current.querySelectorAll('button, [href], input, select, textarea, [tabindex]:not([tabindex="-1"])'),o=n[0],c=n[n.length-1];o&&o.focus();const l=f=>{if(f.key==="Escape"){s?.();return}f.key==="Tab"&&(f.shiftKey?document.activeElement===o&&(f.preventDefault(),c?.focus()):document.activeElement===c&&(f.preventDefault(),o?.focus()))};return document.addEventListener("keydown",l),()=>{document.removeEventListener("keydown",l),i.current instanceof HTMLElement&&i.current.focus()}},[t,s]),r.jsx("div",{ref:a,tabIndex:-1,children:e})}const kn={alert:Ee,confirm:Ee,info:it,default:void 0},En={alert:"text-destructive",confirm:"text-primary",info:"text-muted-foreground",default:""},Sn={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 Xr({open:e,onClose:t,onOpenChange:s,title:a,children:i,footer:n,variant:o="default",onConfirm:c,onCancel:l,confirmLabel:f="Confirm",cancelLabel:u="Cancel",showCancel:d=!0,size:h="md",className:v,closeOnOverlayClick:p,closeOnEscape:w=!0}){const E=m.useId(),j=()=>{s?s(!1):t&&t()},S=async()=>{c&&await c(),j()},I=()=>{l&&l(),j()};m.useEffect(()=>{if(e)return document.body.style.overflow="hidden",()=>{document.body.style.overflow=""}},[e]),m.useEffect(()=>{if(!w||!e)return;const N=C=>{C.key==="Escape"&&j()};return document.addEventListener("keydown",N),()=>document.removeEventListener("keydown",N)},[e,w]);const A=p??o==="default",b=N=>{A&&N.target===N.currentTarget&&j()},_=kn[o],W=En[o],k=n||c||l?n||r.jsxs("div",{className:"flex justify-end gap-2",children:[d&&r.jsx(L,{variant:"outline",onClick:I,children:u}),c&&r.jsx(L,{variant:o==="alert"?"destructive":"default",onClick:S,children:f})]}):void 0;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:b,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(Vt,{children:r.jsxs(we.div,{role:"dialog","aria-modal":"true","aria-labelledby":a?E: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",Sn[h]??"max-w-md",v),onClick:N=>N.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:E,className:"font-bold text-foreground text-lg font-heading",children:a}),r.jsx(L,{variant:"ghost",size:"icon",onClick:j,className:"ml-auto","aria-label":"Fermer",children:r.jsx(he,{className:"w-5 h-5"})})]}),r.jsxs("div",{className:"p-8 overflow-y-auto custom-scrollbar flex-1",children:[a&&_&&r.jsx("div",{className:"flex items-center gap-4 mb-4",children:r.jsx(_,{className:y("h-5 w-5",W)})}),i]}),k&&r.jsx("div",{className:"p-4 border-t border-border bg-card shrink-0 flex justify-end gap-4",children:k})]})})]},"dialog")}),document.body)}const Nn=m.forwardRef(({variant:e="rectangular",width:t,height:s,className:a,...i},n)=>{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:n,className:y(o,c[e],a),style:l,"aria-hidden":"true",...i,children:r.jsx("div",{className:"absolute inset-0 skeleton-shimmer"})})});Nn.displayName="Skeleton";function jn(e){return new Date(e).toLocaleString()}function _n(e){const t=e.config.method?.toUpperCase()||"UNKNOWN",s=e.config.url||"Unknown URL";return`${t} ${s}`}function Tn(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]=m.useState([]),[i,n]=m.useState(null),[o,c]=m.useState(!1);m.useEffect(()=>{if(!e)return;const u=()=>{a(me.getQueue())};u();const d=setInterval(u,1e3);return()=>clearInterval(d)},[e]);const l=async u=>{n(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{n(null)}},f=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(Re,{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(L,{variant:"destructive",size:"sm",onClick:f,disabled:o,children:[r.jsx(Ss,{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:_n(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",Tn(u.priority)),children:u.priority}),r.jsxs("span",{className:"flex items-center gap-1",children:[r.jsx(Re,{className:"w-3 h-3"}),jn(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(L,{variant:"ghost",size:"icon",onClick:()=>l(u.id),disabled:i===u.id,className:"shrink-0",children:i===u.id?r.jsx(Re,{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 Cn(){const e=yn(),[t,s]=m.useState(0),[a,i]=m.useState(!1),[n,o]=m.useState(!1),[c,l]=m.useState(!1),[f,u]=m.useState(!1);return m.useEffect(()=>{const d=()=>{const v=me.getQueueSize();s(v)};d();const h=setInterval(d,1e3);return()=>clearInterval(h)},[]),m.useEffect(()=>{if(e&&t>0){i(!0);const d=setInterval(()=>{me.getQueueSize()===0&&(i(!1),clearInterval(d))},500);return()=>clearInterval(d)}else{i(!1);return}},[e,t]),m.useEffect(()=>{const d=()=>{o(Gr())};d();const h=setInterval(d,2e3);return()=>clearInterval(h)},[]),m.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&&!n?null:!e||n?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(js,{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&&f?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 Rn(e,t){const s=B(e),a=ut(s),i=typeof navigator<"u"?navigator.userAgent:"Unknown",n=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:** ${n}`),l.push(`**User Agent:** ${i}`),l.push(`**Browser:** ${In(i)}`),l.push(`**Platform:** ${Ln(i)}`),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 f=l.join(`
`);return{title:c,body:f,metadata:{requestId:s.request_id,errorCode:s.code,statusCode:s.code,category:a,timestamp:o,userAgent:i,url:n}}}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 An(e,t){const s=Pn();if(!s){Yr(e);return}const a=new URLSearchParams({title:e.title,body:e.body}),i=`${s}/issues/new?${a.toString()}`;window.open(i,"_blank")}function Pn(){return null}function In(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 Ln(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 Dn(e){if(typeof e=="string")return{message:e};if(e instanceof Error)return{message:e.message,stack:e.stack};if(e&&typeof e=="object")try{const t=B(e);return{message:t.message||"An error occurred",code:t.code,status:typeof t.code=="number"?t.code:void 0,details:t.details}}catch{return{message:e.message||String(e),code:e.code,status:e.status,details:e.details}}return{message:String(e)}}const Jr=m.forwardRef(({error:e,onRetry:t,onDismiss:s,showDetails:a,context:i,variant:n="inline",severity:o="error",size:c="md",className:l,dismissible:f,title:u,icon:d,actions:h=[],...v},p)=>{const[w,E]=m.useState(!1),[j,S]=m.useState(!1),[I,A]=m.useState(!0),b=m.useMemo(()=>Dn(e),[e]),_=m.useMemo(()=>B(e),[e]),W=m.useMemo(()=>ut(_),[_]),k=m.useMemo(()=>W==="server_error"||b.status!==void 0&&b.status>=500,[W,e]),C=a??!1,O=m.useMemo(()=>{if(b.message)try{return Or(b,i?.resource,!1)}catch{return b.message}return"An unexpected error occurred"},[b,i]),V=m.useMemo(()=>{if(u)return u;if(i?.action)return`Error ${i.action}`;switch(o){case"error":return"Error";case"warning":return"Warning";case"info":return"Information";default:return"Error"}},[u,i,o]),Z=m.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(Me,{className:y(U,"text-warning")});case"info":return r.jsx(it,{className:y(U,"text-info")});default:return r.jsx(Ee,{className:y(U,"text-destructive")})}},[d,o,c]),G=m.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=m.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=m.useCallback(async()=>{if(!(!t||j)){S(!0);try{await t()}finally{S(!1)}}},[t,j]),je=m.useCallback(()=>{s&&s(),n==="modal"&&A(!1)},[s,n]),ft=m.useCallback(async()=>{try{const U=Rn(e,{component:i?.resource,action:i?.action,userId:i?.userId,additionalInfo:i});try{An(U),K.success("Opening GitHub issue...")}catch{await Yr(U),K.success("Issue report copied to clipboard")}}catch{K.error("Failed to generate issue report")}},[e,i]),ht=m.useCallback(async()=>{if(_.request_id)try{await navigator.clipboard.writeText(_.request_id),K.success("Request ID copied to clipboard")}catch{K.error("Failed to copy request ID")}},[_.request_id]),pt=f??(s!==void 0||n==="modal"),Ue=()=>{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}),i&&U.push({label:"Context",value:JSON.stringify(i,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",G.bg,G.border,G.text,Y.padding,Y.gap,l),...v,children:[r.jsx("div",{className:"flex-shrink-0 pt-0.5",children:Z}),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}),Ue(),(t||h.length>0||k||C&&(b.code||b.details||b.stack||i))&&r.jsxs("div",{className:"mt-4 flex flex-wrap gap-2 items-center",children:[t&&r.jsx(L,{variant:"outline",size:c==="sm"?"sm":"default",onClick:re,disabled:j,className:"border-current text-current hover:bg-current/10 bg-transparent",children:j?"Retrying...":"Retry"}),k&&_.request_id&&r.jsxs(r.Fragment,{children:[r.jsxs(L,{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(_s,{className:"w-4 h-4 mr-1.5"}),"Copy ID"]}),r.jsxs(L,{variant:"outline",size:c==="sm"?"sm":"default",onClick:ft,className:"border-current text-current hover:bg-current/10 bg-transparent",children:[r.jsx(Ts,{className:"w-4 h-4 mr-1.5"}),"Report"]})]}),h.map((U,le)=>r.jsx(L,{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||i)&&r.jsx(L,{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(Cs,{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:je,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(n){case"banner":return r.jsx("div",{className:"w-full",children:_e});case"card":return r.jsx(zt,{className:y(G.border,l,"glass"),children:r.jsx(Br,{className:y(Y.padding,"pt-6"),children:_e})});case"modal":return r.jsx(Xr,{open:I,onClose:je,title:V,variant:o==="error"?"alert":"default",footer:r.jsxs("div",{className:"flex gap-2 justify-end",children:[t&&r.jsx(L,{variant:"outline",onClick:re,disabled:j,children:j?"Retrying...":"Retry"}),h.map((U,le)=>r.jsx(L,{variant:U.variant||"outline",onClick:U.onClick,children:U.label},le)),r.jsx(L,{variant:"default",onClick:je,children:t?"Close":"Dismiss"})]}),children:r.jsxs("div",{className:y(G.text),children:[r.jsx("div",{className:y("opacity-90 mb-4",Y.text),children:O}),Ue()]})});default:return _e}});Jr.displayName="ErrorDisplay";class Se extends m.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=ga(),i={...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",i),typeof window<"u"&&bs(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}=te();return br({queryKey:["user","me"],queryFn:Ot,enabled:e,retry:!1,staleTime:300*1e3,gcTime:600*1e3})}const es=()=>{const{isAuthenticated:e,logout:t}=te(),{data:s}=Zr();return{user:s??null,accessToken:null,refreshToken:null,isAuthenticated:e,logout:async()=>{await t()}}};function qn({children:e}){const{isAuthenticated:t}=es(),[s,a]=m.useState(!0),i=!1,{isLoading:n}=te();return m.useEffect(()=>{const c=setTimeout(()=>{a(!1)},200);return()=>clearTimeout(c)},[]),s||n?null:t||i?r.jsx(r.Fragment,{children:e}):r.jsx(Ze,{to:"/login",replace:!0})}function Mn(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(Me,{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:Mn(t)}),r.jsxs("div",{className:"flex flex-col gap-3",children:[s&&r.jsxs(L,{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(L,{onClick:()=>window.location.reload(),variant:"default",className:"w-full flex items-center justify-center gap-2",children:"Refresh Page"})]})]})})}class On extends m.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 zn={default:"text-primary",muted:"text-muted-foreground",white:"text-foreground",current:"text-current"},Fn={sm:"h-4 w-4",md:"h-8 w-8",lg:"h-12 w-12"},Vn={sm:"h-4 w-4",md:"h-5 w-5",lg:"h-6 w-6"};function Un({size:e="md",className:t,text:s,inline:a=!1,variant:i="default","aria-label":n="Chargement en cours"}){return a?r.jsxs(r.Fragment,{children:[r.jsx(ye,{className:y("animate-spin",Vn[e],zn[i],t),"aria-hidden":"true"}),r.jsx("span",{className:"sr-only",children:n})]}):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",Fn[e]),role:"status","aria-label":n,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 $n(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?()=>$n(e,s):e,i=m.lazy(a);return function(o){const{fallback:c,...l}=o,f=r.jsx(m.Suspense,{fallback:r.jsx(Un,{}),children:r.jsx(i,{...l})});return s?r.jsx(On,{pageName:s,children:f}):f}}const Qn=q(()=>T(()=>import("./DashboardPage-B-iSrgp-.js"),__vite__mapDeps([4,1,0,2,3,5,6,7,8,9,10,11,12,13])),void 0,"Dashboard"),Bn=q(()=>T(()=>import("./ChatPage-CblRq44g.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"),Kn=q(()=>T(()=>import("./LibraryPage-_jEblTu2.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"),Hn=q(()=>T(()=>import("./UserProfilePage-CQ7fZ2k2.js"),__vite__mapDeps([27,1,0,2,3,6,28,11,23,24,29,30,31,5,10,32,12,20,9,33,8,13])).then(e=>({default:e.UserProfilePage})),void 0,"Profile"),Wn=q(()=>T(()=>import("./SettingsPage-CSSzd1W-.js"),__vite__mapDeps([34,1,0,2,3,28,11,33,15,10,16,17,8,35,26,31,12,5,6,13])).then(e=>({default:e.SettingsPage})),void 0,"Settings"),Gn=q(()=>T(()=>import("./LoginPage-p0io7VQ6.js"),__vite__mapDeps([36,1,0,2,3,5,6,37,10,38,15,26,35,11,12,8,13])),void 0,"Login"),Xn=q(()=>T(()=>import("./RegisterPage-BDtil_L9.js"),__vite__mapDeps([39,1,0,2,3,38,5,6,35,10,37,40,11,12,8,13])),void 0,"Register"),Yn=q(()=>T(()=>import("./ForgotPasswordPage-ReoHn_Ds.js"),__vite__mapDeps([41,1,0,2,3,5,38,37,10,42,6,11,12,8,13])),void 0,"Forgot Password"),Jn=q(()=>T(()=>import("./VerifyEmailPage-D6Xy8Bf-.js"),__vite__mapDeps([43,1,0,2,3,5,38,6,11,12,10,8,13])),void 0,"Verify Email"),Zn=q(()=>T(()=>import("./ResetPasswordPage-GoxeiCUp.js"),__vite__mapDeps([44,1,0,2,3,5,38,37,10,40,42,6,11,12,8,13])),void 0,"Reset Password"),ei=q(()=>T(()=>import("./SessionsPage-Bf46A7Ge.js"),__vite__mapDeps([45,1,0,2,3,19,10,5,6,11,12,8,13])),void 0,"Sessions"),ti=q(()=>T(()=>import("./NotFoundPage-Clc8zsY1.js"),__vite__mapDeps([46,1,0,2,3,5,10,6,11,12,8,13])),void 0,"Not Found"),ri=q(()=>T(()=>import("./ServerErrorPage-KZ-LUqM6.js"),__vite__mapDeps([47,1,0,2,3,5,10,6,11,12,8,13])),void 0,"Server Error"),si=q(()=>T(()=>import("./UserProfilePage-CQ7fZ2k2.js"),__vite__mapDeps([27,1,0,2,3,6,28,11,23,24,29,30,31,5,10,32,12,20,9,33,8,13])).then(e=>({default:e.UserProfilePage})),void 0,"User Profile"),ai=q(()=>T(()=>import("./RolesPage-CkteR03X.js"),__vite__mapDeps([48,1,0,2,3,11,31,15,10,49,16,17,8,5,6,12,13])).then(e=>({default:e.RolesPage})),void 0,"Roles"),ni=q(()=>T(()=>import("./TrackDetailPage-anfAR6Sx.js"),__vite__mapDeps([50,1,0,2,3,6,11,24,18,17,8,10,33,20,15,19,12,23,51,26,5,13])).then(e=>({default:e.TrackDetailPage})),void 0,"Track Detail"),ii=q(()=>T(()=>import("./routes-DOpzcRDM.js"),__vite__mapDeps([52,1,0,2,3,22,8,6,30,31,29,5,10,53,12,15,49,35,16,17,20,19,33,54,11,13,55])).then(e=>({default:e.PlaylistRoutes})),void 0,"Playlists"),oi=q(()=>T(()=>import("./AdminDashboardView-CyXR3eeG.js"),__vite__mapDeps([56,1,0,2,3,10,9,33,8,5,6,11,12,13])).then(e=>({default:e.AdminDashboardView})),void 0,"Admin Dashboard"),li=q(()=>T(()=>import("./AnalyticsView-DOCH2HDI.js"),__vite__mapDeps([57,1,0,2,3,10,58,9,5,6,11,12,8,13])).then(e=>({default:e.AnalyticsView})),void 0,"Analytics"),ci=q(()=>T(()=>import("./WebhooksView-BNyrs3j-.js"),__vite__mapDeps([59,1,0,2,3,15,10,60,5,6,11,12,8,13])).then(e=>({default:e.WebhooksView})),void 0,"Webhooks"),ui=q(()=>T(()=>import("./DesignSystemDemo-evd169sp.js"),__vite__mapDeps([61,1,0,2,3])).then(e=>({default:e.DesignSystemDemo})),void 0,"Design System Demo"),di=q(()=>T(()=>import("./SocialView-Btb90uBJ.js"),__vite__mapDeps([62,1,0,2,3,24,11,10,20,8,5,6,12,13])).then(e=>({default:e.SocialView})),void 0,"Social"),mi=q(()=>T(()=>import("./GearView-ZVOHN4tS.js"),__vite__mapDeps([63,1,0,2,3,10,15,5,6,11,12,8,13])).then(e=>({default:e.GearView})),void 0,"Gear"),fi=q(()=>T(()=>import("./LiveView-CfyW_3Yz.js"),__vite__mapDeps([64,1,0,2,3,10,8,5,6,11,12,13])).then(e=>({default:e.LiveView})),void 0,"Live"),hi=q(()=>T(()=>import("./EducationView-CbR_C7CK.js"),__vite__mapDeps([65,1,0,2,3,25,10,15,8,5,6,11,12,13])).then(e=>({default:e.EducationView})),void 0,"Education"),pi=q(()=>T(()=>import("./QueueView-C0ORvlAn.js"),__vite__mapDeps([66,1,0,2,3,15,10,30,31,5,6,11,12,8,13])).then(e=>({default:e.QueueView})),void 0,"Queue"),gi=q(()=>T(()=>import("./DeveloperDashboardView-B2Z9Gz1F.js"),__vite__mapDeps([67,1,0,2,3,58,9,10,15,51,60,33,5,6,11,12,8,13])).then(e=>({default:e.DeveloperDashboardView})),void 0,"Developer"),vi=q(()=>T(()=>import("./NotificationsView-DR29OiUl.js"),__vite__mapDeps([68,1,0,2,3,10,32,5,6,11,12,8,13])).then(e=>({default:e.NotificationsView})),void 0,"Notifications"),yi=q(()=>T(()=>import("./MarketplaceHome-DLm6-klV.js"),__vite__mapDeps([69,1,0,2,3,70,10,15,71,8,53,5,6,11,12,13])).then(e=>({default:e.MarketplaceHome})),void 0,"Marketplace"),xi=q(()=>T(()=>import("./SearchPage-B5C5XA5d.js"),__vite__mapDeps([72,1,0,2,3,5,54,10,33,20,12,6,11,8,13])).then(e=>({default:e.SearchPage})),void 0,"Search"),bi=q(()=>T(()=>import("./SellerDashboardView-DWQLxmBy.js"),__vite__mapDeps([73,1,0,2,3,10,70,74,5,6,11,12,8,13])).then(e=>({default:e.SellerDashboardView})),void 0,"Seller Dashboard"),wi=q(()=>T(()=>import("./WishlistView-DGHnFMPQ.js"),__vite__mapDeps([75,1,0,2,3,71,6,70,10,8,5,11,12,13])).then(e=>({default:e.WishlistView})),void 0,"Wishlist"),ki=q(()=>T(()=>import("./PurchasesView-E5u00cpv.js"),__vite__mapDeps([76,1,0,2,3,10,74,15,8,5,6,11,12,13])).then(e=>({default:e.PurchasesView})),void 0,"Purchases");function Ei({children:e}){const{isAuthenticated:t}=es(),s=!1,{isLoading:a}=te();return a?null:t||s?r.jsx(Ze,{to:"/dashboard",replace:!0}):r.jsx(r.Fragment,{children:e})}function Si(){const{i18n:e,t}=qt(),{language:s,setLanguage:a}=ue(),i=n=>{e.changeLanguage(n),a(n)};return{t,i18n:{...e,changeLanguage:async n=>{await e.changeLanguage(n)},isInitialized:e.isInitialized},language:s,changeLanguage:i,isReady:e.isInitialized}}function Ni({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 Le?new Error(t.response?.data?.error||t.message||"Failed to fetch notifications"):t}}async function _i(e){try{await F.post(`/notifications/${e}/read`)}catch(t){throw t instanceof Le?new Error(t.response?.data?.error||t.message||"Failed to mark notification as read"):t}}async function Ti(){try{await F.post("/notifications/read-all")}catch(e){throw e instanceof Le?new Error(e.response?.data?.error||e.message||"Failed to mark all notifications as read"):e}}function Ci(){return{success:(e,t)=>K.success(e,{duration:t}),error:(e,t)=>K.error(e,{duration:t}),warning:(e,t)=>K(e,{icon:"⚠️",duration:t}),info:(e,t)=>K(e,{icon:"",duration:t}),toast:e=>{const t={duration:e.duration};switch(e.type){case"success":K.success(e.message,t);break;case"error":K.error(e.message,t);break;case"warning":K(e.message,{...t,icon:"⚠️"});break;default:K(e.message,t)}}}}const Ri=3e4,Ai=50;function Pi(e){const[t,s]=m.useState(!1),a=m.useRef(null),i=st(),n=At(),{success:o,error:c}=Ci(),l=br({queryKey:["notifications","menu"],queryFn:()=>ji({limit:Ai}),refetchInterval:Ri,staleTime:1e4,enabled:e?.notificationsOverride===void 0&&e?.isLoadingOverride===void 0&&e?.errorOverride===void 0}),f=e?.notificationsOverride!==void 0?e.notificationsOverride??[]:l.data?.notifications??[],u=e?.isLoadingOverride??l.isLoading,d=e?.errorOverride!==void 0?e.errorOverride:l.error?String(l.error):null,h=f.filter(b=>!b.read).length,v=l.refetch,p=["notifications","menu"],w=Bt({mutationFn:_i,onMutate:async b=>{await n.cancelQueries({queryKey:p});const _=n.getQueryData(p);return _&&n.setQueryData(p,{..._,notifications:_.notifications.map(W=>W.id===b?{...W,read:!0}:W),unreadCount:Math.max((_.unreadCount??1)-1,0)}),{previous:_}},onError:(b,_,W)=>{W?.previous&&n.setQueryData(p,W.previous),c("Erreur lors du marquage")},onSuccess:()=>{n.invalidateQueries({queryKey:p})}}),E=Bt({mutationFn:Ti,onMutate:async()=>{await n.cancelQueries({queryKey:p});const b=n.getQueryData(p);return b&&n.setQueryData(p,{...b,notifications:b.notifications.map(_=>({..._,read:!0})),unreadCount:0}),{previous:b}},onError:(b,_,W)=>{W?.previous&&n.setQueryData(p,W.previous),c("Erreur lors du marquage")},onSuccess:()=>{n.invalidateQueries({queryKey:p}),o("Toutes les notifications ont été marquées comme lues")}});m.useEffect(()=>{function b(_){a.current&&!a.current.contains(_.target)&&s(!1)}return t&&document.addEventListener("mousedown",b),()=>document.removeEventListener("mousedown",b)},[t]),m.useEffect(()=>{t&&v()},[t,v]);const j=m.useCallback(b=>w.mutate(b),[w]),S=m.useCallback(()=>E.mutate(),[E]),I=m.useCallback(b=>{b.read||j(b.id),b.link&&(i(b.link),s(!1))},[j,i]),A=m.useCallback(()=>{i("/notifications"),s(!1)},[i]);return{menuRef:a,isOpen:t,setIsOpen:s,notifications:f,isLoading:u,error:d,unreadCount:h,handleMarkAsRead:j,handleMarkAllAsRead:S,handleNotificationClick:I,handleViewAll:A,markAsReadMutation:w,markAllAsReadMutation:E}}function Ii({isOpen:e,unreadCount:t,onClick:s}){return r.jsxs(L,{variant:"ghost",size:"icon",className:"relative",onClick:s,"aria-label":"Notifications","aria-expanded":e,"aria-haspopup":"true",children:[r.jsx(Nr,{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 Li({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:ws(new Date(e.created_at),{addSuffix:!0,locale:ks})})]}),r.jsx("div",{className:"flex items-center space-x-1 ml-2 shrink-0",children:!e.read&&r.jsx(L,{variant:"ghost",size:"icon",className:"h-6 w-6",onClick:i=>{i.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(Rs,{className:"h-3 w-3"})})})]})})}const rs=Rt.memo(Li);rs.displayName="NotificationMenuItem";function Di({isLoading:e,error:t,notifications:s,onMarkAsRead:a,onNotificationClick:i,isMarkingAsRead:n}){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(Nr,{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(rs,{notification:o,onMarkAsRead:a,onClick:i,isMarking:n})},o.id))})}function qi({unreadCount:e,notifications:t,isLoading:s,onMarkAllAsRead:a,onMarkAsRead:i,onNotificationClick:n,onViewAll:o,markAllPending:c,markPending:l,error:f}){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(L,{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(As,{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(Di,{isLoading:s,error:f??null,notifications:t,onMarkAsRead:i,onNotificationClick:n,isMarkingAsRead:l})}),t.length>0&&r.jsx("div",{className:"p-4 border-t shrink-0",children:r.jsx(L,{variant:"ghost",size:"sm",className:"w-full",onClick:o,children:"Voir toutes les notifications"})})]})}function Mi({isLoadingOverride:e,errorOverride:t,notificationsOverride:s}={}){const{menuRef:a,isOpen:i,setIsOpen:n,notifications:o,isLoading:c,error:l,unreadCount:f,handleMarkAsRead:u,handleMarkAllAsRead:d,handleNotificationClick:h,handleViewAll:v,markAsReadMutation:p,markAllAsReadMutation:w}=Pi({isLoadingOverride:e,errorOverride:t,notificationsOverride:s??void 0});return r.jsxs("div",{className:"relative",ref:a,children:[r.jsx(Ii,{isOpen:i,unreadCount:f,onClick:()=>n(!i)}),r.jsx(Dt,{children:i&&r.jsx(qi,{unreadCount:f,notifications:o,isLoading:c,error:l,onMarkAllAsRead:d,onMarkAsRead:u,onNotificationClick:h,onViewAll:v,markAllPending:w.isPending,markPending:p.isPending})})]})}function Oi(){const{limit:e,remaining:t,reset:s,isLimited:a}=jt(),[i,n]=m.useState(null);m.useEffect(()=>{if(!s){n(null);return}const u=()=>{const h=Math.floor(Date.now()/1e3),v=s-h;n(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),h=u%60;if(d<60)return h>0?`${d}m ${h}s`:`${d}m`;const v=Math.floor(d/60),p=d%60;return p>0?`${v}h ${p}m`:`${v}h`},f=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",f?"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(Me,{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"}),i!==null&&r.jsxs("span",{className:"flex items-center gap-1",children:[r.jsx(Re,{className:"w-3 h-3"}),l(i)]})]}):r.jsxs(r.Fragment,{children:[r.jsx("span",{children:t!==null?`${t}/${e} requests`:`${e} requests`}),i!==null&&r.jsxs("span",{className:"flex items-center gap-1 opacity-75",children:[r.jsx(Re,{className:"w-3 h-3"}),"resets in ",l(i)]})]})})]})}function zi(e,t,s,a){const[i,n]=m.useState(!1),[o,c]=m.useState(!1),[l,f]=m.useState(e),[u,d]=m.useState({}),h=m.useRef(null),v=m.useRef(null),p=m.useRef(null),w=m.useRef(null),E=m.useCallback(()=>{if(!p.current||!w.current||!i)return;const b=p.current.getBoundingClientRect(),_=w.current.getBoundingClientRect(),W=window.innerWidth,k=window.innerHeight,N=8;let C=e,O=0,V=0;switch(e){case"top":b.top-_.height-N<0&&(C="bottom");break;case"bottom":b.bottom+_.height+N>k&&(C="top");break;case"left":b.left-_.width-N<0&&(C="right");break;case"right":b.right+_.width+N>W&&(C="left");break}if(C==="top"||C==="bottom"){const Z=b.left+b.width/2,G=_.width/2,Y=N,re=W-N;Z-G<Y?O=Y-(Z-G):Z+G>re&&(O=re-(Z+G))}else{const Z=b.top+b.height/2,G=_.height/2,Y=N,re=k-N;Z-G<Y?V=Y-(Z-G):Z+G>re&&(V=re-(Z+G))}f(C),d({...O!==0&&{transform:`translate(calc(-50% + ${O}px), 0)`},...V!==0&&{transform:`translate(0, calc(-50% + ${V}px))`}})},[e,i]);m.useEffect(()=>{i&&E()},[i,E]),m.useEffect(()=>{o&&i&&E()},[o,i,E]);const j=m.useCallback(()=>{h.current&&clearTimeout(h.current),h.current=setTimeout(()=>{n(!0),c(!0)},s)},[s]),S=m.useCallback(()=>{h.current&&clearTimeout(h.current),v.current&&clearTimeout(v.current),v.current=setTimeout(()=>{n(!1)},100)},[]),I=m.useCallback(()=>{t==="click"&&n(b=>{const _=!b;return _&&c(!0),_})},[t]),A=t==="hover"?{onMouseEnter:j,onMouseLeave:S}:t==="click"?{onClick:I}:{onFocus:j,onBlur:S};return m.useEffect(()=>()=>{h.current&&clearTimeout(h.current),v.current&&clearTimeout(v.current)},[]),{visible:i,isMounted:o,calculatedPosition:l,tooltipStyle:u,wrapperRef:p,tooltipRef:w,triggerProps:a?{}:A}}const Fi={top:"bottom-full left-1/2 -translate-x-1/2 mb-2",bottom:"top-full left-1/2 -translate-x-1/2 mt-2",left:"right-full top-1/2 -translate-y-1/2 mr-2",right:"left-full top-1/2 -translate-y-1/2 ml-2"},Vi={top:"top-full left-1/2 -translate-x-1/2 border-t-card border-l-transparent border-r-transparent border-b-transparent",bottom:"bottom-full left-1/2 -translate-x-1/2 border-b-card border-l-transparent border-r-transparent border-t-transparent",left:"left-full top-1/2 -translate-y-1/2 border-l-card border-t-transparent border-b-transparent border-r-transparent",right:"right-full top-1/2 -translate-y-1/2 border-r-card border-t-transparent border-b-transparent border-l-transparent"};function Ui({content:e,visible:t,calculatedPosition:s,tooltipStyle:a,tooltipRef:i,showArrow:n,maxWidth:o,className:c}){return r.jsxs("div",{ref:i,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)]",Fi[s],t?"opacity-100 scale-100":"opacity-0 scale-95",c),role:"tooltip",style:{...o!=null&&{maxWidth:`${o}px`},...a},children:[e,n&&r.jsx("div",{className:y("absolute w-0 h-0 border-4",Vi[s])})]})}function ce({content:e,children:t,position:s="top",trigger:a="hover",delay:i=200,showArrow:n=!0,maxWidth:o,disabled:c=!1,className:l}){const{visible:f,isMounted:u,calculatedPosition:d,tooltipStyle:h,wrapperRef:v,tooltipRef:p,triggerProps:w}=zi(s,a,i,c);if(c)return r.jsx(r.Fragment,{children:t});const E=a==="hover",j=E?w:{},S=!E&&m.isValidElement(t)&&m.Children.only(t)?m.cloneElement(t,w):t;return r.jsxs("div",{ref:v,className:"relative inline-block",...j,children:[S,u&&r.jsx(Ui,{content:e,visible:f,calculatedPosition:d,tooltipStyle:h,tooltipRef:p,showArrow:n,maxWidth:o,className:l})]})}function $i(e){const[t,s]=m.useState(!1),{logout:a}=te(),{data:i}=Zr(),{theme:n,setTheme:o,sidebarOpen:c,setSidebarOpen:l}=ue(),{t:f}=Si(),u=st(),d=async()=>{await a(),u("/login")},h=()=>{o(n==="light"?"dark":n==="dark"?"system":"light")},v=()=>{switch(n){case"light":return r.jsx(Os,{className:"h-4 w-4"});case"dark":return r.jsx(Ms,{className:"h-4 w-4"});default:return r.jsx(qs,{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(Ps,{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(Is,{className:"absolute left-3 w-4 h-4 text-muted-foreground pointer-events-none"}),r.jsx("input",{type:"search",placeholder:f("header.searchPlaceholder"),"aria-label":f("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(Ls,{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:f("header.online")})]}),r.jsx(Mi,{}),r.jsx(Oi,{}),r.jsx("div",{className:"h-6 w-px bg-border mx-1","aria-hidden":!0}),r.jsx(ce,{content:f("common.changeTheme"),children:r.jsx(L,{variant:"ghost",size:"icon",onClick:h,className:"min-h-10 min-w-10 rounded-full hover:bg-muted/50 text-muted-foreground hover:text-foreground transition-colors duration-[var(--duration-fast)]",children: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:i?.username?.substring(0,2).toUpperCase()||"VZ"})}),r.jsx("span",{className:"hidden lg:block text-sm font-medium text-foreground truncate max-w-24",children:i?.username})]}),t&&r.jsx(Vt,{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:i?.username}),r.jsx("p",{className:"text-xs text-muted-foreground truncate",children:i?.email}),!i?.is_verified&&r.jsx("div",{className:"mt-2 flex justify-center",children:r.jsx(Ni,{verified:!1})})]}),r.jsxs("div",{className:"p-1 space-y-0.5",children:[r.jsxs(et,{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(Ds,{className:"w-4 h-4"})," ",f("header.profile")]}),r.jsxs(et,{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(jr,{className:"w-4 h-4"})," ",f("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"})," ",f("header.signOut")]})})]})})]})]})]})})}const Qi=1024;function Bi(){const e=st(),{logout:t}=te(),{setSidebarOpen:s}=ue(),a=m.useCallback(()=>{typeof window<"u"&&window.innerWidth<Qi&&s(!1)},[s]),i=m.useCallback(()=>{t(),e("/login")},[t,e]);return{handleMobileNav:a,handleLogout:i}}const Ki={myStudio:"nav.sections.myStudio",vezaNetwork:"nav.sections.vezaNetwork",commerce:"nav.sections.commerce",library:"nav.sections.library",system:"nav.sections.system"},Hi={dashboard:r.jsx(Er,{className:"w-4 h-4"}),tracks:r.jsx(ea,{className:"w-4 h-4"}),gear:r.jsx(Zs,{className:"w-4 h-4"}),analytics:r.jsx(Js,{className:"w-4 h-4"}),social:r.jsx(Ys,{className:"w-4 h-4"}),marketplace:r.jsx(Xs,{className:"w-4 h-4"}),live:r.jsx(Gs,{className:"w-4 h-4"}),chat:r.jsx(Ws,{className:"w-4 h-4"}),education:r.jsx(Hs,{className:"w-4 h-4"}),sell:r.jsx(Ks,{className:"w-4 h-4"}),wishlist:r.jsx(Lt,{className:"w-4 h-4"}),purchases:r.jsx(Bs,{className:"w-4 h-4"}),playlists:r.jsx(It,{className:"w-4 h-4"}),queue:r.jsx(Qs,{className:"w-4 h-4"}),developer:r.jsx($s,{className:"w-4 h-4"}),admin:r.jsx(Us,{className:"w-4 h-4"})},ur={live:3,chat:12},Wi=[{sectionKey:"myStudio",itemIds:["dashboard","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 Gi(e){return Wi.map(({sectionKey:t,itemIds:s})=>({section:e(Ki[t]??t),items:s.map(a=>({id:a,label:e(`nav.items.${a}`),icon:Hi[a],...ur[a]!=null?{badge:ur[a]}:{}}))}))}const wt={dashboard:"/dashboard",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,Xi=({currentView:e})=>{const{t}=qt(),s=ds(),{sidebarOpen:a,setSidebarOpen:i}=ue(),{handleMobileNav:n,handleLogout:o}=Bi(),c=m.useMemo(()=>Gi(t),[t]),[l,f]=m.useState(()=>typeof window<"u"?window.innerWidth<hr:!1);m.useEffect(()=>{const d=window.matchMedia(`(max-width: ${hr-1}px)`),h=()=>f(d.matches);return h(),d.addEventListener("change",h),()=>d.removeEventListener("change",h)},[]);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:()=>i(!1),"aria-hidden":"true",role:"presentation"}),r.jsx(Vt,{active:a&&l,onEscape:()=>i(!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(zs,{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(L,{variant:"ghost",size:"icon",onClick:()=>i(!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(Fs,{className:"w-4 h-4"}):r.jsx(Vs,{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,h)=>r.jsxs("div",{children:[h>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(et,{to:p,onClick:n,"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(et,{to:"/settings",onClick:n,"aria-current":u==="settings"?"page":void 0,className:y(dr,u==="settings"?fr:mr,!a&&"justify-center px-0"),children:[r.jsx(jr,{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(L,{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")})]})})]})]})})]})},Ut=at()(nt((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(),i=a.findIndex(n=>n.id===s.id);if(i>=0)e({currentTrack:s,currentIndex:i,isPlaying:!0,currentTime:0});else{const n=[...a,s];e({currentTrack:s,currentIndex:n.length-1,queue:n,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:i,shuffle:n}=t();if(s.length===0)return;let o=a;if(n)o=Math.floor(Math.random()*s.length);else if(a<s.length-1)o=a+1;else if(i==="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 i=a-1,n=s[i];n&&e({currentIndex:i,currentTrack:n,currentTime:0,isPlaying:!0})},seek:s=>{const{duration:a}=t(),i=Math.max(0,Math.min(s,a||0));e({currentTime:i})},setCurrentTime:s=>{const{duration:a}=t(),i=Math.max(0,Math.min(s,a||0));e({currentTime:i})},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(),i=[...a,...s];e({queue:i})},removeFromQueue:s=>{const{queue:a,currentIndex:i}=t();if(s<0||s>=a.length)return;const n=a.filter((c,l)=>l!==s);let o=i;if(s<i)o=i-1;else if(s===i)if(n.length>0){o=Math.min(o,n.length-1),e({queue:n,currentIndex:o,currentTrack:n[o]||null,isPlaying:n[o]?t().isPlaying:!1});return}else{o=-1,e({queue:n,currentIndex:o,currentTrack:null,isPlaying:!1});return}e({queue:n,currentIndex:o})},reorderQueue:(s,a)=>{const{queue:i,currentIndex:n}=t();if(s<0||s>=i.length||a<0||a>=i.length||s===a)return;const o=[...i],[c]=o.splice(s,1);if(!c)return;o.splice(a,0,c);let l=n;s===n?l=a:s<n&&a>=n?l=n-1:s>n&&a<=n&&(l=n+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 Yi(e){return e?!!(e.id&&e.title&&e.url):!1}class $t{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(!Yi(t))throw new Error("Invalid track");if(!$t.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 $t;function Ji(e){const t=Ut(),s=m.useRef(null),a=e?.current||s.current;m.useEffect(()=>{if(a)return z.initialize(a),()=>{z.cleanup()}},[a]),m.useEffect(()=>{if(!a)return;const d=t.muted?0:t.volume/100;z.setVolume(d),z.setMuted(t.muted)},[a,t.volume,t.muted]),m.useEffect(()=>{if(!a)return;(async()=>{try{await z.loadTrack(t.currentTrack)}catch(h){g.error("Failed to load track:",{error:h})}})()},[a,t.currentTrack]),m.useEffect(()=>{if(!a)return;(async()=>{try{t.isPlaying?await z.play():z.pause()}catch(h){g.error("Failed to sync playback:",{error:h}),t.pause()}})()},[a,t.isPlaying,t]),m.useEffect(()=>{if(a)return z.onTimeUpdate(d=>{t.setCurrentTime(d)}),z.onDurationChange(d=>{t.setDuration(d)}),z.onEnded(()=>{t.repeat==="track"?(z.seek(0),z.play().catch(d=>g.error("Failed to reply track:",{error:d}))):t.next()}),z.onError(d=>{const h=d instanceof Error?d.message:String(d);h.includes("fetch")||h.includes("Invalid")||h.includes("MEDIA_ERR")?g.debug("Audio playback error (invalid URL or network):",{error:h}):g.error("Audio playback error:",{error:d}),t.pause()}),z.onPlay(()=>{t.isPlaying||t.resume()}),z.onPause(()=>{t.isPlaying&&t.pause()}),()=>{z.onTimeUpdate(null),z.onDurationChange(null),z.onEnded(null),z.onError(null),z.onPlay(null),z.onPause(null)}},[a,t]);const i=m.useCallback(async d=>{if(t.play(d),d&&a)try{await z.loadTrack(d),await z.play()}catch(h){g.error("Failed to play track:",{error:h}),t.pause()}},[t,a]),n=m.useCallback(()=>{t.pause(),a&&z.pause()},[t,a]),o=m.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=m.useCallback(()=>{t.stop(),a&&z.stop()},[t,a]),l=m.useCallback(d=>{t.seek(d),a&&z.seek(d)},[t,a]),f=m.useCallback(d=>{if(t.setVolume(d),a){const h=t.muted?0:d/100;z.setVolume(h)}},[t,a]),u=m.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:i,pause:n,resume:o,stop:c,next:t.next,previous:t.previous,seek:l,setVolume:f,toggleMute:u,toggleShuffle:t.toggleShuffle,setRepeat:t.setRepeat,addToQueue:t.addToQueue,clearQueue:t.clearQueue}}const Zi=5,eo=5;function to(e,t={}){const{enabled:s=!0,seekStep:a=Zi,volumeStep:i=eo,preventDefault:n=!0}=t,o=m.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":{n&&c.preventDefault(),e.isPlaying?e.pause():e.resume();break}case"ArrowLeft":{n&&c.preventDefault();const f=Math.max(0,e.currentTime-a);e.seek(f);break}case"ArrowRight":{n&&c.preventDefault();const f=Math.min(e.duration||0,e.currentTime+a);e.seek(f);break}case"ArrowUp":{n&&c.preventDefault();const f=Math.min(100,e.volume+i);e.setVolume(f);break}case"ArrowDown":{n&&c.preventDefault();const f=Math.max(0,e.volume-i);e.setVolume(f);break}}},[s,n,a,i,e.isPlaying,e.currentTime,e.duration,e.volume,e.pause,e.resume,e.seek,e.setVolume]);m.useEffect(()=>{if(s)return window.addEventListener("keydown",o),()=>{window.removeEventListener("keydown",o)}},[s,o])}const We=24,ro=.7;function so(e,t){const[s,a]=m.useState(()=>Array(We).fill(0)),i=m.useRef(null),n=m.useRef(null),o=m.useRef(null),c=m.useRef(null);return m.useEffect(()=>e?((()=>{try{const f=new AudioContext,u=f.createMediaElementSource(e),d=f.createAnalyser();d.fftSize=256,d.smoothingTimeConstant=ro,d.minDecibels=-60,d.maxDecibels=-10,u.connect(d),d.connect(f.destination),i.current=f,n.current=d,o.current=u}catch{}})(),()=>{c.current&&cancelAnimationFrame(c.current),o.current?.disconnect(),n.current?.disconnect(),i.current?.close(),i.current=null,n.current=null,o.current=null}):void 0,[e]),m.useEffect(()=>{const l=n.current,f=i.current;if(!l||!f||!t){t||a(Array(We).fill(0));return}f.state==="suspended"&&f.resume();const u=new Uint8Array(l.frequencyBinCount),d=()=>{if(!n.current)return;n.current.getByteFrequencyData(u);const h=Math.floor(u.length/We),v=Array.from({length:We},(p,w)=>(u[Math.min(w*h,u.length-1)]??0)/255);a(v),c.current=requestAnimationFrame(d)};return c.current=requestAnimationFrame(d),()=>{c.current&&cancelAnimationFrame(c.current)}},[t]),s}const Ge="flex items-center justify-center rounded-full flex-shrink-0 transition-all duration-[var(--sumi-duration-normal)] active:scale-95";function ao({isPlaying:e,onPlayPause:t,onNext:s,onPrevious:a,onShuffle:i,onRepeat:n,shuffle:o,repeat:c,isExpanded:l=!1,compact:f=!1}){const u=f?"w-8 h-8":"w-10 h-10",d=l?"w-16 h-16":f?"w-10 h-10":"w-12 h-12",h=l?"w-6 h-6":f?"w-4 h-4":"w-5 h-5",v=l?"w-8 h-8":f?"w-5 h-5":"w-6 h-6",p=f?"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:i,className:y(Ge,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(Ge,u,"text-foreground hover:text-primary hover:bg-white/5"),children:r.jsx(Cr,{className:y(h,"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(Ge,u,"text-foreground hover:text-primary hover:bg-white/5"),children:r.jsx(Pr,{className:y(h,"fill-current")})}),r.jsx(ce,{content:"Repeat",children:r.jsxs("button",{onClick:n,className:y(Ge,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 ss=m.forwardRef(({label:e,variant:t="cyan",icon:s,size:a="md",dot:i,count:n,children:o,className:c,onDismiss:l,pulse:f,...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"},j=e||o,S=v;return i&&!j&&!s&&n===void 0?r.jsx("span",{ref:d,className:y("inline-block h-2 w-2 rounded-full",E[S]||E.cyan,f&&"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],f&&"animate-pulse",c),...u,children:[i&&r.jsx("span",{className:"w-3 h-3 rounded-full bg-current"}),s&&r.jsx("span",{className:"w-3 h-3",children:s}),j,n!==void 0&&n>0&&r.jsx("span",{className:"ml-1 px-1.5 py-0.5 rounded-full bg-current/20 text-xs",children:n}),l&&r.jsx("button",{type:"button",onClick:I=>{I.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"})})]})});ss.displayName="Badge";const as=m.forwardRef(({className:e,children:t,...s},a)=>r.jsx("div",{ref:a,className:y("relative overflow-auto custom-scrollbar",e),...s,children:t}));as.displayName="ScrollArea";const no=m.forwardRef(({className:e,...t},s)=>r.jsx("div",{ref:s,className:y("flex touch-none select-none transition-colors",e),...t}));no.displayName="ScrollBar";function io({icon:e,title:t,description:s,action:a,className:i,size:n="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"},f={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",f[n]),children:r.jsx("div",{className:y("text-muted-foreground",l[n]),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(L,{onClick:a.onClick,variant:a.variant||"default",size:n==="sm"?"sm":"default",children:a.label})]});return o==="centered"?r.jsx("div",{className:y("flex flex-1 items-center justify-center text-center",c[n],i),children:u}):o==="card"?r.jsx("div",{className:y("border-2 border-dashed border-border rounded-xl text-center",c[n],i),children:u}):r.jsx(zt,{className:y(i),children:r.jsx(Br,{className:y("text-center",c[n]),children:u})})}function oo({isOpen:e,onClose:t,onPlay:s}){const{queue:a,currentIndex:i,removeFromQueue:n,clearQueue:o}=Ut(),{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(ss,{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(io,{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(as,{className:"h-full max-h-layout-list",children:r.jsx("div",{className:"p-2 space-y-1",children:a.map((l,f)=>{const u=f===i,d=f<i;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(ta,{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"}):f+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:h=>{h.stopPropagation(),n(f)},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}-${f}`)})})})})]}),r.jsx("div",{className:"fixed inset-0 bg-black/20 -z-10 backdrop-blur-sm md:hidden",onClick:t})]}):null}const Qt=m.forwardRef(({className:e,value:t=[0],onValueChange:s,min:a=0,max:i=100,step:n=1,disabled:o,"aria-label":c,"aria-labelledby":l,...f},u)=>{const d=v=>{const p=[Number(v.target.value)];s&&s(p)},h=((t[0]??a)-a)/(i-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:`${h}%`}})}),r.jsx("input",{ref:u,type:"range",min:a,max:i,step:n,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":i,...f}),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(${h}% - 10px)`}})]})});Qt.displayName="Slider";function lo({isPlaying:e,isLoading:t=!1,size:s="md",variant:a="default",className:i,disabled:n,onClick:o,...c}){const l={sm:"h-8 w-8",md:"h-10 w-10",lg:"h-12 w-12"},f={sm:"h-4 w-4",md:"h-5 w-5",lg:"h-6 w-6"},u={default:"bg-primary text-primary-foreground hover:bg-primary focus:ring-primary",ghost:"bg-transparent text-foreground hover:bg-muted focus:ring-primary",outline:"border border-border bg-card text-foreground hover:bg-muted focus:ring-muted"},d=h=>{n||t||o?.(h)};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],(n||t)&&"opacity-50 cursor-not-allowed",i),disabled:n||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(f[s],"animate-spin"),"aria-hidden":"true"}),r.jsx("span",{className:"sr-only",children:"Chargement..."})]}):e?r.jsxs(r.Fragment,{children:[r.jsx(Rr,{className:f[s],"aria-hidden":"true"}),r.jsx("span",{className:"sr-only",children:"Mettre en pause"})]}):r.jsxs(r.Fragment,{children:[r.jsx(Ar,{className:y(f[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:i="md",variant:n="ghost",className:o,disabled:c=!1}){const l={sm:"h-8 w-8",md:"h-10 w-10",lg:"h-12 w-12"},f={sm:"h-4 w-4",md:"h-5 w-5",lg:"h-6 w-6"},u={default:"bg-primary text-primary-foreground hover:bg-primary focus:ring-primary",ghost:"bg-transparent text-foreground hover:bg-muted focus:ring-primary",outline:"border border-border bg-card text-foreground hover:bg-muted focus:ring-muted"},d=c||!a,h=c||!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[i],u[n],d&&"opacity-50 cursor-not-allowed"),"aria-label":"Piste précédente","aria-disabled":d,children:[r.jsx(Cr,{className:f[i],"aria-hidden":"true"}),r.jsx("span",{className:"sr-only",children:"Piste précédente"})]}),r.jsxs("button",{type:"button",onClick:e,disabled:h,className:y("rounded-full flex items-center justify-center transition-colors focus:outline-none focus:ring-2 focus:ring-offset-2",l[i],u[n],h&&"opacity-50 cursor-not-allowed"),"aria-label":"Piste suivante","aria-disabled":h,children:[r.jsx(Pr,{className:f[i],"aria-hidden":"true"}),r.jsx("span",{className:"sr-only",children:"Piste suivante"})]})]})}function co({repeat:e,shuffle:t,onRepeatChange:s,onShuffleToggle:a,className:i,disabled:n=!1,size:o="md",variant:c="ghost"}){const l={sm:"h-8 w-8",md:"h-10 w-10",lg:"h-12 w-12"},f={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=()=>{n||s(e==="off"?"track":e==="track"?"playlist":"off")},h=()=>{switch(e){case"track":return"Répéter la piste";case"playlist":return"Répéter la playlist";default:return"Répéter désactivé"}},v=()=>{switch(e){case"track":return"Répéter la piste (actif)";case"playlist":return"Répéter la playlist (actif)";default:return"Répéter désactivé"}};return r.jsxs("div",{className:y("flex items-center gap-2",i),children:[r.jsx(ce,{content:h(),disabled:n,children:r.jsxs("button",{type:"button",onClick:d,disabled:n,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",n&&"opacity-50 cursor-not-allowed"),"aria-label":v(),"aria-pressed":e!=="off","aria-disabled":n,children:[r.jsx(Ir,{className:y(f[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:h()})]})}),r.jsx(ce,{content:t?"Mélanger activé":"Mélanger désactivé",disabled:n,children:r.jsxs("button",{type:"button",onClick:a,disabled:n,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",n&&"opacity-50 cursor-not-allowed"),"aria-label":t?"Mélanger activé":"Mélanger désactivé","aria-pressed":t,"aria-disabled":n,children:[r.jsx(Tr,{className:y(f[o],t&&"fill-current"),"aria-hidden":"true"}),r.jsx("span",{className:"sr-only",children:t?"Mélanger activé":"Mélanger désactivé"})]})})]})}function uo({isOpen:e,onClose:t,currentTime:s,duration:a,onSeek:i,player:n}){const{currentTrack:o}=Ut(),[c,l]=m.useState(!1),[f,u]=m.useState(!0),d=m.useRef(null);if(!e||!o)return null;const h=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 m.useEffect(()=>{if(!f||!h?.length||!d.current)return;const p=h.findIndex((w,E)=>s>=w.time&&(E===h.length-1||s<(h[E+1]?.time??1/0)));p>=0&&d.current.children[p]?.scrollIntoView({behavior:"smooth",block:"center"})},[s,h,f]),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(L,{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(L,{variant:"ghost",className:"text-foreground hover:bg-white/10 rounded-full",children:r.jsx(ra,{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(L,{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(Qt,{value:[s],onValueChange:p=>i(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(co,{repeat:n.repeat,shuffle:n.shuffle,onRepeatChange:n.setRepeat,onShuffleToggle:n.toggleShuffle,size:"lg"})}),r.jsxs("div",{className:"flex items-center gap-6 md:gap-8",children:[r.jsx(gr,{onNext:n.next,onPrevious:n.previous,canGoNext:!0,canGoPrevious:!0,size:"lg"}),r.jsx(lo,{isPlaying:n.isPlaying,onClick:()=>n.isPlaying?n.pause():n.resume(),size:"lg",className:"scale-125"}),r.jsx(gr,{onNext:n.next,onPrevious:n.previous,canGoNext:!0,canGoPrevious:!0,size:"lg",className:"hidden"})]}),r.jsxs("div",{className:"flex items-center gap-4",children:[r.jsx(L,{size:"icon",variant:"ghost",className:"text-muted-foreground hover:text-foreground",children:r.jsx(sa,{className:"w-5 h-5"})}),r.jsx(ce,{content:c?"Hide lyrics":"Show lyrics",children:r.jsx(L,{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(L,{variant:"ghost",size:"icon",className:f?"bg-primary/20 text-primary":"text-muted-foreground",onClick:()=>u(!f),children:r.jsx(aa,{className:"w-4 h-4"})})})}),h?.length?r.jsx("div",{ref:d,className:"flex-1 overflow-y-auto custom-scrollbar px-6 py-8 space-y-6 text-center",children:h.map((p,w)=>{const E=s>=p.time&&(w===h.length-1||s<(h[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:()=>i(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 mo({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((i,n)=>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+i*28)}px`:"4px"}},n))})}function fo({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 ho({currentTime:e,duration:t,onSeek:s,className:a}){const i=m.useRef(null),n=t>0?Math.max(0,Math.min(1,e/t)):0,o=c=>{if(!i.current)return;const l=i.current.getBoundingClientRect(),f=c.clientX-l.left;s(Math.max(0,Math.min(1,f/l.width)))};return r.jsx("div",{ref:i,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(${n})`,transformOrigin:"left"}})})}const kt="h-8 w-8 sm:h-9 sm:w-9 rounded-full transition-transform duration-150 active:scale-95";function po({volume:e,muted:t,onVolumeChange:s,onToggleMute:a,showQueue:i,onToggleQueue:n,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(mo,{levels:o,playing:c})}),r.jsxs("div",{className:"flex items-center gap-0.5 group/volume flex-shrink-0",children:[r.jsx(L,{variant:"ghost",size:"icon",className:y(kt,"text-muted-foreground hover:text-foreground"),onClick:a,children:t||e===0?r.jsx(na,{className:"w-4 h-4"}):r.jsx(ia,{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(Qt,{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(L,{variant:"ghost",size:"icon",className:y(kt,i?"text-primary bg-primary/10":"text-muted-foreground hover:text-foreground"),onClick:n,children:r.jsx(It,{className:"w-4 h-4"})}),r.jsx(L,{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 go({title:e,artist:t,cover:s,isIdle:a,isPlaying:i,onExpand:n}){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:n,children:[s?r.jsx("img",{src:s,alt:"",className:y("w-full h-full object-cover transition-transform duration-700",i&&"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:n,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 vo={title:"System Online",artist:"Select a track to play",cover:""};function yo(){const e=m.useRef(null),[t,s]=m.useState(null),a=m.useCallback(E=>{e.current=E,s(E)},[]),{sidebarOpen:i}=ue(),n=Ji(e);to(n);const[o,c]=m.useState(!1),[l,f]=m.useState(!1),[u,d]=m.useState(!1),h=so(t,n.isPlaying),v=n.currentTrack,p=v||vo,w=!v;return r.jsxs(r.Fragment,{children:[r.jsx("audio",{ref:a}),r.jsx(uo,{isOpen:l,onClose:()=>f(!1),currentTime:n.currentTime,duration:n.duration,onSeek:n.seek,player:n}),r.jsx(oo,{isOpen:u,onClose:()=>d(!1),currentTrackId:v?.id,onPlay:E=>n.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",i?"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(fo,{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(go,{title:p.title,artist:p.artist||"Unknown Artist",cover:p.cover,isIdle:w,isPlaying:n.isPlaying,onExpand:()=>!w&&f(!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(ao,{compact:!0,isPlaying:n.isPlaying,onPlayPause:()=>{n.isPlaying?n.pause():w||n.resume()},onNext:n.next,onPrevious:n.previous,onShuffle:n.toggleShuffle,onRepeat:()=>{const E=["off","track","playlist"],j=n.repeat??"off",S=E[(E.indexOf(j)+1)%E.length]??"off";n.setRepeat(S)},shuffle:n.shuffle,repeat:n.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(n.currentTime)}),r.jsx("span",{className:"opacity-30",children:"/"}),r.jsx("span",{children:pr(n.duration)})]})]}),r.jsx(po,{volume:n.volume,muted:n.muted,onVolumeChange:n.setVolume,onToggleMute:n.toggleMute,showQueue:u,onToggleQueue:()=>d(!u),waveformLevels:h,isPlaying:n.isPlaying})]}),!w&&r.jsx(ho,{currentTime:n.currentTime,duration:n.duration,onSeek:E=>n.seek(E*n.duration)})]})}),document.body)]})}function xo({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(Xi,{}),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($i,{}),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(yo,{})})]})]})}function bo({children:e}){return r.jsx(xo,{children:e})}function Ce(e){return r.jsx(Ei,{children:r.jsx(Se,{children:e})})}function Q(e){return r.jsx(qn,{children:r.jsx(bo,{children:r.jsx(Se,{children:e})})})}function wo(){return[{path:"/login",element:Ce(r.jsx(Gn,{}))},{path:"/register",element:Ce(r.jsx(Xn,{}))},{path:"/forgot-password",element:Ce(r.jsx(Yn,{}))},{path:"/verify-email",element:Ce(r.jsx(Jn,{}))},{path:"/reset-password",element:Ce(r.jsx(Zn,{}))}]}function ko(){return[{path:"/design-system",element:r.jsx(Se,{children:r.jsx(ui,{})})},{path:"/u/:username",element:r.jsx(Se,{children:r.jsx(si,{})})}]}function Eo(){return[{path:"/dashboard",element:Q(r.jsx(Qn,{}))},{path:"/marketplace",element:Q(r.jsx(yi,{}))},{path:"/sell",element:Q(r.jsx(bi,{onCreateProduct:()=>{}}))},{path:"/wishlist",element:Q(r.jsx(wi,{}))},{path:"/purchases",element:Q(r.jsx(ki,{}))},{path:"/chat",element:Q(r.jsx(Bn,{}))},{path:"/library",element:Q(r.jsx(Kn,{}))},{path:"/profile",element:Q(r.jsx(Hn,{}))},{path:"/settings",element:Q(r.jsx(Wn,{}))},{path:"/settings/sessions",element:Q(r.jsx(ei,{}))},{path:"/admin/roles",element:Q(r.jsx(ai,{}))},{path:"/tracks/:id",element:Q(r.jsx(ni,{}))},{path:"/playlists/*",element:Q(r.jsx(ii,{}))},{path:"/search",element:Q(r.jsx(xi,{}))},{path:"/notifications",element:Q(r.jsx(vi,{}))},{path:"/analytics",element:Q(r.jsx(li,{onNavigateTrack:()=>{}}))},{path:"/webhooks",element:Q(r.jsx(ci,{}))},{path:"/admin",element:Q(r.jsx(oi,{}))},{path:"/social",element:Q(r.jsx(di,{onViewProfile:()=>{}}))},{path:"/education",element:Q(r.jsx(hi,{}))},{path:"/queue",element:Q(r.jsx(pi,{}))},{path:"/developer",element:Q(r.jsx(gi,{}))},{path:"/gear",element:Q(r.jsx(mi,{}))},{path:"/live",element:Q(r.jsx(fi,{}))}]}function So(){return[{path:"/404",element:r.jsx(Se,{children:r.jsx(ti,{})})},{path:"/500",element:r.jsx(Se,{children:r.jsx(ri,{})})}]}function No(){const e=wo(),t=ko(),s=Eo(),a=So();return r.jsxs(ms,{children:[e.map(({path:i,element:n})=>r.jsx(xe,{path:i,element:n},i)),t.map(({path:i,element:n})=>r.jsx(xe,{path:i,element:n},i)),s.map(({path:i,element:n})=>r.jsx(xe,{path:i,element:n},i)),a.map(({path:i,element:n})=>r.jsx(xe,{path:i,element:n},i)),r.jsx(xe,{path:"/",element:r.jsx(Ze,{to:"/dashboard",replace:!0})}),r.jsx(xe,{path:"*",element:r.jsx(Ze,{to:"/404",replace:!0})})]})}function jo(e={}){const{enabled:t=!0,preventDefault:s=!0,onHelpOpen:a}=e,i=st(),{setSidebarOpen:n,sidebarOpen:o}=ue(),c=m.useCallback(l=>{if(!t)return;const f=l.target;if(f&&(f.tagName==="INPUT"||f.tagName==="TEXTAREA"||f.isContentEditable===!0||f.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()):i("/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()):i("/search");return}if((l.ctrlKey||l.metaKey)&&l.key==="n"){s&&l.preventDefault(),i("/chat");return}if((l.ctrlKey||l.metaKey)&&l.key==="b"){s&&l.preventDefault(),n(!o);return}if(l.key==="Escape"){document.querySelectorAll('[role="menu"][aria-expanded="true"]').forEach(d=>{const h=d.previousElementSibling;h&&h.click()});return}if(l.key==="?"&&!l.ctrlKey&&!l.metaKey){s&&l.preventDefault(),a&&a();return}},[t,s,i,n,o,a]);m.useEffect(()=>{if(t)return window.addEventListener("keydown",c),()=>{window.removeEventListener("keydown",c)}},[t,c])}const _o=[{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 To({isOpen:e,onClose:t}){return m.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:_o.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((i,n)=>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:i}),n<a.keys.length-1&&r.jsx("span",{className:"mx-0.5 text-xs text-muted-foreground",children:"+"})]},n))})]},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 Co(e={}){const{hydrateAuth:t=!0,hydrateLibrary:s=!1,hydrateChat:a=!1,requireAuth:i=!0}=e,n={success:!0,hydrated:[],errors:[]};try{if(i){const{isAuthenticated:o}=te.getState();if(!o)return g.debug("[StateHydration] User not authenticated, skipping hydration"),n}if(t)try{const{isAuthenticated:o,isLoading:c}=te.getState(),l=ee.hasTokens();o&&l&&!c||(await Ro(),n.hydrated.push("auth"),g.debug("[StateHydration] Auth state hydrated"))}catch(o){const c=o instanceof Error?o:new Error(String(o));n.errors.push({store:"auth",error:c}),n.success=!1,g.error("[StateHydration] Failed to hydrate auth state",{error:c.message})}if(s)try{await Ao(),n.hydrated.push("library"),g.debug("[StateHydration] Library state hydrated")}catch(o){const c=o instanceof Error?o:new Error(String(o));n.errors.push({store:"library",error:c}),n.success=!1,g.error("[StateHydration] Failed to hydrate library state",{error:c.message})}if(a)try{await Po(),n.hydrated.push("chat"),g.debug("[StateHydration] Chat state hydrated")}catch(o){const c=o instanceof Error?o:new Error(String(o));n.errors.push({store:"chat",error:c}),n.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}),n.success=!1}return n}async function Ro(){const{refreshUser:e,isAuthenticated:t}=te.getState();await e()}async function Ao(){g.debug("[StateHydration] Library state hydration skipped - using React Query")}async function Po(){g.debug("[StateHydration] Chat state hydration skipped - using React Query")}function Io(e={}){const[t,s]=m.useState(!0),[a,i]=m.useState(null);return m.useEffect(()=>{let n=!0;return Co(e).then(o=>{n&&(i(o),s(!1))}).catch(o=>{n&&(g.error("[StateHydration] Hook error:",o),i({success:!1,hydrated:[],errors:[{store:"unknown",error:o instanceof Error?o:new Error(String(o))}]}),s(!1))}),()=>{n=!1}},[]),{isHydrating:t,hydrationResult:a}}function Lo(){const e=At();m.useEffect(()=>{const t=s=>{const{queryKeys:a,resourceType:i,resourceId:n}=s.detail;if(a&&a.length>0)for(const o of a)e.invalidateQueries({queryKey:o});if(i){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:[]}[i]||[];for(const l of c)e.invalidateQueries({queryKey:n?[...l,n]:l})}};return window.addEventListener("veza:invalidate-queries",t),()=>{window.removeEventListener("veza:invalidate-queries",t)}},[e])}function Do(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 qo(){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 Mo(e,t={}){const s=t.channelName||"veza-react-query-sync",a=t.enabled!==!1,i=t.shouldSync||(()=>!0);if(!a)return()=>{};const n=Do(s);if(!n)return g.warn("[ReactQuerySync] BroadcastChannel not available, sync disabled"),()=>{};const o=qo(),c=new Set;let l=!1;function f(v){if(l||!i(v,"query-invalidate"))return;const p={type:"query-invalidate",queryKey:v,timestamp:Date.now(),messageId:yr(),tabId:o};try{n&&(n.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)),!!i(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)}}}n.addEventListener("message",u);const d=e.getMutationCache().subscribe(v=>{if(!(!v||!n)&&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{n.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})}}}}),h=e.getQueryCache().subscribe(v=>{if(v?.type==="removed"||v?.type==="updated"&&v.query?.state.isInvalidated){const p=v.query.queryKey;f(p)}});return g.debug("[ReactQuerySync] React Query cache synchronization enabled",{channelName:s,tabId:o}),()=>{n.removeEventListener("message",u),d(),h(),n.close(),g.debug("[ReactQuerySync] React Query cache synchronization disabled")}}const Xe=[{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())}],Oo={mode:"waveform",color:"#7c9dd6",sensitivity:50};function zo(){const[e,t]=m.useState(null),[s,a]=m.useState([]),[i,n]=m.useState([]),[o,c]=m.useState(!1),[l,f]=m.useState(0),[u,d]=m.useState(0),[h,v]=m.useState(80),[p,w]=m.useState(!1),[E,j]=m.useState(!1),[S,I]=m.useState("off"),[A,b]=m.useState(1),[_,W]=m.useState(!0),[k,N]=m.useState(Oo),[C,O]=m.useState(!0),V=m.useRef(null);m.useEffect(()=>{t(Xe[0]??null),a(Xe.slice(1))},[]);const Z=()=>{if(s.length>0){const P=E?s[Math.floor(Math.random()*s.length)]:s[0];if(!P)return;n(M=>e?[...M,e]:M),a(S!=="all"?M=>M.filter(X=>X.id!==P.id):M=>[...M.filter(X=>X.id!==P.id),P]),t(P),d(0),c(!0)}else if(C){const P=Math.floor(Math.random()*Xe.length),M=Xe[P];if(!M)return;n(X=>e?[...X,e]:X),t({...M,id:`auto-${Date.now()}`,title:`Autoplay: ${M.title}`}),d(0),c(!0)}else c(!1),d(0)};m.useEffect(()=>(o&&e?V.current=window.setInterval(()=>{d(P=>{if(e?.durationSec&&P>=e.durationSec){if(S==="one")return 0;if(s.length>0||C)Z();else return c(!1),P;return 0}return P+1*A})},1e3/A):V.current&&clearInterval(V.current),()=>{V.current&&clearInterval(V.current)}),[o,e,S,A,s.length,C]),m.useEffect(()=>{e?.durationSec&&f(u/e.durationSec*100)},[u,e]);const G=(P,M)=>{if(e&&e.id!==P.id&&n(X=>[...X,e]),t(P),M){const X=M.findIndex($e=>$e.id===P.id);X!==-1&&a(M.slice(X+1))}c(!0),d(0)},Y=()=>c(!o),re=()=>{if(u>3)d(0);else if(i.length>0){const P=i[i.length-1];if(!P)return;a(M=>e?[e,...M]:M),n(M=>M.slice(0,-1)),t(P),d(0),c(!0)}},je=P=>{if(e?.durationSec){const M=P/100*e.durationSec;d(M),f(P)}},ft=P=>v(P),ht=()=>w(P=>!P),pt=()=>j(!E),Ue=()=>{const P=["off","all","one"],M=P[(P.indexOf(S)+1)%P.length]??"off";I(M)},_e=()=>W(!_),U=()=>O(!C),le=P=>a(M=>[...M,P]),gt=P=>a(M=>[P,...M]),os=P=>a(M=>M.filter(X=>X.id!==P)),ls=()=>a([]),cs=(P,M)=>{const X=Array.from(s),[$e]=X.splice(P,1);$e&&(X.splice(M,0,$e),a(X))};return{currentTrack:e,isPlaying:o,queue:s,history:i,progress:l,currentTime:u,duration:e?.durationSec||0,volume:h,isMuted:p,shuffle:E,repeatMode:S,playbackRate:A,pitchCorrection:_,visualizerSettings:k,autoplay:C,playTrack:G,togglePlay:Y,nextTrack:Z,prevTrack:re,seek:je,setVolume:ft,toggleMute:ht,toggleShuffle:pt,toggleRepeat:Ue,setPlaybackRate:b,togglePitchCorrection:_e,setVisualizerSettings:N,toggleAutoplay:U,addToQueue:le,removeFromQueue:os,playNext:gt,reorderQueue:cs,clearQueue:ls}}const ns=m.createContext(void 0),cc=()=>{const e=m.useContext(ns);if(!e)throw new Error("useAudio must be used within AudioProvider");return e},Fo=({children:e})=>{const t=zo();return r.jsx(ns.Provider,{value:t,children:e})};function Vo(){const{t:e}=qt(),{refreshUser:t}=te(),{theme:s,setTheme:a,language:i,setLanguage:n}=ue(),[o,c]=m.useState(!1),[l,f]=m.useState(!1),u=At();return jo({enabled:!0,onHelpOpen:()=>c(!0)}),Io({hydrateAuth:!0,hydrateLibrary:!1,hydrateChat:!1,requireAuth:!1}),Lo(),m.useEffect(()=>Mo(u,{enabled:!0,channelName:"veza-react-query-sync"}),[u]),m.useEffect(()=>{if((async()=>{await new Promise(v=>setTimeout(v,100));const{isAuthenticated:h}=te.getState();h&&J.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 h=document.documentElement;!h.classList.contains("dark")&&!h.classList.contains("light")?a("dark"):a(s)}else a(s);if(typeof window<"u"&&window.i18n){const h=window.i18n.language||i;h!==i?window.i18n.changeLanguage(i):i!==h&&n(h)}},[a,s,i,n]),m.useEffect(()=>{(async()=>{try{await t()}catch(h){g.error("[App] Auth initialization failed",{error:h instanceof Error?h.message:String(h),stack:h instanceof Error?h.stack:void 0})}finally{f(!0)}})()},[t]),m.useEffect(()=>{if(s!=="system")return;const d=window.matchMedia("(prefers-color-scheme: dark)"),h=v=>{const p=document.documentElement;v.matches?p.classList.add("dark"):p.classList.remove("dark")};return d.addEventListener?d.addEventListener("change",h):d.addListener(h),()=>{d.removeEventListener?d.removeEventListener("change",h):d.removeListener(h)}},[s]),l?r.jsx(dn,{children:r.jsx(vn,{children:r.jsxs(Fo,{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(Cn,{}),r.jsx(No,{}),r.jsx(To,{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 Uo={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"},$o={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é"}},Qo={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é"}},Bo={title:"Bientôt disponible",description:"Cette fonctionnalité est en cours de développement et sera bientôt disponible.",notifyMe:"Me notifier",goBack:"Retour"},Ko={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"},Ho={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..."}},Wo={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"}},Go={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..."}},Xo={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..."},Yo={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"}},Jo={dashboard:"Tableau de bord",chat:"Chat",library:"Bibliothèque",profile:"Profil",settings:"Paramètres",menu:"Menu",close:"Fermer"},Zo={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é"},el={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"}}},tl={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"},rl={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"},sl={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"},al={title:"Recherche",placeholder:"Rechercher des pistes, playlists, utilisateurs...",results:"Résultats",noResults:"Aucun résultat trouvé",tracks:"Pistes",playlists:"Playlists",users:"Utilisateurs",all:"Tout"},nl={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"},il={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é"},ol={title:"Tableau de bord administrateur",users:"Utilisateurs",systemStats:"Statistiques système",auditLogs:"Journaux d'audit",suspiciousActivity:"Activité suspecte"},ll={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"}},cl={searchPlaceholder:"Que voulez-vous écouter ?",searchAriaLabel:"Rechercher des pistes, artistes, playlists",online:"En ligne",profile:"Profil",signOut:"Déconnexion"},ul={sections:{myStudio:"Mon Studio",vezaNetwork:"Réseau Veza",commerce:"Commerce",library:"Bibliothèque",system:"Système"},items:{dashboard:"Centre de contrôle",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"},dl={common:Uo,auth:$o,dashboard:Qo,comingSoon:Bo,player:Ko,chat:Ho,library:Wo,profile:Go,settings:Xo,errors:Yo,navigation:Jo,validation:Zo,pwa:el,tracks:tl,playlists:rl,notifications:sl,search:al,analytics:nl,webhooks:il,admin:ol,keyboard:ll,header:cl,nav:ul},ml={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"},fl={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"}},hl={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"}},pl={title:"Coming Soon",description:"This feature is currently under development and will be available soon.",notifyMe:"Notify me",goBack:"Go back"},gl={play:"Play",pause:"Pause",next:"Next track",previous:"Previous track",shuffleOn:"Shuffle: On",shuffleOff:"Shuffle: Off",repeatOff:"Repeat: Off",repeatTrack:"Repeat: Track",repeatPlaylist:"Repeat: Playlist",mute:"Mute",unmute:"Unmute",showQueue:"Show queue",hideQueue:"Hide queue"},vl={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..."}},yl={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"}},xl={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..."}},bl={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..."},wl={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"}},kl={dashboard:"Dashboard",chat:"Chat",library:"Library",profile:"Profile",settings:"Settings",menu:"Menu",close:"Close"},El={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"},Sl={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"}}},Nl={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"},_l={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"},Tl={title:"Search",placeholder:"Search tracks, playlists, users...",results:"Results",noResults:"No results found",tracks:"Tracks",playlists:"Playlists",users:"Users",all:"All"},Cl={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"},Rl={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"},Al={title:"Admin Dashboard",users:"Users",systemStats:"System Statistics",auditLogs:"Audit Logs",suspiciousActivity:"Suspicious Activity"},Pl={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"}},Il={searchPlaceholder:"What do you want to play?",searchAriaLabel:"Search tracks, artists, playlists",online:"Online",profile:"Profile",signOut:"Sign Out"},Ll={sections:{myStudio:"My Studio",vezaNetwork:"Veza Network",commerce:"Commerce",library:"Library",system:"System"},items:{dashboard:"Command Center",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"},Dl={common:ml,auth:fl,dashboard:hl,comingSoon:pl,player:gl,chat:vl,library:yl,profile:xl,settings:bl,errors:wl,navigation:kl,validation:El,pwa:Sl,tracks:Nl,playlists:jl,notifications:_l,search:Tl,analytics:Cl,webhooks:Rl,admin:Al,keyboard:Pl,header:Il,nav:Ll},ql={fr:{translation:dl},en:{translation:Dl}};Lr.use(oa).use(la).init({resources:ql,fallbackLng:"en",debug:!1,interpolation:{escapeValue:!1},detection:{order:["localStorage","navigator","htmlTag"],caches:["localStorage"]}});typeof window<"u"&&(window.i18n=Lr);function Ml(){const e="production";{g.debug("[Sentry] Error tracking disabled",{reason:"DSN not configured",environment:e});return}}const Ol={theme:"system",setTheme:()=>null},zl=m.createContext(Ol);function Fl({children:e,defaultTheme:t="system",storageKey:s="vite-ui-theme"}){const[a,i]=m.useState(()=>localStorage.getItem(s)||t);m.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]),m.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 n={theme:a,setTheme:o=>{localStorage.setItem(s,o),i(o)}};return r.jsx(zl.Provider,{value:n,children:e})}typeof window<"u"&&(window.addEventListener("error",e=>{},!0),window.addEventListener("unhandledrejection",e=>{}));Ml();const is=new hs({defaultOptions:{queries:{retry:!1,refetchOnWindowFocus:!1,staleTime:60*1e3,gcTime:300*1e3,refetchOnMount:!0,refetchOnReconnect:!0}}});da(is);async function Vl(){ct.USE_MSW}const Ul=()=>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 i of s)try{(i.cssRules!==null||i.href===null)&&a++}catch{i.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,i=setInterval(()=>{s++,(t()||s>=a)&&(clearInterval(i),requestAnimationFrame(()=>{requestAnimationFrame(()=>{requestAnimationFrame(()=>{setTimeout(()=>{e()},50)})})}))},50)},{once:!0});else{let s=0;const a=20,i=setInterval(()=>{s++,(t()||s>=a)&&(clearInterval(i),requestAnimationFrame(()=>{requestAnimationFrame(()=>{requestAnimationFrame(()=>{setTimeout(()=>{e()},50)})})}))},50)}}),$l=()=>{us.createRoot(document.getElementById("root")).render(r.jsx(Rt.StrictMode,{children:r.jsx(ps,{client:is,children:r.jsx(Fl,{defaultTheme:"dark",storageKey:"vite-ui-theme",children:r.jsxs(fs,{future:{v7_startTransition:!0,v7_relativeSplatPath:!0},children:[r.jsx(Vo,{}),r.jsx(ha,{position:"top-right"})]})})})}))},Ql=T(()=>import("./vendor-CveO81sn.js").then(e=>e.aB),__vite__mapDeps([0,1,2,3])).then(e=>e).catch(e=>{});Promise.all([Vl(),Ql]).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(()=>Ul()).finally(()=>{$l()});export{Ha as A,L as B,zt as C,Xr as D,io as E,es as F,Ut as G,nr as H,_t as I,Xa as J,Un as L,Nn as S,ce as T,T as _,rc as a,ac as b,y as c,nc as d,ic as e,Br as f,F as g,te as h,Jr as i,cc as j,ss as k,g as l,oc as m,Ci as n,Qt as o,B as p,Ot as q,tc as r,cn as s,Si as t,lc as u,Zr as v,K as w,ct as x,Vr as y,jt as z};